text
stringlengths
2
99.9k
meta
dict
/* * Copyright (C) 2017 Schürmann & Breitmoser GbR * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.sufficientlysecure.keychain.pgp; import java.util.Arrays; import java.util.Iterator; import java.util.NoSuchElementException; import org.bouncycastle.openpgp.PGPPublicKey; import org.bouncycastle.openpgp.PGPSignature; import org.bouncycastle.openpgp.PGPUserAttributeSubpacketVector; import org.sufficientlysecure.keychain.util.Utf8Util; @SuppressWarnings("unchecked") // BouncyCastle doesn't do generics here :( class PGPPublicKeyUtils { static PGPPublicKey keepOnlyRawUserId(PGPPublicKey masterPublicKey, byte[] rawUserIdToKeep) { boolean elementToKeepFound = false; Iterator<byte[]> it = masterPublicKey.getRawUserIDs(); while (it.hasNext()) { byte[] rawUserId = it.next(); if (Arrays.equals(rawUserId, rawUserIdToKeep)) { elementToKeepFound = true; } else { masterPublicKey = PGPPublicKey.removeCertification(masterPublicKey, rawUserId); } } if (!elementToKeepFound) { throw new NoSuchElementException(); } return masterPublicKey; } static PGPPublicKey keepOnlyUserId(PGPPublicKey masterPublicKey, String userIdToKeep) { boolean elementToKeepFound = false; Iterator<byte[]> it = masterPublicKey.getRawUserIDs(); while (it.hasNext()) { byte[] rawUserId = it.next(); String userId = Utf8Util.fromUTF8ByteArrayReplaceBadEncoding(rawUserId); if (userId.contains(userIdToKeep)) { elementToKeepFound = true; } else { masterPublicKey = PGPPublicKey.removeCertification(masterPublicKey, rawUserId); } } if (!elementToKeepFound) { throw new NoSuchElementException(); } return masterPublicKey; } static PGPPublicKey keepOnlySelfCertsForUserIds(PGPPublicKey masterPubKey) { long masterKeyId = masterPubKey.getKeyID(); Iterator<byte[]> it = masterPubKey.getRawUserIDs(); while (it.hasNext()) { byte[] rawUserId = it.next(); masterPubKey = keepOnlySelfCertsForRawUserId(masterPubKey, masterKeyId, rawUserId); } return masterPubKey; } private static PGPPublicKey keepOnlySelfCertsForRawUserId( PGPPublicKey masterPubKey, long masterKeyId, byte[] rawUserId) { Iterator<PGPSignature> it = masterPubKey.getSignaturesForID(rawUserId); while (it.hasNext()) { PGPSignature sig = it.next(); if (sig.getKeyID() != masterKeyId) { masterPubKey = PGPPublicKey.removeCertification(masterPubKey, rawUserId, sig); } } return masterPubKey; } static PGPPublicKey removeAllUserAttributes(PGPPublicKey masterPubKey) { Iterator<PGPUserAttributeSubpacketVector> it = masterPubKey.getUserAttributes(); while (it.hasNext()) { masterPubKey = PGPPublicKey.removeCertification(masterPubKey, it.next()); } return masterPubKey; } static PGPPublicKey removeAllDirectKeyCerts(PGPPublicKey masterPubKey) { Iterator<PGPSignature> it = masterPubKey.getSignaturesOfType(PGPSignature.DIRECT_KEY); while (it.hasNext()) { masterPubKey = PGPPublicKey.removeCertification(masterPubKey, it.next()); } return masterPubKey; } }
{ "pile_set_name": "Github" }
/* * This file is part of OpenModelica. * * Copyright (c) 1998-2014, Open Source Modelica Consortium (OSMC), * c/o Linköpings universitet, Department of Computer and Information Science, * SE-58183 Linköping, Sweden. * * All rights reserved. * * THIS PROGRAM IS PROVIDED UNDER THE TERMS OF GPL VERSION 3 LICENSE OR * THIS OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.2. * ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3, * ACCORDING TO RECIPIENTS CHOICE. * * The OpenModelica software and the Open Source Modelica * Consortium (OSMC) Public License (OSMC-PL) are obtained * from OSMC, either from the above address, * from the URLs: http://www.ida.liu.se/projects/OpenModelica or * http://www.openmodelica.org, and in the OpenModelica distribution. * GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html. * * This program is distributed WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH * IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS OF OSMC-PL. * * See the full OSMC Public License conditions for more details. * */ encapsulated package ExpressionSolve " file: ExpressionSolve.mo package: ExpressionSolve description: ExpressionSolve This file contains the module ExpressionSolve, which contains functions to solve a DAE.Exp for a DAE.Exp" // public imports public import Absyn; public import AbsynUtil; public import DAE; // protected imports protected import ComponentReference; protected import Debug; protected import Differentiate; protected import ElementSource; protected import Expression; protected import ExpressionDump; protected import ExpressionSimplify; protected import Flags; protected import List; protected import Inline; protected import BackendEquation; protected import BackendVariable; protected import BackendDAEUtil; // ============================================================================= // section for postOptModule >>solveSimpleEquations<< // // solve simple equations otherwise detect EQUATIONSYSTEM // ============================================================================= public function solveSimpleEquations input output BackendDAE.BackendDAE DAE; algorithm DAE.eqs := list( (match syst local BackendDAE.StrongComponents comps; array<Integer> ass1 "eqn := ass1[var]"; array<Integer> ass2 "var := ass2[eqn]"; case BackendDAE.EQSYSTEM(matching = BackendDAE.MATCHING(comps=comps,ass1=ass1, ass2=ass2)) algorithm comps := list( (match comp local BackendDAE.Equation eqn; BackendDAE.Var var; Integer eindex,vindx; Boolean solved; BackendDAE.StrongComponent tmpComp; case BackendDAE.SINGLEEQUATION() algorithm BackendDAE.SINGLEEQUATION(eqn=eindex,var=vindx) := comp; eqn := BackendEquation.get(syst.orderedEqs, eindex); var := BackendVariable.getVarAt(syst.orderedVars, vindx); tmpComp := comp; if BackendEquation.isEquation(eqn) then (eqn,solved) := solveSimpleEquationsWork(eqn, var, DAE.shared); syst.orderedEqs := BackendEquation.setAtIndex(syst.orderedEqs, eindex, eqn); if not solved then tmpComp := BackendDAE.EQUATIONSYSTEM({eindex}, {vindx}, BackendDAE.EMPTY_JACOBIAN() ,BackendDAE.JAC_NONLINEAR(), false); end if; end if; // isEquation then tmpComp; else comp; end match) for comp in comps); syst.matching := BackendDAE.MATCHING(ass1, ass2, comps); then syst; else syst; end match) for syst in DAE.eqs); end solveSimpleEquations; protected function solveSimpleEquationsWork input output BackendDAE.Equation eqn; input BackendDAE.Var var "solve eq with respect to var"; input BackendDAE.Shared shared; output Boolean solved; protected DAE.ComponentRef cr; DAE.Exp e1,e2,varexp,e; BackendDAE.EquationAttributes attr; DAE.ElementSource source; Boolean isContinuousIntegration = BackendDAEUtil.isSimulationDAE(shared); algorithm BackendDAE.EQUATION(exp=e1, scalar=e2, source=source,attr=attr) := eqn; BackendDAE.VAR(varName = cr) := var; varexp := Expression.crefExp(cr); if BackendVariable.isStateVar(var) then varexp := Expression.expDer(varexp); cr := ComponentReference.crefPrefixDer(cr); end if; if (Types.isIntegerOrRealOrSubTypeOfEither(Expression.typeof(e1)) and Types.isIntegerOrRealOrSubTypeOfEither(Expression.typeof(e2))) then (e1, e2) := preprocessingSolve(e1, e2, varexp, SOME(shared.functionTree), NONE(), 0, false); end if; try e := solve2(e1, e2, varexp, SOME(shared.functionTree), NONE(), false, isContinuousIntegration); source := ElementSource.addSymbolicTransformationSolve(true, source, cr, e1, e2, e, {}); eqn := BackendEquation.generateEquation(varexp, e, source, attr); solved := true; else //eqn is change by possible simplification inside preprocessingSolve for solve the eqn with respect to varexp //source := ElementSource.addSymbolicTransformationSimplify(true, source, DAE.PARTIAL_EQUATION(e1), DAE.PARTIAL_EQUATION(e2)); eqn := BackendEquation.generateEquation(e1, e2, source, attr); solved := false; end try; end solveSimpleEquationsWork; /* public function eqnLst2Alg input list<BackendDAE.Equation> eqns; input DAE.ElementSource source; input BackendDAE.EquationAttributes attr; output BackendDAE.Equation alg; protected Integer len = 0; DAE.ElementSource source_ = DAE.emptyElementSource; //EquationAttributes attr_ := BackendDAE.EQ_ATTR_DEFAULT_UNKNOWN; DAE.Expand expand = DAE.NOT_EXPAND(); DAE.Exp e1,e2,e11,e22; list<DAE.Statement> statementLst = {}; DAE.Type tp; DAE.Algorithm alg_; DAE.ComponentRef cr; algorithm for eqn in eqns loop try BackendDAE.EQUATION(exp=e1, scalar=e2, source=source_) := eqn; else BackendDAE.SOLVED_EQUATION(cr, e2, source=source_) := eqn; e1 := Expression.crefExp(cr); end try; tp := Expression.typeof(e1); statementLst := DAE.STMT_ASSIGN(type_ = tp, exp1 = e1, exp = e2, source = source_) :: statementLst; len := len + 1; end for; alg_ := DAE.ALGORITHM_STMTS(statementLst=statementLst); alg := BackendDAE.ALGORITHM(len, alg_, source, expand, attr); end eqnLst2Alg; */ public function solve "Solves an equation consisting of a right hand side (rhs) and a left hand side (lhs), with respect to the expression given as third argument, usually a variable." input DAE.Exp inExp1 "lhs"; input DAE.Exp inExp2 "rhs"; input DAE.Exp inExp3 "DAE.CREF or 'der(DAE.CREF())'"; input Option<DAE.FunctionTree> functions = NONE() "need for solve modelica functions"; output DAE.Exp outExp; output list<DAE.Statement> outAsserts; protected list<BackendDAE.Equation> dummy1; list<DAE.ComponentRef> dummy2; Integer dummyI; algorithm /* print("Try to solve: rhs: " + ExpressionDump.dumpExpStr(inExp1,0) + " lhs: " + ExpressionDump.dumpExpStr(inExp2,0) + " with respect to: " + ExpressionDump.printExpStr(inExp3) + "\n"); */ (outExp,outAsserts,dummy1, dummy2, dummyI) := matchcontinue inExp1 case _ then solveSimple(inExp1, inExp2, inExp3, 0); case _ then solveSimple(inExp2, inExp1, inExp3, 0); case _ then solveWork(inExp1, inExp2, inExp3, functions, NONE(), 0, false, false); else equation if Flags.isSet(Flags.FAILTRACE) then Error.addInternalError("Failed to solve \"" + ExpressionDump.printExpStr(inExp1) + " = " + ExpressionDump.printExpStr(inExp2) + "\" w.r.t. \"" + ExpressionDump.printExpStr(inExp3) + "\"", sourceInfo()); end if; then fail(); end matchcontinue; (outExp,_) := ExpressionSimplify.simplify1(outExp); end solve; public function solve2 "Solves an equation with modelica function consisting of a right hand side (rhs) and a left hand side (lhs), with respect to the expression given as third argument, usually a variable. " input DAE.Exp inExp1 "lhs"; input DAE.Exp inExp2 "rhs"; input DAE.Exp inExp3 "DAE.CREF or 'der(DAE.CREF())'"; input Option<DAE.FunctionTree> functions "need for solve modelica functions"; input Option<Integer> uniqueEqIndex "offset for tmp vars"; input Boolean doInline = true; input Boolean isContinuousIntegration = false; output DAE.Exp outExp; output list<DAE.Statement> outAsserts; output list<BackendDAE.Equation> eqnForNewVars "eqn for tmp vars"; output list<DAE.ComponentRef> newVarsCrefs; protected Integer dummyI; algorithm /* print("Try to solve: rhs: " + ExpressionDump.dumpExpStr(inExp1,0) + " lhs: " + ExpressionDump.dumpExpStr(inExp2,0) + " with respect to: " + ExpressionDump.printExpStr(inExp3) + "\n"); */ (outExp,outAsserts,eqnForNewVars,newVarsCrefs,dummyI) := matchcontinue inExp1 case _ then solveSimple(inExp1, inExp2, inExp3, 0); case _ then solveSimple(inExp2, inExp1, inExp3, 0); case _ then solveWork(inExp1, inExp2, inExp3, functions, uniqueEqIndex, 0, doInline, isContinuousIntegration); else equation if Flags.isSet(Flags.FAILTRACE) then Error.addInternalError("Failed to solve \"" + ExpressionDump.printExpStr(inExp1) + " = " + ExpressionDump.printExpStr(inExp2) + "\" w.r.t. \"" + ExpressionDump.printExpStr(inExp3) + "\"", sourceInfo()); end if; then fail(); end matchcontinue; end solve2; protected function solveWork input DAE.Exp inExp1 "lhs"; input DAE.Exp inExp2 "rhs"; input DAE.Exp inExp3 "DAE.CREF or 'der(DAE.CREF())'"; input Option<DAE.FunctionTree> functions; input Option<Integer> uniqueEqIndex "offset for tmp vars"; input Integer idepth; input Boolean doInline; input Boolean isContinuousIntegration; output DAE.Exp outExp; output list<DAE.Statement> outAsserts; output list<BackendDAE.Equation> eqnForNewVars "eqn for tmp vars"; output list<DAE.ComponentRef> newVarsCrefs; output Integer depth; protected DAE.Exp e1, e2; list<BackendDAE.Equation> eqnForNewVars1, eqnForNewVars2; list<DAE.ComponentRef> newVarsCrefs1, newVarsCrefs2; algorithm (e1, e2, eqnForNewVars1, newVarsCrefs1, depth) := matchcontinue inExp1 case _ then preprocessingSolve(inExp1, inExp2, inExp3, functions, uniqueEqIndex, idepth, doInline); else equation if Flags.isSet(Flags.FAILTRACE) then Debug.trace("\n-ExpressionSolve.preprocessingSolve failed:\n"); Debug.trace(ExpressionDump.printExpStr(inExp1) + " = " + ExpressionDump.printExpStr(inExp2)); Debug.trace(" with respect to: " + ExpressionDump.printExpStr(inExp3)); end if; then (inExp1,inExp2,{},{}, idepth); end matchcontinue; (outExp, outAsserts, eqnForNewVars2, newVarsCrefs2, depth) := matchcontinue e1 case _ then solveIfExp(e1, e2, inExp3, functions, uniqueEqIndex, depth, doInline, isContinuousIntegration); case _ then solveSimple(e1, e2, inExp3, depth); case _ then solveLinearSystem(e1, e2, inExp3, functions, depth); end matchcontinue; eqnForNewVars := listAppend(eqnForNewVars1, eqnForNewVars2); newVarsCrefs := listAppend(newVarsCrefs1, newVarsCrefs2); end solveWork; public function solveLin "function: solve linear equation Solves an equation consisting of a right hand side (rhs) and a left hand side (lhs), with respect to the expression given as third argument, usually a variable." input DAE.Exp inExp1; input DAE.Exp inExp2; input DAE.Exp inExp3; output DAE.Exp outExp; output list<DAE.Statement> outAsserts; algorithm (outExp,outAsserts) := matchcontinue(inExp1, inExp2, inExp3) case(_,_,_) then solve(inExp1,inExp2,inExp3); else equation if Flags.isSet(Flags.FAILTRACE) then Debug.trace("\n-ExpressionSolve.solveLin failed:\n"); Debug.trace(ExpressionDump.printExpStr(inExp1) + " = " + ExpressionDump.printExpStr(inExp2)); Debug.trace(" with respect to: " + ExpressionDump.printExpStr(inExp3)); end if; then fail(); end matchcontinue; end solveLin; protected function solveSimple "Solves simple equations like a = f(..) der(a) = f(..) -a = f(..) -der(a) = f(..)" input DAE.Exp inExp1 "lhs"; input DAE.Exp inExp2 "rhs"; input DAE.Exp inExp3 "DAE.CREF or 'der(DAE.CREF())'"; input Integer idepth; output DAE.Exp outExp; output list<DAE.Statement> outAsserts; output list<BackendDAE.Equation> eqnForNewVars = {} "eqn for tmp vars"; output list<DAE.ComponentRef> newVarsCrefs = {}; output Integer odepth = idepth; algorithm /* print("Try to solve: rhs: " + ExpressionDump.dumpExpStr(inExp1,0) + " lhs: " + ExpressionDump.dumpExpStr(inExp2,0) + " with respect to: " + ExpressionDump.printExpStr(inExp3) + "\n"); */ (outExp,outAsserts) := match (inExp1,inExp2,inExp3) local DAE.ComponentRef cr,cr1; DAE.Type tp; DAE.Exp e1,e2,res,e11; Real r, r2; list<DAE.Statement> asserts; // special case when already solved, cr1 = rhs, otherwise division by zero when dividing with derivative case (DAE.CREF(componentRef = cr1),_,DAE.CREF(componentRef = cr)) guard ComponentReference.crefEqual(cr, cr1) and (not Expression.expHasCrefNoPreOrStart(inExp2, cr)) then (inExp2,{}); case (DAE.CALL(path = Absyn.IDENT(name = "der"),expLst = {DAE.CREF(componentRef = cr1)}),_,DAE.CALL(path = Absyn.IDENT(name = "der"),expLst = {DAE.CREF(componentRef = cr)})) guard ComponentReference.crefEqual(cr, cr1) and (not Expression.expHasDerCref(inExp2, cr)) then (inExp2,{}); // -cr = exp case (DAE.UNARY(operator = DAE.UMINUS(), exp = DAE.CREF(componentRef = cr1)),_,DAE.CREF(componentRef = cr)) guard ComponentReference.crefEqual(cr1,cr) and (not Expression.expHasCrefNoPreOrStart(inExp2,cr)) then (Expression.negate(inExp2),{}); case (DAE.UNARY(operator = DAE.UMINUS_ARR(), exp = DAE.CREF(componentRef = cr1)),_,DAE.CREF(componentRef = cr)) guard ComponentReference.crefEqual(cr1,cr) and (not Expression.expHasCrefNoPreOrStart(inExp2,cr)) // cr not in e2 then (Expression.negate(inExp2),{}); case (DAE.UNARY(operator = DAE.UMINUS(), exp = DAE.CALL(path = Absyn.IDENT(name = "der"),expLst = {DAE.CREF(componentRef = cr1)})),_,DAE.CALL(path = Absyn.IDENT(name = "der"),expLst = {DAE.CREF(componentRef = cr)})) guard ComponentReference.crefEqual(cr1,cr) and (not Expression.expHasDerCref(inExp2,cr)) // cr not in e2 then (Expression.negate(inExp2),{}); case (DAE.UNARY(operator = DAE.UMINUS_ARR(), exp = DAE.CALL(path = Absyn.IDENT(name = "der"),expLst = {DAE.CREF(componentRef = cr1)})),_,DAE.CALL(path = Absyn.IDENT(name = "der"),expLst = {DAE.CREF(componentRef = cr)})) guard ComponentReference.crefEqual(cr1,cr) and (not Expression.expHasDerCref(inExp2,cr)) then (Expression.negate(inExp2),{}); // !cr = exp case (DAE.LUNARY(operator = DAE.NOT(), exp = DAE.CREF(componentRef = cr1)),_,DAE.CREF(componentRef = cr)) guard ComponentReference.crefEqual(cr1,cr) and (not Expression.expHasCrefNoPreOrStart(inExp2,cr)) then (Expression.negate(inExp2),{}); // Integer(enumcr) = ... case (DAE.CALL(path = Absyn.IDENT(name = "Integer"),expLst={DAE.CREF(componentRef = cr1)}),_,DAE.CREF(componentRef = cr,ty=tp)) guard ComponentReference.crefEqual(cr, cr1) and (not Expression.expHasCrefNoPreorDer(inExp2,cr)) equation asserts = generateAssertType(tp,cr,inExp3,{}); then (DAE.CAST(tp,inExp2),asserts); else fail(); end match; end solveSimple; protected function generateAssertType input DAE.Type tp; input DAE.ComponentRef cr; input DAE.Exp iExp; input list<DAE.Statement> inAsserts; output list<DAE.Statement> outAsserts; algorithm outAsserts := match(tp,cr,iExp,inAsserts) local Absyn.Path path,p1,pn; list<String> names; Integer n; DAE.Exp e1,en,e,es; String s1,sn,se,estr,crstr; case (DAE.T_ENUMERATION(path=path,names=names),_,_,_) equation p1 = AbsynUtil.suffixPath(path,listHead(names)); e1 = DAE.ENUM_LITERAL(p1,1); n = listLength(names); pn = AbsynUtil.suffixPath(path,listGet(names,n)); en = DAE.ENUM_LITERAL(p1,n); s1 = AbsynUtil.pathString(p1); sn = AbsynUtil.pathString(pn); _ = ExpressionDump.printExpStr(iExp); crstr = ComponentReference.printComponentRefStr(cr); estr = "Expression for " + crstr + " out of min(" + s1 + ")/max(" + sn + ") = "; // iExp >= e1 and iExp <= en e = DAE.LBINARY(DAE.RELATION(iExp,DAE.GREATEREQ(DAE.T_INTEGER_DEFAULT),e1,-1,NONE()),DAE.AND(DAE.T_BOOL_DEFAULT), DAE.RELATION(iExp,DAE.LESSEQ(DAE.T_INTEGER_DEFAULT),en,-1,NONE())); es = Expression.makePureBuiltinCall("String", {iExp,DAE.SCONST("d")}, DAE.T_STRING_DEFAULT); es = DAE.BINARY(DAE.SCONST(estr),DAE.ADD(DAE.T_STRING_DEFAULT),es); then DAE.STMT_ASSERT(e,es,DAE.ASSERTIONLEVEL_ERROR,DAE.emptyElementSource)::inAsserts; else inAsserts; end match; end generateAssertType; public function preprocessingSolve " preprocessing for solve1, sorting and split terms , with respect to the expression given as third argument. {f(x,y), g(x,y),x} -> {h(x), k(y)} author: Vitalij Ruge " input output DAE.Exp x "lhs"; input output DAE.Exp y "rhs"; input DAE.Exp inExp3 "DAE.CREF or 'der(DAE.CREF())'"; input Option<DAE.FunctionTree> functions; input Option<Integer> uniqueEqIndex "offset for tmp vars"; input Integer idepth; input Boolean doInline; output list<BackendDAE.Equation> eqnForNewVars = {} "eqn for tmp vars"; output list<DAE.ComponentRef> newVarsCrefs = {}; output Integer depth = idepth; protected DAE.Exp res; list<DAE.Exp> lhs, rhs; list<DAE.Exp> lhsWithX, rhsWithX, lhsWithoutX, rhsWithoutX, eWithX, factorWithX, factorWithoutX; DAE.Exp lhsX, rhsX, lhsY, rhsY, N; DAE.ComponentRef cr; DAE.Boolean con, new_x, inlineFun = true; Integer iter; Integer numSimplifed = 0 ; algorithm // split and sort (lhsX, lhsY) := preprocessingSolve5(x, inExp3,true); (rhsX, rhsY) := preprocessingSolve5(y, inExp3,true); x := Expression.expSub(lhsX, rhsX); y := Expression.expSub(rhsY, lhsY); con := not Expression.isCref(x); iter := 0; if con then x := unifyFunCalls(x, inExp3); end if; while con and iter < 1000 and (not Expression.isCref(x)) loop (x, y, con) := preprocessingSolve2(x,y, inExp3); (x, y, new_x) := preprocessingSolve3(x,y, inExp3); con := con or new_x; while new_x loop (x, y, new_x) := preprocessingSolve3(x,y, inExp3); end while; if Expression.isCref(x) then break; end if; (x, y, new_x) := removeSimpleCalls(x,y, inExp3); con := con or new_x; (x, y, new_x) := preprocessingSolve4(x,y, inExp3); con := new_x or con; // TODO: use new defined function, which missing in the cpp runtime if not (stringEqual(Config.simCodeTarget(), "Cpp") )then (x, y, new_x, eqnForNewVars, newVarsCrefs, depth) := preprocessingSolveTmpVars(x, y, inExp3, uniqueEqIndex, eqnForNewVars, newVarsCrefs, depth); con := new_x or con; end if; if (not con) then if (numSimplifed < 3) then (x, con) := ExpressionSimplify.simplify(x); numSimplifed := numSimplifed + 1; end if; // Z/N = rhs -> Z = rhs*N (x,N) := Expression.makeFraction(x); if not Expression.isOne(N) then //print("\nx ");print(ExpressionDump.printExpStr(x));print("\nN ");print(ExpressionDump.printExpStr(N)); new_x := true; y := Expression.expMul(y,N); end if; con := new_x or con; end if; if con then (lhsX, lhsY) := preprocessingSolve5(x, inExp3, true); (rhsX, rhsY) := preprocessingSolve5(y, inExp3, false); x := Expression.expSub(lhsX, rhsX); y := Expression.expSub(rhsY, lhsY); elseif doInline and inlineFun then iter := iter + 50; if inlineFun then (x,con) := solveFunCalls(x, inExp3, functions); inlineFun := false; if con then numSimplifed := 0; end if; end if; end if; iter := iter + 1; //print("\nx ");print(ExpressionDump.printExpStr(x));print("\ny ");print(ExpressionDump.printExpStr(y)); end while; y := ExpressionSimplify.simplify1(y); /* if not Expression.expEqual(inExp1,x) then print("\nIn: ");print(ExpressionDump.printExpStr(inExp1));print(" = ");print(ExpressionDump.printExpStr(inExp2)); print("\nOut: ");print(ExpressionDump.printExpStr(x));print(" = ");print(ExpressionDump.printExpStr(y)); print("\t w.r.t ");print(ExpressionDump.printExpStr(inExp3)); end if; */ end preprocessingSolve; protected function preprocessingSolve2 " helprer function for preprocessingSolve e.g. x/(x+c1) = -c2 --> x + (x+c1)*c2 = 0 author: Vitalij Ruge " input DAE.Exp inExp1 "lhs"; input DAE.Exp inExp2 "rhs"; input DAE.Exp inExp3 "DAE.CREF or 'der(DAE.CREF())'"; output DAE.Exp olhs; output DAE.Exp orhs; output Boolean con "continue"; algorithm (olhs, orhs, con) := match (inExp1) local DAE.Exp e,a, b, fb, fa, ga, lhs; DAE.Type tp; DAE.Operator op; list<DAE.Exp> eWithX, factorWithX, factorWithoutX; DAE.Exp pWithX, pWithoutX; // -f(a) = b => f(a) = -b case DAE.UNARY(op as DAE.UMINUS(), fa) guard expHasCref(fa, inExp3) and not expHasCref(inExp2, inExp3) equation b = Expression.negate(inExp2); then (fa, b, true); case DAE.UNARY(op as DAE.UMINUS_ARR(), fa) guard expHasCref(fa, inExp3) and not expHasCref(inExp2, inExp3) equation b = Expression.negate(inExp2); then (fa, b, true); // b/f(a) = rhs => f(a) = b/rhs solve for a case DAE.BINARY(b,DAE.DIV(_),fa) guard expHasCref(fa, inExp3) and (not expHasCref(b, inExp3)) and (not expHasCref(inExp2, inExp3)) equation e = Expression.makeDiv(b, inExp2); then(fa, e, true); // b*f(a) = rhs => f(a) = rhs/b solve for a case DAE.BINARY(b, DAE.MUL(_), fa) guard expHasCref(fa, inExp3) and (not expHasCref(b, inExp3)) and (not expHasCref(inExp2, inExp3)) equation eWithX = Expression.expandFactors(inExp1); (factorWithX, factorWithoutX) = List.split1OnTrue(eWithX, expHasCref, inExp3); pWithX = makeProductLstSort(factorWithX); pWithoutX = makeProductLstSort(factorWithoutX); e = Expression.makeDiv(inExp2, pWithoutX); then(pWithX, e, true); // b*a = rhs => a = rhs/b solve for a case DAE.BINARY(b, DAE.MUL(_), fa) guard expHasCref(fa, inExp3) and (not expHasCref(b, inExp3)) and (not expHasCref(inExp2, inExp3)) equation e = Expression.makeDiv(inExp2, b); then(fa, e, true); // a*b = rhs => a = rhs/b solve for a case DAE.BINARY(fa, DAE.MUL(_), b) guard expHasCref(fa, inExp3) and (not expHasCref(b, inExp3)) and (not expHasCref(inExp2, inExp3)) equation e = Expression.makeDiv(inExp2, b); then(fa, e, true); // f(a)/b = rhs => f(a) = rhs*b solve for a case DAE.BINARY(fa, DAE.DIV(_), b) guard expHasCref(fa, inExp3) and (not expHasCref(b, inExp3)) and (not expHasCref(inExp2, inExp3)) equation e = Expression.expMul(inExp2, b); then (fa, e, true); // g(a)/f(a) = rhs => rhs*f(a) - g(a) = 0 solve for a case DAE.BINARY(ga, DAE.DIV(tp), fa) guard expHasCref(fa, inExp3) and expHasCref(ga, inExp3) and (not expHasCref(inExp2, inExp3)) equation e = Expression.expMul(inExp2, fa); lhs = Expression.expSub(e, ga); e = Expression.makeConstZero(tp); then(lhs, e, true); else (inExp1, inExp2, false); end match; end preprocessingSolve2; protected function preprocessingSolve3 " helprer function for preprocessingSolve (r1)^f(a) = r2 => f(a) = ln(r2)/ln(r1) f(a)^b = 0 => f(a) = 0 f(a)^n = c => f(a) = c^(1/n) abs(x) = 0 author: Vitalij Ruge " input DAE.Exp inExp1 "lhs"; input DAE.Exp inExp2 "rhs"; input DAE.Exp inExp3 "DAE.CREF or 'der(DAE.CREF())'"; output DAE.Exp olhs; output DAE.Exp orhs; output Boolean con "continue"; algorithm (olhs, orhs, con) := match(inExp1, inExp2) local Real r, r1, r2; DAE.Exp e1, e2, res; // (r1)^f(a) = r2 => f(a) = ln(r2)/ln(r1) case (DAE.BINARY(e1 as DAE.RCONST(r1),DAE.POW(_),e2), DAE.RCONST(r2)) guard r2 > 0.0 and r1 > 0.0 and (not Expression.isConstOne(e1)) and expHasCref(e2, inExp3) equation r = log(r2) / log(r1); res = DAE.RCONST(r); then (e2, res, true); // f(a)^b = 0 => f(a) = 0 case (DAE.BINARY(e1,DAE.POW(_),e2), DAE.RCONST(real = 0.0)) guard expHasCref(e1, inExp3) and (not expHasCref(e2, inExp3)) then (e1, inExp2, true); // f(a)^n = c => f(a) = c^(1/n) // where n is odd case (DAE.BINARY(e1,DAE.POW(_),e2 as DAE.RCONST(r)), _) guard (not expHasCref(inExp2, inExp3)) and expHasCref(e1, inExp3) and (1.0 == realMod(r,2.0)) equation res = Expression.makeDiv(DAE.RCONST(1.0),e2); res = Expression.expPow(inExp2,res); then (e1, res, true); // sqrt(f(a)) = f(a)^n = c => f(a) = c^(1/n) case (DAE.BINARY(e1,DAE.POW(_),DAE.RCONST(0.5)), _) guard not expHasCref(inExp2, inExp3) and expHasCref(e1, inExp3) equation res = Expression.expPow(inExp2,DAE.RCONST(2.0)); then (e1, res, true); // abs(x) = 0 case (DAE.CALL(path = Absyn.IDENT(name = "abs"),expLst = {e1}), DAE.RCONST(0.0)) then (e1,inExp2,true); // sign(x) = 0 case (DAE.CALL(path = Absyn.IDENT(name = "sign"),expLst = {e1}), DAE.RCONST(0.0)) then (e1,inExp2,true); else (inExp1, inExp2, false); end match; end preprocessingSolve3; protected function preprocessingSolve4 " helprer function for preprocessingSolve e.g. sqrt(f(x)) - sqrt(g(x))) = 0 = f(x) - g(x) exp(f(x)) - exp(g(x))) = 0 = f(x) - g(x) author: Vitalij Ruge " input DAE.Exp inExp1; input DAE.Exp inExp2; input DAE.Exp inExp3 "DAE.CREF or 'der(DAE.CREF())'"; output DAE.Exp oExp1; output DAE.Exp oExp2; output Boolean newX; algorithm (oExp1, oExp2, newX) := match(inExp1, inExp2, inExp3) local String s1,s2; DAE.Operator op; DAE.Exp e1,e2,e3,e4, e, e_1, e_2; DAE.Type tp; // exp(f(x)) - exp(g(x)) = 0 case(DAE.BINARY(DAE.CALL(path = Absyn.IDENT("exp"), expLst={e1}), DAE.SUB(_), DAE.CALL(path = Absyn.IDENT("exp"), expLst={e2})),DAE.RCONST(0.0),_) then (e1, e2, true); // log(f(x)) - log(g(x)) = 0 case(DAE.BINARY(DAE.CALL(path = Absyn.IDENT("log"), expLst={e1}), DAE.SUB(_), DAE.CALL(path = Absyn.IDENT("log"), expLst={e2})),DAE.RCONST(0.0),_) then (e1, e2, true); // log10(f(x)) - log10(g(x)) = 0 case(DAE.BINARY(DAE.CALL(path = Absyn.IDENT("log10"), expLst={e1}), DAE.SUB(_), DAE.CALL(path = Absyn.IDENT("log10"), expLst={e2})),DAE.RCONST(0.0),_) then (e1, e2, true); // sinh(f(x)) - sinh(g(x)) = 0 case(DAE.BINARY(DAE.CALL(path = Absyn.IDENT("sinh"), expLst={e1}), DAE.SUB(_), DAE.CALL(path = Absyn.IDENT("sinh"), expLst={e2})),DAE.RCONST(0.0),_) then (e1, e2, true); // tanh(f(x)) - tanh(g(x)) = 0 case(DAE.BINARY(DAE.CALL(path = Absyn.IDENT("tanh"), expLst={e1}), DAE.SUB(_), DAE.CALL(path = Absyn.IDENT("tanh"), expLst={e2})),DAE.RCONST(0.0),_) then (e1, e2, true); // sqrt(f(x)) - sqrt(g(x)) = 0 case(DAE.BINARY(DAE.CALL(path = Absyn.IDENT("sqrt"), expLst={e1}), DAE.SUB(_), DAE.CALL(path = Absyn.IDENT("sqrt"), expLst={e2})),DAE.RCONST(0.0),_) then (e1, e2, true); // sinh(f(x)) - cosh(g(x)) = 0 case(DAE.BINARY(DAE.CALL(path = Absyn.IDENT("sinh"), expLst={e1}), DAE.SUB(_), DAE.CALL(path = Absyn.IDENT("cosh"), expLst={e2})),DAE.RCONST(0.0),_) guard Expression.expEqual(e1,e2) then (e1, inExp2, true); case(DAE.BINARY(DAE.CALL(path = Absyn.IDENT("cosh"), expLst={e1}), DAE.SUB(_), DAE.CALL(path = Absyn.IDENT("sinh"), expLst={e2})),DAE.RCONST(0.0),_) guard Expression.expEqual(e1,e2) then (e1, inExp2, true); // y*sinh(x) - z*cosh(x) = 0 case(DAE.BINARY(DAE.BINARY(e3,DAE.MUL(),DAE.CALL(path = Absyn.IDENT("sinh"), expLst={e1})), DAE.SUB(tp), DAE.BINARY(e4,DAE.MUL(),DAE.CALL(path = Absyn.IDENT("cosh"), expLst={e2}))),DAE.RCONST(0.0),_) guard Expression.expEqual(e1,e2) equation e = Expression.makePureBuiltinCall("tanh",{e1},tp); then (Expression.expMul(e3,e), e4, true); case(DAE.BINARY(DAE.BINARY(e4,DAE.MUL(),DAE.CALL(path = Absyn.IDENT("cosh"), expLst={e2})), DAE.SUB(tp), DAE.BINARY(e3,DAE.MUL(),DAE.CALL(path = Absyn.IDENT("sinh"), expLst={e1}))),DAE.RCONST(0.0),_) guard Expression.expEqual(e1,e2) equation e = Expression.makePureBuiltinCall("tanh",{e1},tp); then (Expression.expMul(e3,e), e4, true); // sqrt(x) - x = 0 -> x = x^2 case(DAE.BINARY(DAE.CALL(path = Absyn.IDENT("sqrt"), expLst={e1}), DAE.SUB(_),e2), DAE.RCONST(0.0),_) then (e1, Expression.expPow(e2, DAE.RCONST(2.0)), true); case(DAE.BINARY(e2, DAE.SUB(_),DAE.CALL(path = Absyn.IDENT("sqrt"), expLst={e1})), DAE.RCONST(0.0),_) then (e1, Expression.expPow(e2, DAE.RCONST(2.0)), true); // f(x)^n - g(x)^n = 0 -> (f(x)/g(x))^n = 1 case(DAE.BINARY(DAE.BINARY(e1, DAE.POW(), e2), DAE.SUB(tp), DAE.BINARY(e3, DAE.POW(), e4)), DAE.RCONST(0.0),_) guard Expression.expEqual(e2,e4) and expHasCref(e1,inExp3) and expHasCref(e3,inExp3) equation e = Expression.expPow(Expression.makeDiv(e1,e3),e2); (e_1, e_2, _) = preprocessingSolve3(e, Expression.makeConstOne(tp), inExp3); then (e_1, e_2, true); else (inExp1, inExp2, false); end match; end preprocessingSolve4; protected function expAddX " helprer function for preprocessingSolve if(y,g(x),h(x)) + x => if(y, g(x) + x, h(x) + x) a*f(x) + b*f(x) = (a+b)*f(x) author: Vitalij Ruge " input DAE.Exp inExp1 "lhs"; input DAE.Exp inExp2 "rhs"; input DAE.Exp inExp3 "DAE.CREF or 'der(DAE.CREF())'"; output DAE.Exp ores; algorithm ores := matchcontinue(inExp1, inExp2, inExp3) local DAE.Exp e, e1, e2, e3, e4, res; case(DAE.IFEXP(e,e1,e2), _,_) guard expHasCref(e1, inExp3) and expHasCref(e2, inExp3) and (not expHasCref(e, inExp3)) equation e3 = expAddX(inExp2, e1, inExp3); e4 = expAddX(inExp2, e2, inExp3); res = DAE.IFEXP(e, e3, e4); then res; case(_, DAE.IFEXP(e,e1,e2), _) guard expHasCref(e1, inExp3) and expHasCref(e2, inExp3) and (not expHasCref(e, inExp3)) equation e3 = expAddX(inExp1, e1, inExp3); e4 = expAddX(inExp1, e2, inExp3); res = DAE.IFEXP(e, e3, e4); then res; else equation res = expAddX2(inExp1, inExp2, inExp3); then res; end matchcontinue; end expAddX; protected function expAddX2 " helprer function for preprocessingSolve a*f(x) + b*f(x) = (a+b)*f(x) author: Vitalij Ruge " input DAE.Exp inExp1 "lhs"; input DAE.Exp inExp2 "rhs"; input DAE.Exp inExp3 "DAE.CREF or 'der(DAE.CREF())'"; output DAE.Exp ores; protected list<DAE.Exp> f1, f2; DAE.Exp e0,e1,e2; DAE.Boolean neg; list<DAE.Exp> factorWithX1, factorWithoutX1, factorWithX2, factorWithoutX2; DAE.Exp pWithX1, pWithoutX1, pWithX2, pWithoutX2; algorithm (e0, e1, neg) := match(inExp1) local DAE.Exp ee1, ee2; case(DAE.BINARY(ee1,DAE.ADD(),ee2)) then(ee1, ee2, false); case(DAE.BINARY(ee1,DAE.SUB(),ee2)) then(ee1, ee2, true); else then(DAE.RCONST(0.0), inExp1, false); end match; f1 := Expression.expandFactors(e1); (factorWithX1, factorWithoutX1) := List.split1OnTrue(f1, expHasCref, inExp3); pWithX1 := makeProductLstSort(factorWithX1); pWithoutX1 := makeProductLstSort(factorWithoutX1); f2 := Expression.expandFactors(inExp2); (factorWithX2, factorWithoutX2) := List.split1OnTrue(f2, expHasCref, inExp3); (pWithX2,_) := ExpressionSimplify.simplify1(makeProductLstSort(factorWithX2)); pWithoutX2 := makeProductLstSort(factorWithoutX2); //print("\nf1 =");print(ExpressionDump.printExpListStr(f1)); //print("\nf2 =");print(ExpressionDump.printExpListStr(f2)); if Expression.expEqual(pWithX2,pWithX1) then // e0 + a*x + b*x -> e0 + (a+b)*x if not neg then ores := Expression.expAdd(pWithoutX1, pWithoutX2); else // e0 - a*x + b*x -> e0 + (b-a)*x ores := Expression.expSub(pWithoutX2, pWithoutX1); end if; ores := Expression.expMul(ores, pWithX2); elseif Expression.expEqual(pWithX2, Expression.negate(pWithX1)) then // e0 + a*(-x) + b*x -> e0 + (b-a)*x if not neg then ores := Expression.expSub(pWithoutX2, pWithoutX1); else // e0 - a*(-x) + b*x -> e0 + (b-a)*x ores := Expression.expAdd(pWithoutX1, pWithoutX2); end if; ores := Expression.expMul(ores, pWithX2); else e1 := Expression.expMul(pWithoutX1, pWithX1); e2 := Expression.expMul(pWithoutX2, pWithX2); ores := Expression.expAdd(e1,e2); end if; ores := Expression.expAdd(e0,ores); end expAddX2; public function collectX input DAE.Exp inExp1 "lhs"; input DAE.Exp inExp3 "DAE.CREF"; input DAE.Boolean expand = true; output DAE.Exp outLhs; output DAE.Exp outRhs; algorithm (outLhs, outRhs) := preprocessingSolve5(inExp1, inExp3, expand); end collectX; protected function preprocessingSolve5 " helprer function for preprocessingSolve split and sort with respect to x where x = cref f(x,y) = {h(y)*g(x,y), k(y)} author: Vitalij Ruge " input DAE.Exp inExp1 "lhs"; input DAE.Exp inExp3 "DAE.CREF or 'der(DAE.CREF())'"; input DAE.Boolean expand; output DAE.Exp outLhs; output DAE.Exp outRhs; protected list<DAE.Exp> lhs, rhs; DAE.Exp tmpLhs, e1; Boolean b; DAE.ComponentRef cr; algorithm if expHasCref(inExp1, inExp3) then if expand then (cr, b) := Expression.expOrDerCref(inExp3); if b then (lhs, rhs) := Expression.allTermsForCref(inExp1, cr, Expression.expHasDerCref); else (lhs, rhs) := Expression.allTermsForCref(inExp1, cr, Expression.expHasCrefNoPreOrStart); end if; else (lhs, rhs) := List.split1OnTrue(Expression.terms(inExp1), expHasCref, inExp3); end if; // sort // a*f(x)*b -> c*f(x) outLhs := DAE.RCONST(0.0); tmpLhs := DAE.RCONST(0.0); for e in lhs loop if Expression.isNegativeUnary(e) then DAE.UNARY(exp = e1) := e; tmpLhs := expAddX(e1, tmpLhs, inExp3); // special add else outLhs := expAddX(e, outLhs, inExp3); // special add end if; end for; outLhs := expAddX(outLhs, Expression.negate(tmpLhs), inExp3); //rhs outRhs := Expression.makeSum1(rhs); (outRhs,_) := ExpressionSimplify.simplify1(outRhs); (outLhs,_) := ExpressionSimplify.simplify1(outLhs); else outLhs := DAE.RCONST(0.0); outRhs := inExp1; end if; end preprocessingSolve5; protected function unifyFunCalls " e.g. semiLinear() -> if author: Vitalij Ruge " input DAE.Exp inExp1 "lhs"; input DAE.Exp inExp3 "DAE.CREF or 'der(DAE.CREF())'"; output DAE.Exp oExp; output Boolean newX; algorithm (oExp,_) := Expression.traverseExpTopDown(inExp1, unifyFunCallsWork, (inExp3)); newX := Expression.expEqual(oExp, inExp1); end unifyFunCalls; protected function unifyFunCallsWork input DAE.Exp inExp; input DAE.Exp iT; output DAE.Exp outExp; output Boolean cont; output DAE.Exp oT; algorithm (outExp,cont,oT) := match(inExp, iT) local DAE.Exp e, e1,e2,e3, X; DAE.Type tp; /* case(DAE.CALL(path = Absyn.IDENT(name = "smooth"), expLst = {_, e}),X) guard expHasCref(e, X) then (e, true, iT); case(DAE.CALL(path = Absyn.IDENT(name = "noEvent"), expLst = {e}),X) guard expHasCref(e, X) then (e, true, iT); */ case(DAE.CALL(path = Absyn.IDENT(name = "semiLinear"),expLst = {e1, e2, e3}),_) guard not Expression.isZero(e1) equation tp = Expression.typeof(e1); e = DAE.IFEXP(DAE.RELATION(e1,DAE.GREATEREQ(tp), Expression.makeConstZero(tp),-1,NONE()),Expression.expMul(e1,e2), Expression.expMul(e1,e3)); then (e,true, iT); // df_der(x) = (x-old(x))/dt case(DAE.CALL(path = Absyn.IDENT(name = "$_DF$DER"),expLst = {e1}),X) guard expHasCref(e1, X) equation tp = Expression.typeof(e1); e2 = Expression.crefExp(ComponentReference.makeCrefIdent(BackendDAE.symSolverDT, DAE.T_REAL_DEFAULT, {})); e3 = Expression.makePureBuiltinCall("pre", {e1}, tp); e3 = Expression.expSub(e1,e3); e = Expression.expDiv(e3,e2); then (e,true, iT); else (inExp, true, iT); end match; end unifyFunCallsWork; protected function solveFunCalls " - inline modelica functions - TODO: support annotation inverse author: Vitalij Ruge " input DAE.Exp inExp1 "lhs"; input DAE.Exp inExp3 "DAE.CREF or 'der(DAE.CREF())'"; input Option<DAE.FunctionTree> functions; output DAE.Exp x; output Boolean con; algorithm (x,con) := matchcontinue(functions, inExp1) local DAE.Exp funX; Boolean b; case(_,_) equation (funX,_) = Expression.traverseExpTopDown(inExp1, inlineCallX, (inExp3, functions)); b = not Expression.expEqual(funX, inExp1); then (funX, b); else (inExp1, false); end matchcontinue; end solveFunCalls; protected function removeSimpleCalls " helprer function for preprocessingSolve solve e.g. exp(x) = y log(x) = y " input DAE.Exp inExp1 "lhs"; input DAE.Exp inExp2 "rhs"; input DAE.Exp inExp3 "DAE.CREF or 'der(DAE.CREF())'"; output DAE.Exp outLhs; output DAE.Exp outRhs; output Boolean con "continue"; algorithm (outLhs, outRhs, con) := match(inExp1, inExp2, inExp3) case(DAE.CALL(),_,_) then removeSimpleCalls2(inExp1, inExp2, inExp3); else (inExp1, inExp2, false); end match; end removeSimpleCalls; protected function removeSimpleCalls2 " helprer function for preprocessingSolve solve e.g. exp(x) = y log(x) = y " input DAE.Exp inExp1 "lhs"; input DAE.Exp inExp2 "rhs"; input DAE.Exp inExp3 "DAE.CREF or 'der(DAE.CREF())'"; output DAE.Exp outLhs; output DAE.Exp outRhs; output Boolean con "continue"; algorithm (outLhs, outRhs, con) := matchcontinue (inExp1,inExp2,inExp3) local DAE.Exp e1, e2, e3; //tanh(x) =y -> x = 1/2 * ln((1+y)/(1-y)) case (DAE.CALL(path = Absyn.IDENT(name = "tanh"),expLst = {e1}),_,_) equation true = expHasCref(e1, inExp3); false = expHasCref(inExp2, inExp3); true = not(Expression.isCref(inExp2) or Expression.isConst(inExp2)); e2 = Expression.expAdd(DAE.RCONST(1.0), inExp2); e3 = Expression.expSub(DAE.RCONST(1.0), inExp2); e2 = Expression.makeDiv(e2, e3); e2 = Expression.makePureBuiltinCall("log",{e2},DAE.T_REAL_DEFAULT); e2 = Expression.expMul(DAE.RCONST(0.5), e2); then (e1, e2, true); // sinh(x) -> ln(y+(sqrt(1+y^2)) case (DAE.CALL(path = Absyn.IDENT(name = "sinh"),expLst = {e1}),_,_) equation true = expHasCref(e1, inExp3); false = expHasCref(inExp2, inExp3); true = not(Expression.isCref(inExp2) or Expression.isConst(inExp2)); e2 = Expression.expPow(inExp2, DAE.RCONST(2.0)); e3 = Expression.expAdd(e2,DAE.RCONST(1.0)); e2 = Expression.makePureBuiltinCall("sqrt",{e3},DAE.T_REAL_DEFAULT); e3 = Expression.expAdd(inExp2, e2); e2 = Expression.makePureBuiltinCall("log",{e3},DAE.T_REAL_DEFAULT); then (e1,e2,true); // log10(f(a)) = g(b) => f(a) = 10^(g(b)) case (DAE.CALL(path = Absyn.IDENT(name = "log10"),expLst = {e1}),_,_) equation true = expHasCref(e1, inExp3); false = expHasCref(inExp2, inExp3); e2 = Expression.expPow(DAE.RCONST(10.0), inExp2); then (e1, e2, true); // log(f(a)) = g(b) => f(a) = exp(g(b)) case (DAE.CALL(path = Absyn.IDENT(name = "log"),expLst = {e1}),_,_) equation true = expHasCref(e1, inExp3); false = expHasCref(inExp2, inExp3); e2 = Expression.makePureBuiltinCall("exp",{inExp2},DAE.T_REAL_DEFAULT); then (e1, e2, true); // exp(f(a)) = g(b) => f(a) = log(g(b)) case (DAE.CALL(path = Absyn.IDENT(name = "exp"),expLst = {e1}),_,_) equation true = expHasCref(e1, inExp3); false = expHasCref(inExp2, inExp3); e2 = Expression.makePureBuiltinCall("log",{inExp2},DAE.T_REAL_DEFAULT); then (e1, e2, true); // sqrt(f(a)) = g(b) => f(a) = (g(b))^2 case (DAE.CALL(path = Absyn.IDENT(name = "sqrt"),expLst = {e1}),_,_) equation true = expHasCref(e1, inExp3); false = expHasCref(inExp2, inExp3); e2 = DAE.RCONST(2.0); e2 = Expression.expPow(inExp2,e2); then (e1, e2, true); // semiLinear(0, a, b) = 0 => a = b // rule 1 case (DAE.CALL(path = Absyn.IDENT(name = "semiLinear"),expLst = {DAE.RCONST(real = 0.0), e1, e2}),DAE.RCONST(real = 0.0),_) then (e1,e2,true); // smooth(i,f(a)) = rhs -> f(a) = rhs //case (DAE.CALL(path = Absyn.IDENT(name = "smooth"),expLst = {_, e2}),_,_) // then (e2, inExp2, true); // noEvent(f(a)) = rhs -> f(a) = rhs //case (DAE.CALL(path = Absyn.IDENT(name = "noEvent"),expLst = {e2}),_,_) // then (e2, inExp2, true); else (inExp1, inExp2, false); end matchcontinue; end removeSimpleCalls2; protected function inlineCallX " inline function call if depends on X where X is cref or der(cref) DAE.Exp inExp2 DAE.CREF or 'der(DAE.CREF())' author: vitalij " input DAE.Exp inExp; input tuple<DAE.Exp, Option<DAE.FunctionTree>> iT; output DAE.Exp outExp; output Boolean cont; output tuple<DAE.Exp, Option<DAE.FunctionTree>> oT; algorithm (outExp,cont,oT) := matchcontinue(inExp, iT) local DAE.Exp e, X; DAE.ComponentRef cr; Option<DAE.FunctionTree> functions; Boolean b; case(DAE.CALL(),(X, functions)) guard expHasCref(inExp, X) equation //print("\nfIn: ");print(ExpressionDump.printExpStr(inExp)); (e,_,b) = Inline.forceInlineExp(inExp,(functions,{DAE.NORM_INLINE(),DAE.DEFAULT_INLINE()}),DAE.emptyElementSource); //print("\nfOut: ");print(ExpressionDump.printExpStr(e)); then (e, not b, iT); else (inExp, true, iT); end matchcontinue; end inlineCallX; protected function preprocessingSolveTmpVars " helper function for solveWork creat tmp vars if needed! e.g. for solve abs() author: Vitalij Ruge " input DAE.Exp inExp1; input DAE.Exp inExp2; input DAE.Exp inExp3; input Option<Integer> uniqueEqIndex "offset for tmp vars"; input list<BackendDAE.Equation> ieqnForNewVars; input list<DAE.ComponentRef> inewVarsCrefs; input Integer idepth; output DAE.Exp x; output DAE.Exp y; output Boolean new_x; output list<BackendDAE.Equation> eqnForNewVars "eqn for tmp vars"; output list<DAE.ComponentRef> newVarsCrefs; output Integer odepth; algorithm (x, y, new_x, eqnForNewVars, newVarsCrefs, odepth) := match(uniqueEqIndex) local Integer i; case(SOME(i)) then preprocessingSolveTmpVarsWork(inExp1, inExp2, inExp3, i, ieqnForNewVars, inewVarsCrefs, idepth); else (inExp1, inExp2, false, ieqnForNewVars, inewVarsCrefs, idepth); end match; end preprocessingSolveTmpVars; protected function preprocessingSolveTmpVarsWork " helper function for solveWork creat tmp vars if needed! e.g. for solve abs " input DAE.Exp inExp1; input DAE.Exp inExp2; input DAE.Exp inExp3; input Integer uniqueEqIndex "offset for tmp vars"; input list<BackendDAE.Equation> ieqnForNewVars; input list<DAE.ComponentRef> inewVarsCrefs; input Integer idepth "depth of tmp var"; output DAE.Exp x; output DAE.Exp y; output Boolean new_x; output list<BackendDAE.Equation> eqnForNewVars "eqn for tmp vars"; output list<DAE.ComponentRef> newVarsCrefs; output Integer odepth; algorithm (x, y, new_x, eqnForNewVars, newVarsCrefs, odepth) := matchcontinue(inExp1, inExp2) local DAE.Exp e1, e_1, e, e2, exP, lhs, e3, e4, e5, e6, rhs, a1,x1, a2,x2, ee1, ee2; DAE.Exp acosy, k1, k2; tuple<DAE.Exp, DAE.Exp> a, c; list<DAE.Exp> z1, z2, z3, z4; DAE.ComponentRef cr; DAE.Type tp; BackendDAE.Equation eqn; list<BackendDAE.Equation> eqnForNewVars_; list<DAE.ComponentRef> newVarsCrefs_; Boolean b, b1, b2, b3; DAE.Operator op1, op2; //tanh(x) =y -> x = 1/2 * ln((1+y)/(1-y)) case (DAE.CALL(path = Absyn.IDENT(name = "tanh"),expLst = {e1}),_) equation true = expHasCref(e1, inExp3); false = expHasCref(inExp2, inExp3); tp = Expression.typeof(inExp2); (e, eqnForNewVars_, newVarsCrefs_) = makeTmpEqnAndCrefFromExp(inExp2, tp, "Y$TANH", uniqueEqIndex, idepth, ieqnForNewVars, inewVarsCrefs,false); e2 = Expression.expAdd(DAE.RCONST(1.0), e); e3 = Expression.expSub(DAE.RCONST(1.0), e); e2 = Expression.makeDiv(e2, e3); e2 = Expression.makePureBuiltinCall("log",{e2},DAE.T_REAL_DEFAULT); e2 = Expression.expMul(DAE.RCONST(0.5), e2); then (e1, e2, true,eqnForNewVars_,newVarsCrefs_,idepth + 1); // sinh(x) -> ln(y+(sqrt(1+y^2)) case (DAE.CALL(path = Absyn.IDENT(name = "sinh"),expLst = {e1}),_) equation true = expHasCref(e1, inExp3); false = expHasCref(inExp2, inExp3); tp = Expression.typeof(inExp2); (e, eqnForNewVars_, newVarsCrefs_) = makeTmpEqnAndCrefFromExp(inExp2, tp, "Y$SINH", uniqueEqIndex, idepth, ieqnForNewVars, inewVarsCrefs,false); e2 = Expression.expPow(e, DAE.RCONST(2.0)); e3 = Expression.expAdd(e2,DAE.RCONST(1.0)); e2 = Expression.makePureBuiltinCall("sqrt",{e3},DAE.T_REAL_DEFAULT); e3 = Expression.expAdd(e, e2); e2 = Expression.makePureBuiltinCall("log",{e3},DAE.T_REAL_DEFAULT); then (e1,e2,true,eqnForNewVars_,newVarsCrefs_,idepth + 1); // cosh(x) -> ln(y +- (sqrt(y^2 - 1)) case (DAE.CALL(path = Absyn.IDENT(name = "cosh"),expLst = {e1}),_) equation true = expHasCref(e1, inExp3); false = expHasCref(inExp2, inExp3); tp = Expression.typeof(inExp2); (rhs, eqnForNewVars_, newVarsCrefs_) = makeTmpEqnAndCrefFromExp(inExp2, tp, "Y$SINH", uniqueEqIndex, idepth, ieqnForNewVars, inewVarsCrefs,false); tp = Expression.typeof(e1); exP = makeInitialGuess(tp,inExp3,e1); (exP, eqnForNewVars_, newVarsCrefs_) = makeTmpEqnAndCrefFromExp(exP, tp, "SIGN$SINH", uniqueEqIndex, idepth, eqnForNewVars_, newVarsCrefs_,false); e_1 = Expression.makePureBuiltinCall("$_signNoNull", {exP}, tp); e2 = Expression.expPow(rhs, DAE.RCONST(2.0)); e3 = Expression.expSub(e2, DAE.RCONST(1.0)); e2 = Expression.makePureBuiltinCall("sqrt",{e3},DAE.T_REAL_DEFAULT); e3 = Expression.expAdd(rhs, Expression.expMul(e_1,e2)); e2 = Expression.makePureBuiltinCall("log",{e3},DAE.T_REAL_DEFAULT); then (e1,e2,true,eqnForNewVars_,newVarsCrefs_,idepth + 1); // cos(y) = x -> y = acos(x) + 2*pi*k case (DAE.CALL(path = Absyn.IDENT(name = "cos"),expLst = {e1}),_) equation true = expHasCref(e1, inExp3); false = expHasCref(inExp2, inExp3); tp = Expression.typeof(inExp2); (rhs, eqnForNewVars_, newVarsCrefs_) = makeTmpEqnAndCrefFromExp(inExp2, tp, "Y$COS", uniqueEqIndex, idepth, ieqnForNewVars, inewVarsCrefs,false); acosy = Expression.makePureBuiltinCall("acos", {rhs}, tp); (acosy, eqnForNewVars_, newVarsCrefs_) = makeTmpEqnAndCrefFromExp(acosy, tp, "ACOS$COS", uniqueEqIndex, idepth, eqnForNewVars_, newVarsCrefs_,false); exP = makeInitialGuess(tp,inExp3,e1); (exP, eqnForNewVars_, newVarsCrefs_) = makeTmpEqnAndCrefFromExp(exP, tp, "PREX$COS", uniqueEqIndex, idepth, eqnForNewVars_, newVarsCrefs_, false); k1 = helpInvCos(acosy, exP, tp, true); k2 = helpInvCos(acosy, exP, tp, false); (k1, eqnForNewVars_, newVarsCrefs_) = makeTmpEqnAndCrefFromExp(k1, tp, "k1$COS", uniqueEqIndex, idepth, eqnForNewVars_, newVarsCrefs_, false); (k2, eqnForNewVars_, newVarsCrefs_) = makeTmpEqnAndCrefFromExp(k2, tp, "k2$COS", uniqueEqIndex, idepth, eqnForNewVars_, newVarsCrefs_, false); x1 = helpInvCos2(k1, acosy, tp ,true); x2 = helpInvCos2(k2, acosy, tp ,false); (x1, eqnForNewVars_, newVarsCrefs_) = makeTmpEqnAndCrefFromExp(x1, tp, "x1$COS", uniqueEqIndex, idepth, eqnForNewVars_, newVarsCrefs_, false); (x2, eqnForNewVars_, newVarsCrefs_) = makeTmpEqnAndCrefFromExp(x2, tp, "x2$COS", uniqueEqIndex, idepth, eqnForNewVars_, newVarsCrefs_, false); rhs = helpInvCos3(x1,x2,exP,tp); then(e1, rhs, true, eqnForNewVars_, newVarsCrefs_, idepth + 1); // sin(y) = x -> y = asin(x) + 2*pi*k // = -asin(x) + pi*(2*k+1) case (DAE.CALL(path = Absyn.IDENT(name = "sin"),expLst = {e1}),_) equation true = expHasCref(e1, inExp3); false = expHasCref(inExp2, inExp3); tp = Expression.typeof(inExp2); (rhs, eqnForNewVars_, newVarsCrefs_) = makeTmpEqnAndCrefFromExp(inExp2, tp, "Y$SIN", uniqueEqIndex, idepth, ieqnForNewVars, inewVarsCrefs,false); acosy = Expression.makePureBuiltinCall("asin", {rhs}, tp); (acosy, eqnForNewVars_, newVarsCrefs_) = makeTmpEqnAndCrefFromExp(acosy, tp, "ASIN$SIN", uniqueEqIndex, idepth, eqnForNewVars_, newVarsCrefs_,false); exP = makeInitialGuess(tp,inExp3,e1); (exP, eqnForNewVars_, newVarsCrefs_) = makeTmpEqnAndCrefFromExp(exP, tp, "PREX$SIN", uniqueEqIndex, idepth, eqnForNewVars_, newVarsCrefs_, false); k1 = helpInvSin(acosy, e1, tp, true); k2 = helpInvSin(acosy, e1, tp, false); (k1, eqnForNewVars_, newVarsCrefs_) = makeTmpEqnAndCrefFromExp(k1, tp, "k1$SIN", uniqueEqIndex, idepth, eqnForNewVars_, newVarsCrefs_, false); (k2, eqnForNewVars_, newVarsCrefs_) = makeTmpEqnAndCrefFromExp(k2, tp, "k2$SIN", uniqueEqIndex, idepth, eqnForNewVars_, newVarsCrefs_, false); x1 = helpInvSin2(k1, acosy, tp ,true); x2 = helpInvSin2(k2, acosy, tp ,false); (x1, eqnForNewVars_, newVarsCrefs_) = makeTmpEqnAndCrefFromExp(x1, tp, "x1$SIN", uniqueEqIndex, idepth, eqnForNewVars_, newVarsCrefs_, false); (x2, eqnForNewVars_, newVarsCrefs_) = makeTmpEqnAndCrefFromExp(x2, tp, "x2$SIN", uniqueEqIndex, idepth, eqnForNewVars_, newVarsCrefs_, false); rhs = helpInvCos3(x1,x2,exP,tp); then(e1, rhs, true, eqnForNewVars_, newVarsCrefs_, idepth + 1); // tan(x) = y -> x = atan(y) + k*pi case (DAE.CALL(path = Absyn.IDENT(name = "tan"),expLst = {e1}),_) equation true = expHasCref(e1, inExp3); false = expHasCref(inExp2, inExp3); tp = Expression.typeof(inExp2); (rhs, eqnForNewVars_, newVarsCrefs_) = makeTmpEqnAndCrefFromExp(inExp2, tp, "Y$TAN", uniqueEqIndex, idepth, ieqnForNewVars, inewVarsCrefs,false); acosy = Expression.makePureBuiltinCall("atan", {rhs}, tp); (acosy, eqnForNewVars_, newVarsCrefs_) = makeTmpEqnAndCrefFromExp(acosy, tp, "ATAN$TAN", uniqueEqIndex, idepth, eqnForNewVars_, newVarsCrefs_,false); exP = makeInitialGuess(tp,inExp3,e1); (exP, eqnForNewVars_, newVarsCrefs_) = makeTmpEqnAndCrefFromExp(exP, tp, "PREX$TAN", uniqueEqIndex, idepth, eqnForNewVars_, newVarsCrefs_, false); e = DAE.RCONST(3.1415926535897932384626433832795028841971693993751058); k1 = Expression.expSub(exP, acosy); k1 = Expression.makeDiv(k1,e); k1 = Expression.makePureBuiltinCall("$_round",{k1},tp); rhs = Expression.expMul(k1,e); rhs = Expression.expAdd(acosy, rhs); then(e1, rhs, true, eqnForNewVars_, newVarsCrefs_, idepth + 1); // abs(f(x)) = g(y) -> f(x) = sign(f(x))*g(y) case(DAE.CALL(path = Absyn.IDENT(name = "abs"),expLst = {e1}), _) equation true = expHasCref(e1, inExp3); false = expHasCref(inExp2, inExp3); tp = Expression.typeof(e1); exP = makeInitialGuess(tp,inExp3,e1); (exP, eqnForNewVars_, newVarsCrefs_) = makeTmpEqnAndCrefFromExp(exP, tp, "X$ABS", uniqueEqIndex, idepth, ieqnForNewVars, inewVarsCrefs, false); e_1 = Expression.makePureBuiltinCall("$_signNoNull", {exP}, tp); lhs = Expression.expMul(e_1, inExp2); then(e1, lhs, true, eqnForNewVars_, newVarsCrefs_, idepth + 1); // x^n = y -> x = y^(1/n) case(DAE.BINARY(e1, DAE.POW(tp), e2),_) equation true = expHasCref(e1, inExp3); false = expHasCref(e2, inExp3); tp = Expression.typeof(e1); exP = makeInitialGuess(tp,inExp3,e1); // exP = makeInitialGuess(tp,inExp3,inExp2); (exP, eqnForNewVars_, newVarsCrefs_) = makeTmpEqnAndCrefFromExp(exP, tp, "X$ABS", uniqueEqIndex, idepth, ieqnForNewVars, inewVarsCrefs, false); e_1 = Expression.makePureBuiltinCall("$_signNoNull", {exP}, tp); lhs = Expression.expPow(inExp2,Expression.inverseFactors(e2)); lhs = Expression.makePureBuiltinCall("abs", {lhs}, tp); // lhs = Expression.makePureBuiltinCall("abs", {inExp2}, tp); // lhs = Expression.expPow(lhs,Expression.inverseFactors(e2)); lhs = Expression.expMul(e_1,lhs); then(e1, lhs, true, eqnForNewVars_, newVarsCrefs_, idepth + 1); // $_DF$DER(x) =y -> (x-old(x))/dt = y -> x = y*dt + old(x) case(DAE.CALL(path = Absyn.IDENT(name = "$_DF$DER"),expLst = {e1}), _) equation true = expHasCref(e1, inExp3); false = expHasCref(inExp2, inExp3); tp = Expression.typeof(e1); e2 = Expression.crefExp(ComponentReference.makeCrefIdent(BackendDAE.symSolverDT, DAE.T_REAL_DEFAULT, {})); lhs = Expression.makePureBuiltinCall("pre", {e1}, tp); lhs = Expression.expAdd(Expression.expMul(inExp2,e2), lhs); then(e1, lhs, true, ieqnForNewVars, inewVarsCrefs, idepth + 1); //QE // a*x^n + b*x^m = c // a*x^n - b*x^m = c case(DAE.BINARY(ee1, op1, ee2),_) guard(Expression.isAddOrSub(op1)) equation (z1, z2) = List.split1OnTrue(Expression.factors(ee1), expHasCref, inExp3); (z3, z4) = List.split1OnTrue(Expression.factors(ee2), expHasCref, inExp3); x1 = makeProductLstSort(z1); a1 = makeProductLstSort(z2); x2 = makeProductLstSort(z3); a2 = if Expression.isAdd(op1) then makeProductLstSort(z4) else Expression.negate(makeProductLstSort(z4)); /* print("\nx1 = ");print(ExpressionDump.printExpStr(x1)); print("\nx2 = ");print(ExpressionDump.printExpStr(x2)); print("\na1 = ");print(ExpressionDump.printExpStr(a1)); print("\na2 = ");print(ExpressionDump.printExpStr(a2)); */ a = simplifyBinaryMulCoeff(x1); c = simplifyBinaryMulCoeff(x2); (e2 ,e3) = a; (e5, e6) = c; (lhs, rhs, eqnForNewVars_, newVarsCrefs_) = solveQE(a1,e2,e3,a2,e5,e6,inExp2,inExp3,ieqnForNewVars,inewVarsCrefs,uniqueEqIndex,idepth); then(lhs, rhs, true, eqnForNewVars_, newVarsCrefs_, idepth + 1); else (inExp1, inExp2, false, ieqnForNewVars, inewVarsCrefs, idepth); end matchcontinue; end preprocessingSolveTmpVarsWork; protected function simplifyBinaryMulCoeff "generalization of ExpressionSimplify.simplifyBinaryMulCoeff2" input DAE.Exp inExp; output tuple<DAE.Exp, DAE.Exp> outRes; algorithm outRes := match(inExp) local DAE.Exp e,e1,e2; DAE.Exp coeff; case ((e as DAE.CREF())) then ((e, DAE.RCONST(1.0))); case (DAE.BINARY(exp1 = e1,operator = DAE.POW(),exp2 = DAE.UNARY(operator = DAE.UMINUS(), exp = coeff))) then ((e1, Expression.negate(coeff))); case (DAE.BINARY(exp1 = e1,operator = DAE.POW(),exp2 = coeff)) then ((e1,coeff)); case (DAE.BINARY(exp1 = e1,operator = DAE.MUL(),exp2 = e2)) guard(Expression.expEqual(e1, e2)) then ((e1, DAE.RCONST(2.0))); case(DAE.BINARY(e1, DAE.DIV(), e2)) guard(Expression.isOne(e1)) then(e2, DAE.RCONST(-1.0)); case(DAE.CALL(path=Absyn.IDENT("sqrt"),expLst={e})) then ((e,DAE.RCONST(0.5))); else ((inExp,DAE.RCONST(1.0))); end match; end simplifyBinaryMulCoeff; protected function solveQE " solve Quadratic equation with respect to inExp3 IN: a,x,n,b,y,m where solve(a*x^n + b*y^m = inExp2) with 2*m = n or 2*n = m and y = x author: Vitalij Ruge " input DAE.Exp e1,e2,e3,e4,e5,e6; input DAE.Exp inExp2; input DAE.Exp inExp3; input list<BackendDAE.Equation> ieqnForNewVars "eqn for tmp vars"; input list<DAE.ComponentRef> inewVarsCrefs "cref for tmp vars"; input Integer uniqueEqIndex, idepth "need for tmp vars"; output DAE.Exp rhs, lhs; output list<BackendDAE.Equation> eqnForNewVars; output list<DAE.ComponentRef> newVarsCrefs; protected DAE.Exp e, e7, con, invExp, x1, x2, x, exP; DAE.Exp a,b,c, n, sgnb, b2, ac, sExp1, sExp2; DAE.ComponentRef cr; DAE.Type tp; BackendDAE.Equation eqn; Boolean b1, b3; algorithm false := Expression.isZero(e1) and Expression.isZero(e2); true := Expression.expEqual(e2,e5); b1 := Expression.expEqual(e3, Expression.expMul(DAE.RCONST(2.0),e6)); b3 := Expression.expEqual(e6, Expression.expMul(DAE.RCONST(2.0),e3)); true := b1 or b3; false := expHasCref(e1, inExp3); true := expHasCref(e2, inExp3); false := expHasCref(e3, inExp3); false := expHasCref(e4, inExp3); true := expHasCref(e5, inExp3); false := expHasCref(e6, inExp3); false := expHasCref(inExp2, inExp3); a := if b1 then e1 else e4; b := if b1 then e4 else e1; c := Expression.negate(inExp2); n := if b1 then e6 else e3; tp := Expression.typeof(a); (a, eqnForNewVars, newVarsCrefs) := makeTmpEqnAndCrefFromExp(a, tp, "a$QE", uniqueEqIndex, idepth, ieqnForNewVars, inewVarsCrefs, false); con := DAE.RELATION(a,DAE.EQUAL(tp),DAE.RCONST(0.0),-1,NONE()); tp := Expression.typeof(b); (b, eqnForNewVars, newVarsCrefs) := makeTmpEqnAndCrefFromExp(b, tp, "b$QE", uniqueEqIndex, idepth, eqnForNewVars, newVarsCrefs, false); sgnb := Expression.makePureBuiltinCall("$_signNoNull",{b},tp); b2 := Expression.expPow(b, DAE.RCONST(2.0)); (b2, eqnForNewVars, newVarsCrefs) := makeTmpEqnAndCrefFromExp(b2, tp, "bPow2$QE", uniqueEqIndex, idepth, eqnForNewVars, newVarsCrefs, false); tp := Expression.typeof(c); (c, eqnForNewVars, newVarsCrefs) := makeTmpEqnAndCrefFromExp(c, tp, "c$QE", uniqueEqIndex, idepth, eqnForNewVars, newVarsCrefs, false); ac := Expression.expMul(a,c); ac := Expression.expMul(DAE.RCONST(4.0),ac); sExp1 := Expression.expSub(b2,ac); sExp2 := Expression.makePureBuiltinCall("sqrt",{sExp1},tp); sExp2 := Expression.expMul(sgnb, sExp2); a := DAE.IFEXP(con, Expression.makeConstOne(tp), a); (a, eqnForNewVars, newVarsCrefs) := makeTmpEqnAndCrefFromExp(a, tp, "a1$QE", uniqueEqIndex, idepth, eqnForNewVars, newVarsCrefs, false); x1 := Expression.expAdd(b, sExp2); x1 := Expression.makeDiv(x1, a); x1 := Expression.expMul(DAE.RCONST(-0.5), x1); tp := Expression.typeof(x1); x1 := DAE.IFEXP(con, Expression.makeConstOne(tp), x1); (x1, eqnForNewVars, newVarsCrefs) := makeTmpEqnAndCrefFromExp(x1, tp, "x1$QE", uniqueEqIndex, idepth, eqnForNewVars, newVarsCrefs, false); //Vieta x2 := Expression.expMul(a,x1); x2 := Expression.makeDiv(c,x2); x2 := DAE.IFEXP(con, Expression.makeConstOne(tp), x2); x2 := DAE.IFEXP(DAE.RELATION(x1,DAE.EQUAL(tp),DAE.RCONST(0.0),-1,NONE()), DAE.RCONST(0.0), x2); (x2, eqnForNewVars, newVarsCrefs) := makeTmpEqnAndCrefFromExp(x2, tp, "x2$QE", uniqueEqIndex, idepth, eqnForNewVars, newVarsCrefs, false); tp := Expression.typeof(e2); exP := makeInitialGuess(tp,inExp3,e2); (exP, eqnForNewVars, newVarsCrefs) := makeTmpEqnAndCrefFromExp(exP, tp, "prex$QE", uniqueEqIndex, idepth, eqnForNewVars, newVarsCrefs, false); x := helpInvCos3(x1,x2,exP,tp); (x, eqnForNewVars, newVarsCrefs) := makeTmpEqnAndCrefFromExp(x, tp, "x$QE", uniqueEqIndex, idepth, eqnForNewVars, newVarsCrefs, false); // a = 0 e7 := Expression.makeDiv(inExp2,b); invExp := Expression.inverseFactors(n); (invExp, _) := ExpressionSimplify.simplify1(invExp); e7 := Expression.expPow(e7, invExp); // if a==0 rhs := DAE.IFEXP(con, e7 , x); // lhs lhs := if b1 then Expression.expPow(e2, e6) else Expression.expPow(e2, e3); end solveQE; protected function solveIfExp " solve: if(f(y), f(x), g(x) ) = h(y) w.r.t. x " input DAE.Exp inExp1; input DAE.Exp inExp2; input DAE.Exp inExp3; input Option<DAE.FunctionTree> functions; input Option<Integer> uniqueEqIndex "offset for tmp vars"; input Integer idepth; input Boolean doInline; input Boolean isContinuousIntegration; output DAE.Exp outExp; output list<DAE.Statement> outAsserts; output list<BackendDAE.Equation> eqnForNewVars "eqn for tmp vars"; output list<DAE.ComponentRef> newVarsCrefs; output Integer odepth; algorithm (outExp,outAsserts,eqnForNewVars,newVarsCrefs,odepth) := match inExp1 local DAE.Exp e1,e2,e3,res,lhs,rhs; list<DAE.Statement> asserts,asserts1,asserts2; list<BackendDAE.Equation> eqns, eqns1; list<DAE.ComponentRef> var, var1; Integer depth; // f(a) if(g(b)) then f1(a) else f2(a) => // a1 = solve(f(a),f1(a)) for a // a2 = solve(f(a),f2(a)) for a // => a = if g(b) then a1 else a2 case DAE.IFEXP(e1,e2,e3) guard isContinuousIntegration or not expHasCref(e1, inExp3) equation (lhs, asserts1, eqns, var, depth) = solveWork(e2, inExp2, inExp3, functions, uniqueEqIndex, idepth, doInline, isContinuousIntegration); (rhs,_, eqns1, var1, depth) = solveWork(e3, inExp2, inExp3, functions, uniqueEqIndex, depth, doInline, isContinuousIntegration); res = DAE.IFEXP(e1,lhs,rhs); asserts = listAppend(asserts1,asserts1); then (res,asserts,listAppend(eqns1,eqns), listAppend(var1, var), depth); else fail(); end match; end solveIfExp; protected function solveLinearSystem " solve linear system with newton step ToDo: fixed is for ./simulation/modelica/equations/deriveToLog.mos " input DAE.Exp inExp1; input DAE.Exp inExp2; input DAE.Exp inExp3; input Option<DAE.FunctionTree> functions; input Integer idepth; output DAE.Exp outExp; output list<DAE.Statement> outAsserts; output list<BackendDAE.Equation> eqnForNewVars = {} "eqn for tmp vars"; output list<DAE.ComponentRef> newVarsCrefs = {}; output Integer odepth = idepth; algorithm (outExp,outAsserts) := match(inExp1,inExp2,inExp3) local DAE.Exp dere,e,z; DAE.ComponentRef cr; DAE.Exp rhs; DAE.Type tp; Integer i; // cr = (e1-e2)/(der(e1-e2,cr)) case (_,_,DAE.CREF(componentRef = cr)) equation false = hasOnlyFactors(inExp1,inExp2); e = Expression.makeDiff(inExp1,inExp2); (e,_) = ExpressionSimplify.simplify1(e); //print("\ne: ");print(ExpressionDump.printExpStr(e)); dere = Differentiate.differentiateExpSolve(e, cr, functions); //print("\nder(e): ");print(ExpressionDump.printExpStr(dere)); (dere,_) = ExpressionSimplify.simplify(dere); false = Expression.isZero(dere); false = Expression.expHasCrefNoPreOrStart(dere, cr); tp = Expression.typeof(inExp3); (z,_) = Expression.makeZeroExpression(Expression.arrayDimension(tp)); ((e,i)) = Expression.replaceExp(e, inExp3, z); // replace at least once, otherwise it's wrong if i < 1 then fail(); end if; (e,_) = ExpressionSimplify.simplify(e); rhs = Expression.negate(Expression.makeDiv(e,dere)); then (rhs,{}); else fail(); end match; end solveLinearSystem; protected function hasOnlyFactors "help function to solve2, returns true if equation e1 == e2, has either e1 == 0 or e2 == 0 and the expression only contains factors, e.g. a*b*c = 0. In this case we can not solve the equation" input DAE.Exp e1; input DAE.Exp e2; output Boolean res; algorithm res := matchcontinue(e1,e2) // try normal case(_,_) equation true = Expression.isZero(e1); // More than two factors _::_::_ = Expression.factors(e2); //.. and more than two crefs _::_::_ = Expression.extractCrefsFromExp(e2); then true; // swapped args case(_,_) equation true = Expression.isZero(e2); _::_::_ = Expression.factors(e1); _::_::_ = Expression.extractCrefsFromExp(e1); then true; else false; end matchcontinue; end hasOnlyFactors; protected function expHasCref " helper function for solve. case distinction for DAE.CREF or 'der(DAE.CREF())' Expression.expHasCrefNoPreOrStart or Expression.expHasDerCref " input DAE.Exp inExp1; input DAE.Exp inExp3 "DAE.CREF or 'der(DAE.CREF())'"; output DAE.Boolean res; algorithm res := match(inExp1, inExp3) local DAE.ComponentRef cr; case(_, DAE.CREF(componentRef = cr)) then Expression.expHasCrefNoPreOrStart(inExp1, cr); case(_, DAE.CALL(path = Absyn.IDENT(name = "der"),expLst = {DAE.CREF(componentRef = cr)})) then Expression.expHasDerCref(inExp1, cr); else equation if Flags.isSet(Flags.FAILTRACE) then print("\n-ExpressionSolve.solve failed:"); print(" with respect to: ");print(ExpressionDump.printExpStr(inExp3)); print(" not support!"); print("\n"); end if; then fail(); end match; end expHasCref; protected function makeProductLstSort "Takes a list of expressions an makes a product expression multiplying all elements in the list. - a*if(b,c,d) -> if(b,a*c,a*d) " input list<DAE.Exp> inExpLst; output DAE.Exp outExp; protected DAE.Type tp; list<DAE.Exp> expLstDiv, expLst, expLst2; DAE.Exp e, e1, e2; DAE.Operator op; algorithm if listEmpty(inExpLst) then outExp := DAE.RCONST(1.0); return; end if; tp := Expression.typeof(listHead(inExpLst)); (expLstDiv, expLst) := List.splitOnTrue(inExpLst, Expression.isDivBinary); outExp := makeProductLstSort2(expLst, tp); if not listEmpty(expLstDiv) then expLst2 := {}; expLst := {}; for elem in expLstDiv loop DAE.BINARY(e1,op,e2) := elem; expLst := e1::expLst; expLst2 := e2::expLst2; end for; if not listEmpty(expLst2) then e := makeProductLstSort(expLst2); if not Expression.isOne(e) then outExp := Expression.makeDiv(outExp,e); end if; end if; if not listEmpty(expLst) then e := makeProductLstSort(expLst); outExp := Expression.expMul(outExp,e); end if; end if; end makeProductLstSort; protected function makeProductLstSort2 input list<DAE.Exp> inExpLst; input DAE.Type tp; output DAE.Exp outExp = Expression.makeConstOne(tp); protected list<DAE.Exp> rest; algorithm rest := ExpressionSimplify.simplifyList(inExpLst); for elem in rest loop if not Expression.isOne(elem) then outExp := match(elem) local DAE.Exp e1,e2,e3; case(DAE.IFEXP(e1,e2,e3)) then DAE.IFEXP(e1, Expression.expMul(outExp,e2), Expression.expMul(outExp,e3)); else Expression.expMul(outExp, elem); end match; end if; end for; end makeProductLstSort2; protected function makeTmpEqnAndCrefFromExp input DAE.Exp iExp; input DAE.Type tp; input String name; input Integer index1, index2; input list<BackendDAE.Equation> ieqnForNewVars; input list<DAE.ComponentRef> inewVarsCrefs; input Boolean need; output DAE.Exp oExp; output list<BackendDAE.Equation> oeqnForNewVars; output list<DAE.ComponentRef> onewVarsCrefs; protected DAE.ComponentRef cr = ComponentReference.makeCrefIdent("$TMP$VAR$" + intString(index1) + "$" + intString(index2) + name, tp , {}); BackendDAE.Equation eqn; algorithm (oExp,_) := ExpressionSimplify.simplify1(iExp); if need or not (Expression.isCref(oExp) or Expression.isConst(oExp)) then eqn := BackendDAE.SOLVED_EQUATION(cr, oExp, DAE.emptyElementSource, BackendDAE.EQ_ATTR_DEFAULT_UNKNOWN); oExp := Expression.crefExp(cr); oeqnForNewVars := eqn::ieqnForNewVars; onewVarsCrefs := cr :: inewVarsCrefs; else oeqnForNewVars := ieqnForNewVars; onewVarsCrefs := inewVarsCrefs; end if; end makeTmpEqnAndCrefFromExp; protected function makeInitialGuess input DAE.Type tp; input DAE.Exp iExp1; input DAE.Exp iExp2; output DAE.Exp oExp; protected DAE.Exp con, e; algorithm con := Expression.makePureBuiltinCall("initial", {}, tp); e := Expression.traverseExpBottomUp(iExp2, makeInitialGuess2, (iExp1, "pre", tp, true)); oExp := Expression.traverseExpBottomUp(iExp2, makeInitialGuess2, (iExp1, "pre", tp, false)); oExp := DAE.IFEXP(con, e, oExp); end makeInitialGuess; protected function makeInitialGuess2 input DAE.Exp iExp; input tuple<DAE.Exp, String, DAE.Type, Boolean> itpl; output DAE.Exp oExp; output tuple<DAE.Exp, String, DAE.Type, Boolean> otpl = itpl; algorithm oExp := match(iExp, itpl) local DAE.ComponentRef cr1,cr2; DAE.Type tp; String fun; DAE.Exp e; case (DAE.CREF(componentRef=cr1), (DAE.CREF(componentRef=cr2), fun, tp, _)) guard(ComponentReference.crefEqual(cr1, cr2)) algorithm e := Expression.makePureBuiltinCall(fun, {iExp}, tp); then e; case (_, (_, _, tp, true)) algorithm try SOME(e) := makeInitialGuess3(iExp, tp); else e := iExp; end try; then e; else iExp; end match; end makeInitialGuess2; protected function makeInitialGuess3 input DAE.Exp iExp; input DAE.Type tp; output Option<DAE.Exp> oExp; algorithm oExp := match(iExp) local DAE.Exp e, con, o; case(DAE.CALL(path = Absyn.IDENT(name = "log"), expLst={e})) equation con = DAE.RELATION(e, DAE.LESSEQ(tp), DAE.RCONST(0.0), -1, NONE()); o = DAE.IFEXP(con, DAE.RCONST(-1/0.000000001), iExp); then SOME(o); case(DAE.CALL(path = Absyn.IDENT(name = "log10"), expLst={e})) equation con = DAE.RELATION(e, DAE.LESSEQ(tp), DAE.RCONST(0.0), -1, NONE()); o = DAE.IFEXP(con, DAE.RCONST(-1/0.000000001), iExp); then SOME(o); case(DAE.CALL(path = Absyn.IDENT(name = "sqrt"), expLst={e})) equation con = DAE.RELATION(e, DAE.LESSEQ(tp), DAE.RCONST(0.0), -1, NONE()); o = DAE.IFEXP(con, DAE.RCONST(0.0), iExp); then SOME(o); case(DAE.BINARY(exp2=e)) equation con = DAE.RELATION(e, DAE.EQUAL(tp), DAE.RCONST(0.0), -1, NONE()); o = DAE.IFEXP(con, DAE.RCONST(1.0), iExp); then SOME(o); else NONE(); end match; end makeInitialGuess3; protected function helpInvCos input DAE.Exp acosy; input DAE.Exp x; input DAE.Type tp; input Boolean neg; output DAE.Exp k; protected DAE.Exp pi2 = DAE.RCONST(6.283185307179586476925286766559005768394338798750211641949889); algorithm k := if neg then Expression.expAdd(x,acosy) else Expression.expSub(x,acosy); k := Expression.makeDiv(k, pi2); k := Expression.makePureBuiltinCall("$_round",{k},tp); end helpInvCos; protected function helpInvSin input DAE.Exp asiny; input DAE.Exp x; input DAE.Type tp; input Boolean neg; output DAE.Exp k; protected DAE.Exp pi2 = DAE.RCONST(6.283185307179586476925286766559005768394338798750211641949889); algorithm k := if neg then Expression.expAdd(x,asiny) else Expression.expSub(x,asiny); k := Expression.makeDiv(k, pi2); if neg then k := Expression.expSub(k, DAE.RCONST(0.5)); end if; k := Expression.makePureBuiltinCall("$_round",{k},tp); end helpInvSin; protected function helpInvCos2 input DAE.Exp k; input DAE.Exp acosy; input DAE.Type tp; input Boolean neg; output DAE.Exp x; protected DAE.Exp pi2 = DAE.RCONST(6.283185307179586476925286766559005768394338798750211641949889); algorithm x := if neg then Expression.negate(acosy) else acosy; x := Expression.expAdd(x, Expression.expMul(k,pi2)); end helpInvCos2; protected function helpInvSin2 input DAE.Exp k; input DAE.Exp asiny; input DAE.Type tp; input Boolean neg; output DAE.Exp x; protected DAE.Exp pi2 = DAE.RCONST(6.283185307179586476925286766559005768394338798750211641949889); DAE.Exp p = DAE.RCONST(3.1415926535897932384626433832795028841971693993751058); DAE.Exp e; algorithm x := if neg then Expression.negate(asiny) else asiny; e := if neg then Expression.expAdd(Expression.expMul(k,pi2), p) else Expression.expMul(k,pi2); x := Expression.expAdd(x, e); end helpInvSin2; protected function helpInvCos3 input DAE.Exp x1; input DAE.Exp x2; input DAE.Exp x; input DAE.Type tp; output DAE.Exp y; protected DAE.Exp diffx1 = absDiff(x1,x,tp); DAE.Exp diffx2 = absDiff(x2,x,tp); DAE.Exp con = DAE.RELATION(diffx1, DAE.LESS(tp), diffx2, -1, NONE()); algorithm con := Expression.makeNoEvent(con); y := DAE.IFEXP(con, x1, x2); end helpInvCos3; protected function absDiff input DAE.Exp x; input DAE.Exp y; input DAE.Type tp; output DAE.Exp z; algorithm z := Expression.expSub(x,y); z := Expression.makePureBuiltinCall("abs",{z},tp); end absDiff; annotation(__OpenModelica_Interface="backend"); end ExpressionSolve;
{ "pile_set_name": "Github" }
using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Runtime.InteropServices; using System.Text; namespace clawSoft.clawPDF.ftplib.FtpLib { public class FtpConnection : IDisposable { private readonly string _password = ""; private readonly string _username = ""; private IntPtr _hConnect; private IntPtr _hInternet; public FtpConnection(string host) { Host = host; } public FtpConnection(string host, int port) { Host = host; Port = port; } public FtpConnection(string host, string username, string password) { Host = host; _username = username; _password = password; } public FtpConnection(string host, int port, string username, string password) { Host = host; Port = port; _username = username; _password = password; } public int Port { get; } = 21; public string Host { get; } public void Dispose() { if (_hConnect != IntPtr.Zero) WININET.InternetCloseHandle(_hConnect); if (_hInternet != IntPtr.Zero) WININET.InternetCloseHandle(_hInternet); } public void Open() { if (string.IsNullOrEmpty(Host)) throw new ArgumentNullException("Host"); _hInternet = WININET.InternetOpen(Environment.UserName, 0, null, null, 4); if (_hInternet == IntPtr.Zero) Error(); } public void Login() { Login(_username, _password); } public void Login(string username, string password) { if (username == null) throw new ArgumentNullException("username"); if (password == null) throw new ArgumentNullException("password"); _hConnect = WININET.InternetConnect(_hInternet, Host, Port, username, password, 1, 134217728, IntPtr.Zero); if (_hConnect == IntPtr.Zero) Error(); } public void SetCurrentDirectory(string directory) { if (WININET.FtpSetCurrentDirectory(_hConnect, directory) == 0) Error(); } public void SetLocalDirectory(string directory) { if (Directory.Exists(directory)) { Environment.CurrentDirectory = directory; return; } throw new InvalidDataException($"{directory} is not a directory!"); } public string GetCurrentDirectory() { var dwCurrentDirectory = 261; var stringBuilder = new StringBuilder(dwCurrentDirectory); if (WININET.FtpGetCurrentDirectory(_hConnect, stringBuilder, ref dwCurrentDirectory) == 0) { Error(); return null; } return stringBuilder.ToString(); } public FtpDirectoryInfo GetCurrentDirectoryInfo() { var currentDirectory = GetCurrentDirectory(); return new FtpDirectoryInfo(this, currentDirectory); } public void GetFile(string remoteFile, bool failIfExists) { GetFile(remoteFile, remoteFile, failIfExists); } public void GetFile(string remoteFile, string localFile, bool failIfExists) { if (WININET.FtpGetFile(_hConnect, remoteFile, localFile, failIfExists, 128, 2, IntPtr.Zero) == 0) Error(); } public void PutFile(string fileName) { PutFile(fileName, Path.GetFileName(fileName)); } public void PutFile(string localFile, string remoteFile) { if (WININET.FtpPutFile(_hConnect, localFile, remoteFile, 2, IntPtr.Zero) == 0) Error(); } public void RenameFile(string existingFile, string newFile) { if (WININET.FtpRenameFile(_hConnect, existingFile, newFile) == 0) Error(); } public void RemoveFile(string fileName) { if (WININET.FtpDeleteFile(_hConnect, fileName) == 0) Error(); } public void RemoveDirectory(string directory) { if (WININET.FtpRemoveDirectory(_hConnect, directory) == 0) Error(); } [Obsolete("Use GetFiles or GetDirectories instead.")] public List<string> List() { return List(null, false); } [Obsolete("Use GetFiles or GetDirectories instead.")] public List<string> List(string mask) { return List(mask, false); } [Obsolete("Will be removed in later releases.")] private List<string> List(bool onlyDirectories) { return List(null, onlyDirectories); } [Obsolete("Will be removed in later releases.")] private List<string> List(string mask, bool onlyDirectories) { WINAPI.WIN32_FIND_DATA findFileData = default; var intPtr = WININET.FtpFindFirstFile(_hConnect, mask, ref findFileData, 67108864, IntPtr.Zero); try { var list = new List<string>(); if (intPtr == IntPtr.Zero) { if (Marshal.GetLastWin32Error() == 18) return list; Error(); return list; } if (onlyDirectories && (findFileData.dfFileAttributes & 0x10) == 16) { var list2 = list; var text = new string(findFileData.fileName); var trimChars = new char[1]; list2.Add(text.TrimEnd(trimChars)); } else if (!onlyDirectories) { var list3 = list; var text2 = new string(findFileData.fileName); var trimChars2 = new char[1]; list3.Add(text2.TrimEnd(trimChars2)); } findFileData = default; while (WININET.InternetFindNextFile(intPtr, ref findFileData) != 0) { if (onlyDirectories && (findFileData.dfFileAttributes & 0x10) == 16) { var list4 = list; var text3 = new string(findFileData.fileName); var trimChars3 = new char[1]; list4.Add(text3.TrimEnd(trimChars3)); } else if (!onlyDirectories) { var list5 = list; var text4 = new string(findFileData.fileName); var trimChars4 = new char[1]; list5.Add(text4.TrimEnd(trimChars4)); } findFileData = default; } if (Marshal.GetLastWin32Error() != 18) Error(); return list; } finally { if (intPtr != IntPtr.Zero) WININET.InternetCloseHandle(intPtr); } } public FtpFileInfo[] GetFiles() { return GetFiles(GetCurrentDirectory()); } public FtpFileInfo[] GetFiles(string mask) { var findFileData = default(WINAPI.WIN32_FIND_DATA); var intPtr = WININET.FtpFindFirstFile(_hConnect, mask, ref findFileData, 67108864, IntPtr.Zero); try { var list = new List<FtpFileInfo>(); if (intPtr == IntPtr.Zero) { if (Marshal.GetLastWin32Error() == 18) return list.ToArray(); Error(); return list.ToArray(); } if ((findFileData.dfFileAttributes & 0x10) != 16) { var text = new string(findFileData.fileName); var trimChars = new char[1]; var ftpFileInfo = new FtpFileInfo(this, text.TrimEnd(trimChars)); ftpFileInfo.LastAccessTime = findFileData.ftLastAccessTime.ToDateTime(); ftpFileInfo.LastWriteTime = findFileData.ftLastWriteTime.ToDateTime(); ftpFileInfo.CreationTime = findFileData.ftCreationTime.ToDateTime(); ftpFileInfo.Attributes = (FileAttributes)findFileData.dfFileAttributes; list.Add(ftpFileInfo); } findFileData = default; while (WININET.InternetFindNextFile(intPtr, ref findFileData) != 0) { if ((findFileData.dfFileAttributes & 0x10) != 16) { var text2 = new string(findFileData.fileName); var trimChars2 = new char[1]; var ftpFileInfo2 = new FtpFileInfo(this, text2.TrimEnd(trimChars2)); ftpFileInfo2.LastAccessTime = findFileData.ftLastAccessTime.ToDateTime(); ftpFileInfo2.LastWriteTime = findFileData.ftLastWriteTime.ToDateTime(); ftpFileInfo2.CreationTime = findFileData.ftCreationTime.ToDateTime(); ftpFileInfo2.Attributes = (FileAttributes)findFileData.dfFileAttributes; list.Add(ftpFileInfo2); } findFileData = default; } if (Marshal.GetLastWin32Error() != 18) Error(); return list.ToArray(); } finally { if (intPtr != IntPtr.Zero) WININET.InternetCloseHandle(intPtr); } } public FtpDirectoryInfo[] GetDirectories() { return GetDirectories(GetCurrentDirectory()); } public FtpDirectoryInfo[] GetDirectories(string path) { var findFileData = default(WINAPI.WIN32_FIND_DATA); var intPtr = WININET.FtpFindFirstFile(_hConnect, path, ref findFileData, 67108864, IntPtr.Zero); try { var list = new List<FtpDirectoryInfo>(); if (intPtr == IntPtr.Zero) { if (Marshal.GetLastWin32Error() == 18) return list.ToArray(); Error(); return list.ToArray(); } if ((findFileData.dfFileAttributes & 0x10) == 16) { var text = new string(findFileData.fileName); var trimChars = new char[1]; var ftpDirectoryInfo = new FtpDirectoryInfo(this, text.TrimEnd(trimChars)); ftpDirectoryInfo.LastAccessTime = findFileData.ftLastAccessTime.ToDateTime(); ftpDirectoryInfo.LastWriteTime = findFileData.ftLastWriteTime.ToDateTime(); ftpDirectoryInfo.CreationTime = findFileData.ftCreationTime.ToDateTime(); ftpDirectoryInfo.Attributes = (FileAttributes)findFileData.dfFileAttributes; list.Add(ftpDirectoryInfo); } findFileData = default; while (WININET.InternetFindNextFile(intPtr, ref findFileData) != 0) { if ((findFileData.dfFileAttributes & 0x10) == 16) { var text2 = new string(findFileData.fileName); var trimChars2 = new char[1]; var ftpDirectoryInfo2 = new FtpDirectoryInfo(this, text2.TrimEnd(trimChars2)); ftpDirectoryInfo2.LastAccessTime = findFileData.ftLastAccessTime.ToDateTime(); ftpDirectoryInfo2.LastWriteTime = findFileData.ftLastWriteTime.ToDateTime(); ftpDirectoryInfo2.CreationTime = findFileData.ftCreationTime.ToDateTime(); ftpDirectoryInfo2.Attributes = (FileAttributes)findFileData.dfFileAttributes; list.Add(ftpDirectoryInfo2); } findFileData = default; } if (Marshal.GetLastWin32Error() != 18) Error(); return list.ToArray(); } finally { if (intPtr != IntPtr.Zero) WININET.InternetCloseHandle(intPtr); } } public void CreateDirectory(string path) { if (WININET.FtpCreateDirectory(_hConnect, path) == 0) Error(); } public bool DirectoryExists(string path) { var findFileData = default(WINAPI.WIN32_FIND_DATA); var intPtr = WININET.FtpFindFirstFile(_hConnect, path, ref findFileData, 67108864, IntPtr.Zero); try { if (intPtr == IntPtr.Zero) return false; return true; } finally { if (intPtr != IntPtr.Zero) WININET.InternetCloseHandle(intPtr); } } public bool FileExists(string path) { var findFileData = default(WINAPI.WIN32_FIND_DATA); var intPtr = WININET.FtpFindFirstFile(_hConnect, path, ref findFileData, 67108864, IntPtr.Zero); try { if (intPtr == IntPtr.Zero) return false; return true; } finally { if (intPtr != IntPtr.Zero) WININET.InternetCloseHandle(intPtr); } } public string SendCommand(string cmd) { var ftpCommand = default(IntPtr); string a; var num = (a = cmd) == null || !(a == "PASV") ? WININET.FtpCommand(_hConnect, false, 1, cmd, IntPtr.Zero, ref ftpCommand) : WININET.FtpCommand(_hConnect, false, 1, cmd, IntPtr.Zero, ref ftpCommand); var num2 = 8192; if (num == 0) { Error(); } else if (ftpCommand != IntPtr.Zero) { var stringBuilder = new StringBuilder(num2); var bytesRead = 0; do { num = WININET.InternetReadFile(ftpCommand, stringBuilder, num2, ref bytesRead); } while (num == 1 && bytesRead > 1); return stringBuilder.ToString(); } return ""; } public void Close() { WININET.InternetCloseHandle(_hConnect); _hConnect = IntPtr.Zero; WININET.InternetCloseHandle(_hInternet); _hInternet = IntPtr.Zero; } private string InternetLastResponseInfo(ref int code) { var bufferLength = 8192; var stringBuilder = new StringBuilder(bufferLength); WININET.InternetGetLastResponseInfo(ref code, stringBuilder, ref bufferLength); return stringBuilder.ToString(); } private void Error() { var code = Marshal.GetLastWin32Error(); if (code == 12003) { var message = InternetLastResponseInfo(ref code); throw new FtpException(code, message); } throw new Win32Exception(code); } } }
{ "pile_set_name": "Github" }
#topMain>li>a { height:96px; line-height:76px; } #topMain.nav-pills>li { margin-left:3px !important; } #topMain.nav-pills>li:first-child { margin-left:0 !important; } #topMain>li>a>span.theme-color { padding:10px 15px; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; } #header.fixed #topMain>li>a { margin-top:10px; } #topMain.nav-pills>li>a { color:#1F262D; font-weight:400; background-color:transparent; padding-left:0 !important; padding-right:0 !important; } #topMain.nav-pills>li:hover>a, #topMain.nav-pills>li:focus>a { color:#1F262D; } #topMain.nav-pills>li.active>a>span.theme-color, #topMain.nav-pills>li:hover>a>span.theme-color, #topMain.nav-pills>li:focus>a>span.theme-color { background-color:rgba(0,0,0,0.01); } #header.fixed #topNav #topMain>li>a { margin-top:0px; } #topMain.nav-pills>li.active>a { color:#fff; } #topNav .navbar-collapse { float:right; } #topNav a.logo { height:96px; line-height:96px; overflow:hidden; display:inline-block; } #header ul.nav-second-main { border-left:0; } @media only screen and (max-width: 1024px) { #topMain.nav-pills>li>a { font-size:13px; } } @media only screen and (max-width: 992px) { #topMain.nav-pills>li { margin-left:0 !important; } #topMain>li>a>span.theme-color { color:#151515; display:block !important; padding-top:0; height:40px; -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; } #topMain>li.active>a>span.theme-color { color:#fff; } /* Force 60px */ #header { height:60px !important; } #header #topNav a.logo { height:60px !important; line-height:50px !important; } #header #topNav a.logo>img { max-height:60px !important; } #header #topNav #topMain>li>a { height:40px !important; line-height:40px !important; padding-top:0; } #topMain>li { border-bottom:rgba(0,0,0,0.1) 1px solid; } #topMain>li:last-child { border-bottom:0; } #header li.search .search-box { margin:0 !important; position:fixed; left:0; right:0; top:60px !important; width:100%; background-color:#fff; border-top:rgba(0,0,0,0.1) 1px solid; } }
{ "pile_set_name": "Github" }
# # Stage 1 # FROM library/golang as builder ENV APP_DIR $GOPATH/src/flux-web/flux-web RUN mkdir -p $APP_DIR WORKDIR $GOPATH/src/flux-web/flux-web ADD go.* $APP_DIR/ RUN go mod download ADD . $APP_DIR RUN CGO_ENABLED=0 go build -ldflags '-w -s' -o /flux-web && cp -r conf/ /conf # # Stage 2 # FROM alpine:3.12 RUN apk add --no-cache \ python3 \ py3-pip \ && pip3 install --upgrade pip \ && pip3 install \ awscli \ && rm -rf /var/cache/apk/* RUN aws --version # Just to make sure its installed alright RUN adduser -D -u 1000 flux-web COPY --from=builder /flux-web /flux-web COPY --from=builder /conf /conf USER 1000 ENTRYPOINT ["/flux-web"]
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2012 Jake Wharton Copyright (C) 2011 Patrik Åkerfeldt Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources> <declare-styleable name="ViewPagerIndicator"> <!-- Style of the underline indicator. --> <attr name="vpiUnderlinePageIndicatorStyle" format="reference"/> </declare-styleable> <attr name="centered" format="boolean"/> <attr name="selectedColor" format="color"/> <attr name="strokeWidth" format="dimension"/> <attr name="unselectedColor" format="color"/> <declare-styleable name="UnderlinePageIndicator"> <!-- Whether or not the selected indicator fades. --> <attr name="fades" format="boolean"/> <!-- Length of the delay to fade the indicator. --> <attr name="fadeDelay" format="integer"/> <!-- Length of the indicator fade to transparent. --> <attr name="fadeLength" format="integer"/> <!-- Color of the selected line that represents the current page. --> <attr name="selectedColor"/> <!-- View background --> <attr name="android:background"/> </declare-styleable> </resources>
{ "pile_set_name": "Github" }
terraform_version = "0.12.24" planned_values = { "outputs": {}, "resources": { "aws_instance.web": { "address": "aws_instance.web", "depends_on": [], "deposed_key": "", "index": null, "mode": "managed", "module_address": "", "name": "web", "provider_name": "aws", "tainted": false, "type": "aws_instance", "values": { "ami": "ami-2e1ef954", "credit_specification": [], "disable_api_termination": null, "ebs_optimized": null, "get_password_data": false, "hibernation": null, "iam_instance_profile": null, "instance_initiated_shutdown_behavior": null, "instance_type": "t2.micro", "monitoring": null, "source_dest_check": true, "tags": { "Name": "assumed_role_instance", }, "timeouts": null, "user_data": null, "user_data_base64": null, }, }, "module.nested.aws_instance.web": { "address": "module.nested.aws_instance.web", "depends_on": [], "deposed_key": "", "index": null, "mode": "managed", "module_address": "module.nested", "name": "web", "provider_name": "aws", "tainted": false, "type": "aws_instance", "values": { "ami": "ami-2e1ef954", "credit_specification": [], "disable_api_termination": null, "ebs_optimized": null, "get_password_data": false, "hibernation": null, "iam_instance_profile": null, "instance_initiated_shutdown_behavior": null, "instance_type": "t2.micro", "monitoring": null, "source_dest_check": true, "tags": { "Name": "assumed_role_instance", }, "timeouts": null, "user_data": null, "user_data_base64": null, }, }, }, } variables = { "role": { "name": "role", "value": "arn:aws:iam::909012349090:role/role-qa", }, } resource_changes = { "aws_instance.web": { "address": "aws_instance.web", "change": { "actions": [ "create", ], "after": { "ami": "ami-2e1ef954", "credit_specification": [], "disable_api_termination": null, "ebs_optimized": null, "get_password_data": false, "hibernation": null, "iam_instance_profile": null, "instance_initiated_shutdown_behavior": null, "instance_type": "t2.micro", "monitoring": null, "source_dest_check": true, "tags": { "Name": "assumed_role_instance", }, "timeouts": null, "user_data": null, "user_data_base64": null, }, "after_unknown": { "arn": true, "associate_public_ip_address": true, "availability_zone": true, "cpu_core_count": true, "cpu_threads_per_core": true, "credit_specification": [], "ebs_block_device": true, "ephemeral_block_device": true, "host_id": true, "id": true, "instance_state": true, "ipv6_address_count": true, "ipv6_addresses": true, "key_name": true, "metadata_options": true, "network_interface": true, "network_interface_id": true, "password_data": true, "placement_group": true, "primary_network_interface_id": true, "private_dns": true, "private_ip": true, "public_dns": true, "public_ip": true, "root_block_device": true, "security_groups": true, "subnet_id": true, "tags": {}, "tenancy": true, "volume_tags": true, "vpc_security_group_ids": true, }, "before": null, }, "deposed": "", "index": null, "mode": "managed", "module_address": "", "name": "web", "provider_name": "aws", "type": "aws_instance", }, "module.nested.aws_instance.web": { "address": "module.nested.aws_instance.web", "change": { "actions": [ "create", ], "after": { "ami": "ami-2e1ef954", "credit_specification": [], "disable_api_termination": null, "ebs_optimized": null, "get_password_data": false, "hibernation": null, "iam_instance_profile": null, "instance_initiated_shutdown_behavior": null, "instance_type": "t2.micro", "monitoring": null, "source_dest_check": true, "tags": { "Name": "assumed_role_instance", }, "timeouts": null, "user_data": null, "user_data_base64": null, }, "after_unknown": { "arn": true, "associate_public_ip_address": true, "availability_zone": true, "cpu_core_count": true, "cpu_threads_per_core": true, "credit_specification": [], "ebs_block_device": true, "ephemeral_block_device": true, "host_id": true, "id": true, "instance_state": true, "ipv6_address_count": true, "ipv6_addresses": true, "key_name": true, "metadata_options": true, "network_interface": true, "network_interface_id": true, "password_data": true, "placement_group": true, "primary_network_interface_id": true, "private_dns": true, "private_ip": true, "public_dns": true, "public_ip": true, "root_block_device": true, "security_groups": true, "subnet_id": true, "tags": {}, "tenancy": true, "volume_tags": true, "vpc_security_group_ids": true, }, "before": null, }, "deposed": "", "index": null, "mode": "managed", "module_address": "module.nested", "name": "web", "provider_name": "aws", "type": "aws_instance", }, } output_changes = {}
{ "pile_set_name": "Github" }
/* $Id$ */ /* Copyright (C) 2004 Alexander Chernov */ /* This file is derived from `stropts.h' of the GNU C Library, version 2.3.2. The original copyright follows. */ /* Copyright (C) 1998, 1999, 2000, 2002 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C 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 GNU C 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 GNU C Library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #ifndef __RCC_STROPTS_H__ #define __RCC_STROPTS_H__ 1 #include <features.h> #include <sys/types.h> typedef unsigned long int t_uscalar_t; /* Get system specific contants. */ int enum { __SID = ('S' << 8), #define __SID __SID I_NREAD = (__SID | 1), #define I_NREAD I_NREAD I_PUSH = (__SID | 2), #define I_PUSH I_PUSH I_POP = (__SID | 3), #define I_POP I_POP I_LOOK = (__SID | 4), #define I_LOOK I_LOOK I_FLUSH = (__SID | 5), #define I_FLUSH I_FLUSH I_SRDOPT = (__SID | 6), #define I_SRDOPT I_SRDOPT I_GRDOPT = (__SID | 7), #define I_GRDOPT I_GRDOPT I_STR = (__SID | 8), #define I_STR I_STR I_SETSIG = (__SID | 9), #define I_SETSIG I_SETSIG I_GETSIG = (__SID |10), #define I_GETSIG I_GETSIG I_FIND = (__SID |11), #define I_FIND I_FIND I_LINK = (__SID |12), #define I_LINK I_LINK I_UNLINK = (__SID |13), #define I_UNLINK I_UNLINK I_PEEK = (__SID |15), #define I_PEEK I_PEEK I_FDINSERT = (__SID |16), #define I_FDINSERT I_FDINSERT I_SENDFD = (__SID |17), #define I_SENDFD I_SENDFD I_RECVFD = (__SID |14), #define I_RECVFD I_RECVFD I_SWROPT = (__SID |19), #define I_SWROPT I_SWROPT I_GWROPT = (__SID |20), #define I_GWROPT I_GWROPT I_LIST = (__SID |21), #define I_LIST I_LIST I_PLINK = (__SID |22), #define I_PLINK I_PLINK I_PUNLINK = (__SID |23), #define I_PUNLINK I_PUNLINK I_FLUSHBAND = (__SID |28), #define I_FLUSHBAND I_FLUSHBAND I_CKBAND = (__SID |29), #define I_CKBAND I_CKBAND I_GETBAND = (__SID |30), #define I_GETBAND I_GETBAND I_ATMARK = (__SID |31), #define I_ATMARK I_ATMARK I_SETCLTIME = (__SID |32), #define I_SETCLTIME I_SETCLTIME I_GETCLTIME = (__SID |33), #define I_GETCLTIME I_GETCLTIME I_CANPUT = (__SID |34), #define I_CANPUT I_CANPUT }; int enum { FMNAMESZ = 8 }; #define FMNAMESZ FMNAMESZ /* Flush options. */ int enum { FLUSHR = 0x01, #define FLUSHR FLUSHR FLUSHW = 0x02, #define FLUSHW FLUSHW FLUSHRW = 0x03, #define FLUSHRW FLUSHRW FLUSHBAND = 0x04, #define FLUSHBAND FLUSHBAND }; int enum { S_INPUT = 0x0001, #define S_INPUT S_INPUT S_HIPRI = 0x0002, #define S_HIPRI S_HIPRI S_OUTPUT = 0x0004, #define S_OUTPUT S_OUTPUT S_MSG = 0x0008, #define S_MSG S_MSG S_ERROR = 0x0010, #define S_ERROR S_ERROR S_HANGUP = 0x0020, #define S_HANGUP S_HANGUP S_RDNORM = 0x0040, #define S_RDNORM S_RDNORM S_WRNORM = S_OUTPUT, #define S_WRNORM S_WRNORM S_RDBAND = 0x0080, #define S_RDBAND S_RDBAND S_WRBAND = 0x0100, #define S_WRBAND S_WRBAND S_BANDURG = 0x0200, #define S_BANDURG S_BANDURG }; int enum { RS_HIPRI = 0x01 }; #define RS_HIPRI RS_HIPRI /* Options for `I_SRDOPT'. */ int enum { RNORM = 0x0000, #define RNORM RNORM RMSGD = 0x0001, #define RMSGD RMSGD RMSGN = 0x0002, #define RMSGN RMSGN RPROTDAT = 0x0004, #define RPROTDAT RPROTDAT RPROTDIS = 0x0008, #define RPROTDIS RPROTDIS RPROTNORM = 0x0010, #define RPROTNORM RPROTNORM RPROTMASK = 0x001C, #define RPROTMASK RPROTMASK }; /* Possible mode for `I_SWROPT'. */ int enum { SNDZERO = 0x001, #define SNDZERO SNDZERO SNDPIPE = 0x002, #define SNDPIPE SNDPIPE }; int enum { ANYMARK = 0x01, #define ANYMARK ANYMARK LASTMARK = 0x02, #define LASTMARK LASTMARK }; /* Argument for `I_UNLINK'. */ int enum { MUXID_ALL = (-1) }; #define MUXID_ALL MUXID_ALL /* Macros for `getmsg', `getpmsg', `putmsg' and `putpmsg'. */ int enum { MSG_HIPRI = 0x01, #define MSG_HIPRI MSG_HIPRI MSG_ANY = 0x02, #define MSG_ANY MSG_ANY MSG_BAND = 0x04, #define MSG_BAND MSG_BAND }; /* Values returned by getmsg and getpmsg */ int enum { MORECTL = 1, #define MORECTL MORECTL MOREDATA = 2, #define MOREDATA MOREDATA }; struct bandinfo { unsigned char bi_pri; int bi_flag; }; struct strbuf { int maxlen; int len; char *buf; }; struct strpeek { struct strbuf ctlbuf; struct strbuf databuf; t_uscalar_t flags; }; struct strfdinsert { struct strbuf ctlbuf; struct strbuf databuf; t_uscalar_t flags; int fildes; int offset; }; struct strioctl { int ic_cmd; int ic_timout; int ic_len; char *ic_dp; }; struct strrecvfd { int fd; uid_t uid; gid_t gid; char __fill[8]; }; struct str_mlist { char l_name[FMNAMESZ + 1]; }; struct str_list { int sl_nmods; struct str_mlist *sl_modlist; }; int isastream(int fildes); int getmsg(int fildes, struct strbuf *ctlptr, struct strbuf *dataptr, int *flagsp); int getpmsg(int fildes, struct strbuf *ctlptr, struct strbuf *dataptr, int *bandp, int *flagsp); int ioctl(int fd, unsigned long int request, ...); int putmsg(int fildes, const struct strbuf *ctlptr, const struct strbuf *dataptr, int flags); int putpmsg(int fildes, const struct strbuf *ctlptr, const struct strbuf *dataptr, int band, int flags); int fattach(int fildes, const char *path); int fdetach(const char *path); #endif /* __RCC_STROPTS_H__ */
{ "pile_set_name": "Github" }
{ "baseUrl": "https://firebasedynamiclinks-ipv6.googleapis.com/", "servicePath": "", "description": "Programmatically creates and manages Firebase Dynamic Links.", "kind": "discovery#restDescription", "basePath": "", "id": "firebasedynamiclinks:v1", "documentationLink": "https://firebase.google.com/docs/dynamic-links/", "revision": "20171005", "discoveryVersion": "v1", "version_module": true, "schemas": { "SocialMetaTagInfo": { "properties": { "socialDescription": { "description": "A short description of the link. Optional.", "type": "string" }, "socialTitle": { "description": "Title to be displayed. Optional.", "type": "string" }, "socialImageLink": { "description": "An image url string. Optional.", "type": "string" } }, "id": "SocialMetaTagInfo", "description": "Parameters for social meta tag params.\nUsed to set meta tag data for link previews on social sites.", "type": "object" }, "AndroidInfo": { "description": "Android related attributes to the Dynamic Link.", "type": "object", "properties": { "androidPackageName": { "description": "Android package name of the app.", "type": "string" }, "androidMinPackageVersionCode": { "description": "Minimum version code for the Android app. If the installed app’s version\ncode is lower, then the user is taken to the Play Store.", "type": "string" }, "androidLink": { "description": "If specified, this overrides the ‘link’ parameter on Android.", "type": "string" }, "androidFallbackLink": { "description": "Link to open on Android if the app is not installed.", "type": "string" } }, "id": "AndroidInfo" }, "DynamicLinkWarning": { "description": "Dynamic Links warning messages.", "type": "object", "properties": { "warningMessage": { "description": "The warning message to help developers improve their requests.", "type": "string" }, "warningDocumentLink": { "description": "The document describing the warning, and helps resolve.", "type": "string" }, "warningCode": { "enumDescriptions": [ "Unknown code.", "The Android package does not match any in developer's DevConsole project.", "The Android minimum version code has to be a valid integer.", "Android package min version param is not needed, e.g. when\n'apn' is missing.", "Android link is not a valid URI.", "Android link param is not needed, e.g. when param 'al' and 'link' have\nthe same value..", "Android fallback link is not a valid URI.", "Android fallback link has an invalid (non http/https) URI scheme.", "The iOS bundle ID does not match any in developer's DevConsole project.", "The iPad bundle ID does not match any in developer's DevConsole project.", "iOS URL scheme is not needed, e.g. when 'ibi' are 'ipbi' are all missing.", "iOS app store ID format is incorrect, e.g. not numeric.", "iOS app store ID is not needed.", "iOS fallback link is not a valid URI.", "iOS fallback link has an invalid (non http/https) URI scheme.", "iPad fallback link is not a valid URI.", "iPad fallback link has an invalid (non http/https) URI scheme.", "Debug param format is incorrect.", "isAd param format is incorrect.", "Indicates a certain param is deprecated.", "Indicates certain paramater is not recognized.", "Indicates certain paramater is too long.", "Social meta tag image link is not a valid URI.", "Social meta tag image link has an invalid (non http/https) URI scheme.", "", "", "Dynamic Link URL length is too long.", "Dynamic Link URL contains fragments.", "The iOS bundle ID does not match with the given iOS store ID." ], "enum": [ "CODE_UNSPECIFIED", "NOT_IN_PROJECT_ANDROID_PACKAGE_NAME", "NOT_INTEGER_ANDROID_PACKAGE_MIN_VERSION", "UNNECESSARY_ANDROID_PACKAGE_MIN_VERSION", "NOT_URI_ANDROID_LINK", "UNNECESSARY_ANDROID_LINK", "NOT_URI_ANDROID_FALLBACK_LINK", "BAD_URI_SCHEME_ANDROID_FALLBACK_LINK", "NOT_IN_PROJECT_IOS_BUNDLE_ID", "NOT_IN_PROJECT_IPAD_BUNDLE_ID", "UNNECESSARY_IOS_URL_SCHEME", "NOT_NUMERIC_IOS_APP_STORE_ID", "UNNECESSARY_IOS_APP_STORE_ID", "NOT_URI_IOS_FALLBACK_LINK", "BAD_URI_SCHEME_IOS_FALLBACK_LINK", "NOT_URI_IPAD_FALLBACK_LINK", "BAD_URI_SCHEME_IPAD_FALLBACK_LINK", "BAD_DEBUG_PARAM", "BAD_AD_PARAM", "DEPRECATED_PARAM", "UNRECOGNIZED_PARAM", "TOO_LONG_PARAM", "NOT_URI_SOCIAL_IMAGE_LINK", "BAD_URI_SCHEME_SOCIAL_IMAGE_LINK", "NOT_URI_SOCIAL_URL", "BAD_URI_SCHEME_SOCIAL_URL", "LINK_LENGTH_TOO_LONG", "LINK_WITH_FRAGMENTS", "NOT_MATCHING_IOS_BUNDLE_ID_AND_STORE_ID" ], "description": "The warning code.", "type": "string" } }, "id": "DynamicLinkWarning" }, "DynamicLinkStats": { "properties": { "linkEventStats": { "description": "Dynamic Link event stats.", "type": "array", "items": { "$ref": "DynamicLinkEventStat" } } }, "id": "DynamicLinkStats", "description": "Analytics stats of a Dynamic Link for a given timeframe.", "type": "object" }, "NavigationInfo": { "properties": { "enableForcedRedirect": { "description": "If this option is on, FDL click will be forced to redirect rather than\nshow an interstitial page.", "type": "boolean" } }, "id": "NavigationInfo", "description": "Information of navigation behavior.", "type": "object" }, "IosInfo": { "properties": { "iosFallbackLink": { "description": "Link to open on iOS if the app is not installed.", "type": "string" }, "iosAppStoreId": { "description": "iOS App Store ID.", "type": "string" }, "iosIpadFallbackLink": { "description": "If specified, this overrides the ios_fallback_link value on iPads.", "type": "string" }, "iosIpadBundleId": { "description": "iPad bundle ID of the app.", "type": "string" }, "iosCustomScheme": { "description": "Custom (destination) scheme to use for iOS. By default, we’ll use the\nbundle ID as the custom scheme. Developer can override this behavior using\nthis param.", "type": "string" }, "iosBundleId": { "description": "iOS bundle ID of the app.", "type": "string" } }, "id": "IosInfo", "description": "iOS related attributes to the Dynamic Link..", "type": "object" }, "AnalyticsInfo": { "properties": { "itunesConnectAnalytics": { "$ref": "ITunesConnectAnalytics", "description": "iTunes Connect App Analytics." }, "googlePlayAnalytics": { "description": "Google Play Campaign Measurements.", "$ref": "GooglePlayAnalytics" } }, "id": "AnalyticsInfo", "description": "Tracking parameters supported by Dynamic Link.", "type": "object" }, "CreateShortDynamicLinkRequest": { "properties": { "suffix": { "$ref": "Suffix", "description": "Short Dynamic Link suffix. Optional." }, "dynamicLinkInfo": { "$ref": "DynamicLinkInfo", "description": "Information about the Dynamic Link to be shortened.\n[Learn more](https://firebase.google.com/docs/dynamic-links/android#create-a-dynamic-link-programmatically)." }, "longDynamicLink": { "description": "Full long Dynamic Link URL with desired query parameters specified.\nFor example,\n\"https://sample.app.goo.gl/?link=http://www.google.com&apn=com.sample\",\n[Learn more](https://firebase.google.com/docs/dynamic-links/android#create-a-dynamic-link-programmatically).", "type": "string" } }, "id": "CreateShortDynamicLinkRequest", "description": "Request to create a short Dynamic Link.", "type": "object" }, "DynamicLinkEventStat": { "description": "Dynamic Link event stat.", "type": "object", "properties": { "event": { "enum": [ "DYNAMIC_LINK_EVENT_UNSPECIFIED", "CLICK", "REDIRECT", "APP_INSTALL", "APP_FIRST_OPEN", "APP_RE_OPEN" ], "description": "Link event.", "type": "string", "enumDescriptions": [ "Unspecified type.", "Indicates that an FDL is clicked by users.", "Indicates that an FDL redirects users to fallback link.", "Indicates that an FDL triggers an app install from Play store, currently\nit's impossible to get stats from App store.", "Indicates that the app is opened for the first time after an install\ntriggered by FDLs", "Indicates that the app is opened via an FDL for non-first time." ] }, "platform": { "enumDescriptions": [ "Unspecified platform.", "Represents Android platform.\nAll apps and browsers on Android are classfied in this category.", "Represents iOS platform.\nAll apps and browsers on iOS are classfied in this category.", "Represents desktop.\nNote: other platforms like Windows, Blackberry, Amazon fall into this\ncategory." ], "enum": [ "DYNAMIC_LINK_PLATFORM_UNSPECIFIED", "ANDROID", "IOS", "DESKTOP" ], "description": "Requested platform.", "type": "string" }, "count": { "description": "The number of times this event occurred.", "format": "int64", "type": "string" } }, "id": "DynamicLinkEventStat" }, "GetIosPostInstallAttributionRequest": { "properties": { "iosVersion": { "description": "iOS version, ie: 9.3.5.\nConsider adding \"build\".", "type": "string" }, "visualStyle": { "description": "Strong match page information. Disambiguates between default UI and\ncustom page to present when strong match succeeds/fails to find cookie.", "type": "string", "enumDescriptions": [ "Unknown style.", "Default style.", "Custom style." ], "enum": [ "UNKNOWN_VISUAL_STYLE", "DEFAULT_STYLE", "CUSTOM_STYLE" ] }, "retrievalMethod": { "description": "App post install attribution retrieval information. Disambiguates\nmechanism (iSDK or developer invoked) to retrieve payload from\nclicked link.", "type": "string", "enumDescriptions": [ "Unknown method.", "iSDK performs a server lookup by device fingerprint in the background\nwhen app is first-opened; no API called by developer.", "iSDK performs a server lookup by device fingerprint upon a dev API call.", "iSDK performs a strong match only if weak match is found upon a dev\nAPI call." ], "enum": [ "UNKNOWN_PAYLOAD_RETRIEVAL_METHOD", "IMPLICIT_WEAK_MATCH", "EXPLICIT_WEAK_MATCH", "EXPLICIT_STRONG_AFTER_WEAK_MATCH" ] }, "sdkVersion": { "description": "Google SDK version.", "type": "string" }, "bundleId": { "description": "APP bundle ID.", "type": "string" }, "device": { "$ref": "DeviceInfo", "description": "Device information." }, "uniqueMatchLinkToCheck": { "description": "Possible unique matched link that server need to check before performing\nfingerprint match. If passed link is short server need to expand the link.\nIf link is long server need to vslidate the link.", "type": "string" }, "appInstallationTime": { "description": "App installation epoch time (https://en.wikipedia.org/wiki/Unix_time).\nThis is a client signal for a more accurate weak match.", "format": "int64", "type": "string" } }, "id": "GetIosPostInstallAttributionRequest", "description": "Request for iSDK to execute strong match flow for post-install attribution.\nThis is meant for iOS requests only. Requests from other platforms will\nnot be honored.", "type": "object" }, "CreateShortDynamicLinkResponse": { "description": "Response to create a short Dynamic Link.", "type": "object", "properties": { "warning": { "description": "Information about potential warnings on link creation.", "type": "array", "items": { "$ref": "DynamicLinkWarning" } }, "shortLink": { "description": "Short Dynamic Link value. e.g. https://abcd.app.goo.gl/wxyz", "type": "string" }, "previewLink": { "description": "Preivew link to show the link flow chart.", "type": "string" } }, "id": "CreateShortDynamicLinkResponse" }, "Suffix": { "description": "Short Dynamic Link suffix.", "type": "object", "properties": { "option": { "description": "Suffix option.", "type": "string", "enumDescriptions": [ "The suffix option is not specified, performs as NOT_GUESSABLE .", "Short Dynamic Link suffix is a base62 [0-9A-Za-z] encoded string of\na random generated 96 bit random number, which has a length of 17 chars.\nFor example, \"nlAR8U4SlKRZw1cb2\".\nIt prevents other people from guessing and crawling short Dynamic Links\nthat contain personal identifiable information.", "Short Dynamic Link suffix is a base62 [0-9A-Za-z] string starting with a\nlength of 4 chars. the length will increase when all the space is\noccupied." ], "enum": [ "OPTION_UNSPECIFIED", "UNGUESSABLE", "SHORT" ] } }, "id": "Suffix" }, "GooglePlayAnalytics": { "description": "Parameters for Google Play Campaign Measurements.\n[Learn more](https://developers.google.com/analytics/devguides/collection/android/v4/campaigns#campaign-params)", "type": "object", "properties": { "utmMedium": { "description": "Campaign medium; used to identify a medium such as email or cost-per-click.", "type": "string" }, "utmTerm": { "description": "Campaign term; used with paid search to supply the keywords for ads.", "type": "string" }, "utmSource": { "description": "Campaign source; used to identify a search engine, newsletter, or other\nsource.", "type": "string" }, "utmCampaign": { "description": "Campaign name; used for keyword analysis to identify a specific product\npromotion or strategic campaign.", "type": "string" }, "gclid": { "description": "[AdWords autotagging parameter](https://support.google.com/analytics/answer/1033981?hl=en);\nused to measure Google AdWords ads. This value is generated dynamically\nand should never be modified.", "type": "string" }, "utmContent": { "description": "Campaign content; used for A/B testing and content-targeted ads to\ndifferentiate ads or links that point to the same URL.", "type": "string" } }, "id": "GooglePlayAnalytics" }, "DynamicLinkInfo": { "description": "Information about a Dynamic Link.", "type": "object", "properties": { "link": { "description": "The link your app will open, You can specify any URL your app can handle.\nThis link must be a well-formatted URL, be properly URL-encoded, and use\nthe HTTP or HTTPS scheme. See 'link' parameters in the\n[documentation](https://firebase.google.com/docs/dynamic-links/create-manually).\n\nRequired.", "type": "string" }, "iosInfo": { "description": "iOS related information. See iOS related parameters in the\n[documentation](https://firebase.google.com/docs/dynamic-links/create-manually).", "$ref": "IosInfo" }, "socialMetaTagInfo": { "description": "Parameters for social meta tag params.\nUsed to set meta tag data for link previews on social sites.", "$ref": "SocialMetaTagInfo" }, "androidInfo": { "$ref": "AndroidInfo", "description": "Android related information. See Android related parameters in the\n[documentation](https://firebase.google.com/docs/dynamic-links/create-manually)." }, "navigationInfo": { "description": "Information of navigation behavior of a Firebase Dynamic Links.", "$ref": "NavigationInfo" }, "analyticsInfo": { "description": "Parameters used for tracking. See all tracking parameters in the\n[documentation](https://firebase.google.com/docs/dynamic-links/create-manually).", "$ref": "AnalyticsInfo" }, "dynamicLinkDomain": { "description": "Dynamic Links domain that the project owns, e.g. abcd.app.goo.gl\n[Learn more](https://firebase.google.com/docs/dynamic-links/android/receive)\non how to set up Dynamic Link domain associated with your Firebase project.\n\nRequired.", "type": "string" } }, "id": "DynamicLinkInfo" }, "ITunesConnectAnalytics": { "description": "Parameters for iTunes Connect App Analytics.", "type": "object", "properties": { "at": { "description": "Affiliate token used to create affiliate-coded links.", "type": "string" }, "ct": { "description": "Campaign text that developers can optionally add to any link in order to\ntrack sales from a specific marketing campaign.", "type": "string" }, "mt": { "description": "iTune media types, including music, podcasts, audiobooks and so on.", "type": "string" }, "pt": { "description": "Provider token that enables analytics for Dynamic Links from within iTunes\nConnect.", "type": "string" } }, "id": "ITunesConnectAnalytics" }, "DeviceInfo": { "description": "Signals associated with the device making the request.", "type": "object", "properties": { "screenResolutionWidth": { "description": "Device display resolution width.", "format": "int64", "type": "string" }, "deviceModelName": { "description": "Device model name.", "type": "string" }, "screenResolutionHeight": { "description": "Device display resolution height.", "format": "int64", "type": "string" }, "languageCode": { "description": "Device language code setting.", "type": "string" }, "timezone": { "description": "Device timezone setting.", "type": "string" } }, "id": "DeviceInfo" }, "GetIosPostInstallAttributionResponse": { "description": "Response for iSDK to execute strong match flow for post-install attribution.", "type": "object", "properties": { "utmCampaign": { "description": "Scion campaign value to be propagated by iSDK to Scion at post-install.", "type": "string" }, "fallbackLink": { "description": "The link to navigate to update the app if min version is not met.\nThis is either (in order): 1) fallback link (from ?ifl= parameter, if\nspecified by developer) or 2) AppStore URL (from ?isi= parameter, if\nspecified), or 3) the payload link (from required link= parameter).", "type": "string" }, "requestedLink": { "description": "Entire FDL (short or long) attributed post-install via one of several\ntechniques (fingerprint, copy unique).", "type": "string" }, "utmMedium": { "description": "Scion medium value to be propagated by iSDK to Scion at post-install.", "type": "string" }, "utmSource": { "description": "Scion source value to be propagated by iSDK to Scion at post-install.", "type": "string" }, "isStrongMatchExecutable": { "description": "Instruction for iSDK to attemmpt to perform strong match. For instance,\nif browser does not support/allow cookie or outside of support browsers,\nthis will be false.", "type": "boolean" }, "appMinimumVersion": { "description": "The minimum version for app, specified by dev through ?imv= parameter.\nReturn to iSDK to allow app to evaluate if current version meets this.", "type": "string" }, "deepLink": { "description": "The deep-link attributed post-install via one of several techniques\n(fingerprint, copy unique).", "type": "string" }, "invitationId": { "description": "Invitation ID attributed post-install via one of several techniques\n(fingerprint, copy unique).", "type": "string" }, "attributionConfidence": { "enumDescriptions": [ "Unset.", "Weak confidence, more than one matching link found or link suspected to\nbe false positive", "Default confidence, match based on fingerprint", "Unique confidence, match based on \"unique match link to check\" or other\nmeans" ], "enum": [ "UNKNOWN_ATTRIBUTION_CONFIDENCE", "WEAK", "DEFAULT", "UNIQUE" ], "description": "The confidence of the returned attribution.", "type": "string" }, "externalBrowserDestinationLink": { "description": "User-agent specific custom-scheme URIs for iSDK to open. This will be set\naccording to the user-agent tha the click was originally made in. There is\nno Safari-equivalent custom-scheme open URLs.\nie: googlechrome://www.example.com\nie: firefox://open-url?url=http://www.example.com\nie: opera-http://example.com", "type": "string" }, "matchMessage": { "description": "Describes why match failed, ie: \"discarded due to low confidence\".\nThis message will be publicly visible.", "type": "string" }, "resolvedLink": { "description": "The entire FDL, expanded from a short link. It is the same as the\nrequested_link, if it is long. Parameters from this should not be\nused directly (ie: server can default utm_[campaign|medium|source]\nto a value when requested_link lack them, server determine the best\nfallback_link when requested_link specifies \u003e1 fallback links).", "type": "string" } }, "id": "GetIosPostInstallAttributionResponse" } }, "icons": { "x16": "http://www.google.com/images/icons/product/search-16.gif", "x32": "http://www.google.com/images/icons/product/search-32.gif" }, "protocol": "rest", "canonicalName": "Firebase Dynamic Links", "auth": { "oauth2": { "scopes": { "https://www.googleapis.com/auth/firebase": { "description": "View and administer all your Firebase data and settings" } } } }, "rootUrl": "https://firebasedynamiclinks-ipv6.googleapis.com/", "ownerDomain": "google.com", "name": "firebasedynamiclinks", "batchPath": "batch", "title": "Firebase Dynamic Links API", "ownerName": "Google", "resources": { "shortLinks": { "methods": { "create": { "path": "v1/shortLinks", "id": "firebasedynamiclinks.shortLinks.create", "description": "Creates a short Dynamic Link given either a valid long Dynamic Link or\ndetails such as Dynamic Link domain, Android and iOS app information.\nThe created short Dynamic Link will not expire.\n\nRepeated calls with the same long Dynamic Link or Dynamic Link information\nwill produce the same short Dynamic Link.\n\nThe Dynamic Link domain in the request must be owned by requester's\nFirebase project.", "request": { "$ref": "CreateShortDynamicLinkRequest" }, "response": { "$ref": "CreateShortDynamicLinkResponse" }, "parameterOrder": [], "httpMethod": "POST", "scopes": [ "https://www.googleapis.com/auth/firebase" ], "parameters": {}, "flatPath": "v1/shortLinks" } } }, "v1": { "methods": { "getLinkStats": { "description": "Fetches analytics stats of a short Dynamic Link for a given\nduration. Metrics include number of clicks, redirects, installs,\napp first opens, and app reopens.", "response": { "$ref": "DynamicLinkStats" }, "parameterOrder": [ "dynamicLink" ], "httpMethod": "GET", "parameters": { "durationDays": { "location": "query", "description": "The span of time requested in days.", "format": "int64", "type": "string" }, "dynamicLink": { "location": "path", "description": "Dynamic Link URL. e.g. https://abcd.app.goo.gl/wxyz", "required": true, "type": "string" } }, "scopes": [ "https://www.googleapis.com/auth/firebase" ], "flatPath": "v1/{dynamicLink}/linkStats", "path": "v1/{dynamicLink}/linkStats", "id": "firebasedynamiclinks.getLinkStats" }, "installAttribution": { "response": { "$ref": "GetIosPostInstallAttributionResponse" }, "parameterOrder": [], "httpMethod": "POST", "parameters": {}, "scopes": [ "https://www.googleapis.com/auth/firebase" ], "flatPath": "v1/installAttribution", "path": "v1/installAttribution", "id": "firebasedynamiclinks.installAttribution", "request": { "$ref": "GetIosPostInstallAttributionRequest" }, "description": "Get iOS strong/weak-match info for post-install attribution." } } } }, "parameters": { "quotaUser": { "location": "query", "description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.", "type": "string" }, "pp": { "description": "Pretty-print response.", "type": "boolean", "default": "true", "location": "query" }, "bearer_token": { "location": "query", "description": "OAuth bearer token.", "type": "string" }, "oauth_token": { "location": "query", "description": "OAuth 2.0 token for the current user.", "type": "string" }, "upload_protocol": { "location": "query", "description": "Upload protocol for media (e.g. \"raw\", \"multipart\").", "type": "string" }, "prettyPrint": { "location": "query", "description": "Returns response with indentations and line breaks.", "type": "boolean", "default": "true" }, "fields": { "description": "Selector specifying which fields to include in a partial response.", "type": "string", "location": "query" }, "uploadType": { "location": "query", "description": "Legacy upload protocol for media (e.g. \"media\", \"multipart\").", "type": "string" }, "callback": { "location": "query", "description": "JSONP", "type": "string" }, "$.xgafv": { "description": "V1 error format.", "type": "string", "enumDescriptions": [ "v1 error format", "v2 error format" ], "location": "query", "enum": [ "1", "2" ] }, "alt": { "description": "Data format for response.", "default": "json", "enum": [ "json", "media", "proto" ], "type": "string", "enumDescriptions": [ "Responses with Content-Type of application/json", "Media download with context-dependent Content-Type", "Responses with Content-Type of application/x-protobuf" ], "location": "query" }, "access_token": { "description": "OAuth access token.", "type": "string", "location": "query" }, "key": { "description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.", "type": "string", "location": "query" } }, "version": "v1" }
{ "pile_set_name": "Github" }
// Only for Dygraph TypeScript definitions declare module 'src/external/dygraph' { export type DygraphData = DygraphValue[][] type Data = string | DygraphData | google.visualization.DataTable export type DygraphValue = string | number | Date | null interface DygraphAxis { bounds: [number, number] label: string prefix: string suffix: string base: string scale: string } export interface DygraphSeries { [x: string]: { axis: string } } interface PerSeriesOptions { /** * Set to either 'y1' or 'y2' to assign a series to a y-axis (primary or secondary). Must be * set per-series. */ axis?: 'y1' | 'y2' /** * A per-series color definition. Used in conjunction with, and overrides, the colors option. */ color?: string /** * Draw a small dot at each point, in addition to a line going through the point. This makes * the individual data points easier to see, but can increase visual clutter in the chart. * The small dot can be replaced with a custom rendering by supplying a <a * href='#drawPointCallback'>drawPointCallback</a>. */ drawPoints?: boolean /** * Error bars (or custom bars) for each series are drawn in the same color as the series, but * with partial transparency. This sets the transparency. A value of 0.0 means that the error * bars will not be drawn, whereas a value of 1.0 means that the error bars will be as dark * as the line for the series itself. This can be used to produce chart lines whose thickness * varies at each point. */ fillAlpha?: number /** * Should the area underneath the graph be filled? This option is not compatible with error * bars. This may be set on a <a href='per-axis.html'>per-series</a> basis. */ fillGraph?: boolean /** * The size in pixels of the dot drawn over highlighted points. */ highlightCircleSize?: number /** * The size of the dot to draw on each point in pixels (see drawPoints). A dot is always * drawn when a point is "isolated", i.e. there is a missing point on either side of it. This * also controls the size of those dots. */ pointSize?: number /** * Mark this series for inclusion in the range selector. The mini plot curve will be an * average of all such series. If this is not specified for any series, the default behavior * is to average all the series. Setting it for one series will result in that series being * charted alone in the range selector. */ showInRangeSelector?: boolean /** * When set, display the graph as a step plot instead of a line plot. This option may either * be set for the whole graph or for single series. */ stepPlot?: boolean /** * Draw a border around graph lines to make crossing lines more easily distinguishable. * Useful for graphs with many lines. */ strokeBorderWidth?: number /** * Color for the line border used if strokeBorderWidth is set. */ strokeBorderColor?: string /** * A custom pattern array where the even index is a draw and odd is a space in pixels. If * null then it draws a solid line. The array should have a even length as any odd lengthed * array could be expressed as a smaller even length array. This is used to create dashed * lines. */ strokePattern?: number[] /** * The width of the lines connecting data points. This can be used to increase the contrast * or some graphs. */ strokeWidth?: number } interface PerAxisOptions { /** * Color for x- and y-axis labels. This is a CSS color string. */ axisLabelColor?: string /** * Size of the font (in pixels) to use in the axis labels, both x- and y-axis. */ axisLabelFontSize?: number /** * Function to call to format the tick values that appear along an axis. This is usually set * on a <a href='per-axis.html'>per-axis</a> basis. */ axisLabelFormatter?: ( v: number | Date, granularity: number, opts: (name: string) => any, dygraph: Dygraph ) => any /** * Width (in pixels) of the containing divs for x- and y-axis labels. For the y-axis, this * also controls the width of the y-axis. Note that for the x-axis, this is independent from * pixelsPerLabel, which controls the spacing between labels. */ axisLabelWidth?: number /** * Color of the x- and y-axis lines. Accepts any value which the HTML canvas strokeStyle * attribute understands, e.g. 'black' or 'rgb(0, 100, 255)'. */ axisLineColor?: string /** * Thickness (in pixels) of the x- and y-axis lines. */ axisLineWidth?: number /** * The size of the line to display next to each tick mark on x- or y-axes. */ axisTickSize?: number /** * Whether to draw the specified axis. This may be set on a per-axis basis to define the * visibility of each axis separately. Setting this to false also prevents axis ticks from * being drawn and reclaims the space for the chart grid/lines. */ drawAxis?: boolean /** * The color of the gridlines. This may be set on a per-axis basis to define each axis' grid * separately. */ gridLineColor?: string /** * A custom pattern array where the even index is a draw and odd is a space in pixels. If * null then it draws a solid line. The array should have a even length as any odd lengthed * array could be expressed as a smaller even length array. This is used to create dashed * gridlines. */ gridLinePattern?: number[] /** * Thickness (in pixels) of the gridlines drawn under the chart. The vertical/horizontal * gridlines can be turned off entirely by using the drawXGrid and drawYGrid options. This * may be set on a per-axis basis to define each axis' grid separately. */ gridLineWidth?: number /** * Only valid for y and y2, has no effect on x: This option defines whether the y axes should * align their ticks or if they should be independent. Possible combinations: 1.) y=true, * y2=false (default): y is the primary axis and the y2 ticks are aligned to the the ones of * y. (only 1 grid) 2.) y=false, y2=true: y2 is the primary axis and the y ticks are aligned * to the the ones of y2. (only 1 grid) 3.) y=true, y2=true: Both axis are independent and * have their own ticks. (2 grids) 4.) y=false, y2=false: Invalid configuration causes an * error. */ independentTicks?: boolean /** * When set for the y-axis or x-axis, the graph shows that axis in log scale. Any values less * than or equal to zero are not displayed. Showing log scale with ranges that go below zero * will result in an unviewable graph. * * Not compatible with showZero. connectSeparatedPoints is ignored. This is ignored for * date-based x-axes. */ logscale?: boolean /** * When displaying numbers in normal (not scientific) mode, large numbers will be displayed * with many trailing zeros (e.g. 100000000 instead of 1e9). This can lead to unwieldy y-axis * labels. If there are more than <code>maxNumberWidth</code> digits to the left of the * decimal in a number, dygraphs will switch to scientific notation, even when not operating * in scientific mode. If you'd like to see all those digits, set this to something large, * like 20 or 30. */ maxNumberWidth?: number /** * Number of pixels to require between each x- and y-label. Larger values will yield a * sparser axis with fewer ticks. This is set on a <a href='per-axis.html'>per-axis</a> * basis. */ pixelsPerLabel?: number /** * By default, dygraphs displays numbers with a fixed number of digits after the decimal * point. If you'd prefer to have a fixed number of significant figures, set this option to * that number of sig figs. A value of 2, for instance, would cause 1 to be display as 1.0 * and 1234 to be displayed as 1.23e+3. */ sigFigs?: number /** * This lets you specify an arbitrary function to generate tick marks on an axis. The tick * marks are an array of (value, label) pairs. The built-in functions go to great lengths to * choose good tick marks so, if you set this option, you'll most likely want to call one of * them and modify the result. See dygraph-tickers.js for an extensive discussion. This is * set on a <a href='per-axis.html'>per-axis</a> basis. */ ticker?: ( min: number, max: number, pixels: number, opts: (name: string) => any, dygraph: Dygraph, vals: number[] ) => Array<{v: number; label: string}> /** * Function to provide a custom display format for the values displayed on mouseover. This * does not affect the values that appear on tick marks next to the axes. To format those, * see axisLabelFormatter. This is usually set on a <a href='per-axis.html'>per-axis</a> * basis. */ valueFormatter?: ( v: number, opts: (name: string) => any, seriesName: string, dygraph: Dygraph, row: number, col: number ) => any /** * Explicitly set the vertical range of the graph to [low, high]. This may be set on a * per-axis basis to define each y-axis separately. If either limit is unspecified, it will * be calculated automatically (e.g. [null, 30] to automatically calculate just the lower * bound) */ valueRange?: number[] /** * Whether to display gridlines in the chart. This may be set on a per-axis basis to define * the visibility of each axis' grid separately. */ drawGrid?: boolean /** * Show K/M/B for thousands/millions/billions on y-axis. */ labelsKMB?: boolean /** * Show k/M/G for kilo/Mega/Giga on y-axis. This is different than <code>labelsKMB</code> in * that it uses base 2, not 10. */ labelsKMG2?: boolean } export interface SeriesLegendData { /** * Assigned or generated series color */ color: string /** * Series line dash */ dashHTML: string /** * Whether currently focused or not */ isHighlighted: boolean /** * Whether the series line is inside the selected/zoomed region */ isVisible: boolean /** * Assigned label to this series */ label: string /** * Generated label html for this series */ labelHTML: string /** * y value of this series */ y: number /** * Generated html for y value */ yHTML: string } interface LegendData { /** * x value of highlighted points */ x: number /** * Generated HTML for x value */ xHTML: string /** * Series data for the highlighted points */ series: SeriesLegendData[] /** * Dygraph object for this graph */ dygraph: Dygraph } interface SeriesProperties { name: string column: number visible: boolean color: string axis: number } interface Area { x: number y: number w: number h: number } /** * Point structure. * * xval_* and yval_* are the original unscaled data values, * while x_* and y_* are scaled to the range (0.0-1.0) for plotting. * yval_stacked is the cumulative Y value used for stacking graphs, * and bottom/top/minus/plus are used for error bar graphs. */ interface Point { idx: number name: string x?: number xval?: number y_bottom?: number y?: number y_stacked?: number y_top?: number yval_minus?: number yval?: number yval_plus?: number yval_stacked?: number annotation?: dygraphs.Annotation } interface Annotation { /** The name of the series to which the annotated point belongs. */ series: string /** * The x value of the point. This should be the same as the value * you specified in your CSV file, e.g. "2010-09-13". * You must set either x or xval. */ x?: number | string /** * numeric value of the point, or millis since epoch. */ xval?: number /* Text that will appear on the annotation's flag. */ shortText?: string /** A longer description of the annotation which will appear when the user hovers over it. */ text?: string /** * Specify in place of shortText to mark the annotation with an image rather than text. * If you specify this, you must specify width and height. */ icon?: string /* Width (in pixels) of the annotation flag or icon. */ width?: number /** Height (in pixels) of the annotation flag or icon. */ height?: number /* CSS class to use for styling the annotation. */ cssClass?: string /* Height of the tick mark (in pixels) connecting the point to its flag or icon. */ tickHeight?: number /* If true, attach annotations to the x-axis, rather than to actual points. */ attachAtBottom?: boolean div?: HTMLDivElement /** This function is called whenever the user clicks on this annotation. */ clickHandler?: ( annotation: dygraphs.Annotation, point: Point, dygraph: Dygraph, event: MouseEvent<Element> ) => any /** This function is called whenever the user mouses over this annotation. */ mouseOverHandler?: ( annotation: dygraphs.Annotation, point: Point, dygraph: Dygraph, event: MouseEvent<Element> ) => any /** This function is called whenever the user mouses out of this annotation. */ mouseOutHandler?: ( annotation: dygraphs.Annotation, point: Point, dygraph: Dygraph, event: MouseEvent<Element> ) => any /** this function is called whenever the user double-clicks on this annotation. */ dblClickHandler?: ( annotation: dygraphs.Annotation, point: Point, dygraph: Dygraph, event: MouseEvent<Element> ) => any } type Axis = 'x' | 'y' | 'y2' declare class DygraphClass { // Tick granularities (passed to ticker). public static SECONDLY: number public static TWO_SECONDLY: number public static FIVE_SECONDLY: number public static TEN_SECONDLY: number public static THIRTY_SECONDLY: number public static MINUTELY: number public static TWO_MINUTELY: number public static FIVE_MINUTELY: number public static TEN_MINUTELY: number public static THIRTY_MINUTELY: number public static HOURLY: number public static TWO_HOURLY: number public static SIX_HOURLY: number public static DAILY: number public static TWO_DAILY: number public static WEEKLY: number public static MONTHLY: number public static QUARTERLY: number public static BIANNUAL: number public static ANNUAL: number public static DECADAL: number public static CENTENNIAL: number public static NUM_GRANULARITIES: number public static defaultInteractionModel: any public static DOTTED_LINE: number[] public static DASHED_LINE: number[] public static DOT_DASH_LINE: number[] public static Plotters: { errorPlotter: any linePlotter: any fillPlotter: any } // tslint:disable-next-line:variable-name public width_: number public graphDiv: HTMLElement constructor( container: HTMLElement | string, data: DygraphData | (() => DygraphData), options?: Options ) /** * Returns the zoomed status of the chart for one or both axes. * * Axis is an optional parameter. Can be set to 'x' or 'y'. * * The zoomed status for an axis is set whenever a user zooms using the mouse * or when the dateWindow or valueRange are updated (unless the * isZoomedIgnoreProgrammaticZoom option is also specified). */ public isZoomed(axis?: 'x' | 'y'): boolean public predraw_(): () => void public resizeElements_(): () => void /** * Returns information about the Dygraph object, including its containing ID. */ public toString(): string /** * Returns the current value for an option, as set in the constructor or via * updateOptions. You may pass in an (optional) series name to get per-series * values for the option. * * All values returned by this method should be considered immutable. If you * modify them, there is no guarantee that the changes will be honored or that * dygraphs will remain in a consistent state. If you want to modify an option, * use updateOptions() instead. * * @param {string} name The name of the option (e.g. 'strokeWidth') * @param {string=} opt_seriesName Series name to get per-series values. * @return {*} The value of the option. */ public getOption(name: string, seriesName?: string): any /** * Get the value of an option on a per-axis basis. */ public getOptionForAxis(name: string, axis: dygraphs.Axis): any /** * Returns the current rolling period, as set by the user or an option. */ public rollPeriod(): number /** * Returns the currently-visible x-range. This can be affected by zooming, * panning or a call to updateOptions. * Returns a two-element array: [left, right]. * If the Dygraph has dates on the x-axis, these will be millis since epoch. */ public xAxisRange(): [number, number] /** * Returns the lower- and upper-bound x-axis values of the data set. */ public xAxisExtremes(): [number, number] /** * Returns the currently-visible y-range for an axis. This can be affected by * zooming, panning or a call to updateOptions. Axis indices are zero-based. If * called with no arguments, returns the range of the first axis. * Returns a two-element array: [bottom, top]. */ public yAxisRange(idx?: number): [number, number] /** * Returns the currently-visible y-ranges for each axis. This can be affected by * zooming, panning, calls to updateOptions, etc. * Returns an array of [bottom, top] pairs, one for each y-axis. */ public yAxisRanges(): Array<[number, number]> /** * Convert from data coordinates to canvas/div X/Y coordinates. * If specified, do this conversion for the coordinate system of a particular * axis. Uses the first axis by default. * Returns a two-element array: [X, Y] * * Note: use toDomXCoord instead of toDomCoords(x, null) and use toDomYCoord * instead of toDomCoords(null, y, axis). */ public toDomCoords(x: number, y: number, axis?: number): [number, number] /** * Convert from data x coordinates to canvas/div X coordinate. * If specified, do this conversion for the coordinate system of a particular * axis. * Returns a single value or null if x is null. */ public toDomXCoord(x: number): number /** * Convert from data y coordinates to canvas/div Y coordinate and optional * axis. Uses the first axis by default. * * returns a single value or null if y is null. */ public toDomYCoord(y: number, axis?: number): number /** * Convert from canvas/div coords to data coordinates. * If specified, do this conversion for the coordinate system of a particular * axis. Uses the first axis by default. * Returns a two-element array: [X, Y]. * * Note: use toDataXCoord instead of toDataCoords(x, null) and use toDataYCoord * instead of toDataCoords(null, y, axis). */ public toDataCoords(x: number, y: number, axis?: number): [number, number] /** * Convert from canvas/div x coordinate to data coordinate. * * If x is null, this returns null. */ public toDataXCoord(x: number): number /** * Convert from canvas/div y coord to value. * * If y is null, this returns null. * if axis is null, this uses the first axis. */ public toDataYCoord(y: number, axis?: number): number /** * Converts a y for an axis to a percentage from the top to the * bottom of the drawing area. * * If the coordinate represents a value visible on the canvas, then * the value will be between 0 and 1, where 0 is the top of the canvas. * However, this method will return values outside the range, as * values can fall outside the canvas. * * If y is null, this returns null. * if axis is null, this uses the first axis. * * @param {number} y The data y-coordinate. * @param {number} [axis] The axis number on which the data coordinate lives. * @return {number} A fraction in [0, 1] where 0 = the top edge. */ public toPercentYCoord(y: number, axis?: number): number /** * Converts an x value to a percentage from the left to the right of * the drawing area. * * If the coordinate represents a value visible on the canvas, then * the value will be between 0 and 1, where 0 is the left of the canvas. * However, this method will return values outside the range, as * values can fall outside the canvas. * * If x is null, this returns null. * @param {number} x The data x-coordinate. * @return {number} A fraction in [0, 1] where 0 = the left edge. */ public toPercentXCoord(x: number): number /** * Returns the number of columns (including the independent variable). */ public numColumns(): number /** * Returns the number of rows (excluding any header/label row). */ public numRows(): number /** * Returns the value in the given row and column. If the row and column exceed * the bounds on the data, returns null. Also returns null if the value is * missing. * @param {number} row The row number of the data (0-based). Row 0 is the * first row of data, not a header row. * @param {number} col The column number of the data (0-based) * @return {number} The value in the specified cell or null if the row/col * were out of range. */ public getValue(row: number, col: number): number /** * Detach DOM elements in the dygraph and null out all data references. * Calling this when you're done with a dygraph can dramatically reduce memory * usage. See, e.g., the tests/perf.html example. */ public destroy(): void /** * Return the list of colors. This is either the list of colors passed in the * attributes or the autogenerated list of rgb(r,g,b) strings. * This does not return colors for invisible series. * @return {Array.<string>} The list of colors. */ public getColors(): string[] /** * Returns a few attributes of a series, i.e. its color, its visibility, which * axis it's assigned to, and its column in the original data. * Returns null if the series does not exist. * Otherwise, returns an object with column, visibility, color and axis properties. * The "axis" property will be set to 1 for y1 and 2 for y2. * The "column" property can be fed back into getValue(row, column) to get * values for this series. */ public getPropertiesForSeries(seriesName: string): dygraphs.SeriesProperties /** * Reset the zoom to the original view coordinates. This is the same as * double-clicking on the graph. */ public resetZoom(): void /** * Get the current graph's area object. */ public getArea(): dygraphs.Area /** * Convert a mouse event to DOM coordinates relative to the graph origin. * * Returns a two-element array: [X, Y]. */ public eventToDomCoords(event: MouseEvent<Element>): [number, number] /** * Manually set the selected points and display information about them in the * legend. The selection can be cleared using clearSelection() and queried * using getSelection(). * @param {number} row Row number that should be highlighted (i.e. appear with * hover dots on the chart). * @param {seriesName} optional series name to highlight that series with the * the highlightSeriesOpts setting. * @param { locked } optional If true, keep seriesName selected when mousing * over the graph, disabling closest-series highlighting. Call clearSelection() * to unlock it. */ public setSelection( row: number | boolean, seriesName?: string, locked?: boolean ): void /** * Clears the current selection (i.e. points that were highlighted by moving * the mouse over the chart). */ public clearSelection(): void /** * Returns the number of the currently selected row. To get data for this row, * you can use the getValue method. * @return {number} row number, or -1 if nothing is selected */ public getSelection(): number /** * Returns the name of the currently-highlighted series. * Only available when the highlightSeriesOpts option is in use. */ public getHighlightSeries(): string /** * Returns true if the currently-highlighted series was locked * via setSelection(..., seriesName, true). */ public isSeriesLocked(): boolean /** * Returns the number of y-axes on the chart. */ public numAxes(): number /** * Changes various properties of the graph. These can include: * <ul> * <li>file: changes the source data for the graph</li> * <li>errorBars: changes whether the data contains stddev</li> * </ul> * * There's a huge variety of options that can be passed to this method. For a * full list, see http://dygraphs.com/options.html. * * @param {Object} input_attrs The new properties and values * @param {boolean} block_redraw Usually the chart is redrawn after every * call to updateOptions(). If you know better, you can pass true to * explicitly block the redraw. This can be useful for chaining * updateOptions() calls, avoiding the occasional infinite loop and * preventing redraws when it's not necessary (e.g. when updating a * callback). */ public updateOptions(inputAttrs: Options, blockRedraw?: boolean): void /** * Resizes the dygraph. If no parameters are specified, resizes to fill the * containing div (which has presumably changed size since the dygraph was * instantiated. If the width/height are specified, the div will be resized. * * This is far more efficient than destroying and re-instantiating a * Dygraph, since it doesn't have to reparse the underlying data. * * @param {number} width Width (in pixels) * @param {number} height Height (in pixels) */ public resize(width?: number, height?: number): void /** * Adjusts the number of points in the rolling average. Updates the graph to * reflect the new averaging period. * @param {number} length Number of points over which to average the data. */ public adjustRoll(length: number): void /** * Returns a boolean array of visibility statuses. */ public visibility(): boolean[] /** * Changes the visiblity of a series. * * @param {number} num the series index * @param {boolean} value true or false, identifying the visibility. */ public setVisibility(num: number, value: boolean): void /** * Update the list of annotations and redraw the chart. * See dygraphs.com/annotations.html for more info on how to use annotations. * @param ann {Array} An array of annotation objects. * @param suppressDraw {Boolean} Set to "true" to block chart redraw (optional). */ public setAnnotations( ann: dygraphs.Annotation[], suppressDraw?: boolean ): void /** * Return the list of annotations. */ public annotations(): dygraphs.Annotation[] /** * Get the list of label names for this graph. The first column is the * x-axis, so the data series names start at index 1. * * Returns null when labels have not yet been defined. */ public getLabels(): string[] /** * Get the index of a series (column) given its name. The first column is the * x-axis, so the data series start with index 1. */ public indexFromSetName(name: string): number /** * Trigger a callback when the dygraph has drawn itself and is ready to be * manipulated. This is primarily useful when dygraphs has to do an XHR for the * data (i.e. a URL is passed as the data source) and the chart is drawn * asynchronously. If the chart has already drawn, the callback will fire * immediately. * * This is a good place to call setAnnotations(). */ public ready(callback: (g: Dygraph) => any): void } export interface Options extends PerSeriesOptions, PerAxisOptions { /** * Set this option to animate the transition between zoom windows. Applies to programmatic * and interactive zooms. Note that if you also set a drawCallback, it will be called several * times on each zoom. If you set a zoomCallback, it will only be called after the animation * is complete. */ animatedZooms?: boolean /** * If provided, this function is called whenever the user clicks on an annotation. */ annotationClickHandler?: ( annotation: dygraphs.Annotation, point: Point, dygraph: Dygraph, event: MouseEvent<Element> ) => any /** * If provided, this function is called whenever the user double-clicks on an annotation. */ annotationDblClickHandler?: ( annotation: dygraphs.Annotation, point: Point, dygraph: Dygraph, event: MouseEvent<Element> ) => any /** * If provided, this function is called whenever the user mouses out of an annotation. */ annotationMouseOutHandler?: ( annotation: dygraphs.Annotation, point: Point, dygraph: Dygraph, event: MouseEvent<Element> ) => any /** * If provided, this function is called whenever the user mouses over an annotation. */ annotationMouseOverHandler?: ( annotation: dygraphs.Annotation, point: Point, dygraph: Dygraph, event: MouseEvent<Element> ) => any /** * Defines per-axis options. Valid keys are 'x', 'y' and 'y2'. Only some options may be set * on a per-axis basis. If an option may be set in this way, it will be noted on this page. * See also documentation on <a href='http://dygraphs.com/per-axis.html'>per-series and * per-axis options</a>. */ axes?: { x?: PerAxisOptions y?: PerAxisOptions y2?: PerAxisOptions } /** * A function to call when the canvas is clicked. */ clickCallback?: ( e: MouseEvent<Element>, xval: number, points: Point[] ) => any /** * If <strong>colors</strong> is not specified, saturation of the automatically-generated * data series colors. (0.0-1.0). */ colorSaturation?: number /** * If colors is not specified, value of the data series colors, as in hue/saturation/value. * (0.0-1.0, default 0.5) */ colorValue?: number /** * List of colors for the data series. These can be of the form "#AABBCC" or * "rgb(255,100,200)" or "yellow", etc. If not specified, equally-spaced points around a * color wheel are used. Overridden by the 'color' option. */ colors?: string[] /** * Usually, when Dygraphs encounters a missing value in a data series, it interprets this as * a gap and draws it as such. If, instead, the missing values represents an x-value for * which only a different series has data, then you'll want to connect the dots by setting * this to true. To explicitly include a gap with this option set, use a value of NaN. */ connectSeparatedPoints?: boolean /** * When set, parse each CSV cell as "low;middle;high". Error bars will be drawn for each * point between low and high, with the series itself going through middle. */ customBars?: boolean /** * Custom DataHandler. This is an advanced customization. See http://bit.ly/151E7Aq. */ dataHandler?: any /** * Initially zoom in on a section of the graph. Is of the form [earliest, latest], where * earliest/latest are milliseconds since epoch. If the data for the x-axis is numeric, the * values in dateWindow must also be numbers. */ dateWindow?: number[] /** * The delimiter to look for when separating fields of a CSV file. Setting this to a tab is * not usually necessary, since tab-delimited data is auto-detected. */ delimiter?: string /** * Unless it's run in scientific mode (see the <code>sigFigs</code> option), dygraphs * displays numbers with <code>digitsAfterDecimal</code> digits after the decimal point. * Trailing zeros are not displayed, so with a value of 2 you'll get '0', '0.1', '0.12', * '123.45' but not '123.456' (it will be rounded to '123.46'). Numbers with absolute value * less than 0.1^digitsAfterDecimal (i.e. those which would show up as '0.00') will be * displayed in scientific notation. */ digitsAfterDecimal?: number /** * Only applies when Dygraphs is used as a GViz chart. Causes string columns following a data * series to be interpreted as annotations on points in that series. This is the same format * used by Google's AnnotatedTimeLine chart. */ displayAnnotations?: boolean /** * When set, draw the X axis at the Y=0 position and the Y axis at the X=0 position if those * positions are inside the graph's visible area. Otherwise, draw the axes at the bottom or * left graph edge as usual. */ drawAxesAtZero?: boolean /** * When set, this callback gets called every time the dygraph is drawn. This includes the * initial draw, after zooming and repeatedly while panning. */ // tslint:disable-next-line:variable-name drawCallback?: (dygraph: Dygraph, is_initial: boolean) => any /** * Draw points at the edges of gaps in the data. This improves visibility of small data * segments or other data irregularities. */ drawGapEdgePoints?: boolean /** * Draw a custom item when a point is highlighted. Default is a small dot matching the * series color. This method should constrain drawing to within pointSize pixels from (cx, * cy) Also see <a href='#drawPointCallback'>drawPointCallback</a> */ drawHighlightPointCallback?: ( g: Dygraph, seriesName: string, canvasContext: CanvasRenderingContext2D, cx: number, cy: number, color: string, pointSize: number ) => any /** * Draw a custom item when drawPoints is enabled. Default is a small dot matching the series * color. This method should constrain drawing to within pointSize pixels from (cx, cy). * Also see <a href='#drawHighlightPointCallback'>drawHighlightPointCallback</a> */ drawPointCallback?: ( g: Dygraph, seriesName: string, canvasContext: CanvasRenderingContext2D, cx: number, cy: number, color: string, pointSize: number ) => any /** * Does the data contain standard deviations? Setting this to true alters the input format. */ errorBars?: boolean /** * Sets the data being displayed in the chart. This can only be set when calling * updateOptions; it cannot be set from the constructor. For a full description of valid data * formats, see the <a href='http://dygraphs.com/data.html'>Data Formats</a> page. */ file?: Data /** * When set, attempt to parse each cell in the CSV file as "a/b", where a and b are integers. * The ratio will be plotted. This allows computation of Wilson confidence intervals (see * below). */ fractions?: boolean /** * Height, in pixels, of the chart. If the container div has been explicitly sized, this will * be ignored. */ height?: number /** * Whether to hide the legend when the mouse leaves the chart area. */ hideOverlayOnMouseOut?: boolean /** * When set, this callback gets called every time a new point is highlighted. */ highlightCallback?: ( event: MouseEvent<Element>, xval: number, points: Point[], row: number, seriesName: string ) => any /** * Fade the background while highlighting series. 1=fully visible background (disable * fading), 0=hiddden background (show highlighted series only). */ highlightSeriesBackgroundAlpha?: number /** * Sets the background color used to fade out the series in conjunction with 'highlightSeriesBackgroundAlpha'. * Default: rgb(255, 255, 255) */ highlightSeriesBackgroundColor?: string /** * When set, the options from this object are applied to the timeseries closest to the mouse * pointer for interactive highlighting. See also 'highlightCallback'. Example: * highlightSeriesOpts: { strokeWidth: 3 }. */ highlightSeriesOpts?: PerSeriesOptions /** * Usually, dygraphs will use the range of the data plus some padding to set the range of the * y-axis. If this option is set, the y-axis will always include zero, typically as the * lowest value. This can be used to avoid exaggerating the variance in the data */ includeZero?: boolean interactionModel?: any /** * When this option is passed to updateOptions() along with either the * <code>dateWindow</code> or <code>valueRange</code> options, the zoom flags are not changed * to reflect a zoomed state. This is primarily useful for when the display area of a chart * is changed programmatically and also where manual zooming is allowed and use is made of * the <code>isZoomed</code> method to determine this. */ isZoomedIgnoreProgrammaticZoom?: boolean /** * A name for each data series, including the independent (X) series. For CSV files and * DataTable objections, this is determined by context. For raw data, this must be specified. * If it is not, default values are supplied and a warning is logged. */ labels?: string[] /** * Show data labels in an external div, rather than on the graph. This value can either be a * div element or a div id. */ labelsDiv?: string | HTMLElement /** * Additional styles to apply to the currently-highlighted points div. For example, { * 'fontWeight': 'bold' } will make the labels bold. In general, it is better to use CSS to * style the .dygraph-legend class than to use this property. */ labelsDivStyles?: {[cssProperty: string]: string} /** * Width (in pixels) of the div which shows information on the currently-highlighted points. */ labelsDivWidth?: number /** * Put <code>&lt;br/&gt;</code> between lines in the label string. Often used in conjunction * with <strong>labelsDiv</strong>. */ labelsSeparateLines?: boolean /** * Show zero value labels in the labelsDiv. */ labelsShowZeroValues?: boolean /** * Show date/time labels according to UTC (instead of local time). */ labelsUTC?: boolean /** * When to display the legend. By default, it only appears when a user mouses over the chart. * Set it to "always" to always display a legend of some sort. When set to "follow", legend * follows highlighted points. If set to 'never' then it will not appear at all. */ legend?: 'always' | 'follow' | 'onmouseover' | 'never' /** * for details see https://github.com/danvk/dygraphs/pull/683 */ legendFormatter?: (legendData: LegendData) => string /** * A value representing the farthest a graph may be panned, in percent of the display. For * example, a value of 0.1 means that the graph can only be panned 10% pased the edges of the * displayed values. null means no bounds. */ panEdgeFraction?: number /** * A function (or array of functions) which plot each data series on the chart. * TODO(danvk): more details! May be set per-series. */ plotter?: any /** * Defines per-graph plugins. Useful for per-graph customization */ plugins?: any[] /** * A function to call when a data point is clicked. and the point that was clicked. */ pointClickCallback?: (e: MouseEvent<Element>, point: Point) => any /** * Height, in pixels, of the range selector widget. This option can only be specified at * Dygraph creation time. */ rangeSelectorHeight?: number /** * The range selector mini plot fill color. This can be of the form "#AABBCC" or * "rgb(255,100,200)" or "yellow". You can also specify null or "" to turn off fill. */ rangeSelectorPlotFillColor?: string /** * The range selector mini plot stroke color. This can be of the form "#AABBCC" or * "rgb(255,100,200)" or "yellow". You can also specify null or "" to turn off stroke. */ rangeSelectorPlotStrokeColor?: string /** * Number of pixels to leave blank at the right edge of the Dygraph. This makes it easier to * highlight the right-most data point. */ rightGap?: number /** * Number of days over which to average data. Discussed extensively above. */ rollPeriod?: number /** * Defines per-series options. Its keys match the y-axis label names, and the values are * dictionaries themselves that contain options specific to that series. When this option is * missing, it falls back on the old-style of per-series options comingled with global * options. */ series?: { [seriesName: string]: PerSeriesOptions } /** * Whether to show the legend upon mouseover. */ showLabelsOnHighlight?: boolean /** * Show or hide the range selector widget. */ showRangeSelector?: boolean /** * If the rolling average period text box should be shown. */ showRoller?: boolean /** * When errorBars is set, shade this many standard deviations above/below each point. */ sigma?: number /** * If set, stack series on top of one another rather than drawing them independently. The * first series specified in the input data will wind up on top of the chart and the last * will be on bottom. NaN values are drawn as white areas without a line on top, see * stackedGraphNaNFill for details. */ stackedGraph?: boolean /** * Controls handling of NaN values inside a stacked graph. NaN values are * interpolated/extended for stacking purposes, but the actual point value remains NaN in the * legend display. Valid option values are "all" (interpolate internally, repeat leftmost and * rightmost value as needed), "inside" (interpolate internally only, use zero outside * leftmost and rightmost value), and "none" (treat NaN as zero everywhere). */ stackedGraphNaNFill?: string /** * Text to display above the chart. You can supply any HTML for this value, not just text. If * you wish to style it using CSS, use the 'dygraph-label' or 'dygraph-title' classes. */ title?: string /** * Height of the chart title, in pixels. This also controls the default font size of the * title. If you style the title on your own, this controls how much space is set aside above * the chart for the title's div. */ titleHeight?: number /** * When set, this callback gets called before the chart is drawn. It details on how to use * this. */ underlayCallback?: ( context: CanvasRenderingContext2D, area: dygraphs.Area, dygraph: Dygraph ) => any /** * When set, this callback gets called every time the user stops highlighting any point by * mousing out of the graph. */ unhighlightCallback?: (event: MouseEvent<Element>) => any /** * Which series should initially be visible? Once the Dygraph has been constructed, you can * access and modify the visibility of each series using the <code>visibility</code> and * <code>setVisibility</code> methods. */ visibility?: boolean[] /** * Width, in pixels, of the chart. If the container div has been explicitly sized, this will * be ignored. */ width?: number /** * Use in conjunction with the "fractions" option. Instead of plotting +/- N standard * deviations, dygraphs will compute a Wilson confidence interval and plot that. This has * more reasonable behavior for ratios close to 0 or 1. */ wilsonInterval?: boolean /** * Height, in pixels, of the x-axis. If not set explicitly, this is computed based on * axisLabelFontSize and axisTickSize. */ xAxisHeight?: number /** * Height of the x-axis label, in pixels. This also controls the default font size of the * x-axis label. If you style the label on your own, this controls how much space is set * aside below the chart for the x-axis label's div. */ xLabelHeight?: number /** * Add the specified amount of extra space (in pixels) around the X-axis value range to * ensure points at the edges remain visible. */ xRangePad?: number /** * A function which parses x-values (i.e. the dependent series). Must return a number, even * when the values are dates. In this case, millis since epoch are used. This is used * primarily for parsing CSV data. *=Dygraphs is slightly more accepting in the dates which * it will parse. See code for details. */ xValueParser?: (val: string) => number /** * Text to display below the chart's x-axis. You can supply any HTML for this value, not just * text. If you wish to style it using CSS, use the 'dygraph-label' or 'dygraph-xlabel' * classes. */ xlabel?: string /** * Text to display to the right of the chart's secondary y-axis. This label is only displayed * if a secondary y-axis is present. See <a * href='http://dygraphs.com/tests/two-axes.html'>this test</a> for an example of how to do * this. The comments for the 'ylabel' option generally apply here as well. This label gets a * 'dygraph-y2label' instead of a 'dygraph-ylabel' class. */ y2label?: string /** * Width of the div which contains the y-axis label. Since the y-axis label appears rotated * 90 degrees, this actually affects the height of its div. */ yLabelWidth?: number /** * If set, add the specified amount of extra space (in pixels) around the Y-axis value range * to ensure points at the edges remain visible. If unset, use the traditional Y padding * algorithm. */ yRangePad?: number /** * Text to display to the left of the chart's y-axis. You can supply any HTML for this value, * not just text. If you wish to style it using CSS, use the 'dygraph-label' or * 'dygraph-ylabel' classes. The text will be rotated 90 degrees by default, so CSS rules may * behave in unintuitive ways. No additional space is set aside for a y-axis label. If you * need more space, increase the width of the y-axis tick labels using the yAxisLabelWidth * option. If you need a wider div for the y-axis label, either style it that way with CSS * (but remember that it's rotated, so width is controlled by the 'height' property) or set * the yLabelWidth option. */ ylabel?: string /** * A function to call when the zoom window is changed (either by zooming in or out). */ zoomCallback?: ( minDate: number, maxDate: number, yRanges: Array<[number, number]> ) => any } export default DygraphClass } // Allow typescript to recognize json files declare module '*.json' { const value: any export default value } declare module '*.md' { const value: string export default value }
{ "pile_set_name": "Github" }
temptable_limit 0
{ "pile_set_name": "Github" }
# This source code was written by the Go contributors. # The master list of contributors is in the main Go distribution, # visible at http://tip.golang.org/CONTRIBUTORS.
{ "pile_set_name": "Github" }
# [[[ PREPROCESSOR ]]] # <<< PARSE_ERROR: 'ERROR ECOPARP00' >>> # [[[ HEADER ]]] use RPerl; package RPerl::Test::VersionNumber::Class_00_Bad_04; use strict; use warnings; our $VERSION = 0.1001_000; # [[[ OO INHERITANCE ]]] use parent qw(RPerl::Test); use RPerl::Test; # [[[ OO PROPERTIES ]]] our hashref $properties = { empty_property => my integer $TYPED_empty_property = 2 }; # [[[ SUBROUTINES & OO METHODS ]]] sub empty_method { { my void::method $RETURN_TYPE }; return 2; } 1; # end of class
{ "pile_set_name": "Github" }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.openwire.amq; import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.MessageListener; import javax.jms.Session; import java.lang.Thread.UncaughtExceptionHandler; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.apache.activemq.ActiveMQMessageConsumer; import org.apache.activemq.artemis.tests.integration.openwire.BasicOpenWireTest; import org.apache.activemq.artemis.utils.ActiveMQThreadFactory; import org.apache.activemq.command.ActiveMQDestination; import org.junit.Test; /** * adapted from: org.apache.activemq.JMSConsumerTest */ public class JMSConsumer2Test extends BasicOpenWireTest { @Test public void testMessageListenerWithConsumerCanBeStoppedConcurently() throws Exception { final AtomicInteger counter = new AtomicInteger(0); final CountDownLatch closeDone = new CountDownLatch(1); connection.start(); Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); ActiveMQDestination destination = createDestination(session, ActiveMQDestination.QUEUE_TYPE); // preload the queue sendMessages(session, destination, 2000); final ActiveMQMessageConsumer consumer = (ActiveMQMessageConsumer) session.createConsumer(destination); final Map<Thread, Throwable> exceptions = Collections.synchronizedMap(new HashMap<Thread, Throwable>()); Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { exceptions.put(t, e); } }); final class AckAndClose implements Runnable { private final Message message; AckAndClose(Message m) { this.message = m; } @Override public void run() { try { int count = counter.incrementAndGet(); if (count == 590) { // close in a separate thread is ok by jms consumer.close(); closeDone.countDown(); } if (count % 200 == 0) { // ensure there are some outstanding messages // ack every 200 message.acknowledge(); } } catch (Exception e) { exceptions.put(Thread.currentThread(), e); } } } final ExecutorService executor = Executors.newCachedThreadPool(ActiveMQThreadFactory.defaultThreadFactory()); consumer.setMessageListener(new MessageListener() { @Override public void onMessage(Message m) { // ack and close eventually in separate thread executor.execute(new AckAndClose(m)); } }); assertTrue(closeDone.await(20, TimeUnit.SECONDS)); // await possible exceptions Thread.sleep(1000); assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); executor.shutdown(); } @Test public void testDupsOkConsumer() throws Exception { // Receive a message with the JMS API connection.start(); Session session = connection.createSession(false, Session.DUPS_OK_ACKNOWLEDGE); ActiveMQDestination destination = createDestination(session, ActiveMQDestination.QUEUE_TYPE); MessageConsumer consumer = session.createConsumer(destination); // Send the messages sendMessages(session, destination, 4); // Make sure only 4 message are delivered. for (int i = 0; i < 4; i++) { Message m = consumer.receive(1000); assertNotNull(m); } assertNull(consumer.receive(1000)); // Close out the consumer.. no other messages should be left on the queue. consumer.close(); consumer = session.createConsumer(destination); assertNull(consumer.receive(1000)); } @Test public void testRedispatchOfUncommittedTx() throws Exception { connection.start(); Session session = connection.createSession(true, Session.SESSION_TRANSACTED); ActiveMQDestination destination = createDestination(session, ActiveMQDestination.QUEUE_TYPE); sendMessages(connection, destination, 2); MessageConsumer consumer = session.createConsumer(destination); Message m = consumer.receive(1000); assertNotNull(m); m = consumer.receive(5000); assertNotNull(m); assertFalse("redelivered flag set", m.getJMSRedelivered()); // install another consumer while message dispatch is unacked/uncommitted Session redispatchSession = connection.createSession(true, Session.SESSION_TRANSACTED); MessageConsumer redispatchConsumer = redispatchSession.createConsumer(destination); // no commit so will auto rollback and get re-dispatched to // redisptachConsumer session.close(); Message msg = redispatchConsumer.receive(3000); assertNotNull(msg); assertTrue("redelivered flag set", msg.getJMSRedelivered()); assertEquals(2, msg.getLongProperty("JMSXDeliveryCount")); msg = redispatchConsumer.receive(1000); assertNotNull(msg); assertTrue(msg.getJMSRedelivered()); assertEquals(2, msg.getLongProperty("JMSXDeliveryCount")); redispatchSession.commit(); assertNull(redispatchConsumer.receive(500)); redispatchSession.close(); } @Test public void testRedispatchOfRolledbackTx() throws Exception { connection.start(); Session session = connection.createSession(true, Session.SESSION_TRANSACTED); ActiveMQDestination destination = createDestination(session, ActiveMQDestination.QUEUE_TYPE); sendMessages(connection, destination, 2); MessageConsumer consumer = session.createConsumer(destination); assertNotNull(consumer.receive(1000)); assertNotNull(consumer.receive(1000)); // install another consumer while message dispatch is unacked/uncommitted Session redispatchSession = connection.createSession(true, Session.SESSION_TRANSACTED); MessageConsumer redispatchConsumer = redispatchSession.createConsumer(destination); session.rollback(); session.close(); Message msg = redispatchConsumer.receive(1000); assertNotNull(msg); assertTrue(msg.getJMSRedelivered()); assertEquals(2, msg.getLongProperty("JMSXDeliveryCount")); msg = redispatchConsumer.receive(1000); assertNotNull(msg); assertTrue(msg.getJMSRedelivered()); assertEquals(2, msg.getLongProperty("JMSXDeliveryCount")); redispatchSession.commit(); assertNull(redispatchConsumer.receive(500)); redispatchSession.close(); } }
{ "pile_set_name": "Github" }
<?php /** * This file implements the Current Item filters Widget class. * * This file is part of the evoCore framework - {@link http://evocore.net/} * See also {@link https://github.com/b2evolution/b2evolution}. * * @license GNU GPL v2 - {@link http://b2evolution.net/about/gnu-gpl-license} * * @copyright (c)2003-2020 by Francois Planque - {@link http://fplanque.com/} * Parts of this file are copyright (c)2008 by Daniel HAHLER - {@link http://daniel.hahler.de/}. * * @package evocore */ if( !defined('EVO_MAIN_INIT') ) die( 'Please, do not access this page directly.' ); load_class( 'widgets/model/_widget.class.php', 'ComponentWidget' ); /** * ComponentWidget Class * * A ComponentWidget is a displayable entity that can be placed into a Container on a web page. * * @package evocore */ class coll_current_filters_Widget extends ComponentWidget { var $icon = 'filter'; /** * Constructor */ function __construct( $db_row = NULL ) { // Call parent constructor: parent::__construct( $db_row, 'core', 'coll_current_filters' ); } /** * Get help URL * * @return string URL */ function get_help_url() { return get_manual_url( 'current-filters-widget' ); } /** * Get name of widget */ function get_name() { return T_('Current Item filters'); } /** * Get a very short desc. Used in the widget list. */ function get_short_desc() { return format_to_output( $this->disp_params['title'] ); } /** * Get short description */ function get_desc() { return T_('Summary of the current Item filters.'); } /** * Get definitions for editable params * * @see Plugin::GetDefaultSettings() * @param array local params */ function get_param_definitions( $params ) { $r = array_merge( array( 'title' => array( 'type' => 'text', 'label' => T_('Block title'), 'defaultvalue' => T_('Current Item filters'), 'maxlength' => 100, ), 'show_filters' => array( 'type' => 'checklist', 'label' => T_('Show filters'), 'options' => array( array( 'category', T_('Category'), 1 ), array( 'archive', T_('Archive'), 1 ), array( 'keyword', T_('Keyword'), 1 ), array( 'tag', /* TRANS: noun */ T_('Tag'), 1 ), array( 'author', T_('Author'), 1 ), array( 'assignee', T_('Assignee'), 1 ), array( 'locale', T_('Locale'), 1 ), array( 'status', T_('Status'), 1 ), array( 'itemtype', T_('Item Type'), 0 ), array( 'visibility', T_('Visibility'), 0 ), array( 'time', T_('Past/Future'), 0 ), array( 'limit', T_('Limit by days'), 1 ), array( 'flagged', T_('Flagged'), 1 ), array( 'mustread', T_('Must read'), 1 ), ), ), ), parent::get_param_definitions( $params ) ); return $r; } /** * Display the widget! * * @param array MUST contain at least the basic display params */ function display( $params ) { global $MainList; $params = array_merge( array( 'ItemList' => $MainList, 'display_button_reset' => true, // Display a button to reset all filters 'display_empty_filter' => false, // Display a block with text "No filters" ), $params ); if( empty( $params['ItemList'] ) ) { // Empty ItemList object $this->display_debug_message( 'Widget "'.$this->get_name().'" is hidden because there is an empty param "ItemList".' ); return false; } if( isset( $params['show_filters'] ) ) { // Get the predefined filters $show_filters = $params['show_filters']; unset( $params['show_filters'] ); } $this->init_display( $params ); if( isset( $show_filters ) ) { // Rewrite default filters by predefined $this->disp_params['show_filters'] = array_merge( $this->disp_params['show_filters'], $show_filters ); } $filters = implode( ' '.T_('AND').' ', $params['ItemList']->get_filter_titles( array(), array( 'categories_text' => '', 'categories_nor_text' => T_('NOT').' ', 'tags_nor_text' => T_('NOT').' ', 'authors_nor_text' => T_('NOT').' ', 'group_mask' => '$filter_items$', 'filter_mask' => '<div class="filter_item $filter_class$">'."\n" .'<div class="group">$group_title$</div>'."\n" .'<div class="name">$filter_name$</div>'."\n" .'<div class="icon">$clear_icon$</div>'."\n" .'</div>', 'filter_mask_nogroup' => '<div class="filter_item $filter_class$">'."\n" .'<div class="name">$filter_name$</div>'."\n" .'<div class="icon">$clear_icon$</div>'."\n" .'</div>', 'before_items' => '( ', 'after_items' => ' )', 'separator_and' => ' '.T_('AND').' ', 'separator_or' => ' '.T_('OR').' ', 'separator_nor' => ' '.T_('NOR').' ', 'separator_comma' => ' '.T_('OR').' ', 'display_category' => ! empty( $this->disp_params['show_filters']['category'] ), 'display_archive' => ! empty( $this->disp_params['show_filters']['archive'] ), 'display_keyword' => ! empty( $this->disp_params['show_filters']['keyword'] ), 'display_tag' => ! empty( $this->disp_params['show_filters']['tag'] ), 'display_author' => ! empty( $this->disp_params['show_filters']['author'] ), 'display_assignee' => ! empty( $this->disp_params['show_filters']['assignee'] ), 'display_locale' => ! empty( $this->disp_params['show_filters']['locale'] ), 'display_status' => ! empty( $this->disp_params['show_filters']['status'] ), 'display_visibility' => ! empty( $this->disp_params['show_filters']['visibility'] ), 'display_itemtype' => ! empty( $this->disp_params['show_filters']['itemtype'] ), 'display_time' => ! empty( $this->disp_params['show_filters']['time'] ), 'display_limit' => ! empty( $this->disp_params['show_filters']['limit'] ), 'display_flagged' => ! empty( $this->disp_params['show_filters']['flagged'] ), 'display_mustread' => ! empty( $this->disp_params['show_filters']['mustread'] ), ) ) ); if( empty( $filters ) && ! $params['display_empty_filter'] ) { // No filters $this->display_debug_message( 'Widget "'.$this->get_name().'" is hidden because there are no filters.' ); return false; } // START DISPLAY: echo $this->disp_params['block_start']; // Display title if requested $this->disp_title(); echo $this->disp_params['block_body_start']; if( empty( $filters ) ) { // No filters if( $params['display_empty_filter'] ) { if( is_admin_page() && get_param( 'tab' ) == 'type' ) { // Try to get a title for current selected post type on back-office pages: switch( get_param( 'tab_type' ) ) { case 'page': $current_post_type_title = T_('Pages'); break; case 'special': $current_post_type_title = T_('Special Items'); break; case 'intro': $current_post_type_title = T_('Intros'); break; case 'content-block': $current_post_type_title = T_('Content Blocks'); break; default: // post $current_post_type_title = T_('Posts'); } $current_post_type_title = '"'.$current_post_type_title.'"'; } if( empty( $current_post_type_title ) ) { // Use this title by default for unknown selected post type: $current_post_type_title = T_('items'); } echo sprintf( T_('No filters - Showing all %s'), $current_post_type_title ); } } else { // Display the filters echo $filters; if( $params['display_button_reset'] ) { // Display link/button to reset all filters: global $Blog; if( is_admin_page() || ! isset( $Blog ) ) { // Regenerate URL by removing all filters from current URL on back-office: $remove_filters_url = regenerate_url( 'catsel,cat,' .$params['ItemList']->param_prefix.'tag,' .$params['ItemList']->param_prefix.'author,' .$params['ItemList']->param_prefix.'author_login,' .$params['ItemList']->param_prefix.'assgn,' .$params['ItemList']->param_prefix.'assgn_login,' .$params['ItemList']->param_prefix.'author_assignee,' .$params['ItemList']->param_prefix.'lc,' .$params['ItemList']->param_prefix.'status,' .$params['ItemList']->param_prefix.'show_statuses,' .$params['ItemList']->param_prefix.'types,' .$params['ItemList']->param_prefix.'s,' .$params['ItemList']->param_prefix.'sentence,' .$params['ItemList']->param_prefix.'exact,' .$params['ItemList']->param_prefix.'p,' .$params['ItemList']->param_prefix.'title,' .$params['ItemList']->param_prefix.'pl,' .$params['ItemList']->param_prefix.'m,' .$params['ItemList']->param_prefix.'w,' .$params['ItemList']->param_prefix.'dstart,' .$params['ItemList']->param_prefix.'dstop,' .$params['ItemList']->param_prefix.'show_past,' .$params['ItemList']->param_prefix.'show_future,' .$params['ItemList']->param_prefix.'flagged,' .$params['ItemList']->param_prefix.'mustread' ); } else { // Use home page of the current Collection on front-office: $remove_filters_url = $Blog->get( 'url' ); } echo '<p>'.action_icon( T_('Remove filters'), 'reset_filters', $remove_filters_url, ' '.T_('Remove filters'), 3, 4 ).'<p>'; } } echo $this->disp_params['block_body_end']; echo $this->disp_params['block_end']; return true; } } ?>
{ "pile_set_name": "Github" }
3 10
{ "pile_set_name": "Github" }
// Microsoft Visual C++ generated resource script. // #include "resource.h" #define APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 2 resource. // #include "windows.h" ///////////////////////////////////////////////////////////////////////////// #undef APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // English (U.S.) resources #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) #ifdef _WIN32 LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US #pragma code_page(1252) #endif //_WIN32 #ifdef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // TEXTINCLUDE // 1 TEXTINCLUDE BEGIN "resource.h\0" END 2 TEXTINCLUDE BEGIN "#include ""windows.h""\r\n" "\0" END 3 TEXTINCLUDE BEGIN "\r\n" "\0" END #endif // APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // Menu // IDR_MENU1 MENU BEGIN POPUP "&File" BEGIN MENUITEM "Choose &Device", ID_FILE_CHOOSEDEVICE END END ///////////////////////////////////////////////////////////////////////////// // // Dialog // IDD_CHOOSE_DEVICE DIALOGEX 0, 0, 186, 90 STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU CAPTION "Select Device" FONT 8, "MS Shell Dlg", 400, 0, 0x1 BEGIN DEFPUSHBUTTON "OK",IDOK,129,7,50,14 PUSHBUTTON "Cancel",IDCANCEL,129,24,50,14 LISTBOX IDC_DEVICE_LIST,7,7,110,76,LBS_SORT | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP END ///////////////////////////////////////////////////////////////////////////// // // DESIGNINFO // #ifdef APSTUDIO_INVOKED GUIDELINES DESIGNINFO BEGIN IDD_CHOOSE_DEVICE, DIALOG BEGIN LEFTMARGIN, 7 RIGHTMARGIN, 179 TOPMARGIN, 7 BOTTOMMARGIN, 83 END END #endif // APSTUDIO_INVOKED #endif // English (U.S.) resources ///////////////////////////////////////////////////////////////////////////// #ifndef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 3 resource. // ///////////////////////////////////////////////////////////////////////////// #endif // not APSTUDIO_INVOKED
{ "pile_set_name": "Github" }
exports.json = { home:[ { "title":"Making Material Design", "author":"Google Design", "views":"409,130", "short_views":"409K" "rel_date": "1 year ago", "date":"May 28, 2015", "subs" : "41,367" "thumbs_up":"7K" "thumbs_down" : "156" "video":"https://dl.dropboxusercontent.com/u/143270556/YouTube/making-material-design.mp4", "thumbnail":"https://i.ytimg.com/vi/rrT6v5sOwJg/maxresdefault.jpg", "profile_pic":"https://yt3.ggpht.com/-99RMkL32yk8/AAAAAAAAAAI/AAAAAAAAAAA/VRQkMbulnco/s88-c-k-no-rj-c0xffffff/photo.jpg" }, { "title":"$18,000 a night HOTEL ROOM", "author":"CaiseyNeistat", "views":"2,123,725", "short_views":"2M" "date":"May 19, 2016", "rel_date": "3 days ago", "subs" : "3,053,812", "thumbs_up":"74K" "thumbs_down" : "1.9K" "video":"https://dl.dropboxusercontent.com/u/143270556/YouTube/casey-neistat.mp4", "thumbnail":"https://i.ytimg.com/vi/8sqY6QXtTsI/hqdefault.jpg", "profile_pic":"https://yt3.ggpht.com/-x2NNN2y49G0/AAAAAAAAAAI/AAAAAAAAAAA/RhwVaxMvqW8/s88-c-k-no-rj-c0xffffff/photo.jpg" }, { "title":"Hillary & Bernie Cold Open - SNL", "author":"Saturday Night Live", "views":"1,027,676", "short_views":"1M" "rel_date": "1 day ago", "date":"May 22, 2016", "subs" : "2,400,022", "thumbs_up":"11K" "thumbs_down" : "988" "video":"https://dl.dropboxusercontent.com/u/143270556/YouTube/hilary-bernie.mp4", "thumbnail":"https://i.ytimg.com/vi/HRqZhJcae3M/maxresdefault.jpg", "profile_pic":"https://yt3.ggpht.com/-x-pKW1yb6y8/AAAAAAAAAAI/AAAAAAAAAAA/jPbMU4ZW0sA/s88-c-k-no-rj-c0xffffff/photo.jpg" }, { "title":"European windows are awesome", "author":"Matthias Wandel", "views":"489,647", "short_views":"489K" "rel_date": "1 day ago", "date":"May 22, 2016", "subs" : "21,409", "thumbs_up":"3K" "thumbs_down" : "105" "video":"https://dl.dropboxusercontent.com/u/143270556/YouTube/european-windows.mp4", "thumbnail":"https://i.ytimg.com/vi/LT8eBjlcT8s/maxresdefault.jpg", "profile_pic":"https://yt3.ggpht.com/-S1HYZOVjayE/AAAAAAAAAAI/AAAAAAAAAAA/UY73x3DoIvg/s88-c-k-no-rj-c0xffffff/photo.jpg" }, { "title":"Yo", "author":"Saturday Night Live", "views":"1,027,676", "short_views":"1M" "rel_date": "1 day ago", "date":"May 22, 2016", "subs" : "2,400,022", "thumbs_up":"11K" "thumbs_down" : "988" "video":"https://dl.dropboxusercontent.com/u/143270556/YouTube/hilary-bernie.mp4", "thumbnail":"https://i.ytimg.com/vi/HRqZhJcae3M/maxresdefault.jpg", "profile_pic":"https://www.youtube.com/user/SaturdayNightLive" } ] }
{ "pile_set_name": "Github" }
import { BufferTimeSignature } from '../../operator/bufferTime'; declare module '../../Observable' { interface Observable<T> { bufferTime: BufferTimeSignature<T>; } }
{ "pile_set_name": "Github" }
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.ArrayList; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class Shell { static List<ArrayList<ArrayList<Integer>>> read(String filename) { ArrayList<ArrayList<Integer>> A = new ArrayList<ArrayList<Integer>>(); ArrayList<ArrayList<Integer>> B = new ArrayList<ArrayList<Integer>>(); String thisLine; try { BufferedReader br = new BufferedReader(new FileReader(filename)); // Begin reading A while ((thisLine = br.readLine()) != null) { if (thisLine.trim().equals("")) { break; } else { ArrayList<Integer> line = new ArrayList<Integer>(); String[] lineArray = thisLine.split("\t"); for (String number : lineArray) { line.add(Integer.parseInt(number)); } A.add(line); } } // Begin reading B while ((thisLine = br.readLine()) != null) { ArrayList<Integer> line = new ArrayList<Integer>(); String[] lineArray = thisLine.split("\t"); for (String number : lineArray) { line.add(Integer.parseInt(number)); } B.add(line); } br.close(); } catch (IOException e) { System.err.println("Error: " + e); } List<ArrayList<ArrayList<Integer>>> res = new LinkedList<ArrayList<ArrayList<Integer>>>(); res.add(A); res.add(B); return res; } static void printMatrix(int[][] matrix) { for (int[] line : matrix) { int i = 0; StringBuilder sb = new StringBuilder(matrix.length); for (int number : line) { if (i != 0) { sb.append("\t"); } else { i++; } sb.append(number); } System.out.println(sb.toString()); } } public static int[][] parallelMult(ArrayList<ArrayList<Integer>> A, ArrayList<ArrayList<Integer>> B, int threadNumber) { int[][] C = new int[A.size()][B.get(0).size()]; ExecutorService executor = Executors.newFixedThreadPool(threadNumber); List<Future<int[][]>> list = new ArrayList<Future<int[][]>>(); int part = A.size() / threadNumber; if (part < 1) { part = 1; } for (int i = 0; i < A.size(); i += part) { System.err.println(i); Callable<int[][]> worker = new LineMultiplier(A, B, i, i+part); Future<int[][]> submit = executor.submit(worker); list.add(submit); } // now retrieve the result int start = 0; int CF[][]; for (Future<int[][]> future : list) { try { CF = future.get(); for (int i=start; i < start+part; i += 1) { C[i] = CF[i]; } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } start+=part; } executor.shutdown(); return C; } public static void main(String[] args) { String filename; int cores = Runtime.getRuntime().availableProcessors(); System.err.println("Number of cores:\t" + cores); int threads; if (args.length < 3) { filename = "3.in"; threads = cores; } else { filename = args[1]; threads = Integer.parseInt(args[2]); } List<ArrayList<ArrayList<Integer>>> matrices = read(filename); ArrayList<ArrayList<Integer>> A = matrices.get(0); ArrayList<ArrayList<Integer>> B = matrices.get(1); int[][] C = parallelMult(A, B, threads); printMatrix(C); } }
{ "pile_set_name": "Github" }
# LibreSprite Network Library *Copyright (C) 2001-2015 David Capello* > Distributed under [MIT license](LICENSE.txt) Simple curl wrapper.
{ "pile_set_name": "Github" }
//--------------------------------------------------------------------- // <copyright file="ArchiveFileInfo.cs" company="Microsoft Corporation"> // Copyright (c) 1999, Microsoft Corporation. All rights reserved. // </copyright> // <summary> // Part of the Deployment Tools Foundation project. // </summary> //--------------------------------------------------------------------- namespace Microsoft.PackageManagement.Archivers.Internal.Compression { using System; using System.Diagnostics.CodeAnalysis; using System.IO; #if !CORECLR using System.Security.Permissions; #endif /// <summary> /// Abstract object representing a compressed file within an archive; /// provides operations for getting the file properties and unpacking /// the file. /// </summary> public abstract class ArchiveFileInfo : FileSystemInfo { private ArchiveInfo archiveInfo; private string name; private string path; private bool initialized; private bool exists; private int archiveNumber; private FileAttributes attributes; private DateTime lastWriteTime; private long length; /// <summary> /// Creates a new ArchiveFileInfo object representing a file within /// an archive in a specified path. /// </summary> /// <param name="archiveInfo">An object representing the archive /// containing the file.</param> /// <param name="filePath">The path to the file within the archive. /// Usually, this is a simple file name, but if the archive contains /// a directory structure this may include the directory.</param> protected ArchiveFileInfo(ArchiveInfo archiveInfo, string filePath) : base() { if (filePath == null) { throw new ArgumentNullException("filePath"); } this.Archive = archiveInfo; this.name = System.IO.Path.GetFileName(filePath); this.path = System.IO.Path.GetDirectoryName(filePath); this.attributes = FileAttributes.Normal; this.lastWriteTime = DateTime.MinValue; } /// <summary> /// Creates a new ArchiveFileInfo object with all parameters specified; /// used by subclasses when reading the metadata out of an archive. /// </summary> /// <param name="filePath">The internal path and name of the file in /// the archive.</param> /// <param name="archiveNumber">The archive number where the file /// starts.</param> /// <param name="attributes">The stored attributes of the file.</param> /// <param name="lastWriteTime">The stored last write time of the /// file.</param> /// <param name="length">The uncompressed size of the file.</param> protected ArchiveFileInfo( string filePath, int archiveNumber, FileAttributes attributes, DateTime lastWriteTime, long length) : this(null, filePath) { this.exists = true; this.archiveNumber = archiveNumber; this.attributes = attributes; this.lastWriteTime = lastWriteTime; this.length = length; this.initialized = true; } /// <summary> /// Gets the name of the file. /// </summary> /// <value>The name of the file, not including any path.</value> public override string Name { get { return this.name; } } /// <summary> /// Gets the internal path of the file in the archive. /// </summary> /// <value>The internal path of the file in the archive, not including /// the file name.</value> public string Path { get { return this.path; } } /// <summary> /// Gets the full path to the file. /// </summary> /// <value>The full path to the file, including the full path to the /// archive, the internal path in the archive, and the file name.</value> /// <remarks> /// For example, the path <c>"C:\archive.cab\file.txt"</c> refers to /// a file "file.txt" inside the archive "archive.cab". /// </remarks> public override string FullName { get { string fullName = System.IO.Path.Combine(this.Path, this.Name); if (this.Archive != null) { fullName = System.IO.Path.Combine(this.ArchiveName, fullName); } return fullName; } } public string FullNameExtension { get { // GetFullPathInternal would have already stripped out the terminating "." if present. int len = FullName.Length; for (int i = len; --i >= 0;) { char ch = FullName[i]; if (ch == '.') return FullName.Substring(i, len - i); if (ch == System.IO.Path.DirectorySeparatorChar || ch == System.IO.Path.AltDirectorySeparatorChar || ch == System.IO.Path.VolumeSeparatorChar) break; } return String.Empty; } } /// <summary> /// Gets or sets the archive that contains this file. /// </summary> /// <value> /// The ArchiveInfo instance that retrieved this file information -- this /// may be null if the ArchiveFileInfo object was returned directly from /// a stream. /// </value> public ArchiveInfo Archive { get { return (ArchiveInfo) this.archiveInfo; } internal set { this.archiveInfo = value; // protected instance members inherited from FileSystemInfo: this.OriginalPath = (value != null ? value.FullName : null); this.FullPath = this.OriginalPath; } } /// <summary> /// Gets the full path of the archive that contains this file. /// </summary> /// <value>The full path of the archive that contains this file.</value> public string ArchiveName { get { return this.Archive != null ? this.Archive.FullName : null; } } /// <summary> /// Gets the number of the archive where this file starts. /// </summary> /// <value>The number of the archive where this file starts.</value> /// <remarks>A single archive or the first archive in a chain is /// numbered 0.</remarks> public int ArchiveNumber { get { return this.archiveNumber; } } /// <summary> /// Checks if the file exists within the archive. /// </summary> /// <value>True if the file exists, false otherwise.</value> public override bool Exists { get { if (!this.initialized) { this.Refresh(); } return this.exists; } } /// <summary> /// Gets the uncompressed size of the file. /// </summary> /// <value>The uncompressed size of the file in bytes.</value> public long Length { get { if (!this.initialized) { this.Refresh(); } return this.length; } } /// <summary> /// Gets the attributes of the file. /// </summary> /// <value>The attributes of the file as stored in the archive.</value> public new FileAttributes Attributes { get { if (!this.initialized) { this.Refresh(); } return this.attributes; } } /// <summary> /// Gets the last modification time of the file. /// </summary> /// <value>The last modification time of the file as stored in the /// archive.</value> public new DateTime LastWriteTime { get { if (!this.initialized) { this.Refresh(); } return this.lastWriteTime; } } /// <summary> /// Gets the full path to the file. /// </summary> /// <returns>The same as <see cref="FullName"/></returns> public override string ToString() { return this.FullName; } /// <summary> /// Deletes the file. NOT SUPPORTED. /// </summary> /// <exception cref="NotSupportedException">Files cannot be deleted /// from an existing archive.</exception> public override void Delete() { throw new NotSupportedException(); } /// <summary> /// Refreshes the attributes and other cached information about the file, /// by re-reading the information from the archive. /// </summary> public new void Refresh() { base.Refresh(); if (this.Archive != null) { string filePath = System.IO.Path.Combine(this.Path, this.Name); ArchiveFileInfo updatedFile = this.Archive.GetFile(filePath); if (updatedFile == null) { throw new FileNotFoundException( "File not found in archive.", filePath); } this.Refresh(updatedFile); } } /// <summary> /// Extracts the file. /// </summary> /// <param name="destFileName">The destination path where the file /// will be extracted.</param> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "dest")] public void CopyTo(string destFileName) { this.CopyTo(destFileName, false); } /// <summary> /// Extracts the file, optionally overwriting any existing file. /// </summary> /// <param name="destFileName">The destination path where the file /// will be extracted.</param> /// <param name="overwrite">If true, <paramref name="destFileName"/> /// will be overwritten if it exists.</param> /// <exception cref="IOException"><paramref name="overwrite"/> is false /// and <paramref name="destFileName"/> exists.</exception> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "dest")] public void CopyTo(string destFileName, bool overwrite) { if (destFileName == null) { throw new ArgumentNullException("destFileName"); } if (!overwrite && File.Exists(destFileName)) { throw new IOException(); } if (this.Archive == null) { throw new InvalidOperationException(); } this.Archive.UnpackFile( System.IO.Path.Combine(this.Path, this.Name), destFileName); } /// <summary> /// Opens the archive file for reading without actually extracting the /// file to disk. /// </summary> /// <returns> /// A stream for reading directly from the packed file. Like any stream /// this should be closed/disposed as soon as it is no longer needed. /// </returns> public Stream OpenRead() { return this.Archive.OpenRead(System.IO.Path.Combine(this.Path, this.Name)); } /// <summary> /// Opens the archive file reading text with UTF-8 encoding without /// actually extracting the file to disk. /// </summary> /// <returns> /// A reader for reading text directly from the packed file. Like any reader /// this should be closed/disposed as soon as it is no longer needed. /// </returns> /// <remarks> /// To open an archived text file with different encoding, use the /// <see cref="OpenRead" /> method and pass the returned stream to one of /// the <see cref="StreamReader" /> constructor overloads. /// </remarks> public StreamReader OpenText() { return this.Archive.OpenText(System.IO.Path.Combine(this.Path, this.Name)); } /// <summary> /// Refreshes the information in this object with new data retrieved /// from an archive. /// </summary> /// <param name="newFileInfo">Fresh instance for the same file just /// read from the archive.</param> /// <remarks> /// Subclasses may override this method to refresh sublcass fields. /// However they should always call the base implementation first. /// </remarks> protected virtual void Refresh(ArchiveFileInfo newFileInfo) { this.exists = newFileInfo.exists; this.length = newFileInfo.length; this.attributes = newFileInfo.attributes; this.lastWriteTime = newFileInfo.lastWriteTime; } } }
{ "pile_set_name": "Github" }
""" CFEngine 3 code generator. """ import base64 import codecs from collections import defaultdict import errno import logging import os import os.path import re import tarfile import time import copy import json from pprint import pprint from blueprint import util from blueprint import walk def cfengine3(b, relaxed=False): """ Generate CFEngine 3 code. """ s = Sketch(b.name, policy="main.cf", comment=b.DISCLAIMER) # print json.dumps(b, skipkeys=True, ensure_ascii=False, sort_keys=True, indent=4, separators=(',', ': ')) # # Set the default `PATH` for exec resources. # m.add(Exec.defaults(path=os.environ['PATH'])) def source(dirname, filename, gen_content, url): """ Create file and exec resources to fetch and extract a source tarball. """ s.add(Source(dirname, filename, gen_content, url)); def file(pathname, f): """ Create a file promise. """ s.add(File(pathname, f)) def package(manager, package, version): """ Create a package resource. """ s.add(Package(package, manager, version)) def service(manager, service): """ Create a service resource and subscribe to its dependencies. """ s.add(Service(service, manager)) b.walk(source=source, file=file, # before_packages=before_packages, package=package, service=service) return s class Sketch(object): """ A CFEngine 3 sketch contains any deliverables in file format. """ def __init__(self, name, policy="main.cf", comment=None): """ Each sketch has a name. """ if name is None: self.name = "unknown_blueprint" else: self.name = name self.sketch_name = time.strftime('Blueprint::Sketch::%%s::%Y-%m-%d') % (self.name) self.comment = comment self.namespace = "blueprint_%s" % (self.name) self.policy = Policy(self, name=policy) self.dependencies = { "CFEngine::stdlib": { "version": 105 }, "CFEngine::dclib": {}, "CFEngine::Blueprint": {}, "cfengine": { "version": "3.5.0" } } self.contents = [ self.policy ] def add(self, p): if isinstance(p, File): self.contents.append(p) self.policy.add(p) def allfiles(self): """ Generate the pathname and content of every file. """ for item in self.contents: yield item.pathname, item.dirname if hasattr(item, "dirname") else "", item.content if hasattr(item, "content") else "", item.meta if hasattr(item, "meta") else {} def make_manifest(self): """ Generate the sketch manifest. """ ret = {} for pathname, dirname, content, meta in self.allfiles(): ret[os.path.join(dirname, pathname[1:])] = meta return ret def make_metadata(self): """ Generate the sketch manifest. """ ret = { "name": self.name, "description": "Auto-generated sketch from Blueprint", "version": 1, "license": "unspecified", "tags": [ "blueprint" ], "depends": self.dependencies, "authors": [ "Your Name Here" ], } return ret def make_api(self): """ Generate the sketch API. """ return { "install": [ { "name": "runenv", "type": "environment" }, { "name" : "metadata", "type" : "metadata" }, ], } def _dump(self, w, inline=False, tab=''): """ Generate the sketch index, `sketch.json`. This will call the callable `w` with each line of output. `dumps` and `dumpf` use this to append to a list and write to a file with the same code. If present, a comment is written first. This is followed by the JSON data. """ if self.comment is not None: comment, count = re.subn(r'#', '//', unicode(self.comment)) w(comment) w(json.dumps({ "manifest": self.make_manifest(), "metadata": self.make_metadata(), "namespace": self.namespace, "interface": [ self.policy.interface ], "api": self.make_api(), }, skipkeys=True, ensure_ascii=False, sort_keys=True, indent=4, separators=(',', ': '))) def dumps(self): """ Generate a string containing `sketch.json` only. """ out = [] self._dump(out.append, inline=True) return u''.join(out) def dumpf(self, gzip=False): """ Generate files containing CFEngine 3 code and templates. The directory structure generated is a sketch (sketch.json plus all the rest). """ os.mkdir(self.name) filename = os.path.join(self.name, 'sketch.json') f = codecs.open(filename, 'w', encoding='utf-8') self._dump(f.write, inline=False) f.close() self.policy.make_content() for pathname, dirname, content, meta in self.allfiles(): pathname = os.path.join(self.name, dirname, pathname[1:]) try: os.makedirs(os.path.dirname(pathname)) except OSError as e: if errno.EEXIST != e.errno: raise e if isinstance(content, unicode): f = codecs.open(pathname, 'w', encoding='utf-8') else: f = open(pathname, 'w') f.write(content) f.close() if gzip: filename = 'cfengine3-{0}.tar.gz'.format(self.name) tarball = tarfile.open(filename, 'w:gz') tarball.add(self.name) tarball.close() return filename return filename class Policy(object): """ CFEngine 3 policy: a container for promises. """ def __init__(self, sketch, name="main.cf"): """ The policy name is its filename. """ self.interface = name self.pathname = "/" + name self.promises = [ ] self.sketch = sketch def add(self, promise): self.promises.append(promise) def make_vars(self): """ Generate the variables as CFEngine code. """ v = { "files": {}, "sources": [], "package_manager": [], "service_manager": [] } for promise in self.promises: if isinstance(promise, File): v['files'][promise.pathname] = copy.deepcopy(promise.meta) # we do not support URL sources v['files'][promise.pathname]['source'] = promise.dirname + promise.pathname # TODO: source elif isinstance(promise, Source): logging.warning('TODO: CFEngine handler for Source promise {0}, {1}'.format(promise.filename, promise.dirname)) # v['sources'].append(promise.filename) # v['sources'].append(promise.dirname) # # v['sources'].append(promise.content) # v['sources'].append(promise.url) elif isinstance(promise, Package): if not promise.manager in v['package_manager']: v['package_manager'].append(promise.manager) v.setdefault('packages_' + promise.manager, {})[promise.name] = promise.version elif isinstance(promise, Service): logging.warning('TODO: CFEngine handler for Service promise {0}, {1}'.format(promise.manager, promise.name)) # if not promise.manager in v['service_manager']: # v['service_manager'].append(promise.manager) # v.setdefault('services_' + promise.manager, []).append(promise.name) # return json.dumps(v, skipkeys=True, ensure_ascii=False, sort_keys=True, indent=4, separators=(',', ': ')) return cfe_recurse_print(v, " "), v def make_content(self): """ Generate the policy as CFEngine code and put it in 'content'. """ myvars, v = self.make_vars() ns = self.sketch.namespace packages = "\n".join(map(lambda x: ' "packages %s" inherit => "true", usebundle => cfdc_blueprint:packages($(runenv), "%s", $(%s_packages), "$(blueprint_packages_%s[$(%s_packages)])");' % (x, x, x, x, x), v['package_manager'])) packvars = "\n".join(map(lambda x: ' "%s_packages" slist => getindices("blueprint_packages_%s");' % (x, x), v['package_manager'])) self.content = """ body file control { namespace => "%s"; } bundle agent install(runenv, metadata) { classes: "$(vars)" expression => "default:runenv_$(runenv)_$(vars)"; "not_$(vars)" expression => "!default:runenv_$(runenv)_$(vars)"; vars: "vars" slist => { "@(default:$(runenv).env_vars)" }; "$(vars)" string => "$(default:$(runenv).$(vars))"; "all_files" slist => getindices("blueprint_files"); %s %s methods: "utils" usebundle => default:eu($(runenv)); activated:: "files" inherit => "true", usebundle => cfdc_blueprint:files($(runenv), concat(dirname($(this.promise_filename)), "/files"), $(default:eu.path_prefix), $(all_files), "%s:install.blueprint_files[$(all_files)]"); %s # "sources" inherit => "true", usebundle => cfdc_blueprint:sources($(runenv), dirname($(this.promise_filename)), $(blueprint_sources)); verbose:: "metadata" usebundle => default:report_metadata($(this.bundle), $(metadata)), inherit => "true"; } """ % (ns, myvars, packvars, ns, packages) class Promise(object): """ CFEngine 3 base promise. """ pass class Package(Promise): """ CFEngine 3 packages promise. Only one version is supported. """ def __init__(self, name, manager, version): """ The policy name is a filename. """ self.name = name manager, count = re.subn(r'\W', '_', unicode(manager)) self.manager = manager self.version = version class Service(Promise): """ CFEngine 3 services promise. Not implemented. """ def __init__(self, service, manager): """ The service name is a unique identifier. """ self.name = service manager, count = re.subn(r'\W', '_', unicode(manager)) self.manager = manager class Source(Promise): """ CFEngine 3 services promise. """ def __init__(self, dirname, filename, content, url): """ A source->destination mapping """ self.dirname = dirname self.filename = filename self.content = content self.url = url class File(Promise): """ CFEngine 3 files promise. """ def __init__(self, filename, f): """ A file spec """ self.pathname = filename self.dirname = "files" self.data = f self.meta = { "owner": f['owner'], "group": f['group'], "perms": "" + f['mode'][-4:] } self.content = f['content'] if 'base64' == f['encoding']: self.content = base64.b64decode(self.content) if 'template' in f: logging.warning('TODO: CFEngine file template {0}'.format(pathname)) return def cfe_recurse_print(d, indent): """ CFEngine 3 data dump (to arrays and slists). Currently only supports simple lists and one or two level dicts. """ quoter = lambda x: x if re.match("concat\(", x) else "'%s'" % (x) lines = [] for varname, value in d.iteritems(): if isinstance(value, dict): for k, v in value.iteritems(): if isinstance(v, dict): for k2, v2 in v.iteritems(): lines.append("%s'blueprint_%s[%s][%s]' string => %s;" % (indent, varname, k, k2, quoter(v2))) else: lines.append("%s'blueprint_%s[%s]' string => %s;" % (indent, varname, k, quoter(v))) elif isinstance(value, list): p = map(quoter, value) lines.append("%s'blueprint_%s' slist => { %s };" % (indent, varname, ", ".join(p))) else: logging.warning('Unsupported data in variable %s' % (varname)) return "\n".join(lines)
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Hello World, JSONparse!</string> <string name="app_name">JSONparse</string> </resources>
{ "pile_set_name": "Github" }
<?php namespace Oro\Bundle\ApiBundle\Tests\Unit\Processor\Shared; use Doctrine\ORM\Query; use Doctrine\ORM\QueryBuilder; use Oro\Bundle\ApiBundle\Config\EntityDefinitionConfig; use Oro\Bundle\ApiBundle\Processor\Shared\SetTotalCountHeader; use Oro\Bundle\ApiBundle\Tests\Unit\Fixtures\Entity\Group; use Oro\Bundle\ApiBundle\Tests\Unit\Processor\GetList\GetListProcessorOrmRelatedTestCase; use Oro\Bundle\BatchBundle\ORM\QueryBuilder\CountQueryBuilderOptimizer; use Oro\Component\DoctrineUtils\ORM\ResultSetMappingUtil; use Oro\Component\DoctrineUtils\ORM\SqlQuery; use Oro\Component\DoctrineUtils\ORM\SqlQueryBuilder; use Oro\Component\EntitySerializer\QueryResolver; class SetTotalCountHeaderTest extends GetListProcessorOrmRelatedTestCase { /** @var \PHPUnit\Framework\MockObject\MockObject|CountQueryBuilderOptimizer */ private $countQueryBuilderOptimizer; /** @var \PHPUnit\Framework\MockObject\MockObject|QueryResolver */ private $queryResolver; /** @var SetTotalCountHeader */ private $processor; protected function setUp(): void { parent::setUp(); $this->countQueryBuilderOptimizer = $this->createMock(CountQueryBuilderOptimizer::class); $this->queryResolver = $this->createMock(QueryResolver::class); $this->processor = new SetTotalCountHeader($this->countQueryBuilderOptimizer, $this->queryResolver); } public function testProcessWithoutRequestHeader() { $this->processor->process($this->context); self::assertFalse($this->context->getResponseHeaders()->has('X-Include-Total-Count')); } public function testProcessOnExistingHeader() { $testCount = 135; $this->context->getResponseHeaders()->set('X-Include-Total-Count', $testCount); $this->processor->process($this->context); self::assertEquals( $testCount, $this->context->getResponseHeaders()->get('X-Include-Total-Count') ); } public function testProcessWithTotalCallback() { $testCount = 135; $this->context->setTotalCountCallback( function () use ($testCount) { return $testCount; } ); $this->context->getRequestHeaders()->set('X-Include', ['totalCount']); $this->processor->process($this->context); self::assertEquals( $testCount, $this->context->getResponseHeaders()->get('X-Include-Total-Count') ); } public function testProcessWithWrongTotalCallback() { $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('Expected callable for "totalCount", "stdClass" given.'); $this->context->setTotalCountCallback(new \stdClass()); $this->context->getRequestHeaders()->set('X-Include', ['totalCount']); $this->processor->process($this->context); } public function testProcessWithWrongTotalCallbackResult() { $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('Expected integer as result of "totalCount" callback, "string" given.'); $this->context->setTotalCountCallback( function () { return 'non integer value'; } ); $this->context->getRequestHeaders()->set('X-Include', ['totalCount']); $this->processor->process($this->context); } public function testProcessOrmQueryBuilder() { $entityClass = Group::class; $config = new EntityDefinitionConfig(); $totalCount = 123; $query = $this->doctrineHelper->createQueryBuilder($entityClass, 'e'); $query->setFirstResult(20); $query->setMaxResults(10); $this->countQueryBuilderOptimizer->expects(self::once()) ->method('getCountQueryBuilder') ->willReturnCallback( function (QueryBuilder $qb) { $qb->select('e.id'); return $qb; } ); $this->queryResolver->expects(self::once()) ->method('resolveQuery') ->with(self::isInstanceOf(Query::class), self::identicalTo($config)); $this->setQueryExpectation( $this->getDriverConnectionMock($this->em), 'SELECT count(DISTINCT g0_.id) AS sclr_0 FROM group_table g0_', [['sclr_0' => $totalCount]] ); $this->context->getRequestHeaders()->set('X-Include', ['totalCount']); $this->context->setQuery($query); $this->context->setConfig($config); $this->processor->process($this->context); self::assertEquals( $totalCount, $this->context->getResponseHeaders()->get('X-Include-Total-Count') ); } public function testProcessOrmQuery() { $entityClass = Group::class; $config = new EntityDefinitionConfig(); $totalCount = 123; $query = $this->doctrineHelper->createQueryBuilder($entityClass, 'e'); $query->setFirstResult(20); $query->setMaxResults(10); $this->queryResolver->expects(self::once()) ->method('resolveQuery') ->with(self::isInstanceOf(Query::class), self::identicalTo($config)); $this->setQueryExpectation( $this->getDriverConnectionMock($this->em), 'SELECT count(DISTINCT g0_.id) AS sclr_0 FROM group_table g0_', [['sclr_0' => $totalCount]] ); $this->context->getRequestHeaders()->set('X-Include', ['totalCount']); $this->context->setQuery($query->getQuery()); $this->context->setConfig($config); $this->processor->process($this->context); self::assertEquals( $totalCount, $this->context->getResponseHeaders()->get('X-Include-Total-Count') ); } public function testProcessSqlQueryBuilder() { $config = new EntityDefinitionConfig(); $totalCount = 123; $rsm = ResultSetMappingUtil::createResultSetMapping($this->em->getConnection()->getDatabasePlatform()); $rsm ->addScalarResult('id', 'id') ->addScalarResult('name', 'name'); $qb = new SqlQueryBuilder($this->em, $rsm); $qb ->select('e.id AS id, e.name AS name') ->from('group_table', 'e') ->setFirstResult(20) ->setMaxResults(10); $this->queryResolver->expects(self::never()) ->method('resolveQuery'); $this->getDriverConnectionMock($this->em)->expects(self::once()) ->method('query') ->willReturnCallback(function ($sql) use ($totalCount) { self::assertEquals( 'SELECT COUNT(*)' . ' FROM (SELECT e.id AS id, e.name AS name FROM group_table e) count_query', $sql ); return $this->createCountStatementMock($totalCount); }); $this->context->getRequestHeaders()->set('X-Include', ['totalCount']); $this->context->setQuery($qb); $this->context->setConfig($config); $this->processor->process($this->context); self::assertEquals( $totalCount, $this->context->getResponseHeaders()->get('X-Include-Total-Count') ); } public function testProcessSqlQuery() { $config = new EntityDefinitionConfig(); $totalCount = 123; /** @var Query\ResultSetMapping $rsm */ $rsm = $this->createMock(Query\ResultSetMapping::class); $qb = new SqlQueryBuilder($this->em, $rsm); $qb ->select('e.id AS id, e.name AS name') ->from('group_table', 'e') ->setFirstResult(20) ->setMaxResults(10); $query = new SqlQuery($this->em); $query->setSqlQueryBuilder($qb); $this->queryResolver->expects(self::never()) ->method('resolveQuery'); $this->getDriverConnectionMock($this->em)->expects(self::once()) ->method('query') ->willReturnCallback(function ($sql) use ($totalCount) { self::assertEquals( 'SELECT COUNT(*)' . ' FROM (SELECT e.id AS id, e.name AS name FROM group_table e) count_query', $sql ); return $this->createCountStatementMock($totalCount); }); $this->context->getRequestHeaders()->set('X-Include', ['totalCount']); $this->context->setQuery($query); $this->context->setConfig($config); $this->processor->process($this->context); self::assertEquals( $totalCount, $this->context->getResponseHeaders()->get('X-Include-Total-Count') ); } public function testProcessOnWrongQuery() { $this->expectException(\RuntimeException::class); $this->expectExceptionMessage( 'Expected instance of Doctrine\ORM\QueryBuilder, Doctrine\ORM\Query, ' . 'Oro\Component\DoctrineUtils\ORM\SqlQueryBuilder or Oro\Component\DoctrineUtils\ORM\SqlQuery, ' . '"stdClass" given.' ); $this->context->getRequestHeaders()->set('X-Include', ['totalCount']); $this->context->setQuery(new \stdClass()); $this->context->setConfig(new EntityDefinitionConfig()); $this->processor->process($this->context); } }
{ "pile_set_name": "Github" }
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // <ostream> // template <class charT, class traits = char_traits<charT> > // class basic_ostream; // template<class traits> // basic_ostream<char,traits>& operator<<(basic_ostream<char,traits>& out, const char* s); #include <ostream> #include <cassert> #include "test_macros.h" template <class CharT> class testbuf : public std::basic_streambuf<CharT> { typedef std::basic_streambuf<CharT> base; std::basic_string<CharT> str_; public: testbuf() { } std::basic_string<CharT> str() const {return std::basic_string<CharT>(base::pbase(), base::pptr());} protected: virtual typename base::int_type overflow(typename base::int_type ch = base::traits_type::eof()) { if (ch != base::traits_type::eof()) { int n = static_cast<int>(str_.size()); str_.push_back(static_cast<CharT>(ch)); str_.resize(str_.capacity()); base::setp(const_cast<CharT*>(str_.data()), const_cast<CharT*>(str_.data() + str_.size())); base::pbump(n+1); } return ch; } }; int main(int, char**) { { std::ostream os((std::streambuf*)0); const char* c = "123"; os << c; assert(os.bad()); assert(os.fail()); } { testbuf<char> sb; std::ostream os(&sb); const char* c = "123"; os << c; assert(sb.str() == "123"); } { testbuf<char> sb; std::ostream os(&sb); os.width(5); const char* c = "123"; os << c; assert(sb.str() == " 123"); assert(os.width() == 0); } { testbuf<char> sb; std::ostream os(&sb); os.width(5); left(os); const char* c = "123"; os << c; assert(sb.str() == "123 "); assert(os.width() == 0); } return 0; }
{ "pile_set_name": "Github" }
/**************************************************************************** * Copyright (c) 2013 by Michael Blandford. All rights reserved. * * 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 the author 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * **************************************************************************** * Other Authors: * - Fabian Schurig <[email protected]> * - Max Mäusezahl * - Andre Bernet * - Bertrand Songis * - Bryan J. Rentoul (Gruvin) * - Cameron Weeks * - Erez Raviv * - Jean-Pierre Parisy * - Karl Szmutny * - Michal Hlavinka * - Pat Mackenzie * - Philip Moss * - Rob Thomson * - Romolo Manfredini * - Thomas Husterer * ****************************************************************************/ #define STR_ON "AN " #define STR_OFF "AUS" #define STR_ALTEQ "Hoe=" #define STR_TXEQ "\003Sn=Swr" #define STR_RXEQ "Em=" #define STR_RX "Em" #define STR_TRE012AG "TRE012AGG" // STR_YELORGRED je genau 3 Zeichen lang #define STR_YELORGRED "\003---GelOrgRot" #define STR_A_EQ "A =" #define STR_SOUNDS "\006Warn1 ""Warn2 ""Cheap ""Ring ""SciFi ""Robot ""Chirp ""Tada ""Crickt""Siren ""AlmClk""Ratata""Tick ""Haptc1""Haptc2""Haptc3" #define STR_SWITCH_WARN "Schalter Warnung" // STR_TIMER genau 5 Zeichen lang #define STR_TIMER "Timer" // STR_PPMCHANNELS je genau 4 Zeichen lang #define STR_PPMCHANNELS "\0044CH 6CH 8CH 10CH12CH14CH16CH" #define STR_MAH_ALARM "mAh Limit" // er9x.cpp // ******** #define STR_LIMITS "GRENZEN" #define STR_EE_LOW_MEM "EEPROM wenig Speicher" #define STR_ALERT " ALARM" #define STR_THR_NOT_IDLE "Gas nicht im Ruhezstd" #define STR_RST_THROTTLE "setze auf Standgas" #define STR_PRESS_KEY_SKIP "bel. Taste druecken" #define STR_ALARMS_DISABLE "Alarm ist deaktiviert" #define STR_OLD_VER_EEPROM " EEPROM ist veraltet TESTE EINSTELL/KALIB" #define STR_RESET_SWITCHES "Schalter ausschalten" #define STR_LOADING "LAEDT" #define STR_MESSAGE "NACHRICHT" #define STR_PRESS_ANY_KEY "Taste druecken" #define STR_MSTACK_UFLOW "mStack uflow" #define STR_MSTACK_OFLOW "mStack oflow" #define STR_CHANS_GV "\004P1 P2 P3 HALBVOLLCYC1CYC2CYC3PPM1PPM2PPM3PPM4PPM5PPM6PPM7PPM8CH1 CH2 CH3 CH4 CH5 CH6 CH7 CH8 CH9 CH10CH11CH12CH13CH14CH15CH16SWCHGV1 GV2 GV3 GV4 GV5 GV6 GV7 THIS" #define STR_CHANS_RAW "\004P1 P2 P3 HALBVOLLCYC1CYC2CYC3PPM1PPM2PPM3PPM4PPM5PPM6PPM7PPM8CH1 CH2 CH3 CH4 CH5 CH6 CH7 CH8 CH9 CH10CH11CH12CH13CH14CH15CH16SWCH" #define STR_CH "CH" #define STR_TMR_MODE "\003AUSAN Se0Se%Ho0Ho%Ga0Ga%Qu0Qu%P1 P1%P2 P2%P3 P3%" // OFF=AUS=Timer aus ; ABS=AN=Timer an ; RUs=Se0=Seite bei 0 ; Ru%=Se%=Seite bei x% usw. #define STR_TRIGA_OPTS "OFFAN GasGa%" // pers.cpp // ******** #define STR_ME "ICH " #define STR_MODEL "MODELL " #define STR_BAD_EEPROM "falsche EEprom Daten" #define STR_EE_FORMAT "formatiere EEPROM" #define STR_GENWR_ERROR "Schreibfehler" #define STR_EE_OFLOW "EEPROM oflow" // templates.cpp // *********** #define STR_T_S_4CHAN "Einfache 4-CH" #define STR_T_TCUT "Gas aus" #define STR_T_STICK_TCUT "dauer Gas aus" #define STR_T_V_TAIL "V-Leitw" #define STR_T_ELEVON "Delta\\Nurfluegler" #define STR_T_HELI_SETUP "Heli Einst" #define STR_T_GYRO "Gyro Einst" #define STR_T_SERVO_TEST16 "Servo Test(16)" #define STR_T_SERVO_TEST8 "Servo Test(8)" // menus.cpp // *********** #define STR_TELEM_ITEMS "\004----A1= A2= RSSITSSITim1Tim2HoehGHoeGGesT1= T2= UPM TANKMah1Mah2CvltAkkuAmpsMah CtotFasVBesXBesYBesZVGesGvr1Gvr2Gvr3Gvr4Gvr5Gvr6Gvr7FwatRxV Hdg A3= A4= SC1 SC2 SC3 SC4 TmOK" #define STR_TELEM_SHORT "\004----TIM1TIM2AKKUGvr1Gvr2Gvr3Gvr4Gvr5Gvr6Gvr7" #define STR_GV "GV" #define STR_OFF_ON "AUSAN " #define STR_HYPH_INV "\003---UMK" // Umkehren #define STR_VERSION "Version" #define STR_TRAINER "Trainer" #define STR_SLAVE "\007Slave" #define STR_MENU_DONE "[MENU] WENN FERTIG" #define STR_CURVES "Kurven" #define STR_CURVE "KURVE" #define STR_GLOBAL_VAR "GlobaleVar" #define STR_VALUE "Wert" #define STR_PRESET "VOREINST" #define STR_CV "KV" #define STR_LIMITS "GRENZEN" #define STR_COPY_TRIM "KOPIE TRIM [MENU]" #define STR_TELEMETRY "TELEMETRIE" #define STR_USR_PROTO_UNITS "BenProto\037Units" #define STR_USR_PROTO "BenProto" #define STR_FRHUB_WSHHI "\005FrHubWSHhi" #define STR_MET_IMP "\003MetImp" // Metrisches System / Imperiales System #define STR_A_CHANNEL "A Kanal" #define STR_ALRM "Alrm" #define STR_TELEMETRY2 "TELEMETRIE2" #define STR_TX_RSSIALRM "SnRSSIAlrm" // Sender #define STR_NUM_BLADES "Num Blaetter" //#if ALT_ALARM //#define STR_ALT_ALARM "HoeAlarm" //#define STR_OFF122400 "\003AUS122400" //#endif #define STR_VOLT_THRES "MaxSpannung" #define STR_GPS_ALTMAIN "GPSHoeheHalten" #define STR_CUSTOM_DISP "Ind. Bildschirm" #define STR_FAS_OFFSET "FAS Offset" // FrSky Amperage Sensor (FAS-100) Offset //#define STR_VARIO_SRC_IDX "Vario: Quelle\000\132\002\004----vGesA2 " #define STR_VARIO_SRC "Vario: Quelle" // Variometerquelle #define STR_VSPD_A2 "\004----VGesA2 " // VGeschwindigkeit #define STR_2SWITCH "\001Schalter" #define STR_2SENSITIVITY "\001Empfindlichkt" #define STR_GLOBAL_VARS "GLOBALE VARS" #define STR_GV_SOURCE "\003---StmHtmGtmQtmRENSeiHoeGasQueP1 P2 P3 " // xtm=Trim for channel "x" REN=Rotary Encoder ... = Variablennamen #define STR_TEMPLATES "Vorlagen" #define STR_CHAN_ORDER "Kanal Reihenfolge" #define STR_SP_RETA " SHGQ" // Seitenleitwerk=Rud Höhenleitwerk=Ele Gas=Thr Querruder=Ail #define STR_CLEAR_MIXES "LOESCHE MISCHER [MENU]" #define STR_SAFETY_SW "SICHERHEITS SCH" #define STR_SAFETY_SW2 "Safety Sws" #define STR_NUM_VOICE_SW "Nummer Ton Sch" #define STR_V_OPT1 "\007 8 Sek 12 Sek 16 Sek " #define STR_VS "VS" // ? #define STR_VOICE_OPT "\006AN AUS BEIDE 15Sek 30Sek 60Sek Eigene" #define STR_VOICE_V2OPT "\004 AN AUSBEID ALLONCE" #define STR_CUST_SWITCH "IND. SCHALTER" // Individueller Schalter //#define STR_S "S" #define STR_15_ON "\015An" #define STR_EDIT_MIX "Bearb MISCHER " // Bearbeite Mischer #define STR_2SOURCE "\001Quelle" #define STR_2WEIGHT "\001Dual Rate" #define STR_OFFSET "Offset" #define STR_2FIX_OFFSET "\001Fix Offset" #define STR_FLMODETRIM "\001FlModustrim" #define STR_ENABLEEXPO "\001EnableExpoDR" #define STR_2TRIM "\001Trimmen" #define STR_15DIFF "\015Diff" #define STR_Curve "Kurve" #define STR_2WARNING "\001Warnung" #define STR_2MULTIPLEX "\001Multpx" // STR_ADD_MULT_REP je genau 8 Zeichen #define STR_ADD_MULT_REP "\010Hinzufgn MultipliziErsetzen " #define STR_2DELAY_DOWN "\001Verz. runter" #define STR_2DELAY_UP "\001Verz. hoch" #define STR_2SLOW_DOWN "\001Langsam runtr" #define STR_2SLOW_UP "\001Langsam hoch" #define STR_MAX_MIXERS_EXAB "Max mix erreicht: 32\037\037[EXIT] zum Abbrechen" #define STR_MAX_MIXERS "Max Mix erreicht: 32" #define STR_PRESS_EXIT_AB "[EXIT] zum Abbrechen" #define STR_YES_NO_MENU_EXIT "\003JA \013NEIN\037\003[MENU]\013[EXIT]" #define STR_MENU_EXIT "\003[MENU]\013[EXIT]" #define STR_DELETE_MIX "LOESCHE MISCHER?" #define STR_MIX_POPUP "BEARBEI\0EINFUEG\0KOPIER\0BEWEGE\0LOESCH\0CLEAR ALL" #define STR_MIXER "MISCHER" // CHR_S S for Slow / Langsam #define CHR_S 'L' // CHR_D D for Delay / Verzögert #define CHR_D 'V' // CHR_d d for differential #define CHR_d 'd' #define STR_EXPO_DR "Expo/Dr" #define STR_4DR_HIMIDLO "\008\004DR Hoch\004DR Mitt\004DR Tief" #define STR_4DR_MID "\004DR Mittel" #define STR_4DR_LOW "\004DR Tief" #define STR_4DR_HI "\004DR Hoch" #define STR_EXPO_TEXT "\002Expo\037\037\001Dual Rate\037\037DrSch1\037DrSch2" #define STR_2EXPO "\002Expo" #define STR_DR_SW1 "DrSch1" #define STR_DR_SW2 "DrSch2" #define STR_DUP_MODEL "KOPIERE MODELL" #define STR_DELETE_MODEL "LOESCHE MODELL" #define STR_DUPLICATING "Kopiere Modell" #define STR_SETUP "EINST" #define STR_NAME "Name" #define STR_VOICE_INDEX "Tonfreq \021MENU" #define STR_TIMER_TEXT "Timer\037SignalA\037SignalB\037Timer\037\037\037Reset Switch" #define STR_TIMER_TEXT_X "Timer\037SignalA\037SignalB\037Timer\037Reset Switch" #define STR_TRIGGER "SignalA" #define STR_TRIGGERB "SignalB" //STR_COUNT_DOWN_UP indexed, 10 chars each #define STR_COUNT_DOWN_UP "\012Zaehl runtZaehl hoch" #define STR_T_TRIM "G-Trim" #define STR_T_EXPO "G-Expo-Dr" #define STR_TRIM_INC "Trim Ink" // STR_TRIM_OPTIONS indexed 6 chars each #define STR_TRIM_OPTIONS "\006Expon ExFeinFein MittelGrob " #ifdef V2 #define STR_TRIM_PAGE STR_TRIM_INC"\037"STR_TRIM_SWITCH"\037"STR_TRAINER"\037"STR_BEEP_CENTRE #else #define STR_TRIM_PAGE STR_TRIM_INC"\037"STR_TRIM_SWITCH"\037Hi.Res Slow/Delay\037"STR_TRAINER"\037"STR_BEEP_CENTRE #endif #define STR_TRIM_SWITCH "Trim Sch" #define STR_BEEP_CENTRE "Piep Cen" // Zentrum #define STR_RETA123 "SHGQ123" #define STR_PROTO "Proto" // Protokoll // STR_21_USEC after \021 max 4 chars #define STR_21_USEC "\021uSek" #define STR_13_RXNUM "\014EmNum" //Empfänger // STR_23_US after \023 max 2 chars #define STR_23_US "\023uS" // STR_PPMFRAME_MSEC before \015 max 9 chars, after max 4 chars #define STR_PPMFRAME_MSEC "PPM Laenge\015mSek" // Puls Pausen Modulation #define STR_SEND_RX_NUM "Bind Range" #define STR_DSM_TYPE "DSM Typ" //#if defined(CPUM128) || defined(CPUM2561) #define STR_PXX_TYPE " Type\037 Chans\037 Country\037Bind\037Range" //#else //#define STR_PXX_TYPE " Type\037 Country\037Bind\037Range" //#endif #ifdef MULTI_PROTOCOL #define STR_MULTI_TYPE "Protocol\037Type\037Power\037Bind Autobind\037Range" #define STR_MULTI_OPTION "\013Option" #define M_NONE_STR "\004None" #define M_NY_STR_NZ {1,'N','Y'} #define M_LH_STR "\004HighLow " #endif // MULTI_PROTOCOL #define STR_1ST_CHAN_PROTO "1. Kanal\037Proto" #define STR_PPM_1ST_CHAN "1. Kanal" #define STR_SHIFT_SEL "Signalart" // Signalart // STR_POS_NEG indexed 3 chars each #define STR_VOL_PAGE STR_E_LIMITS"\037""Thr. Default\037"STR_THR_REVERSE"\037""Throttle Open""\037"STR_T_TRIM"\037"STR_T_EXPO #define STR_POS_NEG "\003POSNEG" #define STR_E_LIMITS "E. Grenze" //Erweiterte Grenze #define STR_Trainer "Trainer" #define STR_T2THTRIG "GasStaT2" // 2. Timer startet wenn Gas um 5% bewegt #define STR_AUTO_LIMITS "Autogrenze" // STR_1_RETA indexed 1 char each #define STR_1_RETA "\001SHGQ" #define STR_FL_MODE "FL MODUS" #define STR_SWITCH_TRIMS "Schalter\037Trimmer" #define STR_SWITCH "Schalter" #define STR_TRIMS "Trimmer" #define STR_MODES "MODI" #define STR_SP_FM0 " FM0" #define STR_SP_FM " FM" #define STR_HELI_SETUP "HELI EINST" #define STR_HELI_TEXT "Taumeltyp\037Kollektiv\037Anschlag\037HOE Umkehr\037QUE Umkehr\037COL Direction" #define STR_SWASH_TYPE "Taumeltyp" #define STR_COLLECTIVE "Kollektiv" #define STR_SWASH_RING "Anschlag" #define STR_ELE_DIRECTION "HOE Umkehr" #define STR_AIL_DIRECTION "QUE Umkehr" #define STR_COL_DIRECTION "KOL Umkehr" //Kollektiv #define STR_MODEL_POPUP "EDIT\0BEARBEI\0SEL/EDIT\0KOPIER\0BEWEGE\0LOESCH\0BACKUP\0RESTORE" #define STR_MODELSEL "MODELWAHL" // STR_11_FREE after \011 max 4 chars #define STR_11_FREE "\011frei" #define STR_CALIBRATION "Kalibrierung" // STR_MENU_TO_START after \003 max 15 chars #define STR_MENU_TO_START "\003[MENU] ZUM START" // STR_SET_MIDPOINT after \005 max 11 chars #define STR_SET_MIDPOINT "\005SET MITPUNKT" // STR_MOVE_STICKS after \003 max 15 chars #define STR_MOVE_STICKS "\003BEWG STICKS/POTS" #define STR_ANA "ANA" // Analog Input und Batterie Spannung Kalibrierung #define STR_DIAG "DIAG" // Diagnostics #define STR_KEYNAMES "Links\037Recht\037 Hoch\037Runtr\037 Exit\037Menue" #define STR_TRIM_M_P "Trim- +" // STR_OFF_PLUS_EQ indexed 3 chars each #define STR_OFF_PLUS_EQ "\003aus += :=" // STR_CH1_4 indexed 3 chars each #define STR_CH1_4 "\003ch1ch2ch3ch4" #define STR_MULTIPLIER "Multiplika" #define STR_CAL "Kal" #define STR_MODE_SRC_SW "\003mode\012% que sch" // Quelle Schalter #define STR_RADIO_SETUP "General" #define STR_OWNER_NAME "Nutzername" #define STR_BEEPER "Pieper" // STR_BEEP_MODES indexed 6 chars each #define STR_BEEP_MODES "\006Lautls""TstAus""xKurz ""Kurz ""Normal""Lang ""xLang " // x = seh #define STR_SOUND_MODE "Soundmodus" // STR_SPEAKER_OPTS indexed 10 chars each #define STR_SPEAKER_OPTS "\012Pieper ""PiLautspre""PieprTon ""PieLautTon""MegaSound " #define STR_VOLUME "Lautst" #define STR_SPEAKER_PITCH "Tonhoehe" #define STR_HAPTICSTRENGTH "Haptische Staerke" #define STR_CONTRAST "Kontrast" #define STR_BATT_WARN "Batterie Warnung" // STR_INACT_ALARM m for minutes after \023 - single char #define STR_INACT_ALARM "Inaktivitatalarm\023m" #define STR_THR_REVERSE "Gasumkehr" #define STR_MINUTE_BEEP "Minutenton" #define STR_BEEP_COUNTDOWN "Piep Countdown" #define STR_FLASH_ON_BEEP "Blitz bei Piep" #define STR_LIGHT_SW_TEXT "Lichtschalter\037\037Licht aus nach\023s\037Licht an Stkbeweg\023s" #define STR_LIGHT_SWITCH "Lichtschalter" #define STR_LIGHT_INVERT "Licht umkehren" #define STR_LIGHT_AFTER "Licht aus nach\023s" #define STR_LIGHT_STICK "Licht an Stkbeweg\023s" #define STR_SPLASH_SCREEN "Startbildschirm" #define STR_SPLASH_NAME "Start Name" #define STR_THR_WARNING "Gas Warnung" #define STR_DEAFULT_SW_PAGE "StdSchlt\037CustomStkNames\037Autogrenze\037Throttle Default" #define STR_DEAFULT_SW "Stdr.Schalt" #define STR_MEM_WARN "Speicher Warnung" #define STR_ALARM_WARN "Alarm Warnung" #define STR_POTSCROLL "PotScroll" #define STR_STICKSCROLL "StickScroll" #define STR_BANDGAP "BandLuecke" #define STR_ENABLE_PPMSIM "Aktiviere PPMSIM" #define STR_CROSSTRIM "KreuzTrim" #define STR_INT_FRSKY_ALRM "Int. Frsky alarm" #define STR_MODE "Modus" // SWITCHES_STR 3 chars each #ifdef XSW_MOD #define SWITCHES_STR "\003IDLGASSEIHOEQUEFWKPB1PB2TRNL1 L2 L3 L4 L5 L6 L7 L8 L9 LA LB LC LD LE LF LG LH LI ID0ID1ID2TH\200TH-TH\201RU\200RU-RU\201EL\200EL-EL\201AI\200AI-AI\201GE\200GE-GE\201" #else // !XSW_MOD #if defined(CPUM128) || defined(CPUM2561) #define SWITCHES_STR "\003GASSEIHOEID0ID1ID2QUEFWKTRNL1 L2 L3 L4 L5 L6 L7 L8 L9 LA LB LC LD LE LF LG LH LI EL\200EL-EL\201RU\200RU-RU\201AI\200AI-AI\201GE\200GE-GE\201PB1PB2" #else #define SWITCHES_STR "\003GASSEIHOEID0ID1ID2QUEFWKTRNL1 L2 L3 L4 L5 L6 L7 L8 L9 LA LB LC " #endif #endif // XSW_MOD #define SWITCH_WARN_STR "Schalter Warnung" // CURV_STR indexed 3 chars each #define CURV_STR "\003---x>0x<0|x|f>0f<0|f|c1 c2 c3 c4 c5 c6 c7 c8 c9 c10c11c12c13c14c15c16" // CSWITCH_STR indexed 7 chars each #ifdef VERSION3 #if defined(CPUM128) || defined(CPUM2561) #define CSWITCH_STR "\007---- v>val v<val |v|>val|v|<valAND OR XOR v1==v2 v1!=v2 v1>v2 v1<v2 Latch F-Flop TimeOffv\140=val 1-Shot 1-ShotR" #else #define CSWITCH_STR "\007---- v>val v<val |v|>val|v|<valAND OR XOR v1==v2 v1!=v2 v1>v2 v1<v2 Latch F-Flop TimeOffv\140=val " #endif #else #define CSWITCH_STR "\007---- v>val v<val |v|>val|v|<valUND ODER XOR ""v1==v2 ""v1!=v2 ""v1>v2 ""v1<v2 ""v1>=v2 ""v1<=v2 ZeitAusv1\140=val" #endif #define SWASH_TYPE_STR "\004----""120 ""120X""140 ""90 " #if defined(CPUM128) || defined(CPUM2561) #define STR_STICK_NAMES "Sei \0Hoe \0Gas \0Que " #else #define STR_STICK_NAMES "Sei Hoe Gas Que " #endif #define STR_STAT "STAT" #define STR_STAT2 "STAT2" // STR_TRIM_OPTS indexed 3 chars each #define STR_TRIM_OPTS "\003ExpxFeFeiMitStk" // ExF= extra fein; Fne = fein; Med = medium; Crs = Coarse sehr stark #define STR_TTM "GTm" // Gas Trim #define STR_FUEL "TANK" #define STR_12_RPM "\012UPM" #define STR_LAT_EQ "Bre=" #define STR_LON_EQ "Lae=" #define STR_ALT_MAX "Hoe=\011m Max=" #define STR_SPD_KTS_MAX "Ges=\011kts Max=" #define STR_11_MPH "\011mph" #define STR_SINK_TONES "Sink Tones" //#define STR_NO_SINK_TONES "Kein Sinkton" #define STR_FRSKY_MOD "Frsky Mod Fertig" #define STR_TEZ_R90 "TelemetrEZ>=r90" // ersky9x strings #define STR_ST_CARD_STAT "SD CARD STAT" #define STR_4_READY "\004Bereit" #define STR_NOT "NICHT" #define STR_BOOT_REASON "BOOT GRUND" #define STR_6_WATCHDOG "\006WAECHTER" #define STR_5_UNEXPECTED "\005UNERWARTET" #define STR_6_SHUTDOWN "\006AUSSCHALTEN" #define STR_6_POWER_ON "\006EINSCHALTEN" // STR_MONTHS indexed 3 chars each #define STR_MONTHS "\003XxxJanFebMrzAprMaiJunJulAugSepOktNovDez" #define STR_MENU_REFRESH "[MENU] NEU LADEN" #define STR_DATE_TIME "DATUM-ZEIT" #define STR_SEC "Sek." #define STR_MIN_SET "Min.\015Set" #define STR_HOUR_MENU_LONG "Std.\012MENU LANG" #define STR_DATE "Datum" #define STR_MONTH "Monat" #define STR_YEAR_TEMP "Jahr\013Temp." #define STR_YEAR "Jahr" #define STR_BATTERY "BATTERIE" #define STR_Battery "Batterie" #define STR_CURRENT_MAX "Momentan\016Max" #define STR_CPU_TEMP_MAX "CPU temp.\014C Max\024C" #define STR_MEMORY_STAT "SPEICHER STAT" #define STR_GENERAL "Generell" #define STR_Model "Modell" #define STR_RADIO_SETUP2 "FERNST EINST2" #define STR_BRIGHTNESS "Helligkeit" #define STR_CAPACITY_ALARM "Kapazitaet Alarm" #define STR_BT_BAUDRATE "Bt baudrate" #define STR_ROTARY_DIVISOR "Rot Teiler" #define STR_STICK_LV_GAIN "Stick LV Anstieg" #define STR_STICK_LH_GAIN "Stick LH Anstieg" #define STR_STICK_RV_GAIN "Stick RV Anstieg" #define STR_STICK_RH_GAIN "Stick RH Anstieg" #define STR_DISPLAY "Display" #define STR_HARDWARE "Hardware" ; #define STR_ALARMS "Alarms" ; #define STR_CONTROLS "Controls" ; #define STR_AUDIOHAPTIC "AudioHaptic" ; #define STR_DIAGSWTCH "DiagSwtch" ; #define STR_DIAGANA "DiagAna" ; #define STR_PROTOCOL "Protocol" #define STR_MIXER2 "Mixer" #define STR_CSWITCHES "L.Switches" #define STR_VOICE "Voice" #define STR_VOICEALA "Voice Alarms" #define STR_CLEAR_ALL_MIXES "Clear ALL mixes?" #define STR_MAIN_POPUP "Model Select\0Model Setup\0Last Menu\0Radio Setup\0Statistics" #define MODEL_SETUP_OFFSET 13 #define RADIO_SETUP_OFFSET 35 /* Extra data for MavLink via FrSky */ #define STR_MAV_FM_0 "STAB" #define STR_MAV_FM_1 "ACRO" #define STR_MAV_FM_2 "A-Hold" #define STR_MAV_FM_3 "AUTO" #define STR_MAV_FM_4 "GUIDED" #define STR_MAV_FM_5 "LOITER" #define STR_MAV_FM_6 "RTL" #define STR_MAV_FM_7 "CIRCLE" #define STR_MAV_FM_8 "MODE8" #define STR_MAV_FM_9 "LAND" #define STR_MAV_ARMED "ARMED" #define STR_MAV_DISARMED "DISARM" #define STR_MAV_NODATA "NODATA" #define STR_MAV_CURRENT "Cur" #define STR_MAV_GPS_NO_GPS "No GPS" #define STR_MAV_GPS "GPS:" #define STR_MAV_GPS_NO_FIX "No Fix" // 1 #define STR_MAV_GPS_2DFIX "2D Fix" // 2 #define STR_MAV_GPS_3DFIX "3D Fix" // 3 #define STR_MAV_GPS_SAT_COUNT "sat" #define STR_MAV_GPS_HDOP "hdop" #define STR_MAV_THR_OUT "THR%" #define STR_MAV_WP_DIST "WP" #define STR_MAV_ALT "alt" #define STR_MAV_GALT "gAl" #define STR_MAV_HOME "dth" #define STR_MAV_CPU "cpu" #define STR_RSSI "Rssi" #define STR_RCQ "Rcq" #define STR_MAV_HEALTH "Health" #define STR_MAV_OK "Ok" /* Extra data for er9x FrSky+MavLink firmware End */ #if defined(CPUM128) || defined(CPUM2561) // Actual for THISFIRMWARE "ArduCopter V3.3-dev" // check actual data at https://github.com/diydrones/ardupilot/search?q=SEVERITY_HIGH #define STR_MAV_ERR_01 " ARMING MOTORS " #define STR_MAV_ERR_02 "PreArm: RC not calibr" #define STR_MAV_ERR_03 "PreArm: BaroBadHealth" #define STR_MAV_ERR_04 "PreArm: CompassHealth" #define STR_MAV_ERR_05 "PreArm: Bad GPS Pos " #define STR_MAV_ERR_06 " Compass disabled " #define STR_MAV_ERR_07 " Check compass " #define STR_MAV_ERR_08 "MotorTest:RC NotCalib" #define STR_MAV_ERR_09 "MotorTest: Not landed" #define STR_MAV_ERR_10 " Crash: Disarming " #define STR_MAV_ERR_11 "Parachute: Released! " #define STR_MAV_ERR_12 "Error SettingRallyPnt" #define STR_MAV_ERR_13 " AutoTune: Started " #define STR_MAV_ERR_14 " AutoTune: Stopped " #define STR_MAV_ERR_15 " Trim saved " #define STR_MAV_ERR_16 "EKF: Compass Variance" #define STR_MAV_ERR_17 "Verify: InvalidNavCMD" #define STR_MAV_ERR_18 "Verify: InvlidCondCMD" #define STR_MAV_ERR_19 "Disable fence failed " #define STR_MAV_ERR_20 "ESC Cal:Restart Board" #define STR_MAV_ERR_21 "ESC Cal:PassThrToESCs" #define STR_MAV_ERR_22 "---- Low Battery ----" #define STR_MAV_ERR_23 "----- Lost GPS ------" #define STR_MAV_ERR_24 " Fence autodisabled " #endif /* Extra data for er9x FrSky+MavLink firmware End */
{ "pile_set_name": "Github" }
package sangria.util import sangria.util.StringUtil._ import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec class StringUtilSpec extends AnyWordSpec with Matchers with StringMatchers { "camelCaseToUnderscore" should { "convert camel-case identifiers to underscore-based one" in { camelCaseToUnderscore("FooBar") should be ("foo_bar") camelCaseToUnderscore("Foo1Bar") should be ("foo1_bar") camelCaseToUnderscore("FooBar_Baz") should be ("foo_bar_baz") camelCaseToUnderscore("_Foo_Bar_") should be ("foo_bar") } } "quotedOrList" should { "Does not accept an empty list" in { an [IllegalArgumentException] should be thrownBy quotedOrList(Nil) } "Returns single quoted item" in { quotedOrList(Seq("A")) should be ("'A'") } "Returns two item list" in { quotedOrList(Seq("A", "B")) should be ("'A' or 'B'") } "Returns comma separated many item list" in { quotedOrList(Seq("A", "B", "C")) should be ("'A', 'B' or 'C'") } "Limits to five items" in { quotedOrList(Seq("A", "B", "C", "D", "E", "F")) should be ("'A', 'B', 'C', 'D' or 'E'") } } "suggestionList" should { "Returns results when input is empty" in { suggestionList("", Seq("a")) should be (Seq("a")) } "Returns empty array when there are no options" in { suggestionList("input", Seq.empty) should be (Seq.empty) } "Returns options sorted based on similarity" in { suggestionList("abc", Seq("a", "ab", "abc")) should be (Seq("abc", "ab")) } } "blockStringValue" should { "removes uniform indentation from a string" in { blockStringValue( """ | Hello, | World! | | Yours, | GraphQL. |""".stripMargin ) should equal ( """Hello, | World! | |Yours, | GraphQL.""".stripMargin ) (after being strippedOfCarriageReturns) } "removes empty leading and trailing lines" in { blockStringValue( """ | | Hello, | World! | | Yours, | GraphQL. | |""".stripMargin ) should equal ( """Hello, | World! | |Yours, | GraphQL.""".stripMargin ) (after being strippedOfCarriageReturns) } "removes blank leading and trailing lines" in { val spaces = " " * 10 blockStringValue( s""" |$spaces | Hello, | World! | | Yours, | GraphQL. |$spaces |""".stripMargin ) should equal ( """Hello, | World! | |Yours, | GraphQL.""".stripMargin ) (after being strippedOfCarriageReturns) } "retains indentation from first line" in { blockStringValue( """ Hello, | World! | | Yours, | GraphQL. |""".stripMargin ) should equal ( """ Hello, | World! | |Yours, | GraphQL.""".stripMargin ) (after being strippedOfCarriageReturns) } "does not alter trailing spaces" in { val spaces = " " * 10 blockStringValue( s""" | Hello,$spaces | World!$spaces | $spaces | Yours,$spaces | GraphQL.$spaces |""".stripMargin ) should equal ( s"""Hello,$spaces | World!$spaces |$spaces |Yours,$spaces | GraphQL.$spaces""".stripMargin ) (after being strippedOfCarriageReturns) } "handles empty strings" in { val spaces = " " * 10 blockStringValue( s""" |$spaces | |$spaces |""".stripMargin ) should equal ( "".stripMargin ) (after being strippedOfCarriageReturns) blockStringValue("") should equal ("") } } }
{ "pile_set_name": "Github" }
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #include "SequencerKeyActor.h" #include "Components/StaticMeshComponent.h" #include "Sections/MovieScene3DTransformSection.h" #include "SequencerEdMode.h" #include "Materials/MaterialInstance.h" #include "Materials/MaterialInstanceDynamic.h" #include "Engine/Selection.h" #include "EditorModeTools.h" #include "EditorModeManager.h" #include "ModuleManager.h" #include "EditorViewportClient.h" #include "UnrealClient.h" ASequencerKeyActor::ASequencerKeyActor() : Super() { UStaticMesh* KeyEditorMesh = LoadObject<UStaticMesh>(nullptr, TEXT("/Engine/VREditor/TransformGizmo/SM_Sequencer_Key")); check(KeyEditorMesh != nullptr); UMaterial* KeyEditorMaterial = LoadObject<UMaterial>(nullptr, TEXT("/Engine/VREditor/TransformGizmo/Main")); check(KeyEditorMaterial != nullptr); const bool bTransient = true; USceneComponent* SceneComponent = CreateDefaultSubobject<USceneComponent>(TEXT("SceneComponent"), bTransient); check(SceneComponent != nullptr); this->RootComponent = SceneComponent; KeyMeshComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("KeyMesh")); KeyMeshComponent->SetMobility(EComponentMobility::Movable); KeyMeshComponent->SetupAttachment(RootComponent); KeyMeshComponent->SetStaticMesh(KeyEditorMesh); KeyMeshComponent->CreateAndSetMaterialInstanceDynamicFromMaterial(0, KeyEditorMaterial); KeyMeshComponent->SetCollisionEnabled(ECollisionEnabled::QueryOnly); KeyMeshComponent->SetCollisionResponseToAllChannels(ECR_Ignore); KeyMeshComponent->SetCollisionResponseToChannel(ECC_Visibility, ECR_Block); KeyMeshComponent->bGenerateOverlapEvents = false; KeyMeshComponent->SetCanEverAffectNavigation(false); KeyMeshComponent->bCastDynamicShadow = false; KeyMeshComponent->bCastStaticShadow = false; KeyMeshComponent->bAffectDistanceFieldLighting = false; KeyMeshComponent->bAffectDynamicIndirectLighting = false; } void ASequencerKeyActor::PostEditMove(bool bFinished) { // Push the key's transform to the Sequencer track PropagateKeyChange(); Super::PostEditMove(bFinished); } void ASequencerKeyActor::SetKeyData(class UMovieScene3DTransformSection* NewTrackSection, float NewKeyTime) { TrackSection = NewTrackSection; KeyTime = NewKeyTime; // Associate the currently selected actor with this key AssociatedActor = GEditor->GetSelectedActors()->GetTop<AActor>(); // Draw a single transform track based on the data from this key FEditorViewportClient* ViewportClient = StaticCast<FEditorViewportClient*>(GEditor->GetActiveViewport()->GetClient()); if (ViewportClient != nullptr) { FSequencerEdMode* SequencerEdMode = (FSequencerEdMode*)(ViewportClient->GetModeTools()->GetActiveMode(FSequencerEdMode::EM_SequencerMode)); SequencerEdMode->DrawMeshTransformTrailFromKey(this); } } void ASequencerKeyActor::PropagateKeyChange() { if (TrackSection != nullptr) { // Mark the track section as dirty TrackSection->Modify(); // Update the translation keys FRichCurve& TransXCurve = TrackSection->GetTranslationCurve(EAxis::X); FRichCurve& TransYCurve = TrackSection->GetTranslationCurve(EAxis::Y); FRichCurve& TransZCurve = TrackSection->GetTranslationCurve(EAxis::Z); TransXCurve.UpdateOrAddKey(KeyTime, GetActorTransform().GetLocation().X); TransYCurve.UpdateOrAddKey(KeyTime, GetActorTransform().GetLocation().Y); TransZCurve.UpdateOrAddKey(KeyTime, GetActorTransform().GetLocation().Z); // Draw a single transform track based on the data from this key FEditorViewportClient* ViewportClient = StaticCast<FEditorViewportClient*>(GEditor->GetActiveViewport()->GetClient()); if (ViewportClient != nullptr) { FSequencerEdMode* SequencerEdMode = (FSequencerEdMode*)(ViewportClient->GetModeTools()->GetActiveMode(FSequencerEdMode::EM_SequencerMode)); SequencerEdMode->DrawMeshTransformTrailFromKey(this); } } }
{ "pile_set_name": "Github" }
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.test.annotations.onetomany; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToOne; import org.hibernate.annotations.Formula; /** * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ @Entity public class Item implements Serializable { @Id private int id; @Column( name = "code" ) private String code; @Formula( "( SELECT LENGTH( code ) FROM DUAL )" ) private int sortField; @ManyToOne private Box box; public Item() { } public Item(int id, String code, Box box) { this.id = id; this.code = code; this.box = box; } @Override public boolean equals(Object o) { if ( this == o ) return true; if ( !( o instanceof Item ) ) return false; Item item = (Item) o; if ( id != item.id ) return false; if ( sortField != item.sortField ) return false; if ( code != null ? !code.equals( item.code ) : item.code != null ) return false; return true; } @Override public int hashCode() { int result = id; result = 31 * result + ( code != null ? code.hashCode() : 0 ); result = 31 * result + sortField; return result; } @Override public String toString() { return "Item(id = " + id + ", code = " + code + ", sortField = " + sortField + ")"; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public int getSortField() { return sortField; } public void setSortField(int sortField) { this.sortField = sortField; } public Box getBox() { return box; } public void setBox(Box box) { this.box = box; } }
{ "pile_set_name": "Github" }
============== Install OpenMW ============== The (easier) Binary Way ======================= If you're not sure what any of the different methods mean, you should probably stick to this one. Simply download the latest version for your operating system from `github.com/OpenMW/openmw/releases <https://github.com/OpenMW/openmw/releases>`_ and run the install package once downloaded. It's now installed! .. note:: There is no need to uninstall previous versions as OpenMW automatically installs into a separate directory for each new version. Your saves and configuration are compatible and accessible between versions. The (bleeding edge) Source Way ============================== Visit the `Development Environment Setup <https://wiki.openmw.org/index.php?title=Development_Environment_Setup>`_ section of the Wiki for detailed instructions on how to build the engine. The Ubuntu Way ============== A `Launchpad PPA <https://launchpad.net/~openmw/+archive/openmw>`_ is available. Add it and install OpenMW:: $ sudo add-apt-repository ppa:openmw/openmw $ sudo apt-get update $ sudo apt-get install openmw openmw-launcher .. note:: OpenMW-CS must be installed separately by typing:: $ sudo apt-get install openmw-cs The Arch Linux Way ================== The binary package is available in the official [community] Repositories. To install, simply run the following as root (or in sudo):: # pacman -S openmw The Void Linux Way ================== The binary package is available in the official Repository To install simply run the following as root (or in sudo):: # xbps-install openmw The Debian Way ============== OpenMW is available from the unstable (sid) repository of Debian contrib and can be easily installed if you are using testing or unstable. However, it depends on several packages which are not in stable, so it is not possible to install OpenMW in Wheezy without creating a FrankenDebian. This is not recommended or supported.
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2" android:orientation="horizontal" android:layout_width="150dp" android:layout_height="46dp" android:weightSum="3"> <ImageView android:id="@+id/dos" android:background="@drawable/bf1" android:layout_width="0dp" android:layout_height="match_parent" android:src="@drawable/u2" android:scaleType="center" android:layout_weight="1"/> <TextView android:textSize="@dimen/fr" android:textColor="#353535" android:gravity="center" android:id="@+id/dot" android:background="@drawable/bf0" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1"/> <ImageView android:id="@+id/dou" android:background="@drawable/bf5" android:layout_width="0dp" android:layout_height="match_parent" android:src="@drawable/u0" android:scaleType="center" android:layout_weight="1"/> </LinearLayout>
{ "pile_set_name": "Github" }
# -*- coding: utf-8 -*- # Copyright 2015 Objectif Libre # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # import unittest from unittest import mock from oslo_utils import uuidutils from cloudkitty.fetcher import keystone from cloudkitty import tests class FakeRole(object): def __init__(self, name, uuid=None): self.id = uuid if uuid else uuidutils.generate_uuid() self.name = name class FakeTenant(object): def __init__(self, id): self.id = id class FakeKeystoneClient(object): user_id = 'd89e3fee-2b92-4387-b564-63901d62e591' def __init__(self, **kwargs): pass class FakeTenants(object): @classmethod def list(cls): return [FakeTenant('f266f30b11f246b589fd266f85eeec39'), FakeTenant('4dfb25b0947c4f5481daf7b948c14187')] class FakeRoles(object): roles_mapping = { 'd89e3fee-2b92-4387-b564-63901d62e591': { 'f266f30b11f246b589fd266f85eeec39': [FakeRole('rating'), FakeRole('admin')], '4dfb25b0947c4f5481daf7b948c14187': [FakeRole('admin')]}} @classmethod def roles_for_user(cls, user_id, tenant, **kwargs): return cls.roles_mapping[user_id][tenant.id] roles = FakeRoles() tenants = FakeTenants() def Client(**kwargs): return FakeKeystoneClient(**kwargs) class KeystoneFetcherTest(tests.TestCase): def setUp(self): super(KeystoneFetcherTest, self).setUp() self.conf.set_override('backend', 'keystone', 'tenant_fetcher') self.conf.import_group('fetcher_keystone', 'cloudkitty.fetcher.keystone') @unittest.SkipTest def test_fetcher_keystone_filter_list(self): kclient = 'keystoneclient.client.Client' with mock.patch(kclient) as kclientmock: kclientmock.return_value = Client() fetcher = keystone.KeystoneFetcher() kclientmock.assert_called_once_with( auth_url='http://127.0.0.1:5000/v2.0', username='cloudkitty', password='cloudkitty', tenant_name='cloudkitty', region_name='RegionOne') tenants = fetcher.get_tenants() self.assertEqual(['f266f30b11f246b589fd266f85eeec39'], tenants)
{ "pile_set_name": "Github" }
sha256:f66c6c262f966c5dae9767bd3f37a3c03574812f6e1ae79b6d49e78830bb9d5e
{ "pile_set_name": "Github" }
/**************************************************/ /* Deux fenˆtre en mˆme temps, avec fonctions */ /* Laser C WIND3.C */ /**************************************************/ #include <osbind.h> #include "gem_inex.c" int whandle[2], /* Tout pour deux Fenˆtres */ opened[2] = {1, 1}; /* Drapeau si fenˆtre ouverte */ int tampon[8]; /* Les messages AES arrivent ici */ int wx[2] = {20, 50}, /* Dimensions ext‚rieures des fenˆtres */ wy[2] = {20, 50}, /* avec valeurs initiales */ ww[2] = {200, 200}, wh[2] = {120, 120}; int xdesk, ydesk, wdesk, hdesk; /* Dimensions du Bureau */ int i, window; /* Variables */ void clip_window (pxyarray) /* Limite tous les affichages VDI */ int pxyarray[]; /* suivants … une seule zone */ { vs_clip (handle, 1, pxyarray); /* 1: Active le clipping */ } void switch_clipping_off() /* annule clip_window */ { int pxyarray[4]; vs_clip (handle, 0, pxyarray); /* 0: Clipping d‚sactiv‚ */ } void output_text(window) int window; { int pxyarray[4], x,y,w,h; /* Calcul de la zone de travail */ wind_calc (1, 63, wx[window], wy[window], ww[window], wh[window], &x, &y, &w, &h); /* Conversion de hauteur/largeur en deuxiŠme angle: (x2/y2) */ pxyarray[0] = x; pxyarray[1] = y; pxyarray[2] = x+w-1; pxyarray[3] = y+h-1; clip_window (pxyarray); draw_text (pxyarray, x, y); switch_clipping_off(); } draw_text (pxyarray, x, y) int pxyarray[], x, y; { /* D‚sactiver le pointeur souris */ v_hide_c (handle); /* Effacer zone de travail */ vsf_interior (handle, 0); /* Remplir avec couleur du fond */ vsf_perimeter (handle, 0); /* pas de cadre */ v_bar (handle, pxyarray); /* Rectangle rempli de blanc */ vsf_perimeter (handle, 1); /* R‚activer le cadre */ /* Nous ‚crivons un texte quelconque dans la fenˆtre */ v_gtext (handle, x + 8, y + 14, "Salut! Voici une d‚monstration de fenˆtre"); v_gtext (handle, x + 8, y + 30, "Vous pouvez d‚placer la fenˆtre et modifier sa taille."); v_gtext (handle, x + 8, y + 46, "Pour quitter, cliquer sur la boŒte de fermeture!"); /* R‚afficher le pointeur souris */ v_show_c (handle, 1); } int create_windows() { /* Passer la taille du bureau par la commande no 4 de wind_get */ /* Le bureau a un handle (identificateur) de fenˆtre fixe: le 0 */ wind_get (0, 4, &xdesk, &ydesk, &wdesk, &hdesk); for (i = 0; i <= 1; i++) whandle[i] = wind_create (63, xdesk, ydesk, wdesk, hdesk); return (whandle[0] < 0 || whandle[1] < 0); } int intersect (x1, y1, w1, h1, x2, y2, w2, h2, pxyarray) int x1, y1, w1, h1, x2, y2, w2, h2, pxyarray[]; { int x, y, w, h; w = (x2+w2 < x1+w1) ? x2+w2 : x1+w1; h = (y2+h2 < y1+h1) ? y2+h2 : y1+h1; x = (x2 > x1) ? x2 : x1; y = (y2 > y1) ? y2 : y1; pxyarray[0] = x; pxyarray[1] = y; pxyarray[2] = w - 1; pxyarray[3] = h - 1; return (w > x && h > y); } void redraw (window) int window; { int x, y, w, h, /* Nouvelle zone … dessiner */ rx, ry, rw, rh, /* Variables pour la liste des rectangles */ ax, ay, aw, ah, /* Zone de travail */ pxyarray[4]; wind_update (1); /* D‚sactiver souris, bloquer la liste des rectangles */ x = tampon[4]; /* Coordonn‚es de la zone … redessiner */ y = tampon[5]; /* (fait partie du message) */ w = tampon[6]; h = tampon[7]; /* Passer les dimensions de la zone de travail */ wind_calc (1, 63, wx[window], wy[window], ww[window], wh[window], &ax, &ay, &aw, &ah); /* Appel du premier rectangle de la liste: (11) */ wind_get (whandle[window], 11, &rx, &ry, &rw, &rh); while (rw != 0) /* Tant que largeur > 0... */ { if (intersect (x, y, w, h, rx, ry, rw, rh, pxyarray)) { clip_window (pxyarray); draw_text (pxyarray, ax, ay); /* pxyarray indique le rectangle … dessiner et */ /* x et y donnent le coin sup‚rieur gauche */ /* (pas forc‚ment dans le rectangle) */ } wind_get (whandle[window], 12, &rx, &ry, &rw, &rh); /* Rectangle suivant */ } switch_clipping_off(); wind_update (0); /* Nous avons termin‚ */ } main() { gem_init(); graf_mouse (0, 0L); /* Pointeur souris: flŠche */ if (create_windows()) /* La fonction retourne 1 en cas d'erreur */ form_alert (1, "[3][D‚sol‚!|Plus de handle fenˆtre disponible!][OK]"); else { /* Param‚trer lignes de titre et d'information */ wind_set (whandle[0], 2, "Fenˆtre 1", 0, 0); wind_set (whandle[1], 2, "Fenˆtre 2", 0, 0); wind_set (whandle[0], 3, "Veuillez noter:", 0, 0); wind_set (whandle[1], 3, "Veuillez noter ‚galement:", 0, 0); /* Ouvrir une fenˆtre et ‚crire quelque chose */ for (i = 0; i <= 1; i++) { wind_open (whandle[i], wx[i], wy[i], ww[i], wh[i]); output_text (i); } /*******************************************************************/ /* Voici le plus important: */ /* Nous attendons des activit‚s de l'utilisateur et les exploitons */ /*******************************************************************/ do { evnt_mesag (tampon); /* Attente d'un message */ /* Passer l'index de la fenˆtre origine du message */ /* tampon[3] contient le handle de la fenˆtre */ for (window = 0; !(tampon[3] == whandle[window] || window == 2); window++); if (window != 2) /* Trouv‚ le handle ou notre fenˆtre? */ { switch (tampon[0]) { case 20: /* Redraw */ redraw (window); break; case 21: /* Topped */ wind_set(whandle[window], 10, 0, 0, 0, 0); /* 10 -> Top */ break; case 23: /* BoŒte plein ‚cran */ wx[window] = xdesk + 2; wy[window] = ydesk + 2; ww[window] = wdesk - 6; wh[window] = hdesk - 6; wind_set (whandle[window], 5, wx[window], wy[window], ww[window], wh[window]); /* nouvelles dimensions */ break; case 27: /* Size Box (boŒte de modification de taille) */ ww[window] = tampon[6]; wh[window] = tampon[7]; wind_set (whandle[window], 5, wx[window], wy[window], ww[window], wh[window]); /* Nouvelles dimensions */ break; case 28: /* Barre de d‚placement */ wx[window] = tampon[4]; wy[window] = tampon[5]; wind_set (whandle[window], 5, wx[window], wy[window], ww[window], wh[window]); /* Nouvelles dimensions */ break; case 22: /* Close Box (boŒte fermeture) */ wind_close (whandle[window]); wind_delete (whandle[window]); opened[window] = 0; /* d‚signer comme ferm‚ */ break; } } } while (opened[0] || opened[1]); /* Jusqu'… ce que les 2 fenˆtres */ } /* soient ferm‚es */ gem_exit(); }
{ "pile_set_name": "Github" }
<NUnitProject> <Settings activeconfig="Debug" /> <Config name="Debug" binpathtype="Auto"> <assembly path="bin\Debug\IronAHK.Tests.dll" /> </Config> <Config name="Release" binpathtype="Auto" /> </NUnitProject>
{ "pile_set_name": "Github" }
// Copyright (C) 2013 Davis E. King ([email protected]) // License: Boost Software License See LICENSE.txt for the full license. #undef DLIB_DRAW_SURf_POINTS_ABSTRACT_H_ #ifdef DLIB_DRAW_SURf_POINTS_ABSTRACT_H_ #include "surf_abstract.h" #include "../gui_widgets.h" namespace dlib { // ---------------------------------------------------------------------------------------- void draw_surf_points ( image_window& win, const std::vector<surf_point>& sp ); /*! ensures - draws all the SURF points in sp onto the given image_window. They are drawn as overlay circles with extra lines to indicate the rotation of the SURF descriptor. !*/ // ---------------------------------------------------------------------------------------- } #endif // DLIB_DRAW_SURf_POINTS_ABSTRACT_H_
{ "pile_set_name": "Github" }
// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package catmsg // This file implements varint encoding analogous to the one in encoding/binary. // We need a string version of this function, so we add that here and then add // the rest for consistency. import "errors" var ( errIllegalVarint = errors.New("catmsg: illegal varint") errVarintTooLarge = errors.New("catmsg: varint too large for uint64") ) const maxVarintBytes = 10 // maximum length of a varint // encodeUint encodes x as a variable-sized integer into buf and returns the // number of bytes written. buf must be at least maxVarintBytes long func encodeUint(buf []byte, x uint64) (n int) { for ; x > 127; n++ { buf[n] = 0x80 | uint8(x&0x7F) x >>= 7 } buf[n] = uint8(x) n++ return n } func decodeUintString(s string) (x uint64, size int, err error) { i := 0 for shift := uint(0); shift < 64; shift += 7 { if i >= len(s) { return 0, i, errIllegalVarint } b := uint64(s[i]) i++ x |= (b & 0x7F) << shift if b&0x80 == 0 { return x, i, nil } } return 0, i, errVarintTooLarge } func decodeUint(b []byte) (x uint64, size int, err error) { i := 0 for shift := uint(0); shift < 64; shift += 7 { if i >= len(b) { return 0, i, errIllegalVarint } c := uint64(b[i]) i++ x |= (c & 0x7F) << shift if c&0x80 == 0 { return x, i, nil } } return 0, i, errVarintTooLarge }
{ "pile_set_name": "Github" }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Net; using System.Text; // for Encoding using System.Collections.Generic; using System.DirectoryServices; using System.DirectoryServices.ActiveDirectory; using System.DirectoryServices.Protocols; using System.Security.Principal; using Microsoft.Protocols.TestTools; using Microsoft.Protocols.TestTools.StackSdk; using Microsoft.Protocols.TestTools.StackSdk.ActiveDirectory.Drsr; using Microsoft.Protocols.TestTools.StackSdk.Messages; using Microsoft.Protocols.TestTools.StackSdk.Messages.Marshaling; namespace Microsoft.Protocols.TestSuites.ActiveDirectory.Drsr { public struct LDAP_PROPERTY_META_DATA { /// <summary> /// Attribute whose value was revealed. /// </summary> [CLSCompliant(false)] public uint attrType; /// <summary> /// The version of the attribute values, starting at 1 and /// increasing by one with each originating update. /// </summary> [CLSCompliant(false)] public uint dwVersion; /// <summary> /// The time at which the originating update was performed. /// </summary> public long timeChanged; /// <summary> /// The invocationId of the DC that performed the originating /// update. /// </summary> public Guid uuidDsaOriginating; /// <summary> /// The USN of the DC assigned to the originating update. /// </summary> public long usnOriginating; /// <summary> /// USN of local update /// </summary> public long usnProperty; } public struct LDAP_PROPERTY_META_DATA_VECTOR { public ulong dwVersion; public LDAP_PROPERTY_META_DATA_VECTOR_V1 V1; } public struct LDAP_PROPERTY_META_DATA_VECTOR_V1 { public ulong cNumProps; [Inline()] [Size("cNumProps")] public LDAP_PROPERTY_META_DATA[] rgMetaData; } public class RootDSE { public string defaultNamingContext; public string configurationNamingContext; public string schemaNamingContext; public string rootDomainNamingContext; public string serverName; public string dnsHostName; public int domainControllerFunctionality; public int domainFunctionality; public int forestFunctionality; public string dsServiceName; public bool isGcReady; } public class LdapUtility { public static string GetBinaryString(byte[] b) { StringBuilder escapedGuid = new StringBuilder(); for (uint i = 0; i < b.Length; ++i) escapedGuid.AppendFormat(@"\{0:x2}", b[i]); return escapedGuid.ToString(); } public static string GetObjectDnByGuid(DsServer dc, string baseDn, Guid guid) { return GetAttributeValueInString( dc, baseDn, "distinguishedName", "(&(objectClass=*)(objectGuid=" + GetBinaryString(guid.ToByteArray()) + "))", System.DirectoryServices.Protocols.SearchScope.Subtree ); } public static string GetObjectDnBySid(DsServer dc, string baseDn, NT4SID sid) { return GetAttributeValueInString( dc, baseDn, "distinguishedName", "(&(objectClass=*)(objectSid=" + GetBinaryString(sid.Data) + "))", System.DirectoryServices.Protocols.SearchScope.Subtree ); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Convert.ToInt32(System.String)")] public static DSNAME? GetPrimaryGroup( DsServer dc, string name, string baseDn) { // Construct a primary group SID int primaryGroupId = Convert.ToInt32(GetAttributeValueInString(dc, name, "primaryGroupID")); byte[] userSid = GetAttributeValueInBytes(dc, name, "objectSid"); StringBuilder escapedGroupSid = new StringBuilder(); for (uint i = 0; i < userSid.Length - 4; ++i) { escapedGroupSid.AppendFormat(@"\{0:x2}", userSid[i]); } for (uint i = 0; i < 4; ++i) { escapedGroupSid.AppendFormat(@"\{0:x2}", (primaryGroupId & 0xff)); primaryGroupId >>= 8; } string tfilter = "(&(objectClass=group)(objectSid=" + escapedGroupSid.ToString() + "))"; string dn = GetAttributeValueInString(dc, baseDn, "distinguishedName", tfilter, System.DirectoryServices.Protocols.SearchScope.Subtree); return CreateDSNameForObject(dc, dn); } public static bool StampLessThanOrEqualUTD(DS_REPL_ATTR_META_DATA stamp, UPTODATE_VECTOR_V1_EXT utd) { for (int i = 0; i < utd.cNumCursors; ++i) { if (utd.rgCursors[i].uuidDsa == stamp.uuidLastOriginatingDsaInvocationID && utd.rgCursors[i].usnHighPropUpdate >= stamp.usnOriginatingChange) return true; } return false; } public static bool IsObjectExist(DsServer dc, string objDN) { SearchResultEntryCollection results; ResultCode r = Search( dc, objDN, "(objectClass=*)", System.DirectoryServices.Protocols.SearchScope.Base, null, out results); if (r != ResultCode.Success) return false; return true; } public static bool IsUserExist(DsServer dc, string uname, string objDN) { SearchResultEntryCollection results; ResultCode r = Search( dc, objDN, "(samaccountname=" + uname + ")", System.DirectoryServices.Protocols.SearchScope.Base, null, out results); if (r != ResultCode.Success) return false; return true; } /// <summary> /// Get an object name with a proper numerical suffix so that the new object name doesn't present /// in the container. /// /// e.g. if objDn is "User" and there's an object CN=User 0 in the container, then this method /// should return "User 1". (note there's a space between "User" and "1") /// </summary> /// <param name="srv">DC</param> /// <param name="containerDn">Container of the object.</param> /// <param name="objDn">The object name without a numerical suffix.</param> /// <param name="suffix">When return, contains the numerical suffix to the new object.</param> /// <returns>The new object DN</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public static string GetAvailableSuffix(DsServer srv, string containerDn, string objDn, out int suffix) { for (int _suffix = 0; ; _suffix++) { string newObjName = objDn + "-" + _suffix.ToString(); string newObjDn = "CN=" + newObjName + "," + containerDn; // Search the AD database to verify if the newObjDn already exists if (!IsObjectExist(srv, newObjDn)) { // There's no object under the name newObjDn, // that means we have a vacant object name to use. suffix = _suffix; return newObjName; } } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public static string GetAvailableSuffixForUser(DsServer srv, string containerDn, string objDn, out int suffix) { for (int _suffix = 0; ; _suffix++) { string newObjName = objDn + "-" + _suffix.ToString(); string newObjDn = "CN=" + newObjName + "," + containerDn; // Search the AD database to verify if the newObjDn already exists if (!IsUserExist(srv, newObjName, newObjDn)) { // There's no object under the name newObjDn, // that means we have a vacant object name to use. suffix = _suffix; return newObjName; } } } public static DSNAME CreateDSNameForObject(DsServer srv, string dn) { // Get the GUID first Guid? guid = LdapUtility.GetObjectGuid(srv, dn); string sid = GetObjectStringSid(srv, dn); return DrsuapiClient.CreateDsName(dn, guid.Value, sid); } public static string GetObjectStringSid(DsServer srv, string dn) { byte[] data = GetAttributeValueInBytes(srv, dn, "objectSid"); if (data == null) return null; SecurityIdentifier sid = new SecurityIdentifier(data, 0); return sid.ToString(); } public static string GetObjectStringSidHistory(DsServer srv, string dn) { byte[] data = GetAttributeValueInBytes(srv, dn, "SidHistory"); if (data == null) return null; SecurityIdentifier sid = new SecurityIdentifier(data, 0); return sid.ToString(); } public static string ConvertUshortArrayToString(ushort[] data) { if (data == null) return null; byte[] asBytes = new byte[(data.Length - 1) * sizeof(ushort)]; Buffer.BlockCopy(data, 0, asBytes, 0, asBytes.Length - 1); return Encoding.Unicode.GetString(asBytes); } /// <summary> /// Convert string to ushort array in Unicode mode /// </summary> /// <param name="source">the byte array to be converted.</param> /// <returns> the ushort array.</returns> public static ushort[] ConvertUnicodeStringToUshortArray( string source) { ushort[] target; if (source == null) { target = new ushort[0]; } else { byte[] sourceBytes = Encoding.Unicode.GetBytes(source); target = new ushort[(int)Math.Ceiling((double)sourceBytes.Length / 2)]; Buffer.BlockCopy(sourceBytes, 0, target, 0, sourceBytes.Length); } return target; } public static string GetDnFromNcType(DsServer srv, NamingContext ncType) { string baseDn = ""; RootDSE rootDse = LdapUtility.GetRootDSE(srv); switch (ncType) { case NamingContext.DomainNC: baseDn = rootDse.defaultNamingContext; break; case NamingContext.ConfigNC: baseDn = rootDse.configurationNamingContext; break; case NamingContext.SchemaNC: baseDn = rootDse.schemaNamingContext; break; default: throw new NotImplementedException(); //break; } return baseDn; } /// <summary> /// Travel down the base DN to find the object DN matching a given filter. /// </summary> /// <param name="srv">The DC the LDAP connection is connected to.</param> /// <param name="baseDn">The base DN.</param> /// <param name="filter">LDAP filter string.</param> /// <returns>An object DN matching the filter. This DN must be a part of the base DN.</returns> public static string FindObjectNameWithFilter(DsServer srv, string baseDn, string filter) { string[] rDns = baseDn.Split(','); if (rDns.Length <= 1) return null; for (int i = 0; i < rDns.Length; ++i) { string newDn = ""; for (int j = i; j < rDns.Length - 1; ++j) newDn += (rDns[j] + ", "); newDn += rDns[rDns.Length - 1]; string name = GetAttributeValueInString( srv, newDn, "distinguishedName", filter, System.DirectoryServices.Protocols.SearchScope.Base); if (name != null) return newDn; } return null; } /// <summary> /// Get the RootDSE object of an LDAP connection. /// </summary> /// <param name="srv">The DC the LDAP connection is connected to.</param> /// <returns>The RootDSE object.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1304:SpecifyCultureInfo", MessageId = "System.String.ToUpper"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Convert.ToInt32(System.Object)")] public static RootDSE GetRootDSE(DsServer srv) { string rootDseDn = ""; // empty DN means rootDSE RootDSE rootDse = new RootDSE(); rootDse.defaultNamingContext = GetAttributeValueInString(srv, rootDseDn, "defaultNamingContext"); rootDse.configurationNamingContext = GetAttributeValueInString(srv, rootDseDn, "configurationNamingContext"); rootDse.schemaNamingContext = GetAttributeValueInString(srv, rootDseDn, "schemaNamingContext"); rootDse.rootDomainNamingContext = GetAttributeValueInString(srv, rootDseDn, "rootDomainNamingContext"); rootDse.serverName = GetAttributeValueInString(srv, rootDseDn, "serverName"); rootDse.dnsHostName = GetAttributeValueInString(srv, rootDseDn, "dnsHostName"); rootDse.domainControllerFunctionality = Convert.ToInt32(GetAttributeValueInString(srv, rootDseDn, "domainControllerFunctionality")); rootDse.domainFunctionality = Convert.ToInt32(GetAttributeValueInString(srv, rootDseDn, "domainFunctionality")); rootDse.forestFunctionality = Convert.ToInt32(GetAttributeValueInString(srv, rootDseDn, "forestFunctionality")); rootDse.dsServiceName = GetAttributeValueInString(srv, rootDseDn, "dsServiceName"); string gcReady = GetAttributeValueInString(srv, rootDseDn, "isGlobalCatalogReady"); if (gcReady == null || gcReady.ToUpper() != "TRUE") rootDse.isGcReady = false; else rootDse.isGcReady = true; return rootDse; } public static Guid? GetObjectGuid(DsServer srv, string dn) { if (dn == null) return null; byte[] data = GetAttributeValueInBytes(srv, dn, "objectGuid"); if (data != null) return new Guid(data); return null; } public static ResultCode Search( DsServer dc, string baseDn, string ldapFilter, System.DirectoryServices.Protocols.SearchScope searchScope, string[] attributesToReturn, out SearchResultEntryCollection results ) { SearchResponse response = null; try { SearchRequest request = new SearchRequest( baseDn, ldapFilter, searchScope, attributesToReturn ); response = (SearchResponse)dc.LdapConn.SendRequest(request); } catch (DirectoryOperationException e) { results = null; return e.Response.ResultCode; } results = response.Entries; return response.ResultCode; } public static object[] GetAttributeValuesOfType( DsServer dc, string dn, string attributeName, string ldapFilter, System.DirectoryServices.Protocols.SearchScope searchScope, Type valuesType) { SearchResultEntryCollection results = null; ResultCode ret = Search( dc, dn, ldapFilter, searchScope, new string[] { attributeName }, out results); if (ret != ResultCode.Success) return null; foreach (SearchResultEntry e in results) { DirectoryAttribute attr = e.Attributes[attributeName]; if (attr == null) return null; else return attr.GetValues(valuesType); } return null; } public static string[] GetAttributeValuesString( DsServer dc, string dn, string attributeName, string ldapFilter = "(objectClass=*)", System.DirectoryServices.Protocols.SearchScope searchScope = System.DirectoryServices.Protocols.SearchScope.Base) { return (string[])(GetAttributeValuesOfType(dc, dn, attributeName, ldapFilter, searchScope, typeof(string))); } public static byte[][] GetAttributeValuesBytes( DsServer dc, string dn, string attributeName, string ldapFilter = "(objectClass=*)", System.DirectoryServices.Protocols.SearchScope searchScope = System.DirectoryServices.Protocols.SearchScope.Base) { return (byte[][])(GetAttributeValuesOfType(dc, dn, attributeName, ldapFilter, searchScope, typeof(byte[]))); } public static string GetAttributeValueInString( DsServer dc, string dn, string attributeName, string ldapFilter = "(objectClass=*)", System.DirectoryServices.Protocols.SearchScope searchScope = System.DirectoryServices.Protocols.SearchScope.Base) { string[] attrs = GetAttributeValuesString(dc, dn, attributeName, ldapFilter, searchScope); return attrs?[0]; } public static byte[] GetAttributeValueInBytes( DsServer dc, string dn, string attributeName, string ldapFilter = "(objectClass=*)", System.DirectoryServices.Protocols.SearchScope searchScope = System.DirectoryServices.Protocols.SearchScope.Base) { byte[][] attrs = GetAttributeValuesBytes(dc, dn, attributeName, ldapFilter, searchScope); return attrs?[0]; } public static LdapConnection CreateConnection( string hostDnsName, DsUser user, ref DsServer srv, bool forceCreate = false, AuthType authType = AuthType.Kerberos) { if (!forceCreate && srv.LdapConn != null) { // If there is an active connection, return it. return srv.LdapConn; } LdapConnection conn = new LdapConnection(hostDnsName); if (authType == AuthType.Basic) { conn.AuthType = AuthType.Basic; conn.Credential = new NetworkCredential(user.Domain.NetbiosName + "\\" + user.Username, user.Password/*, user.Domain.Name*/); } else { conn.Credential = new NetworkCredential(user.Username, user.Password, user.Domain.DNSName); } conn.Timeout = new TimeSpan(0, 5, 0); // Bind the connection to the server conn.Bind(); srv.LdapConn = conn; return conn; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Convert.ToInt32(System.String)")] public static int GetPort(string hostDnsName) { return Convert.ToInt32(hostDnsName.Split(':')[1]); } // Create a DirectoryEntry using the given credential. public static DirectoryEntry CreateDirectoryEntry( DsServer dc, string path, AuthenticationTypes authType, bool enforceKdc = false ) { string newPath = path; // Insert KDC into the path if a KDC is designated. if (enforceKdc) { newPath = path.Replace("LDAP://", "LDAP://" + dc.DnsHostName + "/"); } return new DirectoryEntry(newPath, dc.Domain.Admin.Username, dc.Domain.Admin.Password, authType); } public static PROPERTY_META_DATA? AttrStamp(DsServer dc, string objDn, uint attrTyp) { byte[] metaDataBer = GetAttributeValueInBytes(dc, objDn, "replPropertyMetaData"); if (metaDataBer == null) return null; PROPERTY_META_DATA_VECTOR metaData = TypeMarshal.ToStruct<PROPERTY_META_DATA_VECTOR>(metaDataBer); for (ulong i = 0; i < metaData.V1.cNumProps; ++i) { PROPERTY_META_DATA d = metaData.V1.rgMetaData[i]; if (d.attrType == attrTyp) return d; } return null; } public static bool StampLessThanOrEqualUTD(PROPERTY_META_DATA? stamp, UPTODATE_VECTOR_V1_EXT utd) { if (stamp == null) return false; for (int i = 0; i < utd.cNumCursors; ++i) { if (utd.rgCursors[i].uuidDsa == stamp.Value.propMetadataExt.uuidDsaOriginating && utd.rgCursors[i].usnHighPropUpdate >= stamp.Value.propMetadataExt.usnOriginating) return true; } return false; } public static int CompareGuid(Guid g1, Guid g2) { byte[] b1 = g1.ToByteArray(); byte[] b2 = g2.ToByteArray(); for (int i = 0; i < b1.Length; ++i) { if (b1[i] > b2[i]) return 1; else if (b1[i] < b2[i]) return -1; } return 0; } public static void InsertGuidToList(List<Guid> list, Guid guid) { // Insert the guid to the proper position in the ascending GUID list int sz = list.Count; if (sz == 0) { list.Add(guid); return; } for (int i = 0; i < sz; ++i) { if (CompareGuid(guid, list[i]) == 0) return; if (CompareGuid(guid, list[i]) < 0) { list.Insert(i, guid); return; } } // If we reach here, add the guid to the end of the list list.Add(guid); } /// <summary> /// get SAM Account name for object /// </summary> /// <param name="svr">dc</param> /// <param name="dn">object dn</param> /// <returns>SAM name</returns> public static string GetObjectSAMNameFromDN(DsServer svr, string dn) { return GetAttributeValueInString(svr, dn, "samaccountname"); } /// <summary> /// get dn from SAM account name /// </summary> /// <param name="svr">dc</param> /// <param name="sam">sam</param> /// <returns>dn</returns> public static string GetObjectDNFromSAMName(DsServer svr, string sam) { SearchResultEntryCollection srec = null; ResultCode ret = Search(svr, svr.Domain.Name, "(samaccountname=" + sam + ")", System.DirectoryServices.Protocols.SearchScope.Subtree, new string[] { "distinguishedname" }, out srec); if (ret != ResultCode.Success) return null; if (srec.Count == 0) return null; return srec[0].Attributes["distinguishedname"][0].ToString(); } public static string UserNameFromNT4AccountName(string nt4AccountName) { int backSlash = nt4AccountName.IndexOf('\\'); if (backSlash < 0) return null; return nt4AccountName.Substring(backSlash + 1); } public static string DomainNameFromNT4AccountName(string nt4AccountName) { int backSlash = nt4AccountName.IndexOf('\\'); if (backSlash < 0) return null; return nt4AccountName.Substring(0, backSlash); } public static LDAP_PROPERTY_META_DATA[] GetMetaData(DsServer dc, string objDn) { byte[] metaDataBer = GetAttributeValueInBytes(dc, objDn, "replPropertyMetaData"); if (metaDataBer == null) return null; LDAP_PROPERTY_META_DATA_VECTOR metaData = TypeMarshal.ToStruct<LDAP_PROPERTY_META_DATA_VECTOR>(metaDataBer); return metaData.V1.rgMetaData; } public static uint attrTyp(DsServer dc, string attrName) { RootDSE rootDse = LdapUtility.GetRootDSE(dc); SCHEMA_PREFIX_TABLE prefixTable = OIDUtility.CreatePrefixTable(); string attrOid = GetAttributeValueInString( dc, rootDse.schemaNamingContext, "attributeID", "(lDAPDisplayName=" + attrName + ")", System.DirectoryServices.Protocols.SearchScope.OneLevel ); uint attrTyp = OIDUtility.MakeAttid(prefixTable, attrOid); return attrTyp; } public static bool ChangeUserPassword(DsServer dc, string cn, string passWord) { string baseDn = LdapUtility.GetDnFromNcType(dc, NamingContext.DomainNC); DirectoryContext userContext = new DirectoryContext(DirectoryContextType.Domain, dc.Domain.DNSName, dc.Domain.Admin.Username, dc.Domain.Admin.Password); Domain userDomain = Domain.GetDomain(userContext); using(DirectoryEntry userRootEntry = userDomain.GetDirectoryEntry()) { cn = cn.Replace(",CN=Users," + baseDn, ""); DirectoryEntry userEntry = null; bool found = false; while (!found) { System.Threading.Thread.Sleep(5000); found = true; try { userEntry = userRootEntry.Children.Find("CN=Users").Children.Find(cn); } catch (Exception /* e */) { found = false; } if (found) break; } using (userEntry) { userEntry.Invoke("SetPassword", new object[] { passWord }); userEntry.CommitChanges(); } return true; } } } }
{ "pile_set_name": "Github" }
Nightmare ========= A tool for debugging bots. Nightmare turns a replay back into the messages that the game engine sends to a bot, allowing you to force your bot to re-experience the same game over and over again. Note that your bot should be deterministic, i.e. it shouldn't rely on random numbers or iteration order over unordered collections. Nightmare is also planned to 'expand' a replay into an uncompressed JSON format that stores all information on every frame, making it easy to work with (but also use much more storage space).
{ "pile_set_name": "Github" }
package D import "github.com/onsi/C" func DoIt() string { return C.DoIt() }
{ "pile_set_name": "Github" }
/* $Id: mntfunc.c,v 1.19.6.4 2005/01/31 12:22:20 armin Exp $ * * Driver for Eicon DIVA Server ISDN cards. * Maint module * * Copyright 2000-2003 by Armin Schindler ([email protected]) * Copyright 2000-2003 Cytronics & Melware ([email protected]) * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. */ #include "platform.h" #include "di_defs.h" #include "divasync.h" #include "debug_if.h" extern char *DRIVERRELEASE_MNT; #define DBG_MINIMUM (DL_LOG + DL_FTL + DL_ERR) #define DBG_DEFAULT (DBG_MINIMUM + DL_XLOG + DL_REG) extern void DIVA_DIDD_Read(void *, int); static dword notify_handle; static DESCRIPTOR DAdapter; static DESCRIPTOR MAdapter; static DESCRIPTOR MaintDescriptor = { IDI_DIMAINT, 0, 0, (IDI_CALL) diva_maint_prtComp }; extern int diva_os_copy_to_user(void *os_handle, void __user *dst, const void *src, int length); extern int diva_os_copy_from_user(void *os_handle, void *dst, const void __user *src, int length); static void no_printf(unsigned char *x, ...) { /* dummy debug function */ } #include "debuglib.c" /* * DIDD callback function */ static void *didd_callback(void *context, DESCRIPTOR *adapter, int removal) { if (adapter->type == IDI_DADAPTER) { DBG_ERR(("cb: Change in DAdapter ? Oops ?.")); } else if (adapter->type == IDI_DIMAINT) { if (removal) { DbgDeregister(); memset(&MAdapter, 0, sizeof(MAdapter)); dprintf = no_printf; } else { memcpy(&MAdapter, adapter, sizeof(MAdapter)); dprintf = (DIVA_DI_PRINTF) MAdapter.request; DbgRegister("MAINT", DRIVERRELEASE_MNT, DBG_DEFAULT); } } else if ((adapter->type > 0) && (adapter->type < 16)) { if (removal) { diva_mnt_remove_xdi_adapter(adapter); } else { diva_mnt_add_xdi_adapter(adapter); } } return (NULL); } /* * connect to didd */ static int __init connect_didd(void) { int x = 0; int dadapter = 0; IDI_SYNC_REQ req; DESCRIPTOR DIDD_Table[MAX_DESCRIPTORS]; DIVA_DIDD_Read(DIDD_Table, sizeof(DIDD_Table)); for (x = 0; x < MAX_DESCRIPTORS; x++) { if (DIDD_Table[x].type == IDI_DADAPTER) { /* DADAPTER found */ dadapter = 1; memcpy(&DAdapter, &DIDD_Table[x], sizeof(DAdapter)); req.didd_notify.e.Req = 0; req.didd_notify.e.Rc = IDI_SYNC_REQ_DIDD_REGISTER_ADAPTER_NOTIFY; req.didd_notify.info.callback = (void *)didd_callback; req.didd_notify.info.context = NULL; DAdapter.request((ENTITY *)&req); if (req.didd_notify.e.Rc != 0xff) return (0); notify_handle = req.didd_notify.info.handle; /* Register MAINT (me) */ req.didd_add_adapter.e.Req = 0; req.didd_add_adapter.e.Rc = IDI_SYNC_REQ_DIDD_ADD_ADAPTER; req.didd_add_adapter.info.descriptor = (void *) &MaintDescriptor; DAdapter.request((ENTITY *)&req); if (req.didd_add_adapter.e.Rc != 0xff) return (0); } else if ((DIDD_Table[x].type > 0) && (DIDD_Table[x].type < 16)) { diva_mnt_add_xdi_adapter(&DIDD_Table[x]); } } return (dadapter); } /* * disconnect from didd */ static void __exit disconnect_didd(void) { IDI_SYNC_REQ req; req.didd_notify.e.Req = 0; req.didd_notify.e.Rc = IDI_SYNC_REQ_DIDD_REMOVE_ADAPTER_NOTIFY; req.didd_notify.info.handle = notify_handle; DAdapter.request((ENTITY *)&req); req.didd_remove_adapter.e.Req = 0; req.didd_remove_adapter.e.Rc = IDI_SYNC_REQ_DIDD_REMOVE_ADAPTER; req.didd_remove_adapter.info.p_request = (IDI_CALL) MaintDescriptor.request; DAdapter.request((ENTITY *)&req); } /* * read/write maint */ int maint_read_write(void __user *buf, int count) { byte data[128]; dword cmd, id, mask; int ret = 0; if (count < (3 * sizeof(dword))) return (-EFAULT); if (diva_os_copy_from_user(NULL, (void *) &data[0], buf, 3 * sizeof(dword))) { return (-EFAULT); } cmd = *(dword *)&data[0]; /* command */ id = *(dword *)&data[4]; /* driver id */ mask = *(dword *)&data[8]; /* mask or size */ switch (cmd) { case DITRACE_CMD_GET_DRIVER_INFO: if ((ret = diva_get_driver_info(id, data, sizeof(data))) > 0) { if ((count < ret) || diva_os_copy_to_user (NULL, buf, (void *) &data[0], ret)) ret = -EFAULT; } else { ret = -EINVAL; } break; case DITRACE_READ_DRIVER_DBG_MASK: if ((ret = diva_get_driver_dbg_mask(id, (byte *) data)) > 0) { if ((count < ret) || diva_os_copy_to_user (NULL, buf, (void *) &data[0], ret)) ret = -EFAULT; } else { ret = -ENODEV; } break; case DITRACE_WRITE_DRIVER_DBG_MASK: if ((ret = diva_set_driver_dbg_mask(id, mask)) <= 0) { ret = -ENODEV; } break; /* Filter commands will ignore the ID due to fact that filtering affects the B- channel and Audio Tap trace levels only. Also MAINT driver will select the right trace ID by itself */ case DITRACE_WRITE_SELECTIVE_TRACE_FILTER: if (!mask) { ret = diva_set_trace_filter(1, "*"); } else if (mask < sizeof(data)) { if (diva_os_copy_from_user(NULL, data, (char __user *)buf + 12, mask)) { ret = -EFAULT; } else { ret = diva_set_trace_filter((int)mask, data); } } else { ret = -EINVAL; } break; case DITRACE_READ_SELECTIVE_TRACE_FILTER: if ((ret = diva_get_trace_filter(sizeof(data), data)) > 0) { if (diva_os_copy_to_user(NULL, buf, data, ret)) ret = -EFAULT; } else { ret = -ENODEV; } break; case DITRACE_READ_TRACE_ENTRY:{ diva_os_spin_lock_magic_t old_irql; word size; diva_dbg_entry_head_t *pmsg; byte *pbuf; if (!(pbuf = diva_os_malloc(0, mask))) { return (-ENOMEM); } for (;;) { if (!(pmsg = diva_maint_get_message(&size, &old_irql))) { break; } if (size > mask) { diva_maint_ack_message(0, &old_irql); ret = -EINVAL; break; } ret = size; memcpy(pbuf, pmsg, size); diva_maint_ack_message(1, &old_irql); if ((count < size) || diva_os_copy_to_user(NULL, buf, (void *) pbuf, size)) ret = -EFAULT; break; } diva_os_free(0, pbuf); } break; case DITRACE_READ_TRACE_ENTRYS:{ diva_os_spin_lock_magic_t old_irql; word size; diva_dbg_entry_head_t *pmsg; byte *pbuf = NULL; int written = 0; if (mask < 4096) { ret = -EINVAL; break; } if (!(pbuf = diva_os_malloc(0, mask))) { return (-ENOMEM); } for (;;) { if (!(pmsg = diva_maint_get_message(&size, &old_irql))) { break; } if ((size + 8) > mask) { diva_maint_ack_message(0, &old_irql); break; } /* Write entry length */ pbuf[written++] = (byte) size; pbuf[written++] = (byte) (size >> 8); pbuf[written++] = 0; pbuf[written++] = 0; /* Write message */ memcpy(&pbuf[written], pmsg, size); diva_maint_ack_message(1, &old_irql); written += size; mask -= (size + 4); } pbuf[written++] = 0; pbuf[written++] = 0; pbuf[written++] = 0; pbuf[written++] = 0; if ((count < written) || diva_os_copy_to_user(NULL, buf, (void *) pbuf, written)) { ret = -EFAULT; } else { ret = written; } diva_os_free(0, pbuf); } break; default: ret = -EINVAL; } return (ret); } /* * init */ int __init mntfunc_init(int *buffer_length, void **buffer, unsigned long diva_dbg_mem) { if (*buffer_length < 64) { *buffer_length = 64; } if (*buffer_length > 512) { *buffer_length = 512; } *buffer_length *= 1024; if (diva_dbg_mem) { *buffer = (void *) diva_dbg_mem; } else { while ((*buffer_length >= (64 * 1024)) && (!(*buffer = diva_os_malloc(0, *buffer_length)))) { *buffer_length -= 1024; } if (!*buffer) { DBG_ERR(("init: Can not alloc trace buffer")); return (0); } } if (diva_maint_init(*buffer, *buffer_length, (diva_dbg_mem == 0))) { if (!diva_dbg_mem) { diva_os_free(0, *buffer); } DBG_ERR(("init: maint init failed")); return (0); } if (!connect_didd()) { DBG_ERR(("init: failed to connect to DIDD.")); diva_maint_finit(); if (!diva_dbg_mem) { diva_os_free(0, *buffer); } return (0); } return (1); } /* * exit */ void __exit mntfunc_finit(void) { void *buffer; int i = 100; DbgDeregister(); while (diva_mnt_shutdown_xdi_adapters() && i--) { diva_os_sleep(10); } disconnect_didd(); if ((buffer = diva_maint_finit())) { diva_os_free(0, buffer); } memset(&MAdapter, 0, sizeof(MAdapter)); dprintf = no_printf; }
{ "pile_set_name": "Github" }
// Put the following line to 0 or comment it to disable vignette weighting #define USE_VIGNETTE_WEIGHTING 1 #include "Common.cginc" #include "EyeAdaptation.cginc" RWStructuredBuffer<uint> _Histogram; Texture2D<float4> _Source; CBUFFER_START(Params) float4 _ScaleOffsetRes; // x: scale, y: offset, z: width, w: height CBUFFER_END groupshared uint gs_histogram[HISTOGRAM_BINS]; #pragma kernel KEyeHistogram [numthreads(HISTOGRAM_THREAD_X,HISTOGRAM_THREAD_Y,1)] void KEyeHistogram(uint2 dispatchThreadId : SV_DispatchThreadID, uint2 groupThreadId : SV_GroupThreadID) { // Pretty straightforward implementation of histogram gathering using atomic ops. // I tried a few methods (no atomic ops / heavy LDS leveraging) but this one turned out to be // the fastest on desktop (Nvidia - Kepler/Maxwell) and PS4. Still need to try it on GCN/desktop // but considering it runs very fast on PS4 we can expect it to run well (?). const uint localThreadId = groupThreadId.y * HISTOGRAM_THREAD_X + groupThreadId.x; // Clears the shared memory if (localThreadId < HISTOGRAM_BINS) gs_histogram[localThreadId] = 0u; GroupMemoryBarrierWithGroupSync(); // Gather local group histogram if (dispatchThreadId.x < (uint)_ScaleOffsetRes.z && dispatchThreadId.y < (uint)_ScaleOffsetRes.w) { #if USE_VIGNETTE_WEIGHTING // Vignette weighting to put more focus on what's in the center of the screen float2 uv01 = float2(dispatchThreadId) / float2(_ScaleOffsetRes.z, _ScaleOffsetRes.w); float2 d = abs(uv01 - (0.5).xx); float vfactor = Pow2(saturate(1.0 - dot(d, d))); uint weight = (uint)(64.0 * vfactor); #else uint weight = 1u; #endif float3 color = _Source[dispatchThreadId].xyz; float luminance = Max3(color); // Looks more natural than using a Rec.709 luminance for some reason float logLuminance = GetHistogramBinFromLuminance(luminance, _ScaleOffsetRes.xy); uint idx = (uint)(logLuminance * (HISTOGRAM_BINS - 1u)); InterlockedAdd(gs_histogram[idx], weight); } GroupMemoryBarrierWithGroupSync(); // Merge everything if (localThreadId < HISTOGRAM_BINS) InterlockedAdd(_Histogram[localThreadId], gs_histogram[localThreadId]); }
{ "pile_set_name": "Github" }
# From https://lists.x.org/archives/xorg-announce/2017-January/002772.html sha256 5afe42ce3cdf4f60520d1658d2b17face45c74050f39af45dccdc95e73fafc4d xauth-1.0.10.tar.bz2
{ "pile_set_name": "Github" }
/* * Ralink RT3662/RT3883 SoC register definitions * * Copyright (C) 2011-2012 Gabor Juhos <[email protected]> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. */ #ifndef _RT3883_REGS_H_ #define _RT3883_REGS_H_ #include <linux/bitops.h> #define RT3883_SDRAM_BASE 0x00000000 #define RT3883_SYSC_BASE 0x10000000 #define RT3883_TIMER_BASE 0x10000100 #define RT3883_INTC_BASE 0x10000200 #define RT3883_MEMC_BASE 0x10000300 #define RT3883_UART0_BASE 0x10000500 #define RT3883_PIO_BASE 0x10000600 #define RT3883_FSCC_BASE 0x10000700 #define RT3883_NANDC_BASE 0x10000810 #define RT3883_I2C_BASE 0x10000900 #define RT3883_I2S_BASE 0x10000a00 #define RT3883_SPI_BASE 0x10000b00 #define RT3883_UART1_BASE 0x10000c00 #define RT3883_PCM_BASE 0x10002000 #define RT3883_GDMA_BASE 0x10002800 #define RT3883_CODEC1_BASE 0x10003000 #define RT3883_CODEC2_BASE 0x10003800 #define RT3883_FE_BASE 0x10100000 #define RT3883_ROM_BASE 0x10118000 #define RT3883_USBDEV_BASE 0x10112000 #define RT3883_PCI_BASE 0x10140000 #define RT3883_WLAN_BASE 0x10180000 #define RT3883_USBHOST_BASE 0x101c0000 #define RT3883_BOOT_BASE 0x1c000000 #define RT3883_SRAM_BASE 0x1e000000 #define RT3883_PCIMEM_BASE 0x20000000 #define RT3883_EHCI_BASE (RT3883_USBHOST_BASE) #define RT3883_OHCI_BASE (RT3883_USBHOST_BASE + 0x1000) #define RT3883_SYSC_SIZE 0x100 #define RT3883_TIMER_SIZE 0x100 #define RT3883_INTC_SIZE 0x100 #define RT3883_MEMC_SIZE 0x100 #define RT3883_UART0_SIZE 0x100 #define RT3883_UART1_SIZE 0x100 #define RT3883_PIO_SIZE 0x100 #define RT3883_FSCC_SIZE 0x100 #define RT3883_NANDC_SIZE 0x0f0 #define RT3883_I2C_SIZE 0x100 #define RT3883_I2S_SIZE 0x100 #define RT3883_SPI_SIZE 0x100 #define RT3883_PCM_SIZE 0x800 #define RT3883_GDMA_SIZE 0x800 #define RT3883_CODEC1_SIZE 0x800 #define RT3883_CODEC2_SIZE 0x800 #define RT3883_FE_SIZE 0x10000 #define RT3883_ROM_SIZE 0x4000 #define RT3883_USBDEV_SIZE 0x4000 #define RT3883_PCI_SIZE 0x40000 #define RT3883_WLAN_SIZE 0x40000 #define RT3883_USBHOST_SIZE 0x40000 #define RT3883_BOOT_SIZE (32 * 1024 * 1024) #define RT3883_SRAM_SIZE (32 * 1024 * 1024) /* SYSC registers */ #define RT3883_SYSC_REG_CHIPID0_3 0x00 /* Chip ID 0 */ #define RT3883_SYSC_REG_CHIPID4_7 0x04 /* Chip ID 1 */ #define RT3883_SYSC_REG_REVID 0x0c /* Chip Revision Identification */ #define RT3883_SYSC_REG_SYSCFG0 0x10 /* System Configuration 0 */ #define RT3883_SYSC_REG_SYSCFG1 0x14 /* System Configuration 1 */ #define RT3883_SYSC_REG_CLKCFG0 0x2c /* Clock Configuration 0 */ #define RT3883_SYSC_REG_CLKCFG1 0x30 /* Clock Configuration 1 */ #define RT3883_SYSC_REG_RSTCTRL 0x34 /* Reset Control*/ #define RT3883_SYSC_REG_RSTSTAT 0x38 /* Reset Status*/ #define RT3883_SYSC_REG_USB_PS 0x5c /* USB Power saving control */ #define RT3883_SYSC_REG_GPIO_MODE 0x60 /* GPIO Purpose Select */ #define RT3883_SYSC_REG_PCIE_CLK_GEN0 0x7c #define RT3883_SYSC_REG_PCIE_CLK_GEN1 0x80 #define RT3883_SYSC_REG_PCIE_CLK_GEN2 0x84 #define RT3883_SYSC_REG_PMU 0x88 #define RT3883_SYSC_REG_PMU1 0x8c #define RT3883_REVID_VER_ID_MASK 0x0f #define RT3883_REVID_VER_ID_SHIFT 8 #define RT3883_REVID_ECO_ID_MASK 0x0f #define RT3883_SYSCFG0_DRAM_TYPE_DDR2 BIT(17) #define RT3883_SYSCFG0_CPUCLK_SHIFT 8 #define RT3883_SYSCFG0_CPUCLK_MASK 0x3 #define RT3883_SYSCFG0_CPUCLK_250 0x0 #define RT3883_SYSCFG0_CPUCLK_384 0x1 #define RT3883_SYSCFG0_CPUCLK_480 0x2 #define RT3883_SYSCFG0_CPUCLK_500 0x3 #define RT3883_SYSCFG1_USB0_HOST_MODE BIT(10) #define RT3883_SYSCFG1_PCIE_RC_MODE BIT(8) #define RT3883_SYSCFG1_PCI_HOST_MODE BIT(7) #define RT3883_SYSCFG1_PCI_66M_MODE BIT(6) #define RT3883_SYSCFG1_GPIO2_AS_WDT_OUT BIT(2) #define RT3883_CLKCFG1_PCIE_CLK_EN BIT(21) #define RT3883_CLKCFG1_UPHY1_CLK_EN BIT(20) #define RT3883_CLKCFG1_PCI_CLK_EN BIT(19) #define RT3883_CLKCFG1_UPHY0_CLK_EN BIT(18) #define RT3883_GPIO_MODE_I2C BIT(0) #define RT3883_GPIO_MODE_SPI BIT(1) #define RT3883_GPIO_MODE_UART0_SHIFT 2 #define RT3883_GPIO_MODE_UART0_MASK 0x7 #define RT3883_GPIO_MODE_UART0(x) ((x) << RT3883_GPIO_MODE_UART0_SHIFT) #define RT3883_GPIO_MODE_UARTF 0x0 #define RT3883_GPIO_MODE_PCM_UARTF 0x1 #define RT3883_GPIO_MODE_PCM_I2S 0x2 #define RT3883_GPIO_MODE_I2S_UARTF 0x3 #define RT3883_GPIO_MODE_PCM_GPIO 0x4 #define RT3883_GPIO_MODE_GPIO_UARTF 0x5 #define RT3883_GPIO_MODE_GPIO_I2S 0x6 #define RT3883_GPIO_MODE_GPIO 0x7 #define RT3883_GPIO_MODE_UART1 BIT(5) #define RT3883_GPIO_MODE_JTAG BIT(6) #define RT3883_GPIO_MODE_MDIO BIT(7) #define RT3883_GPIO_MODE_GE1 BIT(9) #define RT3883_GPIO_MODE_GE2 BIT(10) #define RT3883_GPIO_MODE_PCI_SHIFT 11 #define RT3883_GPIO_MODE_PCI_MASK 0x7 #define RT3883_GPIO_MODE_PCI(_x) ((_x) << RT3883_GPIO_MODE_PCI_SHIFT) #define RT3883_GPIO_MODE_PCI_DEV 0 #define RT3883_GPIO_MODE_PCI_HOST2 1 #define RT3883_GPIO_MODE_PCI_HOST1 2 #define RT3883_GPIO_MODE_PCI_FNC 3 #define RT3883_GPIO_MODE_PCI_GPIO 7 #define RT3883_GPIO_MODE_LNA_A_SHIFT 16 #define RT3883_GPIO_MODE_LNA_A_MASK 0x3 #define RT3883_GPIO_MODE_LNA_A(_x) ((_x) << RT3883_GPIO_MODE_LNA_A_SHIFT) #define RT3883_GPIO_MODE_LNA_A_GPIO 0x3 #define RT3883_GPIO_MODE_LNA_G_SHIFT 18 #define RT3883_GPIO_MODE_LNA_G_MASK 0x3 #define RT3883_GPIO_MODE_LNA_G(_x) ((_x) << RT3883_GPIO_MODE_LNA_G_SHIFT) #define RT3883_GPIO_MODE_LNA_G_GPIO 0x3 #define RT3883_RSTCTRL_PCIE_PCI_PDM BIT(27) #define RT3883_RSTCTRL_FLASH BIT(26) #define RT3883_RSTCTRL_UDEV BIT(25) #define RT3883_RSTCTRL_PCI BIT(24) #define RT3883_RSTCTRL_PCIE BIT(23) #define RT3883_RSTCTRL_UHST BIT(22) #define RT3883_RSTCTRL_FE BIT(21) #define RT3883_RSTCTRL_WLAN BIT(20) #define RT3883_RSTCTRL_UART1 BIT(29) #define RT3883_RSTCTRL_SPI BIT(18) #define RT3883_RSTCTRL_I2S BIT(17) #define RT3883_RSTCTRL_I2C BIT(16) #define RT3883_RSTCTRL_NAND BIT(15) #define RT3883_RSTCTRL_DMA BIT(14) #define RT3883_RSTCTRL_PIO BIT(13) #define RT3883_RSTCTRL_UART BIT(12) #define RT3883_RSTCTRL_PCM BIT(11) #define RT3883_RSTCTRL_MC BIT(10) #define RT3883_RSTCTRL_INTC BIT(9) #define RT3883_RSTCTRL_TIMER BIT(8) #define RT3883_RSTCTRL_SYS BIT(0) #define RT3883_INTC_INT_SYSCTL BIT(0) #define RT3883_INTC_INT_TIMER0 BIT(1) #define RT3883_INTC_INT_TIMER1 BIT(2) #define RT3883_INTC_INT_IA BIT(3) #define RT3883_INTC_INT_PCM BIT(4) #define RT3883_INTC_INT_UART0 BIT(5) #define RT3883_INTC_INT_PIO BIT(6) #define RT3883_INTC_INT_DMA BIT(7) #define RT3883_INTC_INT_NAND BIT(8) #define RT3883_INTC_INT_PERFC BIT(9) #define RT3883_INTC_INT_I2S BIT(10) #define RT3883_INTC_INT_UART1 BIT(12) #define RT3883_INTC_INT_UHST BIT(18) #define RT3883_INTC_INT_UDEV BIT(19) /* FLASH/SRAM/Codec Controller registers */ #define RT3883_FSCC_REG_FLASH_CFG0 0x00 #define RT3883_FSCC_REG_FLASH_CFG1 0x04 #define RT3883_FSCC_REG_CODEC_CFG0 0x40 #define RT3883_FSCC_REG_CODEC_CFG1 0x44 #define RT3883_FLASH_CFG_WIDTH_SHIFT 26 #define RT3883_FLASH_CFG_WIDTH_MASK 0x3 #define RT3883_FLASH_CFG_WIDTH_8BIT 0x0 #define RT3883_FLASH_CFG_WIDTH_16BIT 0x1 #define RT3883_FLASH_CFG_WIDTH_32BIT 0x2 /* UART registers */ #define RT3883_UART_REG_RX 0 #define RT3883_UART_REG_TX 1 #define RT3883_UART_REG_IER 2 #define RT3883_UART_REG_IIR 3 #define RT3883_UART_REG_FCR 4 #define RT3883_UART_REG_LCR 5 #define RT3883_UART_REG_MCR 6 #define RT3883_UART_REG_LSR 7 #endif /* _RT3883_REGS_H_ */
{ "pile_set_name": "Github" }
/*********************************************************************** Copyright (c) 2006-2011, Skype Limited. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of Internet Society, IETF or IETF Trust, nor the names of specific 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************/ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "main_FIX.h" #include "stack_alloc.h" #include "tuning_parameters.h" /* Find pitch lags */ void silk_find_pitch_lags_FIX( silk_encoder_state_FIX *psEnc, /* I/O encoder state */ silk_encoder_control_FIX *psEncCtrl, /* I/O encoder control */ opus_int16 res[], /* O residual */ const opus_int16 x[], /* I Speech signal */ int arch /* I Run-time architecture */ ) { opus_int buf_len, i, scale; opus_int32 thrhld_Q13, res_nrg; const opus_int16 *x_ptr; VARDECL( opus_int16, Wsig ); opus_int16 *Wsig_ptr; opus_int32 auto_corr[ MAX_FIND_PITCH_LPC_ORDER + 1 ]; opus_int16 rc_Q15[ MAX_FIND_PITCH_LPC_ORDER ]; opus_int32 A_Q24[ MAX_FIND_PITCH_LPC_ORDER ]; opus_int16 A_Q12[ MAX_FIND_PITCH_LPC_ORDER ]; SAVE_STACK; /******************************************/ /* Set up buffer lengths etc based on Fs */ /******************************************/ buf_len = psEnc->sCmn.la_pitch + psEnc->sCmn.frame_length + psEnc->sCmn.ltp_mem_length; /* Safety check */ celt_assert( buf_len >= psEnc->sCmn.pitch_LPC_win_length ); /*************************************/ /* Estimate LPC AR coefficients */ /*************************************/ /* Calculate windowed signal */ ALLOC( Wsig, psEnc->sCmn.pitch_LPC_win_length, opus_int16 ); /* First LA_LTP samples */ x_ptr = x + buf_len - psEnc->sCmn.pitch_LPC_win_length; Wsig_ptr = Wsig; silk_apply_sine_window( Wsig_ptr, x_ptr, 1, psEnc->sCmn.la_pitch ); /* Middle un - windowed samples */ Wsig_ptr += psEnc->sCmn.la_pitch; x_ptr += psEnc->sCmn.la_pitch; silk_memcpy( Wsig_ptr, x_ptr, ( psEnc->sCmn.pitch_LPC_win_length - silk_LSHIFT( psEnc->sCmn.la_pitch, 1 ) ) * sizeof( opus_int16 ) ); /* Last LA_LTP samples */ Wsig_ptr += psEnc->sCmn.pitch_LPC_win_length - silk_LSHIFT( psEnc->sCmn.la_pitch, 1 ); x_ptr += psEnc->sCmn.pitch_LPC_win_length - silk_LSHIFT( psEnc->sCmn.la_pitch, 1 ); silk_apply_sine_window( Wsig_ptr, x_ptr, 2, psEnc->sCmn.la_pitch ); /* Calculate autocorrelation sequence */ silk_autocorr( auto_corr, &scale, Wsig, psEnc->sCmn.pitch_LPC_win_length, psEnc->sCmn.pitchEstimationLPCOrder + 1, arch ); /* Add white noise, as fraction of energy */ auto_corr[ 0 ] = silk_SMLAWB( auto_corr[ 0 ], auto_corr[ 0 ], SILK_FIX_CONST( FIND_PITCH_WHITE_NOISE_FRACTION, 16 ) ) + 1; /* Calculate the reflection coefficients using schur */ res_nrg = silk_schur( rc_Q15, auto_corr, psEnc->sCmn.pitchEstimationLPCOrder ); /* Prediction gain */ psEncCtrl->predGain_Q16 = silk_DIV32_varQ( auto_corr[ 0 ], silk_max_int( res_nrg, 1 ), 16 ); /* Convert reflection coefficients to prediction coefficients */ silk_k2a( A_Q24, rc_Q15, psEnc->sCmn.pitchEstimationLPCOrder ); /* Convert From 32 bit Q24 to 16 bit Q12 coefs */ for( i = 0; i < psEnc->sCmn.pitchEstimationLPCOrder; i++ ) { A_Q12[ i ] = (opus_int16)silk_SAT16( silk_RSHIFT( A_Q24[ i ], 12 ) ); } /* Do BWE */ silk_bwexpander( A_Q12, psEnc->sCmn.pitchEstimationLPCOrder, SILK_FIX_CONST( FIND_PITCH_BANDWIDTH_EXPANSION, 16 ) ); /*****************************************/ /* LPC analysis filtering */ /*****************************************/ silk_LPC_analysis_filter( res, x, A_Q12, buf_len, psEnc->sCmn.pitchEstimationLPCOrder, psEnc->sCmn.arch ); if( psEnc->sCmn.indices.signalType != TYPE_NO_VOICE_ACTIVITY && psEnc->sCmn.first_frame_after_reset == 0 ) { /* Threshold for pitch estimator */ thrhld_Q13 = SILK_FIX_CONST( 0.6, 13 ); thrhld_Q13 = silk_SMLABB( thrhld_Q13, SILK_FIX_CONST( -0.004, 13 ), psEnc->sCmn.pitchEstimationLPCOrder ); thrhld_Q13 = silk_SMLAWB( thrhld_Q13, SILK_FIX_CONST( -0.1, 21 ), psEnc->sCmn.speech_activity_Q8 ); thrhld_Q13 = silk_SMLABB( thrhld_Q13, SILK_FIX_CONST( -0.15, 13 ), silk_RSHIFT( psEnc->sCmn.prevSignalType, 1 ) ); thrhld_Q13 = silk_SMLAWB( thrhld_Q13, SILK_FIX_CONST( -0.1, 14 ), psEnc->sCmn.input_tilt_Q15 ); thrhld_Q13 = silk_SAT16( thrhld_Q13 ); /*****************************************/ /* Call pitch estimator */ /*****************************************/ if( silk_pitch_analysis_core( res, psEncCtrl->pitchL, &psEnc->sCmn.indices.lagIndex, &psEnc->sCmn.indices.contourIndex, &psEnc->LTPCorr_Q15, psEnc->sCmn.prevLag, psEnc->sCmn.pitchEstimationThreshold_Q16, (opus_int)thrhld_Q13, psEnc->sCmn.fs_kHz, psEnc->sCmn.pitchEstimationComplexity, psEnc->sCmn.nb_subfr, psEnc->sCmn.arch) == 0 ) { psEnc->sCmn.indices.signalType = TYPE_VOICED; } else { psEnc->sCmn.indices.signalType = TYPE_UNVOICED; } } else { silk_memset( psEncCtrl->pitchL, 0, sizeof( psEncCtrl->pitchL ) ); psEnc->sCmn.indices.lagIndex = 0; psEnc->sCmn.indices.contourIndex = 0; psEnc->LTPCorr_Q15 = 0; } RESTORE_STACK; }
{ "pile_set_name": "Github" }
//#name Glitter //#author bartekd //#include CommonInclude //#vertex //#include VertexInclude varying float vLight; varying vec2 vTextureCoord; varying float vTime; varying float vDirection; float cli(vec4 p, vec3 n, lightSource light){ vec3 ld; if(light.type == 0) return 0.0; else if(light.type == 1) ld = -light.direction; else if(light.type == 2) ld = normalize(light.position - p.xyz); return max(dot(n, ld), 0.0); } float lightIntensity(vec4 p, vec3 n) { float s = cli(p, n, uLight[0]); s += cli(p, n, uLight[1]); s += cli(p, n, uLight[2]); s += cli(p, n, uLight[3]); return s; } void main(void) { vec4 p = mMatrix * (vec4(aVertexPosition, 1.0)); vec4 vp = vMatrix * p; vDirection = dot(normalize(nMatrix * aVertexNormal), vec3(0,0,-1)); gl_Position = pMatrix * vp; gl_PointSize = 10.0; vTextureCoord = getTextureCoord(aTextureCoord); vec3 n = normalize( nMatrix * aVertexNormal ); vLight = lightIntensity(p, n); vTime = (sin(uTime * 2.0 + aVertexNormal.x + aTextureCoord.y) + 1.0); } //#fragment uniform sampler2D uColorSampler; uniform sampler2D uParticle; varying float vLight; varying vec2 vTextureCoord; varying float vTime; varying float vDirection; void main(void) { vec4 tc = texture2D(uColorSampler, vec2(vLight + uTime * 0.1, uTime) ); vec4 pc = texture2D(uParticle, gl_PointCoord); if(vDirection > 0.0) { discard; } else { gl_FragColor = vec4(tc.rgb * 0.5, pc.r * 0.4); } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <style xmlns="http://purl.org/net/xbiblio/csl" class="note" version="1.0" demote-non-dropping-particle="sort-only" default-locale="en-GB"> <info> <title>Thomson Reuters - Legal, Tax &amp; Accounting Australia</title> <id>http://www.zotero.org/styles/thomson-reuters-legal-tax-and-accounting-australia</id> <link href="http://www.zotero.org/styles/thomson-reuters-legal-tax-and-accounting-australia" rel="self"/> <link href="http://www.zotero.org/styles/australian-guide-to-legal-citation" rel="template"/> <link href="https://forums.zotero.org/discussion/4841/new-australian-legal-citation-style/?Focus=20831#Comment_20831" rel="documentation"/> <author> <name>Sebastian Karcher</name> </author> <category citation-format="note"/> <category field="law"/> <summary>Style for a series of Thomson Reuters law publications for Australia</summary> <updated>2012-10-25T21:15:26+00:00</updated> <rights license="http://creativecommons.org/licenses/by-sa/3.0/">This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License</rights> </info> <locale> <terms> <term name="et-al">et al</term> <term name="open-quote">“</term> <term name="close-quote">”</term> <term name="open-inner-quote">‘</term> <term name="close-inner-quote">’</term> <term name="page-range-delimiter">&#8211;</term> </terms> </locale> <!--Authors and Persons--> <macro name="author-note"> <!--for bills & hearing this should start with jurisdiction once available--> <choose> <if type="interview"> <group delimiter=", "> <names variable="interviewer"> <name delimiter-precedes-last="never" and="text" delimiter=", " initialize="false" initialize-with=""/> </names> <names variable="author" prefix="Interview with "> <name delimiter-precedes-last="never" and="text" delimiter=", " initialize="false" initialize-with=""/> </names> </group> </if> <else-if type="personal_communication"> <group delimiter=" "> <group delimiter=" from "> <text variable="genre"/> <names variable="author"> <name delimiter-precedes-last="never" and="text" delimiter=", " initialize="false" initialize-with=""/> </names> </group> <names variable="recipient" prefix="to "> <name delimiter-precedes-last="never" and="text" delimiter=", " initialize="false" initialize-with=""/> </names> </group> </else-if> <else-if type="broadcast"> <text variable="publisher"/> </else-if> <else-if type="legal_case legislation" match="any"/> <else> <names variable="author"> <name delimiter-precedes-last="never" and="text" delimiter=", " initialize-with="" sort-separator=" " name-as-sort-order="all"/> <label form="short" prefix=" (" suffix=")" strip-periods="true"/> <substitute> <names variable="editor"/> <names variable="translator"/> <text macro="title"/> </substitute> </names> </else> </choose> </macro> <macro name="author-short"> <choose> <if type="interview"> <group delimiter=", "> <names variable="interviewer"> <name delimiter-precedes-last="never" and="text" form="short" delimiter=", " initialize="false" initialize-with=""/> </names> <names variable="author" prefix="Interview with "> <name delimiter-precedes-last="never" and="text" form="short" delimiter=", " initialize="false" initialize-with=""/> </names> </group> </if> <else-if type="personal_communication"> <group delimiter=" "> <group delimiter=" from "> <text variable="genre"/> <names variable="author"> <name delimiter-precedes-last="never" and="text" delimiter=", " form="short" initialize="false" initialize-with=""/> </names> </group> <names variable="recipient" prefix="to "> <name delimiter-precedes-last="never" and="text" delimiter=", " initialize="false" form="short" initialize-with=""/> </names> </group> </else-if> <else-if type="broadcast"> <text variable="publisher"/> </else-if> <else> <names variable="author"> <name delimiter-precedes-last="never" and="text" delimiter=", " initialize="false" initialize-with="" form="short"/> <substitute> <names variable="editor"/> <names variable="translator"/> <text macro="title"/> </substitute> </names> </else> </choose> </macro> <macro name="editor"> <group> <choose> <if type="chapter paper-conference" match="any"> <text term="in" suffix=" "/> </if> </choose> <names variable="editor translator" delimiter=", "> <name delimiter-precedes-last="never" and="text" delimiter=", " initialize-with="" name-as-sort-order="all" sort-separator=" "/> <label form="short" prefix=" (" suffix=")" strip-periods="true"/> </names> </group> </macro> <!-- Titles --> <macro name="title"> <choose> <if type="book legislation webpage thesis motion_picture manuscript" match="any"> <text variable="title" font-style="italic" text-case="title"/> </if> <else-if type="bill"> <text variable="title" text-case="title"/> </else-if> <else-if type="legal_case"> <text variable="title" font-style="italic" strip-periods="true" form="short"/> </else-if> <else> <text variable="title" quotes="true" text-case="title"/> </else> </choose> </macro> <macro name="title-short"> <choose> <if type="book legislation webpage thesis motion_picture manuscript" match="any"> <text variable="title" font-style="italic" text-case="title" form="short"/> </if> <else> <text variable="title" quotes="true" text-case="title" form="short"/> </else> </choose> </macro> <!--Dates--> <macro name="issued-year"> <date variable="issued" form="text" date-parts="year"/> </macro> <macro name="issued-full"> <date variable="issued" form="text"/> </macro> <macro name="date-news"> <choose> <if type="article-newspaper broadcast personal_communication manuscript" match="any"> <date variable="issued" form="text"/> </if> </choose> </macro> <macro name="date-parenthesis"> <choose> <if type="legal_case" match="any"> <choose> <if variable="volume"> <text macro="issued-year" prefix="(" suffix=")"/> </if> <else-if variable="container-title volume number" match="any"> <!--no year in square brackets for unreported case w/o medium neutral citation--> <text macro="issued-year" prefix="[" suffix="]"/> </else-if> </choose> </if> <else-if type="article-journal article-magazine" match="any"> <text macro="issued-year" prefix="(" suffix=")"/> </else-if> <else-if type="webpage"> <text macro="issued-full" prefix="(" suffix=")"/> </else-if> <else-if type="legislation"> <text macro="issued-year" font-style="italic"/> </else-if> <else-if type="bill"> <text macro="issued-year"/> </else-if> </choose> </macro> <!--publication info --> <macro name="publisher"> <choose> <if type="book chapter paper-conference article-newspaper report legislation motion_picture speech interview thesis" match="any"> <group prefix="(" suffix=")" delimiter=", "> <choose> <if type="report thesis speech interview" match="any"> <group delimiter=" "> <text variable="genre"/> <text variable="number"/> <text variable="event" prefix="at the "/> </group> </if> </choose> <choose> <if type="article-newspaper"> <text variable="publisher-place"/> </if> <else-if type="legislation bill" match="any"> <!--this should be jurisdiction we use code instead--> <text variable="container-title"/> </else-if> <else> <!--this won't work in Zotero yet, but does no harm --> <names variable="director"> <label form="verb" text-case="capitalize-first" suffix=" "/> <name delimiter-precedes-last="never" and="text" delimiter=", " initialize="false" initialize-with=""/> </names> <choose> <!--if none of these, this we don't want edition either. Might be Loose-Leaf--> <if variable="publisher issued genre container-title" match="any"> <text macro="edition"/> </if> </choose> <text variable="publisher"/> <text variable="publisher-place"/> <choose> <if type="speech"> <text variable="event-place"/> <text macro="issued-full"/> </if> <else-if type="report interview" match="any"> <text macro="issued-full"/> </else-if> <else> <text macro="issued-year"/> </else> </choose> </else> </choose> </group> </if> </choose> </macro> <macro name="looseleaf"> <choose> <if type="book"> <choose> <if variable="publisher issued" match="none"> <group prefix="(at " suffix=")"> <choose> <if variable="edition"> <text variable="edition"/> </if> <else> <date variable="accessed" form="text"/> </else> </choose> </group> </if> </choose> </if> </choose> </macro> <macro name="volume-book"> <choose> <if type="book chapter report" match="any"> <group delimiter=" "> <label variable="volume" form="short" strip-periods="true"/> <text variable="volume"/> </group> </if> </choose> </macro> <macro name="edition"> <choose> <if is-numeric="edition"> <group delimiter=" "> <number variable="edition" form="ordinal"/> <label variable="edition" form="short" strip-periods="true"/> </group> </if> <else> <text variable="edition"/> </else> </choose> </macro> <macro name="book-container"> <choose> <if type="chapter paper-conference" match="any"> <group> <text macro="editor"/> <text variable="container-title" font-style="italic" prefix=", "/> </group> </if> <else-if type="webpage"> <text variable="container-title"/> </else-if> </choose> </macro> <macro name="broadcast-container"> <choose> <if type="broadcast" match="any"> <text variable="container-title" font-style="italic"/> </if> </choose> </macro> <macro name="article-case-info"> <choose> <if type="article-journal article-magazine article-newspaper legal_case" match="any"> <group delimiter=" "> <text variable="volume"/> <choose> <if type="legal_case"> <choose> <if variable="container-title"> <text variable="container-title" form="short"/> </if> <else-if variable="authority number" match="all"> <!--Assume that only cases with a Medium Neutral Citation have a docket number --> <group delimiter=" "> <text variable="authority" form="short" strip-periods="true"/> <text variable="number"/> <text macro="issued-full" prefix="(" suffix=")"/> </group> </else-if> <else> <group delimiter=", " prefix="(" suffix=")"> <text value="Unreported"/> <text variable="authority"/> <names variable="author"> <name name-as-sort-order="all" delimiter-precedes-last="never" and="text" delimiter=", " sort-separator=" "/> </names> <text macro="issued-full"/> </group> </else> </choose> </if> <else> <text variable="container-title" form="short"/> </else> </choose> </group> </if> </choose> </macro> <macro name="page-and-locator"> <choose> <if type="book chapter" match="none"> <group delimiter=" "> <text variable="page-first"/> <text macro="locator"/> </group> </if> <else> <text macro="locator"/> </else> </choose> </macro> <macro name="locator"> <choose> <if type="book chapter" match="any"> <group delimiter=" "> <label variable="locator" form="short" strip-periods="true"/> <text variable="locator"/> </group> </if> <else> <text variable="locator" prefix="at "/> </else> </choose> </macro> <!--Others --> <macro name="manuscript-catchall"> <choose> <if type="manuscript"> <text variable="genre"/> </if> </choose> </macro> <macro name="URL"> <choose> <if type="legal_case legislation bill" match="none"> <group delimiter=" "> <text variable="URL"/> <date variable="accessed" form="text" prefix="viewed "/> </group> </if> </choose> </macro> <citation et-al-min="20" et-al-use-first="19" et-al-subsequent-min="3" et-al-subsequent-use-first="1"> <layout suffix="." delimiter="; "> <choose> <if position="subsequent"> <choose> <if type="legal_case bill legislation manuscript" match="any"> <!--don't use short form and above note for legal citations --> <group delimiter=" "> <group delimiter=", "> <text macro="author-note"/> <text macro="title"/> </group> <!-- we could work with title-short here--> <group delimiter=" "> <text macro="date-parenthesis"/> <text macro="article-case-info"/> <text macro="book-container"/> <text macro="publisher"/> </group> </group> <text macro="manuscript-catchall" prefix=", "/> <text macro="date-news" prefix=", "/> <group delimiter=", " prefix=" "> <text macro="looseleaf"/> <text variable="page-first"/> <text variable="locator"/> </group> </if> <else> <group delimiter=", "> <text macro="author-short"/> <choose> <if disambiguate="true"> <text macro="title-short"/> </if> </choose> <choose> <if type="book chapter" match="any"> <text variable="first-reference-note-number" prefix="n "/> <text macro="locator"/> </if> <else> <group delimiter=" "> <text variable="first-reference-note-number" prefix="n "/> <text macro="locator"/> </group> </else> </choose> </group> </else> </choose> </if> <else> <!--general whole citation --> <group delimiter=" "> <group delimiter=", "> <group delimiter=" "> <group delimiter=", "> <text macro="author-note"/> <text macro="title"/> <text macro="broadcast-container"/> </group> <group delimiter=" "> <text macro="date-parenthesis"/> <text macro="article-case-info"/> <text macro="book-container"/> <text macro="publisher"/> </group> </group> <text macro="manuscript-catchall"/> <text macro="date-news"/> </group> <group delimiter=", "> <group delimiter=" "> <text macro="volume-book"/> <text macro="looseleaf"/> </group> <text macro="page-and-locator"/> </group> </group> <text macro="URL" prefix=", "/> </else> </choose> </layout> </citation> </style>
{ "pile_set_name": "Github" }
ifeq ($(words $(MAKECMDGOALS)), 1) LEVEL = minor else LEVEL = $(filter-out $@,$(MAKECMDGOALS)) endif release: package.json git pull --rebase npm test npm version $(LEVEL) npm publish git push --follow-tags %: @:
{ "pile_set_name": "Github" }
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008 Gael Guennebaud <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "main.h" template<typename From, typename To> bool check_is_convertible(const From&, const To&) { return internal::is_convertible<From,To>::value; } void test_meta() { VERIFY((internal::conditional<(3<4),internal::true_type, internal::false_type>::type::value)); VERIFY(( internal::is_same<float,float>::value)); VERIFY((!internal::is_same<float,double>::value)); VERIFY((!internal::is_same<float,float&>::value)); VERIFY((!internal::is_same<float,const float&>::value)); VERIFY(( internal::is_same<float,internal::remove_all<const float&>::type >::value)); VERIFY(( internal::is_same<float,internal::remove_all<const float*>::type >::value)); VERIFY(( internal::is_same<float,internal::remove_all<const float*&>::type >::value)); VERIFY(( internal::is_same<float,internal::remove_all<float**>::type >::value)); VERIFY(( internal::is_same<float,internal::remove_all<float**&>::type >::value)); VERIFY(( internal::is_same<float,internal::remove_all<float* const *&>::type >::value)); VERIFY(( internal::is_same<float,internal::remove_all<float* const>::type >::value)); // test add_const VERIFY(( internal::is_same< internal::add_const<float>::type, const float >::value)); VERIFY(( internal::is_same< internal::add_const<float*>::type, float* const>::value)); VERIFY(( internal::is_same< internal::add_const<float const*>::type, float const* const>::value)); VERIFY(( internal::is_same< internal::add_const<float&>::type, float& >::value)); // test remove_const VERIFY(( internal::is_same< internal::remove_const<float const* const>::type, float const* >::value)); VERIFY(( internal::is_same< internal::remove_const<float const*>::type, float const* >::value)); VERIFY(( internal::is_same< internal::remove_const<float* const>::type, float* >::value)); // test add_const_on_value_type VERIFY(( internal::is_same< internal::add_const_on_value_type<float&>::type, float const& >::value)); VERIFY(( internal::is_same< internal::add_const_on_value_type<float*>::type, float const* >::value)); VERIFY(( internal::is_same< internal::add_const_on_value_type<float>::type, const float >::value)); VERIFY(( internal::is_same< internal::add_const_on_value_type<const float>::type, const float >::value)); VERIFY(( internal::is_same< internal::add_const_on_value_type<const float* const>::type, const float* const>::value)); VERIFY(( internal::is_same< internal::add_const_on_value_type<float* const>::type, const float* const>::value)); VERIFY(( internal::is_same<float,internal::remove_reference<float&>::type >::value)); VERIFY(( internal::is_same<const float,internal::remove_reference<const float&>::type >::value)); VERIFY(( internal::is_same<float,internal::remove_pointer<float*>::type >::value)); VERIFY(( internal::is_same<const float,internal::remove_pointer<const float*>::type >::value)); VERIFY(( internal::is_same<float,internal::remove_pointer<float* const >::type >::value)); VERIFY(( internal::is_convertible<float,double>::value )); VERIFY(( internal::is_convertible<int,double>::value )); VERIFY(( internal::is_convertible<double,int>::value )); VERIFY((!internal::is_convertible<std::complex<double>,double>::value )); VERIFY(( internal::is_convertible<Array33f,Matrix3f>::value )); // VERIFY((!internal::is_convertible<Matrix3f,Matrix3d>::value )); //does not work because the conversion is prevented by a static assertion VERIFY((!internal::is_convertible<Array33f,int>::value )); VERIFY((!internal::is_convertible<MatrixXf,float>::value )); { float f; MatrixXf A, B; VectorXf a, b; VERIFY(( check_is_convertible(a.dot(b), f) )); VERIFY(( check_is_convertible(a.transpose()*b, f) )); VERIFY((!check_is_convertible(A*B, f) )); VERIFY(( check_is_convertible(A*B, A) )); } VERIFY(internal::meta_sqrt<1>::ret == 1); #define VERIFY_META_SQRT(X) VERIFY(internal::meta_sqrt<X>::ret == int(std::sqrt(double(X)))) VERIFY_META_SQRT(2); VERIFY_META_SQRT(3); VERIFY_META_SQRT(4); VERIFY_META_SQRT(5); VERIFY_META_SQRT(6); VERIFY_META_SQRT(8); VERIFY_META_SQRT(9); VERIFY_META_SQRT(15); VERIFY_META_SQRT(16); VERIFY_META_SQRT(17); VERIFY_META_SQRT(255); VERIFY_META_SQRT(256); VERIFY_META_SQRT(257); VERIFY_META_SQRT(1023); VERIFY_META_SQRT(1024); VERIFY_META_SQRT(1025); }
{ "pile_set_name": "Github" }
require("scripts/globals/survival_guide") function onTrigger(player, targetNpc) dsp.survivalGuide.onTrigger(player) end function onEventUpdate(player, csid, option) dsp.survivalGuide.onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option, targetNpc) dsp.survivalGuide.onEventFinish(player, csid, option) end
{ "pile_set_name": "Github" }
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24" android:tint="?attr/colorControlNormal"> <path android:fillColor="@android:color/white" android:pathData="M20,2L4,2v20h16L20,2zM6,4h5v8l-2.5,-1.5L6,12L6,4zM6,19l3,-3.86 2.14,2.58 3,-3.86L18,19L6,19z"/> </vector>
{ "pile_set_name": "Github" }
<?xml version="1.0" ?> <!DOCTYPE translationbundle> <translationbundle lang="sv"> <translation id="1018656279737460067">Avbröts</translation> <translation id="1195447618553298278">Okänt fel.</translation> <translation id="1413240736185167732">Misslyckades – filterfel</translation> <translation id="1468664791493211953">Erbjudanden</translation> <translation id="1482734542997480527">Den här enheten hanteras av <ph name="ENROLLMENT_DOMAIN" />, som kan ha möjlighet att övervaka din aktivitet.</translation> <translation id="150962533380566081">Ogiltig PUK-kod.</translation> <translation id="1510238584712386396">Startprogram</translation> <translation id="1644574205037202324">Historik</translation> <translation id="1734367976349034509">Enheten är företagshanterad</translation> <translation id="1905710495812624430">Du har försökt för många gånger.</translation> <translation id="1930797645656624981">Tjänst för inmatningsmetod för Chrome OS</translation> <translation id="1947737735496445907">Utskrivet</translation> <translation id="1979103255016296513">Tiden för att ändra lösenordet har gått ut</translation> <translation id="2049639323467105390">Den här enheten hanteras av <ph name="DOMAIN" />.</translation> <translation id="2161394479394250669">Avbryt utskriftsjobb</translation> <translation id="2338501278241028356">Aktivera Bluetooth så att det går att upptäcka enheter i närheten</translation> <translation id="2375079107209812402"><ph name="ATTEMPTS_LEFT" /> försök kvar</translation> <translation id="2805756323405976993">Appar</translation> <translation id="2872961005593481000">Stäng av</translation> <translation id="3008341117444806826">UPPDATERA</translation> <translation id="3091839911843451378">Misslyckades – skrivaren har stannat</translation> <translation id="3268178239013324452">Misslyckades – luckan är öppen</translation> <translation id="3369013195428705271">Vill du rensa all utskriftshistorik? De pågående utskriftsjobben rensas inte.</translation> <translation id="3456078764689556234">Sida <ph name="PRINTED_PAGES" /> av <ph name="TOTAL_PAGES" /> har skrivits ut.</translation> <translation id="3459509316159669723">Skriva ut</translation> <translation id="3515615323037921860">Utskriftsjobb</translation> <translation id="3527036260304016759">Misslyckades – okänt fel</translation> <translation id="3749289110408117711">Filnamn</translation> <translation id="38114475217616659">Rensa all historik</translation> <translation id="3820172043799983114">Ogiltig pinkod</translation> <translation id="3838338534323494292">Nytt lösenord</translation> <translation id="4003259559679196451"><ph name="ENROLLMENT_DOMAIN" /> hanterar den här enheten och har tillgång till all användaraktivitet, inklusive besökta webbsidor, lösenord och e-post.</translation> <translation id="4003384961948020559">Misslyckades – utmatningsfacket är fullt</translation> <translation id="4034824040120875894">Skrivare</translation> <translation id="4227825898293920515">Lösenordet upphör att gälla om <ph name="TIME" /></translation> <translation id="4238516577297848345">Inga utskriftsjobb pågår</translation> <translation id="428217921675623177">Utskriftsjobb som är äldre än 90 dagar tas bort</translation> <translation id="4429881212383817840">Kerberos-biljetten upphör snart att gälla</translation> <translation id="445059817448385655">Gammalt lösenord</translation> <translation id="4627232916386272576"><ph name="DOCUMENT_TITLE" />, <ph name="PRINTER_NAME" />, <ph name="CREATION_TIME" />, <ph name="PRINTED_PAGE_NUMBER" /> av <ph name="TOTAL_PAGE_NUMBER" />. Tryck på retur för att avbryta utskriftsjobbet.</translation> <translation id="467510802200863975">Lösenorden matchar inte</translation> <translation id="4731797938093519117">Föräldraåtkomst</translation> <translation id="4808449224298348341">Utskriftsjobbet <ph name="DOCUMENT_TITLE" /> har avbrutits</translation> <translation id="4890353053343094602">Välj ett nytt omedelbart</translation> <translation id="4932733599132424254">Datum</translation> <translation id="5212543919916444558">Det finns inget på skärmen som jag kan hjälpa till med. Tryck på mikrofonen och fråga om något.</translation> <translation id="5222676887888702881">Logga ut</translation> <translation id="5317780077021120954">Spara</translation> <translation id="5326394068492324457"><ph name="DOCUMENT_TITLE" />, <ph name="PRINTER_NAME" />, <ph name="CREATION_TIME" />, <ph name="COMPLETION_STATUS" /></translation> <translation id="5332948983412042822">Välj ett nytt nu</translation> <translation id="5457599981699367932">Använd som gäst</translation> <translation id="54609108002486618">Hanterade</translation> <translation id="5832805196449965646">Lägg till person</translation> <translation id="5895138241574237353">Starta om</translation> <translation id="6048107060512778456">Misslyckades – papperstrassel</translation> <translation id="6058625436358447366">Slutför genom att ange det gamla och det nya lösenordet</translation> <translation id="6106186594183574873">Slutför genom att ange det gamla lösenordet</translation> <translation id="6146993107019042706">Slutför genom att ange det nya lösenordet</translation> <translation id="6517239166834772319">Utforska</translation> <translation id="6564646048574748301">Misslyckades – skrivaren kan inte nås</translation> <translation id="6643016212128521049">Rensa</translation> <translation id="7162487448488904999">Gallery</translation> <translation id="7274587244503383581"><ph name="PRINTED_PAGES_NUMBER" />/<ph name="TOTAL_PAGES_NUMBER" /></translation> <translation id="7561454561030345039">Den här åtgärden hanteras av administratören</translation> <translation id="7658239707568436148">Avbryt</translation> <translation id="7690294790491645610">Bekräfta det nya lösenordet</translation> <translation id="7805768142964895445">Status</translation> <translation id="808894953321890993">Ändra lösenord</translation> <translation id="8208861521865154048">Förmåner</translation> <translation id="8347227221149377169">Utskriftsjobb</translation> <translation id="8701136875688985581"><ph name="ENROLLMENT_DOMAIN" /> hanterar denna användare och kan fjärrhantera inställningar och övervaka användaraktivitet.</translation> <translation id="871560550817059752">Misslyckades – slut på bläck</translation> <translation id="8747900814994928677">Bekräfta ändring</translation> <translation id="8919837981463578619">Misslyckades – fack saknas</translation> <translation id="8928727111548978589">Misslyckades – slut på papper</translation> <translation id="89415009803968170"><ph name="ERROR_MESSAGE" /> <ph name="ATTEMPTS_LEFT" /> försök kvar</translation> <translation id="910415269708673980">Uppdatera biljetten för <ph name="PRINCIPAL_NAME" /></translation> <translation id="9111102763498581341">Lås upp</translation> </translationbundle>
{ "pile_set_name": "Github" }
color0 #333333 color1 #f8818e color2 #92d3a2 color3 #1a8e63 color4 #8ed0ce color5 #5e468c color6 #31658c color7 #e2d8cd color8 #3d3d3d color9 #fb3d66 color10 #6bb48d color11 #30c85a color12 #39a7a2 color13 #7e62b3 color14 #6096bf color15 #e2d8cd background #051519 selection_foreground #051519 cursor #9e9ecb foreground #e2d8cd selection_background #e2d8cd
{ "pile_set_name": "Github" }
struct InitDialogItem { unsigned char Type; unsigned char X1,Y1,X2,Y2; unsigned char Focus; DWORD_PTR Selected; unsigned int Flags; unsigned char DefaultButton; const TCHAR *Data; }; void SetRegKey(HKEY hRoot,const TCHAR *Key,const TCHAR *ValueName,DWORD ValueData); void SetRegKey(HKEY hRoot,const TCHAR *Key,const TCHAR *ValueName,TCHAR *ValueData); int GetRegKey(HKEY hRoot,const TCHAR *Key,const TCHAR *ValueName,int &ValueData,DWORD Default); int GetRegKey(HKEY hRoot,const TCHAR *Key,const TCHAR *ValueName,DWORD Default); int GetRegKey(HKEY hRoot,const TCHAR *Key,const TCHAR *ValueName,TCHAR *ValueData,const TCHAR *Default,DWORD DataSize); const TCHAR *GetMsg(int MsgId); void InitDialogItems(const struct InitDialogItem *Init,struct FarDialogItem *Item,int ItemsNumber); static struct PluginStartupInfo Info; struct FarStandardFunctions FSF; TCHAR PluginRootKey[80];
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="com.android.tools.idea.welcome.wizard.deprecated.GvmInstallInfoStep"> <grid id="27dc6" binding="myRoot" layout-manager="GridLayoutManager" row-count="4" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1"> <margin top="0" left="0" bottom="0" right="0"/> <constraints> <xy x="20" y="20" width="967" height="400"/> </constraints> <properties/> <border type="none"/> <children> <component id="584cf" class="javax.swing.JLabel"> <constraints> <grid row="0" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/> </constraints> <properties> <text value="This wizard will execute Android Emulator Hypervisor Driver for AMD Processors stand-alone installer. This is an additional step required to install this package. "/> </properties> </component> <component id="e9e13" class="javax.swing.JLabel"> <constraints> <grid row="2" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/> </constraints> <properties> <text value="Click 'Next' to proceed"/> </properties> </component> <vspacer id="b565a"> <constraints> <grid row="3" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"> <preferred-size width="-1" height="150"/> </grid> </constraints> </vspacer> <vspacer id="83705"> <constraints> <grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"> <preferred-size width="-1" height="16"/> </grid> </constraints> </vspacer> </children> </grid> </form>
{ "pile_set_name": "Github" }
itk_wrap_class("itk::BoxMeanImageFilter" POINTER) itk_wrap_image_filter("${WRAP_ITK_SCALAR}" 2) itk_end_wrap_class()
{ "pile_set_name": "Github" }
/* Simple DirectMedia Layer Copyright (C) 1997-2014 Sam Lantinga <[email protected]> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_AUDIO_DRIVER_DSOUND /* Allow access to a raw mixing buffer */ #include "SDL_timer.h" #include "SDL_loadso.h" #include "SDL_audio.h" #include "../SDL_audio_c.h" #include "SDL_directsound.h" #ifndef WAVE_FORMAT_IEEE_FLOAT #define WAVE_FORMAT_IEEE_FLOAT 0x0003 #endif /* DirectX function pointers for audio */ static void* DSoundDLL = NULL; typedef HRESULT(WINAPI*fnDirectSoundCreate8)(LPGUID,LPDIRECTSOUND*,LPUNKNOWN); typedef HRESULT(WINAPI*fnDirectSoundEnumerateW)(LPDSENUMCALLBACKW, LPVOID); typedef HRESULT(WINAPI*fnDirectSoundCaptureEnumerateW)(LPDSENUMCALLBACKW,LPVOID); static fnDirectSoundCreate8 pDirectSoundCreate8 = NULL; static fnDirectSoundEnumerateW pDirectSoundEnumerateW = NULL; static fnDirectSoundCaptureEnumerateW pDirectSoundCaptureEnumerateW = NULL; static void DSOUND_Unload(void) { pDirectSoundCreate8 = NULL; pDirectSoundEnumerateW = NULL; pDirectSoundCaptureEnumerateW = NULL; if (DSoundDLL != NULL) { SDL_UnloadObject(DSoundDLL); DSoundDLL = NULL; } } static int DSOUND_Load(void) { int loaded = 0; DSOUND_Unload(); DSoundDLL = SDL_LoadObject("DSOUND.DLL"); if (DSoundDLL == NULL) { SDL_SetError("DirectSound: failed to load DSOUND.DLL"); } else { /* Now make sure we have DirectX 8 or better... */ #define DSOUNDLOAD(f) { \ p##f = (fn##f) SDL_LoadFunction(DSoundDLL, #f); \ if (!p##f) loaded = 0; \ } loaded = 1; /* will reset if necessary. */ DSOUNDLOAD(DirectSoundCreate8); DSOUNDLOAD(DirectSoundEnumerateW); DSOUNDLOAD(DirectSoundCaptureEnumerateW); #undef DSOUNDLOAD if (!loaded) { SDL_SetError("DirectSound: System doesn't appear to have DX8."); } } if (!loaded) { DSOUND_Unload(); } return loaded; } static int SetDSerror(const char *function, int code) { static const char *error; static char errbuf[1024]; errbuf[0] = 0; switch (code) { case E_NOINTERFACE: error = "Unsupported interface -- Is DirectX 8.0 or later installed?"; break; case DSERR_ALLOCATED: error = "Audio device in use"; break; case DSERR_BADFORMAT: error = "Unsupported audio format"; break; case DSERR_BUFFERLOST: error = "Mixing buffer was lost"; break; case DSERR_CONTROLUNAVAIL: error = "Control requested is not available"; break; case DSERR_INVALIDCALL: error = "Invalid call for the current state"; break; case DSERR_INVALIDPARAM: error = "Invalid parameter"; break; case DSERR_NODRIVER: error = "No audio device found"; break; case DSERR_OUTOFMEMORY: error = "Out of memory"; break; case DSERR_PRIOLEVELNEEDED: error = "Caller doesn't have priority"; break; case DSERR_UNSUPPORTED: error = "Function not supported"; break; default: SDL_snprintf(errbuf, SDL_arraysize(errbuf), "%s: Unknown DirectSound error: 0x%x", function, code); break; } if (!errbuf[0]) { SDL_snprintf(errbuf, SDL_arraysize(errbuf), "%s: %s", function, error); } return SDL_SetError("%s", errbuf); } static BOOL CALLBACK FindAllDevs(LPGUID guid, LPCWSTR desc, LPCWSTR module, LPVOID data) { SDL_AddAudioDevice addfn = (SDL_AddAudioDevice) data; if (guid != NULL) { /* skip default device */ char *str = WIN_StringToUTF8(desc); if (str != NULL) { addfn(str); SDL_free(str); /* addfn() makes a copy of this string. */ } } return TRUE; /* keep enumerating. */ } static void DSOUND_DetectDevices(int iscapture, SDL_AddAudioDevice addfn) { if (iscapture) { pDirectSoundCaptureEnumerateW(FindAllDevs, addfn); } else { pDirectSoundEnumerateW(FindAllDevs, addfn); } } static void DSOUND_WaitDevice(_THIS) { DWORD status = 0; DWORD cursor = 0; DWORD junk = 0; HRESULT result = DS_OK; /* Semi-busy wait, since we have no way of getting play notification on a primary mixing buffer located in hardware (DirectX 5.0) */ result = IDirectSoundBuffer_GetCurrentPosition(this->hidden->mixbuf, &junk, &cursor); if (result != DS_OK) { if (result == DSERR_BUFFERLOST) { IDirectSoundBuffer_Restore(this->hidden->mixbuf); } #ifdef DEBUG_SOUND SetDSerror("DirectSound GetCurrentPosition", result); #endif return; } while ((cursor / this->hidden->mixlen) == this->hidden->lastchunk) { /* FIXME: find out how much time is left and sleep that long */ SDL_Delay(1); /* Try to restore a lost sound buffer */ IDirectSoundBuffer_GetStatus(this->hidden->mixbuf, &status); if ((status & DSBSTATUS_BUFFERLOST)) { IDirectSoundBuffer_Restore(this->hidden->mixbuf); IDirectSoundBuffer_GetStatus(this->hidden->mixbuf, &status); if ((status & DSBSTATUS_BUFFERLOST)) { break; } } if (!(status & DSBSTATUS_PLAYING)) { result = IDirectSoundBuffer_Play(this->hidden->mixbuf, 0, 0, DSBPLAY_LOOPING); if (result == DS_OK) { continue; } #ifdef DEBUG_SOUND SetDSerror("DirectSound Play", result); #endif return; } /* Find out where we are playing */ result = IDirectSoundBuffer_GetCurrentPosition(this->hidden->mixbuf, &junk, &cursor); if (result != DS_OK) { SetDSerror("DirectSound GetCurrentPosition", result); return; } } } static void DSOUND_PlayDevice(_THIS) { /* Unlock the buffer, allowing it to play */ if (this->hidden->locked_buf) { IDirectSoundBuffer_Unlock(this->hidden->mixbuf, this->hidden->locked_buf, this->hidden->mixlen, NULL, 0); } } static Uint8 * DSOUND_GetDeviceBuf(_THIS) { DWORD cursor = 0; DWORD junk = 0; HRESULT result = DS_OK; DWORD rawlen = 0; /* Figure out which blocks to fill next */ this->hidden->locked_buf = NULL; result = IDirectSoundBuffer_GetCurrentPosition(this->hidden->mixbuf, &junk, &cursor); if (result == DSERR_BUFFERLOST) { IDirectSoundBuffer_Restore(this->hidden->mixbuf); result = IDirectSoundBuffer_GetCurrentPosition(this->hidden->mixbuf, &junk, &cursor); } if (result != DS_OK) { SetDSerror("DirectSound GetCurrentPosition", result); return (NULL); } cursor /= this->hidden->mixlen; #ifdef DEBUG_SOUND /* Detect audio dropouts */ { DWORD spot = cursor; if (spot < this->hidden->lastchunk) { spot += this->hidden->num_buffers; } if (spot > this->hidden->lastchunk + 1) { fprintf(stderr, "Audio dropout, missed %d fragments\n", (spot - (this->hidden->lastchunk + 1))); } } #endif this->hidden->lastchunk = cursor; cursor = (cursor + 1) % this->hidden->num_buffers; cursor *= this->hidden->mixlen; /* Lock the audio buffer */ result = IDirectSoundBuffer_Lock(this->hidden->mixbuf, cursor, this->hidden->mixlen, (LPVOID *) & this->hidden->locked_buf, &rawlen, NULL, &junk, 0); if (result == DSERR_BUFFERLOST) { IDirectSoundBuffer_Restore(this->hidden->mixbuf); result = IDirectSoundBuffer_Lock(this->hidden->mixbuf, cursor, this->hidden->mixlen, (LPVOID *) & this-> hidden->locked_buf, &rawlen, NULL, &junk, 0); } if (result != DS_OK) { SetDSerror("DirectSound Lock", result); return (NULL); } return (this->hidden->locked_buf); } static void DSOUND_WaitDone(_THIS) { Uint8 *stream = DSOUND_GetDeviceBuf(this); /* Wait for the playing chunk to finish */ if (stream != NULL) { SDL_memset(stream, this->spec.silence, this->hidden->mixlen); DSOUND_PlayDevice(this); } DSOUND_WaitDevice(this); /* Stop the looping sound buffer */ IDirectSoundBuffer_Stop(this->hidden->mixbuf); } static void DSOUND_CloseDevice(_THIS) { if (this->hidden != NULL) { if (this->hidden->sound != NULL) { if (this->hidden->mixbuf != NULL) { /* Clean up the audio buffer */ IDirectSoundBuffer_Release(this->hidden->mixbuf); this->hidden->mixbuf = NULL; } IDirectSound_Release(this->hidden->sound); this->hidden->sound = NULL; } SDL_free(this->hidden); this->hidden = NULL; } } /* This function tries to create a secondary audio buffer, and returns the number of audio chunks available in the created buffer. */ static int CreateSecondary(_THIS, HWND focus) { LPDIRECTSOUND sndObj = this->hidden->sound; LPDIRECTSOUNDBUFFER *sndbuf = &this->hidden->mixbuf; Uint32 chunksize = this->spec.size; const int numchunks = 8; HRESULT result = DS_OK; DSBUFFERDESC format; LPVOID pvAudioPtr1, pvAudioPtr2; DWORD dwAudioBytes1, dwAudioBytes2; WAVEFORMATEX wfmt; SDL_zero(wfmt); if (SDL_AUDIO_ISFLOAT(this->spec.format)) { wfmt.wFormatTag = WAVE_FORMAT_IEEE_FLOAT; } else { wfmt.wFormatTag = WAVE_FORMAT_PCM; } wfmt.wBitsPerSample = SDL_AUDIO_BITSIZE(this->spec.format); wfmt.nChannels = this->spec.channels; wfmt.nSamplesPerSec = this->spec.freq; wfmt.nBlockAlign = wfmt.nChannels * (wfmt.wBitsPerSample / 8); wfmt.nAvgBytesPerSec = wfmt.nSamplesPerSec * wfmt.nBlockAlign; /* Update the fragment size as size in bytes */ SDL_CalculateAudioSpec(&this->spec); /* Try to set primary mixing privileges */ if (focus) { result = IDirectSound_SetCooperativeLevel(sndObj, focus, DSSCL_PRIORITY); } else { result = IDirectSound_SetCooperativeLevel(sndObj, GetDesktopWindow(), DSSCL_NORMAL); } if (result != DS_OK) { return SetDSerror("DirectSound SetCooperativeLevel", result); } /* Try to create the secondary buffer */ SDL_zero(format); format.dwSize = sizeof(format); format.dwFlags = DSBCAPS_GETCURRENTPOSITION2; if (!focus) { format.dwFlags |= DSBCAPS_GLOBALFOCUS; } else { format.dwFlags |= DSBCAPS_STICKYFOCUS; } format.dwBufferBytes = numchunks * chunksize; if ((format.dwBufferBytes < DSBSIZE_MIN) || (format.dwBufferBytes > DSBSIZE_MAX)) { return SDL_SetError("Sound buffer size must be between %d and %d", DSBSIZE_MIN / numchunks, DSBSIZE_MAX / numchunks); } format.dwReserved = 0; format.lpwfxFormat = &wfmt; result = IDirectSound_CreateSoundBuffer(sndObj, &format, sndbuf, NULL); if (result != DS_OK) { return SetDSerror("DirectSound CreateSoundBuffer", result); } IDirectSoundBuffer_SetFormat(*sndbuf, &wfmt); /* Silence the initial audio buffer */ result = IDirectSoundBuffer_Lock(*sndbuf, 0, format.dwBufferBytes, (LPVOID *) & pvAudioPtr1, &dwAudioBytes1, (LPVOID *) & pvAudioPtr2, &dwAudioBytes2, DSBLOCK_ENTIREBUFFER); if (result == DS_OK) { SDL_memset(pvAudioPtr1, this->spec.silence, dwAudioBytes1); IDirectSoundBuffer_Unlock(*sndbuf, (LPVOID) pvAudioPtr1, dwAudioBytes1, (LPVOID) pvAudioPtr2, dwAudioBytes2); } /* We're ready to go */ return (numchunks); } typedef struct FindDevGUIDData { const char *devname; GUID guid; int found; } FindDevGUIDData; static BOOL CALLBACK FindDevGUID(LPGUID guid, LPCWSTR desc, LPCWSTR module, LPVOID _data) { if (guid != NULL) { /* skip the default device. */ FindDevGUIDData *data = (FindDevGUIDData *) _data; char *str = WIN_StringToUTF8(desc); const int match = (SDL_strcmp(str, data->devname) == 0); SDL_free(str); if (match) { data->found = 1; SDL_memcpy(&data->guid, guid, sizeof (data->guid)); return FALSE; /* found it! stop enumerating. */ } } return TRUE; /* keep enumerating. */ } static int DSOUND_OpenDevice(_THIS, const char *devname, int iscapture) { HRESULT result; SDL_bool valid_format = SDL_FALSE; SDL_bool tried_format = SDL_FALSE; SDL_AudioFormat test_format = SDL_FirstAudioFormat(this->spec.format); FindDevGUIDData devguid; LPGUID guid = NULL; if (devname != NULL) { devguid.found = 0; devguid.devname = devname; if (iscapture) pDirectSoundCaptureEnumerateW(FindDevGUID, &devguid); else pDirectSoundEnumerateW(FindDevGUID, &devguid); if (!devguid.found) { return SDL_SetError("DirectSound: Requested device not found"); } guid = &devguid.guid; } /* Initialize all variables that we clean on shutdown */ this->hidden = (struct SDL_PrivateAudioData *) SDL_malloc((sizeof *this->hidden)); if (this->hidden == NULL) { return SDL_OutOfMemory(); } SDL_memset(this->hidden, 0, (sizeof *this->hidden)); /* Open the audio device */ result = pDirectSoundCreate8(guid, &this->hidden->sound, NULL); if (result != DS_OK) { DSOUND_CloseDevice(this); return SetDSerror("DirectSoundCreate", result); } while ((!valid_format) && (test_format)) { switch (test_format) { case AUDIO_U8: case AUDIO_S16: case AUDIO_S32: case AUDIO_F32: tried_format = SDL_TRUE; this->spec.format = test_format; this->hidden->num_buffers = CreateSecondary(this, NULL); if (this->hidden->num_buffers > 0) { valid_format = SDL_TRUE; } break; } test_format = SDL_NextAudioFormat(); } if (!valid_format) { DSOUND_CloseDevice(this); if (tried_format) { return -1; /* CreateSecondary() should have called SDL_SetError(). */ } return SDL_SetError("DirectSound: Unsupported audio format"); } /* The buffer will auto-start playing in DSOUND_WaitDevice() */ this->hidden->mixlen = this->spec.size; return 0; /* good to go. */ } static void DSOUND_Deinitialize(void) { DSOUND_Unload(); } static int DSOUND_Init(SDL_AudioDriverImpl * impl) { if (!DSOUND_Load()) { return 0; } /* Set the function pointers */ impl->DetectDevices = DSOUND_DetectDevices; impl->OpenDevice = DSOUND_OpenDevice; impl->PlayDevice = DSOUND_PlayDevice; impl->WaitDevice = DSOUND_WaitDevice; impl->WaitDone = DSOUND_WaitDone; impl->GetDeviceBuf = DSOUND_GetDeviceBuf; impl->CloseDevice = DSOUND_CloseDevice; impl->Deinitialize = DSOUND_Deinitialize; return 1; /* this audio target is available. */ } AudioBootStrap DSOUND_bootstrap = { "directsound", "DirectSound", DSOUND_Init, 0 }; #endif /* SDL_AUDIO_DRIVER_DSOUND */ /* vi: set ts=4 sw=4 expandtab: */
{ "pile_set_name": "Github" }
package com.momentolabs.app.security.applocker.di.module import com.iammert.hdwallpapers.di.scope.FragmentScope import com.momentolabs.app.security.applocker.data.database.callblocker.addtoblacklist.AddToBlackListDialog import com.momentolabs.app.security.applocker.ui.background.BackgroundsFragment import com.momentolabs.app.security.applocker.ui.callblocker.blacklist.BlackListFragment import com.momentolabs.app.security.applocker.ui.callblocker.log.CallLogFragment import com.momentolabs.app.security.applocker.ui.security.SecurityFragment import com.momentolabs.app.security.applocker.ui.settings.SettingsFragment import com.momentolabs.app.security.applocker.ui.vault.vaultlist.VaultListFragment import dagger.Module import dagger.android.ContributesAndroidInjector @Module abstract class FragmentBuilderModule { @FragmentScope @ContributesAndroidInjector abstract fun securityFragment(): SecurityFragment @FragmentScope @ContributesAndroidInjector abstract fun backgroundFragment(): BackgroundsFragment @FragmentScope @ContributesAndroidInjector abstract fun settingsFragment(): SettingsFragment @FragmentScope @ContributesAndroidInjector abstract fun vaultListFragment(): VaultListFragment @FragmentScope @ContributesAndroidInjector abstract fun blackListFragment(): BlackListFragment @FragmentScope @ContributesAndroidInjector abstract fun callLogFragment(): CallLogFragment }
{ "pile_set_name": "Github" }
// header block begin // +build !minimal package qtcore // /usr/include/qt/QtCore/qurl.h // #include <qurl.h> // #include <QtCore> // header block end // main block begin // main block end // use block begin // use block end // ext block begin /* #include <stdlib.h> // extern C begin: 12 */ // import "C" import "unsafe" import "reflect" import "fmt" import "log" import "github.com/kitech/qt.go/qtrt" // ext block end // body block begin // body block end // keep block begin func init_unused_10346() { if false { reflect.TypeOf(123) } if false { reflect.TypeOf(unsafe.Sizeof(0)) } if false { fmt.Println(123) } if false { log.Println(123) } if false { qtrt.KeepMe() } } // keep block end
{ "pile_set_name": "Github" }
package jetbrains.mps.lang.generator.behavior; /*Generated by MPS */ import jetbrains.mps.core.aspects.behaviour.BaseBHDescriptor; import org.jetbrains.mps.openapi.language.SAbstractConcept; import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory; import jetbrains.mps.core.aspects.behaviour.api.SMethod; import jetbrains.mps.core.aspects.behaviour.SMethodBuilder; import jetbrains.mps.core.aspects.behaviour.SJavaCompoundTypeImpl; import jetbrains.mps.core.aspects.behaviour.SModifiersImpl; import jetbrains.mps.core.aspects.behaviour.AccessPrivileges; import java.util.List; import java.util.Arrays; import org.jetbrains.annotations.NotNull; import org.jetbrains.mps.openapi.model.SNode; import jetbrains.mps.core.aspects.behaviour.api.SConstructor; import org.jetbrains.annotations.Nullable; import jetbrains.mps.core.aspects.behaviour.api.BHMethodNotFoundException; public final class IGeneratorParameter__BehaviorDescriptor extends BaseBHDescriptor { private static final SAbstractConcept CONCEPT = MetaAdapterFactory.getInterfaceConcept(0xb401a68083254110L, 0x8fd384331ff25befL, 0x90726ff283822d4L, "jetbrains.mps.lang.generator.structure.IGeneratorParameter"); public static final SMethod<String> getUniqueId_id$79JWCe2bn = new SMethodBuilder<String>(new SJavaCompoundTypeImpl(String.class)).name("getUniqueId").modifiers(SModifiersImpl.create(12, AccessPrivileges.PUBLIC)).concept(CONCEPT).id("$79JWCe2bn").build(); private static final List<SMethod<?>> BH_METHODS = Arrays.<SMethod<?>>asList(getUniqueId_id$79JWCe2bn); private static void ___init___(@NotNull SNode __thisNode__) { } /*package*/ IGeneratorParameter__BehaviorDescriptor() { } @Override protected void initNode(@NotNull SNode node, @NotNull SConstructor constructor, @Nullable Object[] parameters) { ___init___(node); } @Override protected <T> T invokeSpecial0(@NotNull SNode node, @NotNull SMethod<T> method, @Nullable Object[] parameters) { int methodIndex = BH_METHODS.indexOf(method); if (methodIndex < 0) { throw new BHMethodNotFoundException(this, method); } switch (methodIndex) { default: throw new BHMethodNotFoundException(this, method); } } @Override protected <T> T invokeSpecial0(@NotNull SAbstractConcept concept, @NotNull SMethod<T> method, @Nullable Object[] parameters) { int methodIndex = BH_METHODS.indexOf(method); if (methodIndex < 0) { throw new BHMethodNotFoundException(this, method); } switch (methodIndex) { default: throw new BHMethodNotFoundException(this, method); } } @NotNull @Override public List<SMethod<?>> getDeclaredMethods() { return BH_METHODS; } @NotNull @Override public SAbstractConcept getConcept() { return CONCEPT; } }
{ "pile_set_name": "Github" }
if(K.Admin) K.Admin.methods({ removeCat: function(cat, type) { if(!K.Admin.isMe()) return false; cat = K.Util.sanitize.regExp(cat); Categories.remove({name: cat, type: type}); if(type==='user') { Users.update({cats: cat }, { $pull: {cats: cat } },{multi:true}); } else if(type==='place') { Places.update({cats: cat }, { $pull: {cats: cat } },{multi:true}); } Users.update({catshist: cat }, { $pull: {catshist: cat } },{multi:true}); console.log('Cats: removeCat', cat, type); }, insertCat: function(name, type) { if(!K.Admin.isMe()) return false; name = K.Util.sanitize.catName(name); try { Categories.insert(_.extend({}, K.schemas.cat, { name: name, type: type })); } catch(e) { throw new Meteor.Error(500, i18n('error_cats_exists',name) ); return null; } console.log('Cats: insertCat', name, type); }, addCatsToUser: function(userId, cats) { if(!K.Admin.isMe()) return false; cats = _.isArray(cats) ? cats : [cats]; cats = _.map(cats, K.Util.sanitize.catName); Users.update(userId, { $addToSet: {'cats': {$each: cats} } }); _.each(cats, function(cat) { catData = _.extend({}, K.schemas.cat, { name: cat, type: 'user' }); delete catData.rank;//path to maintain last value Categories.upsert({ name: cat, type: 'user' }, { $set: catData, $inc: {rank:1} }); }); }, removeCatsFromUser: function(userId, cats) { if(!K.Admin.isMe()) return false; cats = _.isArray(cats) ? cats : [cats]; Users.update(userId, { $pull: {'cats': {$in: cats} } }); Categories.update({name: {$in: cats}, type: 'user'}, { $inc: {rank: -1} },{multi:true}); console.log('Cats: removeCatsFromPlace', userId, cats); }, removeCatsOrphan: function() { if(!K.Admin.isMe()) return false; Categories.remove({rank: {$lt: 1} }); console.log('Cats: cleanCatsOrphan'); }, updateCatsCountsByType: function(type) { if(!K.Admin.isMe()) return false; type = type || 'place'; var coll = (type==='user') ? Users : Places; var n = 0; Categories.find({ type: type }).forEach(function(cat) { let count = coll.find({cats: cat.name}).count(); n += Categories.update({ name: cat.name, type: type, rank: {$ne: count} }, { $set: { rank: count } }); //console.log(n, cat, count) }); console.log('Cats: updateAllCatsCounts', type, n); }, cleanCatsByPlace: function(placeId, cats) { if(!K.Admin.isMe()) return false; Places.update(placeId, { $set: {'cats': [] } }); console.log('Cats: cleanCatsByPlace', placeId); }, cleanAllCatsByType: function(type) { if(!K.Admin.isMe()) return false; type = type || 'place'; if(type==='place') Places.update({}, { $set: {'cats': [] } },{multi:true}); else if(type==='user') Users.update({}, { $set: {'cats': [] } },{multi:true}); else return false; Categories.update({type: type}, { $set: {rank: 0 } }, {multi:true}); console.log('Cats: cleanAllCatsPlaces'); }, cleanCatsByUser: function(userId, cats) { if(!K.Admin.isMe()) return false; Users.update(userId, { $set: {'cats': [] } }); console.log('Cats: cleanCatsByUser', userId); } });
{ "pile_set_name": "Github" }
@import '../../../variables/colors'; @import '../../../variables/sizes'; // Selected dataset styles $w: 820px; $br: 4px; .DatasetSelected { width: $w; margin: 0 0 0 -20px; border: 1px solid #BBD7F2; border-radius: $br; background: #FFF; } .DatasetSelected-item { display: flex; align-items: center; justify-content: flex-start; padding: 20px; } .DatasetSelected-itemExt { width: 38px; min-width: 38px; height: 38px; border: 1px solid #199BDB; border-radius: 4px; color: #419CDB; font-size: $sFontSize-smallUpperCase; line-height: 38px; text-align: center; text-transform: uppercase; } .DatasetSelected-itemInfo { margin-left: 20px; } .DatasetSelected-itemTitle { display: block; color: $cTypography-headers; font-size: $sFontSize-larger; font-weight: $sFontWeight-normal; } .DatasetSelected-itemDescription { display: block; margin-top: 3px; color: $cTypography-secondary; font-size: $sFontSize-normal; } .DatasetSelected-sync { display: block; overflow: hidden; border-bottom-right-radius: $br; border-bottom-left-radius: $br; background: #FFF; } .DatasetSelected-syncOptions { display: flex; align-items: center; margin: 0 20px; padding-top: 20px; padding-bottom: 20px; border-top: 1px solid $cStructure-mainLine; } .DatasetSelected-syncLabel { width: 100px; border-right: 1px solid $cStructure-softLine; } .DatasetSelected-syncOptionsList { display: flex; align-items: center; } .DatasetSelected-syncOptionsList--syncView { margin-left: auto; } .DatasetSelected-syncOptionsItem { margin-left: 24px; } .UpgradeElement.DatasetSelected-upgrade { padding: 20px; border-top: 1px solid #BBD7F2 !important; border-right: 0; border-bottom: 0; border-left: 0; border-radius: 0 0 4px 4px; } .DatasetSelected-upgradeButton { padding-right: 40px; padding-left: 40px; }
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: 5aec0cb62c5e2fe4d99b0138467b304e timeCreated: 1526319039 licenseType: Free MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
/*! * jQuery UI CSS Framework 1.12.1 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/category/theming/ * * To view and modify this theme, visit http://jqueryui.com/themeroller/?ffDefault=Gill%20Sans%2CArial%2Csans-serif&fwDefault=bold&fsDefault=1.2em&cornerRadius=4px&bgColorHeader=35414f&bgTextureHeader=dots_small&bgImgOpacityHeader=35&borderColorHeader=2c4359&fcHeader=e1e463&iconColorHeader=e1e463&bgColorContent=ffffff&bgTextureContent=flat&bgImgOpacityContent=75&borderColorContent=aaaaaa&fcContent=2c4359&iconColorContent=c02669&bgColorDefault=93c3cd&bgTextureDefault=diagonals_small&bgImgOpacityDefault=50&borderColorDefault=93c3cd&fcDefault=333333&iconColorDefault=ffffff&bgColorHover=ccd232&bgTextureHover=diagonals_small&bgImgOpacityHover=75&borderColorHover=999999&fcHover=212121&iconColorHover=454545&bgColorActive=db4865&bgTextureActive=diagonals_small&bgImgOpacityActive=40&borderColorActive=ff6b7f&fcActive=ffffff&iconColorActive=ffffff&bgColorHighlight=ffff38&bgTextureHighlight=dots_medium&bgImgOpacityHighlight=80&borderColorHighlight=b4d100&fcHighlight=363636&iconColorHighlight=88a206&bgColorError=ff3853&bgTextureError=diagonals_small&bgImgOpacityError=50&borderColorError=ff6b7f&fcError=ffffff&iconColorError=ffeb33&bgColorOverlay=f7f7ba&bgTextureOverlay=white_lines&bgImgOpacityOverlay=85&opacityOverlay=80&bgColorShadow=ba9217&bgTextureShadow=flat&bgImgOpacityShadow=75&opacityShadow=20&thicknessShadow=10px&offsetTopShadow=8px&offsetLeftShadow=8px&cornerRadiusShadow=5px */ /* Component containers ----------------------------------*/ .ui-widget { font-family: Gill Sans,Arial,sans-serif; font-size: 1.2em; } .ui-widget .ui-widget { font-size: 1em; } .ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button { font-family: Gill Sans,Arial,sans-serif; font-size: 1em; } .ui-widget.ui-widget-content { border: 1px solid #93c3cd; } .ui-widget-content { border: 1px solid #aaaaaa; background: #ffffff; color: #2c4359; } .ui-widget-content a { color: #2c4359; } .ui-widget-header { border: 1px solid #2c4359; background: #35414f url("images/ui-bg_dots-small_35_35414f_2x2.png") 50% 50% repeat; color: #e1e463; font-weight: bold; } .ui-widget-header a { color: #e1e463; } /* Interaction states ----------------------------------*/ .ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default, .ui-button, /* We use html here because we need a greater specificity to make sure disabled works properly when clicked or hovered */ html .ui-button.ui-state-disabled:hover, html .ui-button.ui-state-disabled:active { border: 1px solid #93c3cd; background: #93c3cd url("images/ui-bg_diagonals-small_50_93c3cd_40x40.png") 50% 50% repeat; font-weight: bold; color: #333333; } .ui-state-default a, .ui-state-default a:link, .ui-state-default a:visited, a.ui-button, a:link.ui-button, a:visited.ui-button, .ui-button { color: #333333; text-decoration: none; } .ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus, .ui-button:hover, .ui-button:focus { border: 1px solid #999999; background: #ccd232 url("images/ui-bg_diagonals-small_75_ccd232_40x40.png") 50% 50% repeat; font-weight: bold; color: #212121; } .ui-state-hover a, .ui-state-hover a:hover, .ui-state-hover a:link, .ui-state-hover a:visited, .ui-state-focus a, .ui-state-focus a:hover, .ui-state-focus a:link, .ui-state-focus a:visited, a.ui-button:hover, a.ui-button:focus { color: #212121; text-decoration: none; } .ui-visual-focus { box-shadow: 0 0 3px 1px rgb(94, 158, 214); } .ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active, a.ui-button:active, .ui-button:active, .ui-button.ui-state-active:hover { border: 1px solid #ff6b7f; background: #db4865 url("images/ui-bg_diagonals-small_40_db4865_40x40.png") 50% 50% repeat; font-weight: bold; color: #ffffff; } .ui-icon-background, .ui-state-active .ui-icon-background { border: #ff6b7f; background-color: #ffffff; } .ui-state-active a, .ui-state-active a:link, .ui-state-active a:visited { color: #ffffff; text-decoration: none; } /* Interaction Cues ----------------------------------*/ .ui-state-highlight, .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight { border: 1px solid #b4d100; background: #ffff38 url("images/ui-bg_dots-medium_80_ffff38_4x4.png") 50% 50% repeat; color: #363636; } .ui-state-checked { border: 1px solid #b4d100; background: #ffff38; } .ui-state-highlight a, .ui-widget-content .ui-state-highlight a, .ui-widget-header .ui-state-highlight a { color: #363636; } .ui-state-error, .ui-widget-content .ui-state-error, .ui-widget-header .ui-state-error { border: 1px solid #ff6b7f; background: #ff3853 url("images/ui-bg_diagonals-small_50_ff3853_40x40.png") 50% 50% repeat; color: #ffffff; } .ui-state-error a, .ui-widget-content .ui-state-error a, .ui-widget-header .ui-state-error a { color: #ffffff; } .ui-state-error-text, .ui-widget-content .ui-state-error-text, .ui-widget-header .ui-state-error-text { color: #ffffff; } .ui-priority-primary, .ui-widget-content .ui-priority-primary, .ui-widget-header .ui-priority-primary { font-weight: bold; } .ui-priority-secondary, .ui-widget-content .ui-priority-secondary, .ui-widget-header .ui-priority-secondary { opacity: .7; filter:Alpha(Opacity=70); /* support: IE8 */ font-weight: normal; } .ui-state-disabled, .ui-widget-content .ui-state-disabled, .ui-widget-header .ui-state-disabled { opacity: .35; filter:Alpha(Opacity=35); /* support: IE8 */ background-image: none; } .ui-state-disabled .ui-icon { filter:Alpha(Opacity=35); /* support: IE8 - See #6059 */ } /* Icons ----------------------------------*/ /* states and images */ .ui-icon { width: 16px; height: 16px; } .ui-icon, .ui-widget-content .ui-icon { background-image: url("images/ui-icons_c02669_256x240.png"); } .ui-widget-header .ui-icon { background-image: url("images/ui-icons_e1e463_256x240.png"); } .ui-state-hover .ui-icon, .ui-state-focus .ui-icon, .ui-button:hover .ui-icon, .ui-button:focus .ui-icon { background-image: url("images/ui-icons_454545_256x240.png"); } .ui-state-active .ui-icon, .ui-button:active .ui-icon { background-image: url("images/ui-icons_ffffff_256x240.png"); } .ui-state-highlight .ui-icon, .ui-button .ui-state-highlight.ui-icon { background-image: url("images/ui-icons_88a206_256x240.png"); } .ui-state-error .ui-icon, .ui-state-error-text .ui-icon { background-image: url("images/ui-icons_ffeb33_256x240.png"); } .ui-button .ui-icon { background-image: url("images/ui-icons_ffffff_256x240.png"); } /* positioning */ .ui-icon-blank { background-position: 16px 16px; } .ui-icon-caret-1-n { background-position: 0 0; } .ui-icon-caret-1-ne { background-position: -16px 0; } .ui-icon-caret-1-e { background-position: -32px 0; } .ui-icon-caret-1-se { background-position: -48px 0; } .ui-icon-caret-1-s { background-position: -65px 0; } .ui-icon-caret-1-sw { background-position: -80px 0; } .ui-icon-caret-1-w { background-position: -96px 0; } .ui-icon-caret-1-nw { background-position: -112px 0; } .ui-icon-caret-2-n-s { background-position: -128px 0; } .ui-icon-caret-2-e-w { background-position: -144px 0; } .ui-icon-triangle-1-n { background-position: 0 -16px; } .ui-icon-triangle-1-ne { background-position: -16px -16px; } .ui-icon-triangle-1-e { background-position: -32px -16px; } .ui-icon-triangle-1-se { background-position: -48px -16px; } .ui-icon-triangle-1-s { background-position: -65px -16px; } .ui-icon-triangle-1-sw { background-position: -80px -16px; } .ui-icon-triangle-1-w { background-position: -96px -16px; } .ui-icon-triangle-1-nw { background-position: -112px -16px; } .ui-icon-triangle-2-n-s { background-position: -128px -16px; } .ui-icon-triangle-2-e-w { background-position: -144px -16px; } .ui-icon-arrow-1-n { background-position: 0 -32px; } .ui-icon-arrow-1-ne { background-position: -16px -32px; } .ui-icon-arrow-1-e { background-position: -32px -32px; } .ui-icon-arrow-1-se { background-position: -48px -32px; } .ui-icon-arrow-1-s { background-position: -65px -32px; } .ui-icon-arrow-1-sw { background-position: -80px -32px; } .ui-icon-arrow-1-w { background-position: -96px -32px; } .ui-icon-arrow-1-nw { background-position: -112px -32px; } .ui-icon-arrow-2-n-s { background-position: -128px -32px; } .ui-icon-arrow-2-ne-sw { background-position: -144px -32px; } .ui-icon-arrow-2-e-w { background-position: -160px -32px; } .ui-icon-arrow-2-se-nw { background-position: -176px -32px; } .ui-icon-arrowstop-1-n { background-position: -192px -32px; } .ui-icon-arrowstop-1-e { background-position: -208px -32px; } .ui-icon-arrowstop-1-s { background-position: -224px -32px; } .ui-icon-arrowstop-1-w { background-position: -240px -32px; } .ui-icon-arrowthick-1-n { background-position: 1px -48px; } .ui-icon-arrowthick-1-ne { background-position: -16px -48px; } .ui-icon-arrowthick-1-e { background-position: -32px -48px; } .ui-icon-arrowthick-1-se { background-position: -48px -48px; } .ui-icon-arrowthick-1-s { background-position: -64px -48px; } .ui-icon-arrowthick-1-sw { background-position: -80px -48px; } .ui-icon-arrowthick-1-w { background-position: -96px -48px; } .ui-icon-arrowthick-1-nw { background-position: -112px -48px; } .ui-icon-arrowthick-2-n-s { background-position: -128px -48px; } .ui-icon-arrowthick-2-ne-sw { background-position: -144px -48px; } .ui-icon-arrowthick-2-e-w { background-position: -160px -48px; } .ui-icon-arrowthick-2-se-nw { background-position: -176px -48px; } .ui-icon-arrowthickstop-1-n { background-position: -192px -48px; } .ui-icon-arrowthickstop-1-e { background-position: -208px -48px; } .ui-icon-arrowthickstop-1-s { background-position: -224px -48px; } .ui-icon-arrowthickstop-1-w { background-position: -240px -48px; } .ui-icon-arrowreturnthick-1-w { background-position: 0 -64px; } .ui-icon-arrowreturnthick-1-n { background-position: -16px -64px; } .ui-icon-arrowreturnthick-1-e { background-position: -32px -64px; } .ui-icon-arrowreturnthick-1-s { background-position: -48px -64px; } .ui-icon-arrowreturn-1-w { background-position: -64px -64px; } .ui-icon-arrowreturn-1-n { background-position: -80px -64px; } .ui-icon-arrowreturn-1-e { background-position: -96px -64px; } .ui-icon-arrowreturn-1-s { background-position: -112px -64px; } .ui-icon-arrowrefresh-1-w { background-position: -128px -64px; } .ui-icon-arrowrefresh-1-n { background-position: -144px -64px; } .ui-icon-arrowrefresh-1-e { background-position: -160px -64px; } .ui-icon-arrowrefresh-1-s { background-position: -176px -64px; } .ui-icon-arrow-4 { background-position: 0 -80px; } .ui-icon-arrow-4-diag { background-position: -16px -80px; } .ui-icon-extlink { background-position: -32px -80px; } .ui-icon-newwin { background-position: -48px -80px; } .ui-icon-refresh { background-position: -64px -80px; } .ui-icon-shuffle { background-position: -80px -80px; } .ui-icon-transfer-e-w { background-position: -96px -80px; } .ui-icon-transferthick-e-w { background-position: -112px -80px; } .ui-icon-folder-collapsed { background-position: 0 -96px; } .ui-icon-folder-open { background-position: -16px -96px; } .ui-icon-document { background-position: -32px -96px; } .ui-icon-document-b { background-position: -48px -96px; } .ui-icon-note { background-position: -64px -96px; } .ui-icon-mail-closed { background-position: -80px -96px; } .ui-icon-mail-open { background-position: -96px -96px; } .ui-icon-suitcase { background-position: -112px -96px; } .ui-icon-comment { background-position: -128px -96px; } .ui-icon-person { background-position: -144px -96px; } .ui-icon-print { background-position: -160px -96px; } .ui-icon-trash { background-position: -176px -96px; } .ui-icon-locked { background-position: -192px -96px; } .ui-icon-unlocked { background-position: -208px -96px; } .ui-icon-bookmark { background-position: -224px -96px; } .ui-icon-tag { background-position: -240px -96px; } .ui-icon-home { background-position: 0 -112px; } .ui-icon-flag { background-position: -16px -112px; } .ui-icon-calendar { background-position: -32px -112px; } .ui-icon-cart { background-position: -48px -112px; } .ui-icon-pencil { background-position: -64px -112px; } .ui-icon-clock { background-position: -80px -112px; } .ui-icon-disk { background-position: -96px -112px; } .ui-icon-calculator { background-position: -112px -112px; } .ui-icon-zoomin { background-position: -128px -112px; } .ui-icon-zoomout { background-position: -144px -112px; } .ui-icon-search { background-position: -160px -112px; } .ui-icon-wrench { background-position: -176px -112px; } .ui-icon-gear { background-position: -192px -112px; } .ui-icon-heart { background-position: -208px -112px; } .ui-icon-star { background-position: -224px -112px; } .ui-icon-link { background-position: -240px -112px; } .ui-icon-cancel { background-position: 0 -128px; } .ui-icon-plus { background-position: -16px -128px; } .ui-icon-plusthick { background-position: -32px -128px; } .ui-icon-minus { background-position: -48px -128px; } .ui-icon-minusthick { background-position: -64px -128px; } .ui-icon-close { background-position: -80px -128px; } .ui-icon-closethick { background-position: -96px -128px; } .ui-icon-key { background-position: -112px -128px; } .ui-icon-lightbulb { background-position: -128px -128px; } .ui-icon-scissors { background-position: -144px -128px; } .ui-icon-clipboard { background-position: -160px -128px; } .ui-icon-copy { background-position: -176px -128px; } .ui-icon-contact { background-position: -192px -128px; } .ui-icon-image { background-position: -208px -128px; } .ui-icon-video { background-position: -224px -128px; } .ui-icon-script { background-position: -240px -128px; } .ui-icon-alert { background-position: 0 -144px; } .ui-icon-info { background-position: -16px -144px; } .ui-icon-notice { background-position: -32px -144px; } .ui-icon-help { background-position: -48px -144px; } .ui-icon-check { background-position: -64px -144px; } .ui-icon-bullet { background-position: -80px -144px; } .ui-icon-radio-on { background-position: -96px -144px; } .ui-icon-radio-off { background-position: -112px -144px; } .ui-icon-pin-w { background-position: -128px -144px; } .ui-icon-pin-s { background-position: -144px -144px; } .ui-icon-play { background-position: 0 -160px; } .ui-icon-pause { background-position: -16px -160px; } .ui-icon-seek-next { background-position: -32px -160px; } .ui-icon-seek-prev { background-position: -48px -160px; } .ui-icon-seek-end { background-position: -64px -160px; } .ui-icon-seek-start { background-position: -80px -160px; } /* ui-icon-seek-first is deprecated, use ui-icon-seek-start instead */ .ui-icon-seek-first { background-position: -80px -160px; } .ui-icon-stop { background-position: -96px -160px; } .ui-icon-eject { background-position: -112px -160px; } .ui-icon-volume-off { background-position: -128px -160px; } .ui-icon-volume-on { background-position: -144px -160px; } .ui-icon-power { background-position: 0 -176px; } .ui-icon-signal-diag { background-position: -16px -176px; } .ui-icon-signal { background-position: -32px -176px; } .ui-icon-battery-0 { background-position: -48px -176px; } .ui-icon-battery-1 { background-position: -64px -176px; } .ui-icon-battery-2 { background-position: -80px -176px; } .ui-icon-battery-3 { background-position: -96px -176px; } .ui-icon-circle-plus { background-position: 0 -192px; } .ui-icon-circle-minus { background-position: -16px -192px; } .ui-icon-circle-close { background-position: -32px -192px; } .ui-icon-circle-triangle-e { background-position: -48px -192px; } .ui-icon-circle-triangle-s { background-position: -64px -192px; } .ui-icon-circle-triangle-w { background-position: -80px -192px; } .ui-icon-circle-triangle-n { background-position: -96px -192px; } .ui-icon-circle-arrow-e { background-position: -112px -192px; } .ui-icon-circle-arrow-s { background-position: -128px -192px; } .ui-icon-circle-arrow-w { background-position: -144px -192px; } .ui-icon-circle-arrow-n { background-position: -160px -192px; } .ui-icon-circle-zoomin { background-position: -176px -192px; } .ui-icon-circle-zoomout { background-position: -192px -192px; } .ui-icon-circle-check { background-position: -208px -192px; } .ui-icon-circlesmall-plus { background-position: 0 -208px; } .ui-icon-circlesmall-minus { background-position: -16px -208px; } .ui-icon-circlesmall-close { background-position: -32px -208px; } .ui-icon-squaresmall-plus { background-position: -48px -208px; } .ui-icon-squaresmall-minus { background-position: -64px -208px; } .ui-icon-squaresmall-close { background-position: -80px -208px; } .ui-icon-grip-dotted-vertical { background-position: 0 -224px; } .ui-icon-grip-dotted-horizontal { background-position: -16px -224px; } .ui-icon-grip-solid-vertical { background-position: -32px -224px; } .ui-icon-grip-solid-horizontal { background-position: -48px -224px; } .ui-icon-gripsmall-diagonal-se { background-position: -64px -224px; } .ui-icon-grip-diagonal-se { background-position: -80px -224px; } /* Misc visuals ----------------------------------*/ /* Corner radius */ .ui-corner-all, .ui-corner-top, .ui-corner-left, .ui-corner-tl { border-top-left-radius: 4px; } .ui-corner-all, .ui-corner-top, .ui-corner-right, .ui-corner-tr { border-top-right-radius: 4px; } .ui-corner-all, .ui-corner-bottom, .ui-corner-left, .ui-corner-bl { border-bottom-left-radius: 4px; } .ui-corner-all, .ui-corner-bottom, .ui-corner-right, .ui-corner-br { border-bottom-right-radius: 4px; } /* Overlays */ .ui-widget-overlay { background: #f7f7ba url("images/ui-bg_white-lines_85_f7f7ba_40x100.png") 50% 50% repeat; opacity: .8; filter: Alpha(Opacity=80); /* support: IE8 */ } .ui-widget-shadow { -webkit-box-shadow: 8px 8px 10px #ba9217; box-shadow: 8px 8px 10px #ba9217; }
{ "pile_set_name": "Github" }
/************************************************************* * * MathJax/jax/output/HTML-CSS/fonts/STIX/General/Regular/Dingbats.js * * Copyright (c) 2009-2010 Design Science, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ MathJax.Hub.Insert( MathJax.OutputJax['HTML-CSS'].FONTDATA.FONTS['STIXGeneral'], { 0x2702: [612,-82,961,35,905], // BLACK SCISSORS 0x2709: [555,-138,690,34,638], // ENVELOPE 0x2713: [707,12,755,34,704], // CHECK MARK 0x2720: [592,87,767,53,714], // MALTESE CROSS 0x272A: [613,106,789,35,733], // CIRCLED WHITE STAR 0x2736: [616,108,695,35,642], // SIX POINTED BLACK STAR 0x273D: [612,108,682,35,626], // HEAVY TEARDROP-SPOKED ASTERISK 0x2772: [719,213,488,188,466], // LIGHT LEFT TORTOISE SHELL BRACKET ORNAMENT 0x2773: [719,213,488,22,300], // LIGHT RIGHT TORTOISE SHELL BRACKET ORNAMENT 0x2780: [705,14,788,35,733], // DINGBAT CIRCLED SANS-SERIF DIGIT ONE 0x2781: [705,14,788,35,733], // DINGBAT CIRCLED SANS-SERIF DIGIT TWO 0x2782: [705,14,788,35,733], // DINGBAT CIRCLED SANS-SERIF DIGIT THREE 0x2783: [705,14,788,35,733], // DINGBAT CIRCLED SANS-SERIF DIGIT FOUR 0x2784: [705,14,788,35,733], // DINGBAT CIRCLED SANS-SERIF DIGIT FIVE 0x2785: [705,14,788,35,733], // DINGBAT CIRCLED SANS-SERIF DIGIT SIX 0x2786: [705,14,788,35,733], // DINGBAT CIRCLED SANS-SERIF DIGIT SEVEN 0x2787: [705,14,788,35,733], // DINGBAT CIRCLED SANS-SERIF DIGIT EIGHT 0x2788: [705,14,788,35,733], // DINGBAT CIRCLED SANS-SERIF DIGIT NINE 0x2789: [705,14,788,35,733], // DINGBAT CIRCLED SANS-SERIF NUMBER TEN 0x278A: [705,14,788,35,733], // DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT ONE 0x278B: [705,14,788,35,733], // DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT TWO 0x278C: [705,14,788,35,733], // DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT THREE 0x278D: [705,14,788,35,733], // DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT FOUR 0x278E: [705,14,788,35,733], // DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT FIVE 0x278F: [705,14,788,35,733], // DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT SIX 0x2790: [705,14,788,35,733], // DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT SEVEN 0x2791: [705,14,788,35,733], // DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT EIGHT 0x2792: [705,14,788,35,733], // DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT NINE 0x2793: [705,14,788,35,733], // DINGBAT NEGATIVE CIRCLED SANS-SERIF NUMBER TEN 0x279B: [433,-70,918,35,861] // DRAFTING POINT RIGHTWARDS ARROW } ); MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir + "/General/Regular/Dingbats.js");
{ "pile_set_name": "Github" }
.timeline { position: relative; padding: 20px 0 20px; list-style: none; } .timeline:before { content: " "; position: absolute; top: 0; bottom: 0; left: 50%; width: 3px; margin-left: -1.5px; background-color: #eeeeee; } .timeline > li { position: relative; margin-bottom: 20px; } .timeline > li:before, .timeline > li:after { content: " "; display: table; } .timeline > li:after { clear: both; } .timeline > li:before, .timeline > li:after { content: " "; display: table; } .timeline > li:after { clear: both; } .timeline > li > .timeline-panel { float: left; position: relative; width: 46%; padding: 20px; border: 1px solid #d4d4d4; border-radius: 2px; -webkit-box-shadow: 0 1px 6px rgba(0,0,0,0.175); box-shadow: 0 1px 6px rgba(0,0,0,0.175); } .timeline > li > .timeline-panel:before { content: " "; display: inline-block; position: absolute; top: 26px; right: -15px; border-top: 15px solid transparent; border-right: 0 solid #ccc; border-bottom: 15px solid transparent; border-left: 15px solid #ccc; } .timeline > li > .timeline-panel:after { content: " "; display: inline-block; position: absolute; top: 27px; right: -14px; border-top: 14px solid transparent; border-right: 0 solid #fff; border-bottom: 14px solid transparent; border-left: 14px solid #fff; } .timeline > li > .timeline-badge { z-index: 100; position: absolute; top: 16px; left: 50%; width: 50px; height: 50px; margin-left: -25px; border-radius: 50% 50% 50% 50%; text-align: center; font-size: 1.4em; line-height: 50px; color: #fff; background-color: #999999; } .timeline > li.timeline-inverted > .timeline-panel { float: right; } .timeline > li.timeline-inverted > .timeline-panel:before { right: auto; left: -15px; border-right-width: 15px; border-left-width: 0; } .timeline > li.timeline-inverted > .timeline-panel:after { right: auto; left: -14px; border-right-width: 14px; border-left-width: 0; } .timeline-badge.primary { background-color: #2e6da4 !important; } .timeline-badge.success { background-color: #3f903f !important; } .timeline-badge.warning { background-color: #f0ad4e !important; } .timeline-badge.danger { background-color: #d9534f !important; } .timeline-badge.info { background-color: #5bc0de !important; } .timeline-title { margin-top: 0; color: inherit; } .timeline-body > p, .timeline-body > ul { margin-bottom: 0; } .timeline-body > p + p { margin-top: 5px; } @media(max-width:767px) { ul.timeline:before { left: 40px; } ul.timeline > li > .timeline-panel { width: calc(100% - 90px); width: -moz-calc(100% - 90px); width: -webkit-calc(100% - 90px); } ul.timeline > li > .timeline-badge { top: 16px; left: 15px; margin-left: 0; } ul.timeline > li > .timeline-panel { float: right; } ul.timeline > li > .timeline-panel:before { right: auto; left: -15px; border-right-width: 15px; border-left-width: 0; } ul.timeline > li > .timeline-panel:after { right: auto; left: -14px; border-right-width: 14px; border-left-width: 0; } }
{ "pile_set_name": "Github" }
//------------------------------------------------------------------------------ // This code was generated by a tool. // // Tool : Bond Compiler 0.10.1.0 // File : MessageData_types.cs // // Changes to this file may cause incorrect behavior and will be lost when // the code is regenerated. // <auto-generated /> //------------------------------------------------------------------------------ // suppress "Missing XML comment for publicly visible type or member" #pragma warning disable 1591 #region ReSharper warnings // ReSharper disable PartialTypeWithSinglePart // ReSharper disable RedundantNameQualifier // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace // ReSharper disable UnusedParameter.Local // ReSharper disable RedundantUsingDirective #endregion namespace AI { using System.Collections.Generic; [global::Bond.Attribute("Description", "Instances of Message represent printf-like trace statements that are text-searched. Log4Net, NLog and other text-based log file entries are translated into intances of this type. The message does not have measurements.")] [global::Bond.Schema] [System.CodeDom.Compiler.GeneratedCode("gbc", "0.10.1.0")] public partial class MessageData : Domain { [global::Bond.Attribute("Description", "Schema version")] [global::Bond.Id(10), global::Bond.Required] public int ver { get; set; } [global::Bond.Attribute("MaxStringLength", "32768")] [global::Bond.Attribute("Description", "Trace message")] [global::Bond.Id(20), global::Bond.Required] public string message { get; set; } [global::Bond.Attribute("Description", "Trace severity level.")] [global::Bond.Id(30), global::Bond.Type(typeof(global::Bond.Tag.nullable<SeverityLevel>))] public SeverityLevel? severityLevel { get; set; } [global::Bond.Attribute("Description", "Collection of custom properties.")] [global::Bond.Attribute("MaxKeyLength", "150")] [global::Bond.Attribute("MaxValueLength", "8192")] [global::Bond.Id(100), global::Bond.Type(typeof(Dictionary<string, string>))] public IDictionary<string, string> properties { get; set; } [global::Bond.Attribute("Description", "Collection of custom measurements.")] [global::Bond.Attribute("MaxKeyLength", "150")] [global::Bond.Id(200), global::Bond.Type(typeof(Dictionary<string, double>))] public IDictionary<string, double> measurements { get; set; } public MessageData() : this("AI.MessageData", "MessageData") {} protected MessageData(string fullName, string name) { ver = 2; message = ""; properties = new Dictionary<string, string>(); measurements = new Dictionary<string, double>(); } } } // AI
{ "pile_set_name": "Github" }
local my _ = BuildRawSyntaxTree::compilerMode() # make sure we are in compiler mode fun trans ( { raw_syntax_tree= { raw_syntax_tree, tidtab, ... }, aidtab, implicits, ... }: BuildRawSyntaxTree::programInfo) = let my { raw_syntax_tree, ... } = SimplifyRawSyntaxTree::simplifyRawSyntaxTree (raw_syntax_tree, tidtab, aidtab, implicits) in raw_syntax_tree end in package SimplifyTest = TestFn (testDir = "../../valid-programs" outDir = "results" trans = trans) end
{ "pile_set_name": "Github" }
"DOTAAbilities" { "item_tranquil_boots" "REMOVED" //================================================================================================================= // Recipe: Tranquil Origin //================================================================================================================= "item_recipe_tranquil_origin" { // General //------------------------------------------------------------------------------------------------------------- "ID" "8640" // unique ID number for this item. Do not change this once established or it will invalidate collected stats. "BaseClass" "item_datadriven" "Model" "models/props_gameplay/recipe.mdl" "AbilityTextureName" "item_recipe" // Item Info //------------------------------------------------------------------------------------------------------------- "ItemCost" "25" "ItemShopTags" "" // Recipe //------------------------------------------------------------------------------------------------------------- "ItemRecipe" "1" "ItemResult" "item_tranquil_origin" "ItemRequirements" { "01" "item_farming_core" } } //================================================================================================================= // Tranquil Origin //================================================================================================================= "item_tranquil_origin" { // General //------------------------------------------------------------------------------------------------------------- "ID" "8641" // unique ID number for this item. Do not change this once established or it will invalidate collected stats. "BaseClass" "item_lua" "ScriptFile" "items/farming/greater_tranquil_boots.lua" "AbilityBehavior" "DOTA_ABILITY_BEHAVIOR_PASSIVE" "AbilityTextureName" "custom/tranquil_origin" // Stats //------------------------------------------------------------------------------------------------------------- "AbilityCooldown" "0.0" "AbilityManaCost" "0" // Item Info //------------------------------------------------------------------------------------------------------------- "ItemCost" "125" "ItemShopTags" "move_speed;regen_health" "ItemQuality" "rare" "ItemAliases" "tranquil spark;tranquil;tranquils;spark" "ItemDeclarations" "DECLARE_PURCHASES_TO_SPECTATORS" "ItemDisplayCharges" "1" // Special //------------------------------------------------------------------------------------------------------------- "AbilitySpecial" { "01" { "var_type" "FIELD_INTEGER" "bonus_movement_speed" "7" } "02" { "var_type" "FIELD_INTEGER" "bonus_armor" "0" } "03" { "var_type" "FIELD_INTEGER" "bonus_health_regen" "5" } "04" { "var_type" "FIELD_FLOAT" "heal_duration" "20.0" } "05" { "var_type" "FIELD_INTEGER" "heal_amount" "250" } "06" { "var_type" "FIELD_FLOAT" "heal_interval" "0.334" } "07" { "var_type" "FIELD_INTEGER" "break_time" "13" } "08" { "var_type" "FIELD_INTEGER" "break_count" "1" } "09" { "var_type" "FIELD_INTEGER" "break_threshold" "20" } "10" { "var_type" "FIELD_INTEGER" "broken_movement_speed" "0" } "11" { "var_type" "FIELD_FLOAT" "distance_per_charge" "80.0" } "12" { "var_type" "FIELD_FLOAT" "check_interval" "0.1" // rupture is 0.25, mana leak is 0.1 } "13" { "var_type" "FIELD_FLOAT" "max_dist" "300" // rupture is 1300, mana leak is 300 } "14" { "var_type" "FIELD_INTEGER" "bonus_gold" "250" } "15" { "var_type" "FIELD_INTEGER" "bonus_xp" "0" } "16" { "var_type" "FIELD_INTEGER" "max_charges" "400" } } // Precache //------------------------------------------------------------------------------------------------------------- "precache" { "particle" "particles/units/heroes/hero_treant/treant_leech_seed_damage_glow.vpcf" "soundfile" "soundevents/game_sounds_heroes/game_sounds_treant.vsndevts" } } }
{ "pile_set_name": "Github" }
// Copyright (c) 2006 - 2008, Clark & Parsia, LLC. <http://www.clarkparsia.com> // This source code is available under the terms of the Affero General Public // License v3. // // Please see LICENSE.txt for full license terms, including the availability of // proprietary exceptions. // Questions, comments, or requests for clarification: [email protected] package pellet; import static pellet.PelletCmdOptionArg.NONE; import static pellet.PelletCmdOptionArg.REQUIRED; import java.io.FileNotFoundException; import java.io.IOException; import java.io.StringWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.StringTokenizer; import java.util.logging.Logger; import org.mindswap.pellet.KBLoader; import org.mindswap.pellet.KRSSLoader; import org.mindswap.pellet.KnowledgeBase; import org.mindswap.pellet.PelletOptions; import org.mindswap.pellet.jena.JenaLoader; import org.mindswap.pellet.utils.Timer; import org.mindswap.pellet.utils.Timers; import com.clarkparsia.pellet.owlapiv3.OWLAPILoader; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.RDFReaderF; import com.hp.hpl.jena.shared.NoReaderForLangException; /** * <p> * Title: PelletCmdLine * </p> * <p> * Description: Provides some functionality for Pellet command line applications * </p> * <p> * Copyright: Copyright (c) 2008 * </p> * <p> * Company: Clark & Parsia, LLC. <http://www.clarkparsia.com> * </p> * * @author Markus Stocker * @author Evren Sirin */ public abstract class PelletCmdApp { public static final Logger logger = Logger.getLogger( PelletCmdApp.class.getName() ); private final static String LINE_BREAK = System.getProperty("line.separator"); private final static RDFReaderF READER_FACTORY = ModelFactory.createDefaultModel(); protected String appId; protected String appCmd; protected String help; protected PelletCmdOptions options; private List<String> inputFiles; protected KBLoader loader; protected boolean verbose; protected Timers timers; protected List<String> tasks; public PelletCmdApp() { this.options = getOptions(); this.appId = getAppId(); this.appCmd = getAppCmd(); this.inputFiles = new ArrayList<String>(); this.timers = new Timers(); buildHelp(); } public boolean requiresInputFiles() { return true; } protected void verbose( String msg ) { if (verbose) System.err.println( msg ); } protected void output( String msg ) { System.out.println( msg ); } protected void output( Model model ) { model.write( System.out ); } public abstract String getAppId(); public abstract String getAppCmd(); public abstract PelletCmdOptions getOptions(); public abstract void run(); public void finish() { if( verbose ) { StringWriter sw = new StringWriter(); timers.print( sw, true, null ); verbose( "" ); verbose( "Timer summary:" ); verbose( sw.toString() ); } } protected String getMandatoryOptions() { StringBuffer ret = new StringBuffer(); Set<PelletCmdOption> mandatory = options.getMandatoryOptions(); for( Iterator<PelletCmdOption> i = mandatory.iterator(); i.hasNext(); ) { PelletCmdOption option = i.next(); ret.append( "-" + option.getShortOption() + " arg " ); } return ret.toString(); } public PelletCmdOption getIgnoreImportsOption() { PelletCmdOption option = new PelletCmdOption("ignore-imports"); //option.setShortOption("I"); option.setDescription("Ignore imported ontologies"); option.setDefaultValue(false); option.setIsMandatory( false ); option.setArg( NONE ); return option; } public PelletCmdOption getLoaderOption() { PelletCmdOption option = new PelletCmdOption( "loader" ); option.setShortOption( "l" ); option.setDescription( "Use Jena, OWLAPI, OWLAPIv3 or KRSS to load the ontology" ); option.setType( "Jena | OWLAPI | OWLAPIv3 | KRSS" ); option.setDefaultValue( "OWLAPIv3" ); option.setIsMandatory( false ); option.setArg( REQUIRED ); return option; } public PelletCmdOptions getGlobalOptions() { PelletCmdOptions options = new PelletCmdOptions(); PelletCmdOption helpOption = new PelletCmdOption( "help" ); helpOption.setShortOption( "h" ); helpOption.setDescription( "Print this message" ); helpOption.setDefaultValue( false ); helpOption.setIsMandatory( false ); helpOption.setArg( NONE ); options.add( helpOption ); PelletCmdOption verboseOption = new PelletCmdOption( "verbose" ); verboseOption.setShortOption( "v" ); verboseOption.setDescription( "Print full stack trace for errors." ); verboseOption.setDefaultValue( false ); verboseOption.setIsMandatory( false ); verboseOption.setArg( NONE ); options.add( verboseOption ); PelletCmdOption configOption = new PelletCmdOption( "config" ); configOption.setShortOption( "C" ); configOption.setDescription( "Use the selected configuration file" ); configOption.setIsMandatory( false ); configOption.setType( "configuration file" ); configOption.setArg( REQUIRED ); options.add( configOption ); return options; } public PelletCmdOption getInputFormatOption() { PelletCmdOption option = new PelletCmdOption( "input-format" ); option.setDefaultValue( null ); option.setDescription( "Format of the input file (valid only for the " + "Jena loader). Default behaviour is to guess " + "the input format based on the file extension." ); option.setType( "RDF/XML | Turtle | N-Triples" ); option.setIsMandatory( false ); option.setArg( REQUIRED ); return option; } protected KnowledgeBase getKB() { return getKB( getLoader() ); } protected KnowledgeBase getKB(KBLoader loader) { try { String[] inputFiles = getInputFiles(); verbose( "There are " + inputFiles.length + " input files:" ); for( String inputFile : inputFiles ) verbose( inputFile ); startTask( "loading" ); KnowledgeBase kb = loader.createKB( inputFiles ); finishTask( "loading" ); if( verbose ) { StringBuilder sb = new StringBuilder(); sb.append( "Classes = " + kb.getAllClasses().size() + ", " ); sb.append( "Properties = " + kb.getProperties().size() + ", " ); sb.append( "Individuals = " + kb.getIndividuals().size() ); verbose( "Input size: " + sb ); verbose( "Expressivity: " + kb.getExpressivity() ); } return kb; } catch( RuntimeException e ) { throw new PelletCmdException( e ); } } protected KBLoader getLoader() { if( loader != null ) return loader; String loaderName = options.getOption( "loader" ).getValueAsString(); return getLoader( loaderName ); } protected KBLoader getLoader(String loaderName) { if( loaderName.equalsIgnoreCase( "Jena" ) ) loader = new JenaLoader(); else if( loaderName.equalsIgnoreCase( "OWLAPIv3" ) || loaderName.equalsIgnoreCase( "OWLAPI" ) ) loader = new OWLAPILoader(); else if( loaderName.equalsIgnoreCase( "KRSS" ) ) loader = new KRSSLoader(); else throw new PelletCmdException( "Unknown loader: " + loaderName ); loader.setIgnoreImports( options.getOption("ignore-imports").getValueAsBoolean() ); PelletCmdOption option = options.getOption( "input-format" ); if( option != null && option.getValueAsString() != null ) { if( loader instanceof JenaLoader ) { String inputFormat = option.getValueAsString().toUpperCase(); try { if( inputFormat != null ) { READER_FACTORY.getReader( inputFormat.toUpperCase() ); ((JenaLoader) loader).setInputFormat( inputFormat ); } } catch( NoReaderForLangException e ) { throw new PelletCmdException( "Unrecognized input format: " + inputFormat ); } } else { // silently ignore } } return loader; } protected String[] getInputFiles() { return inputFiles.toArray( new String[] {} ); } private void buildHelp() { StringBuffer u = new StringBuffer(); HelpTable table = new HelpTable( options ); u.append( appId + LINE_BREAK + LINE_BREAK ); u.append( "Usage: " + appCmd + LINE_BREAK + LINE_BREAK ); u.append( table.print() + LINE_BREAK ); help = u.toString(); } public void parseArgs(String[] args) { HashSet<String> seenOptions = new HashSet<String>(); // skip first arg which is the name of the subcommand int i = 1; for( ; i < args.length; i++ ) { String arg = args[i]; if( arg.equals( "--" ) ) return; if( arg.charAt( 0 ) == '-' ) { if( arg.charAt( 1 ) == '-' ) arg = arg.substring( 2 ); else arg = arg.substring( 1 ); } else // no more options to parse break; PelletCmdOption option = options.getOption( arg ); if( option == null ) throw new PelletCmdException( "Unrecognized option: " + arg ); else if( option.getLongOption().equals( "help" ) ) help(); else if ( option.getLongOption().equals( "verbose" ) ) Pellet.exceptionFormatter.setVerbose( true ); if (seenOptions.contains(option.getLongOption())) { throw new PelletCmdException( "Repeated use of option: " + arg ); } seenOptions.add( option.getLongOption() ); PelletCmdOptionArg optionArg = option.getArg(); boolean nextIsArg = (args.length > i + 1) && args[i + 1].charAt( 0 ) != '-'; switch ( optionArg ) { case NONE: option.setValue( true ); break; case REQUIRED: if( !nextIsArg ) throw new PelletCmdException( "Option <" + option.getLongOption() + "> requires an argument" ); else option.setValue( args[++i] ); break; case OPTIONAL: if( nextIsArg ) option.setValue( args[++i] ); else option.setExists( true ); break; default: throw new PelletCmdException( "Unrecognized option argument: " + optionArg ); } } // Check if all mandatory options are set for( PelletCmdOption option : options.getOptions() ) { if( option.isMandatory() ) { if( option.getValue() == null ) throw new PelletCmdException( "Option <" + option.getLongOption() + "> is mandatory" ); } } loadConfig(); // Input files are given as a list of file URIs at the end for( ; i < args.length; i++ ) { inputFiles.add( args[i] ); } if ( options.getOption( "verbose" ).getValueAsBoolean() ) { verbose = true; } if( requiresInputFiles() ) { if( inputFiles.isEmpty() ) throw new PelletCmdException( "No input file given" ); } else { if( !inputFiles.isEmpty() ) throw new PelletCmdException( "Unexpected argument(s): " + inputFiles ); } } private void loadConfig() { String configFile = options.getOption( "config" ).getValueAsString(); if( configFile != null ) { try { URL url = new URL( "file:" + configFile ); PelletOptions.load( url ); } catch( MalformedURLException e ) { throw new PelletCmdException( "Invalid URL given for the config file: " + configFile ); } catch( FileNotFoundException e ) { throw new PelletCmdException( "The specified configuration file cannot be found: " + configFile ); } catch( IOException e ) { throw new PelletCmdException( "I/O error while reading the configuration file: " + e.toString() ); } } } public void help() { output( help ); System.exit( 0 ); } private static class HelpTable { private final String LINE_BREAK = System.getProperty("line.separator"); private PelletCmdOptions options; private int maxLineWidth = 80; private int indent = 5; public HelpTable(PelletCmdOptions options) { this.options = options; } public String print() { StringBuffer ret = new StringBuffer(); ret.append( "Argument description:" + LINE_BREAK + LINE_BREAK ); int i = 0; boolean last = false; for( PelletCmdOption option : options.getOptions() ) { i++; if (i == options.getOptions().size() ) last = true; String longOption = option.getLongOption(); String shortOption = option.getShortOption(); String type = option.getType(); PelletCmdOptionArg arg = option.getArg(); String description = option.getDescription(); String defaultValue = ""; if( option.getDefaultValue() != null ) defaultValue = option.getDefaultValue().toString(); String firstLine = firstLine( shortOption, longOption, type, arg ); String secondLine = secondLine( description, defaultValue ); ret.append( firstLine ); ret.append( LINE_BREAK ); ret.append( secondLine ); if (!last) ret.append( LINE_BREAK + LINE_BREAK ); } return ret.toString(); } private String fill(int n) { return draw( " ", n ); } private String draw(String c, int n) { StringBuffer ret = new StringBuffer(); for( int i = 0; i < n; i++ ) ret.append( c ); return ret.toString(); } private String firstLine(String shortOption, String longOption, String type, PelletCmdOptionArg arg) { StringBuffer ret = new StringBuffer(); ret.append( "--" + longOption ); if( shortOption != null ) ret.append( ", -" + shortOption ); ret.append( " " ); if( type != null ) { if( arg.equals( PelletCmdOptionArg.OPTIONAL ) && !(type.startsWith( "[" ) || type.startsWith( "(" )) ) ret.append( "[" + type + "] " ); else if( arg.equals( PelletCmdOptionArg.REQUIRED ) && !(type.startsWith( "[" ) || type.startsWith( "(" )) ) ret.append( "(" + type + ") " ); } return ret.toString(); } private String secondLine(String description, String defaultValue) { int colStart = indent; int colLength = colStart; StringBuffer ret = new StringBuffer(); if( description == null && defaultValue == null ) return ret.toString(); String tokens; if( defaultValue != null && defaultValue.length() != 0 && !(defaultValue.equals( "true" ) || defaultValue.equals( "false" )) ) tokens = description + " (Default: " + defaultValue + ")"; else tokens = description; ret.append( fill( colStart ) ); StringTokenizer tokenizer = new StringTokenizer( tokens ); while( tokenizer.hasMoreTokens() ) { String token = tokenizer.nextToken(); colLength = colLength + token.length() + 1; if( colLength > maxLineWidth ) { ret.append( LINE_BREAK + fill( colStart ) ); colLength = colStart + token.length() + 1; } ret.append( token + " " ); } return ret.toString(); } } protected void startTask(String task) { verbose( "Start " + task ); timers.startTimer( task ); } protected void finishTask(String task) { Timer timer = timers.getTimer( task ); timer.stop(); verbose( "Finished " + task + " in " + timer.format() ); } }
{ "pile_set_name": "Github" }
<?xml version="1.0" standalone="no" ?> <!DOCTYPE pov SYSTEM "/usr/share/cgc-docs/replay.dtd"> <pov> <cbid>CROMU_00033</cbid> <replay> <write echo="ascii"><data>SEND\x06/HkRre\x23\x00M0Rhh4Iux9y3igdR4VAcgFB1qjmiFYBv9G7</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /HkRre\n</data></match></read> <write echo="ascii"><data>SEND\x0a/dFaRwfh7i\x27\x00o5JTkdGTmLIovm1wgleKpRtVWQ9y35HQReGQpJR</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /dFaRwfh7i\n</data></match></read> <write echo="ascii"><data>SEND\x06/8w7XJ\x30\x00JBcolxcs7mVkdMTrr4NwUOmb2N0zw3PYP615wT0G2GaDVtma</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /8w7XJ\n</data></match></read> <write echo="ascii"><data>NDIR\x09/TG77Ugqn</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>SEND\x14/TG77Ugqn/iE922lX4yN\x15\x00Ra6GWZuTP98w4bzJHdjKg</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /TG77Ugqn/iE922lX4yN\n</data></match></read> <write echo="ascii"><data>RECV\x06/HkRre</data></write> <read echo="ascii"><delim>\n</delim><match><data>[DATA] M0Rhh4Iux9y3igdR4VAcgFB1qjmiFYBv9G7\n</data></match></read> <write echo="ascii"><data>RECV\x0a/dFaRwfh7i</data></write> <read echo="ascii"><delim>\n</delim><match><data>[DATA] o5JTkdGTmLIovm1wgleKpRtVWQ9y35HQReGQpJR\n</data></match></read> <write echo="ascii"><data>RECV\x06/8w7XJ</data></write> <read echo="ascii"><delim>\n</delim><match><data>[DATA] JBcolxcs7mVkdMTrr4NwUOmb2N0zw3PYP615wT0G2GaDVtma\n</data></match></read> <write echo="ascii"><data>NDIR\x09/SSlo0RbJ</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>SEND\x13/SSlo0RbJ/suS6T4Gi4\x41\x00nwBZVbE6nb2vb8Wky0rV3YAHlxQmln42nRzqOkOoMbCbq7sQMNnzaEeatffk839OV</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /SSlo0RbJ/suS6T4Gi4\n</data></match></read> <write echo="ascii"><data>RECV\x06/HkRre</data></write> <read echo="ascii"><delim>\n</delim><match><data>[DATA] M0Rhh4Iux9y3igdR4VAcgFB1qjmiFYBv9G7\n</data></match></read> <write echo="ascii"><data>NDIR\x0b/0QRtoHxE6k</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>NDIR\x11/TG77Ugqn/mOt8gKO</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>SEND\x08/95DBCXQ\x43\x00OUwtBIqP40LjZ3pY63Ikp2kCCrJsto8aLQ23ODb3SLjfD05v86iW7rkGxBkHpGzH5kg</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /95DBCXQ\n</data></match></read> <write echo="ascii"><data>RECV\x06/HkRre</data></write> <read echo="ascii"><delim>\n</delim><match><data>[DATA] M0Rhh4Iux9y3igdR4VAcgFB1qjmiFYBv9G7\n</data></match></read> <write echo="ascii"><data>SEND\x16/0QRtoHxE6k/cfrbjW32YW\x44\x00WjkBQGWPqnesXyna3YQHMFg9u7irLaSIH09c63JO22YGBtwJcUklQByBYuLwF85ewW6P</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /0QRtoHxE6k/cfrbjW32YW\n</data></match></read> <write echo="ascii"><data>SEND\x16/TG77Ugqn/mOt8gKO/0MlC\x4a\x00JissrmDJUnUZoR42Ejo5ODcY9CDNXQkZi7DIWX96YO02IPQu5mip7LqZ3VQ2EXJsHgnhVeurj6</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /TG77Ugqn/mOt8gKO/0MlC\n</data></match></read> <write echo="ascii"><data>SEND\x13/0QRtoHxE6k/aWJBwgS\x17\x00d3MX24HXtjPZqHfCNsXO77j</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /0QRtoHxE6k/aWJBwgS\n</data></match></read> <write echo="ascii"><data>RECV\x0a/dFaRwfh7i</data></write> <read echo="ascii"><delim>\n</delim><match><data>[DATA] o5JTkdGTmLIovm1wgleKpRtVWQ9y35HQReGQpJR\n</data></match></read> <write echo="ascii"><data>RECV\x13/0QRtoHxE6k/aWJBwgS</data></write> <read echo="ascii"><delim>\n</delim><match><data>[DATA] d3MX24HXtjPZqHfCNsXO77j\n</data></match></read> <write echo="ascii"><data>NDIR\x10/0QRtoHxE6k/HSlf</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>NDIR\x18/0QRtoHxE6k/HSlf/5az3QYg</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>RECV\x13/0QRtoHxE6k/aWJBwgS</data></write> <read echo="ascii"><delim>\n</delim><match><data>[DATA] d3MX24HXtjPZqHfCNsXO77j\n</data></match></read> <write echo="ascii"><data>SEND\x14/SSlo0RbJ/jDLLi2JLfX\x54\x00qM1Uo1lEeK4Eaw1Ofb9isalQrcLvqpHC8ChVnnv3mKtRWNhVtH0qULcO4jFSv6HFQwfcjNUmt9dnZiPNkHZl</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /SSlo0RbJ/jDLLi2JLfX\n</data></match></read> <write echo="ascii"><data>SEND\x0e/SSlo0RbJ/jf73\x21\x008oVKYLa9Wtr1JDBBoSGA2bpF0a2kF2kSJ</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /SSlo0RbJ/jf73\n</data></match></read> <write echo="ascii"><data>SEND\x1b/0QRtoHxE6k/HSlf/wO6VsPJczg\x45\x00lEgOO2JsOYXZmT29nkKcRndODxmkiOR8OuPsbNuud9DLNNxRkKgVvNe3L5EwT0GVauEaa</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /0QRtoHxE6k/HSlf/wO6VsPJczg\n</data></match></read> <write echo="ascii"><data>SEND\x0b/hOM7CwvChJ\x64\x00sNtryb6NXU23hyLFWzcKcEkaN3VFDn4dYplKYcvxhVBEvWU8S7gmD8HfbNJyOA5GLws22z1QyKstncVhj2A3FOwvgFnLbE8tJAhE</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /hOM7CwvChJ\n</data></match></read> <write echo="ascii"><data>SEND\x1b/TG77Ugqn/mOt8gKO/FL7jNgO1B\x62\x00tm7dygAlTNAJgyHcrGR2yRQzUCn39yPoA6YtGv9w9YdxkiNcKhwGFh7cECahMb5Gxn2820s08ByEGHvli4DgVvE0D5sJIg3sgx</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /TG77Ugqn/mOt8gKO/FL7jNgO1B\n</data></match></read> <write echo="ascii"><data>RECV\x13/0QRtoHxE6k/aWJBwgS</data></write> <read echo="ascii"><delim>\n</delim><match><data>[DATA] d3MX24HXtjPZqHfCNsXO77j\n</data></match></read> <write echo="ascii"><data>RECV\x1b/TG77Ugqn/mOt8gKO/FL7jNgO1B</data></write> <read echo="ascii"><delim>\n</delim><match><data>[DATA] tm7dygAlTNAJgyHcrGR2yRQzUCn39yPoA6YtGv9w9YdxkiNcKhwGFh7cECahMb5Gxn2820s08ByEGHvli4DgVvE0D5sJIg3sgx\n</data></match></read> <write echo="ascii"><data>NDIR\x1b/0QRtoHxE6k/HSlf/inFaaRX2i1</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>RECV\x08/95DBCXQ</data></write> <read echo="ascii"><delim>\n</delim><match><data>[DATA] OUwtBIqP40LjZ3pY63Ikp2kCCrJsto8aLQ23ODb3SLjfD05v86iW7rkGxBkHpGzH5kg\n</data></match></read> <write echo="ascii"><data>RECV\x16/TG77Ugqn/mOt8gKO/0MlC</data></write> <read echo="ascii"><delim>\n</delim><match><data>[DATA] JissrmDJUnUZoR42Ejo5ODcY9CDNXQkZi7DIWX96YO02IPQu5mip7LqZ3VQ2EXJsHgnhVeurj6\n</data></match></read> <write echo="ascii"><data>SEND\x24/0QRtoHxE6k/HSlf/inFaaRX2i1/yxjFliDT\x51\x00tTi1adyY6uI79hurBsw2Gah3AyZ60zOA7nUxOV5bZY3akE3QNrpHUGBpHJMSlkjYcRelyqNfwSFzePhrh</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /0QRtoHxE6k/HSlf/inFaaRX2i1/yxjFliDT\n</data></match></read> <write echo="ascii"><data>SEND\x19/TG77Ugqn/mOt8gKO/5iXvmyc\x47\x00WlCZ8RVDmrOemqDtuze2SMIxdr3Ywmsb68D1L7Jtnu460sMPNSdOENvnijYrtgyvLMiGY2q</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /TG77Ugqn/mOt8gKO/5iXvmyc\n</data></match></read> <write echo="ascii"><data>SEND\x1a/0QRtoHxE6k/HSlf/QLtXHil7a\x40\x00gGS9GwgQ0HhZx371czCwzT260yhO1PMW5t7FhjYvTqceSNPBjTgwzMKNbN7Ede2t</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /0QRtoHxE6k/HSlf/QLtXHil7a\n</data></match></read> <write echo="ascii"><data>NDIR\x0e/SSlo0RbJ/pgqB</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>NDIR\x10/SSlo0RbJ/k6Gxas</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>SEND\x1a/SSlo0RbJ/k6Gxas/XVdYY7C2b\x4a\x00Y8YExE4QtkrelpTulwwKCIkyqydxQMxPfs7868UGmGOSDXjxZc6JHbOqdI2r0yMbnhpTc6cHk8</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /SSlo0RbJ/k6Gxas/XVdYY7C2b\n</data></match></read> <write echo="ascii"><data>SEND\x07/ZLRHgm\x15\x00O69DteCEZ61WhcNfsmRjG</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /ZLRHgm\n</data></match></read> <write echo="ascii"><data>SEND\x0f/SSlo0RbJ/uE0Y3\x1e\x00JhNIXtYcKqt0eR7iwXDyDnOONQxHxC</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /SSlo0RbJ/uE0Y3\n</data></match></read> <write echo="ascii"><data>NDIR\x14/SSlo0RbJ/pgqB/dqP1M</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>RECV\x16/TG77Ugqn/mOt8gKO/0MlC</data></write> <read echo="ascii"><delim>\n</delim><match><data>[DATA] JissrmDJUnUZoR42Ejo5ODcY9CDNXQkZi7DIWX96YO02IPQu5mip7LqZ3VQ2EXJsHgnhVeurj6\n</data></match></read> <write echo="ascii"><data>RECV\x14/SSlo0RbJ/jDLLi2JLfX</data></write> <read echo="ascii"><delim>\n</delim><match><data>[DATA] qM1Uo1lEeK4Eaw1Ofb9isalQrcLvqpHC8ChVnnv3mKtRWNhVtH0qULcO4jFSv6HFQwfcjNUmt9dnZiPNkHZl\n</data></match></read> <write echo="ascii"><data>NDIR\x22/0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>SEND\x14/SSlo0RbJ/pgqB/aBmfe\x30\x00ptsOP9Uipj1zQyJbByVjXL7K3JMJmdSo8kbXZOQeNpKH1cHc</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /SSlo0RbJ/pgqB/aBmfe\n</data></match></read> <write echo="ascii"><data>RECV\x1a/0QRtoHxE6k/HSlf/QLtXHil7a</data></write> <read echo="ascii"><delim>\n</delim><match><data>[DATA] gGS9GwgQ0HhZx371czCwzT260yhO1PMW5t7FhjYvTqceSNPBjTgwzMKNbN7Ede2t\n</data></match></read> <write echo="ascii"><data>NDIR\x18/SSlo0RbJ/pgqB/vpjPkL9Zc</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>NDIR\x14/0QRtoHxE6k/0b9Jqmfz</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>SEND\x13/SSlo0RbJ/SQNwlx1t1\x63\x003LrjCyKe2dUu9WNluxJ1hZL3yaBjGCyrZ06LKZaZXKRyxT5UGfv0GuzUYQ1c3NfnS5mEUmipFz6PLXbYud7k61ohnbqCSWl2ZiU</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /SSlo0RbJ/SQNwlx1t1\n</data></match></read> <write echo="ascii"><data>RECV\x13/SSlo0RbJ/SQNwlx1t1</data></write> <read echo="ascii"><delim>\n</delim><match><data>[DATA] 3LrjCyKe2dUu9WNluxJ1hZL3yaBjGCyrZ06LKZaZXKRyxT5UGfv0GuzUYQ1c3NfnS5mEUmipFz6PLXbYud7k61ohnbqCSWl2ZiU\n</data></match></read> <write echo="ascii"><data>NDIR\x2b/0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>NDIR\x36/0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW/rjuCkPFhil</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>NDIR\x30/0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW/m6ec</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>NDIR\x36/0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW/tTK5AnKmw8</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>SEND\x20/0QRtoHxE6k/HSlf/inFaaRX2i1/eTQe\x27\x002ZdYsBNrtKStMboExxqv29mW7y2LMjT69y23296</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /0QRtoHxE6k/HSlf/inFaaRX2i1/eTQe\n</data></match></read> <write echo="ascii"><data>NDIR\x3b/0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW/rjuCkPFhil/r37I</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>NDIR\x17/SSlo0RbJ/pgqB/ihrYUUF5</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>SEND\x1e/0QRtoHxE6k/HSlf/5az3QYg/5OQNl\x27\x00xLBzbUMcY2bZq8HhskuvSgkIxM23NIBQFGTIyd0</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /0QRtoHxE6k/HSlf/5az3QYg/5OQNl\n</data></match></read> <write echo="ascii"><data>RECV\x07/ZLRHgm</data></write> <read echo="ascii"><delim>\n</delim><match><data>[DATA] O69DteCEZ61WhcNfsmRjG\n</data></match></read> <write echo="ascii"><data>SEND\x18/0QRtoHxE6k/HSlf/y1lzPU5\x38\x00jRuEk6RNHfbyeaDzImndRE6AayWKQXpwlilRkU0zWyOMjnSa42XfARF1</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /0QRtoHxE6k/HSlf/y1lzPU5\n</data></match></read> <write echo="ascii"><data>NDIR\x06/dA0qz</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>SEND\x18/TG77Ugqn/mOt8gKO/45GdKd\x4c\x00LgrFpHF4cyRSbPWPIQA05xPgusuaCynLhbzT2oftBEtuIkQ7VkJ34SvcvKYlJkHfa6h9n2a0qv8W</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /TG77Ugqn/mOt8gKO/45GdKd\n</data></match></read> <write echo="ascii"><data>NDIR\x3e/0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW/rjuCkPFhil/WiDkKNH</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>SEND\x17/0QRtoHxE6k/HSlf/F2Vuu0\x3b\x008yi1oLp9M9l73OOS5NG0rRYeg0KfM3UZnmmS4Yzs7YuBGxxetS5dzz6oIdj</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /0QRtoHxE6k/HSlf/F2Vuu0\n</data></match></read> <write echo="ascii"><data>SEND\x19/0QRtoHxE6k/HSlf/K6RbJtv1\x1a\x006iXa4K2tywZnlKt14hYLZYLDWc</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /0QRtoHxE6k/HSlf/K6RbJtv1\n</data></match></read> <write echo="ascii"><data>NDIR\x3e/0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW/tTK5AnKmw8/QExGf9u</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>NDIR\x0f/dA0qz/BtUjrOSH</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>NDIR\x1a/dA0qz/BtUjrOSH/sQIAE9sZVR</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>NDIR\x18/dA0qz/BtUjrOSH/3g1xhcUW</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>NDIR\x3d/0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW/tTK5AnKmw8/M0r1Sx</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>SEND\x20/SSlo0RbJ/pgqB/ihrYUUF5/W8Rxpo8y\x3c\x00lLUjqo03TdM9Ew3H8kofMg6FBNeFBfS0e5sQWue92dseV3wQcO4Kee1k9zkf</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /SSlo0RbJ/pgqB/ihrYUUF5/W8Rxpo8y\n</data></match></read> <write echo="ascii"><data>SEND\x3c/0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW/rjuCkPFhil/BBKdJ\x4c\x002eQIWgVTYpeayhKZYdgdr7nAZqFHDuGyHcgC76aPLVOX5k0iGs8wcb0DDa9GIzYWX6iS396sYcH0</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW/rjuCkPFhil/BBKdJ\n</data></match></read> <write echo="ascii"><data>NDIR\x45/0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW/rjuCkPFhil/WiDkKNH/SvFCtb</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>NDIR\x11/SSlo0RbJ/4xcXI0a</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>NDIR\x19/0QRtoHxE6k/0b9Jqmfz/OfGC</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>NDIR\x4a/0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW/rjuCkPFhil/WiDkKNH/SvFCtb/HYzm</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>NDIR\x10/SSlo0RbJ/BJx7UL</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>SEND\x1d/0QRtoHxE6k/HSlf/5az3QYg/cUaf\x19\x00KGGGIkiNWNTtyaneo8cL9YzHL</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /0QRtoHxE6k/HSlf/5az3QYg/cUaf\n</data></match></read> <write echo="ascii"><data>SEND\x22/SSlo0RbJ/pgqB/vpjPkL9Zc/N2pGbIC3j\x63\x00HrYoN80h1Mc049xOzK6qdQZba56TYeCG9w2Rr9Y876Eeh2A6w2xrLMNmwM9VqIhKgSzNqqVHRkyTKl4skW4tqnEQmVElS5y0vnt</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /SSlo0RbJ/pgqB/vpjPkL9Zc/N2pGbIC3j\n</data></match></read> <write echo="ascii"><data>SEND\x23/SSlo0RbJ/pgqB/vpjPkL9Zc/XlRbTFuXZ2\x18\x00Y0gpp3GgmfY7CNXm9w81k6mx</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /SSlo0RbJ/pgqB/vpjPkL9Zc/XlRbTFuXZ2\n</data></match></read> <write echo="ascii"><data>SEND\x46/0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW/rjuCkPFhil/r37I/qjDozE5sm5\x52\x006AbUmTwVPnwc7XYmydCxTUJh6yYtZ3g4WV9UjpHbA5qOL78DwWweWPyBYCerEEDOJ0xDmLeRqWeRrFtJtS</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW/rjuCkPFhil/r37I/qjDozE5sm5\n</data></match></read> <write echo="ascii"><data>RECV\x18/TG77Ugqn/mOt8gKO/45GdKd</data></write> <read echo="ascii"><delim>\n</delim><match><data>[DATA] LgrFpHF4cyRSbPWPIQA05xPgusuaCynLhbzT2oftBEtuIkQ7VkJ34SvcvKYlJkHfa6h9n2a0qv8W\n</data></match></read> <write echo="ascii"><data>SEND\x0f/TG77Ugqn/YWIZd\x54\x00uuxrfoX3cqQ0BHMwAFKGkumIEQKasuP6f2RVJArJosrY76NDvQlsnXPVsrztS3YghLn2yTQruGSatzUnb7dG</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /TG77Ugqn/YWIZd\n</data></match></read> <write echo="ascii"><data>SEND\x25/dA0qz/BtUjrOSH/sQIAE9sZVR/eSQOqkDQ14\x48\x00tbxjlOrngqMJ8UH3SGfPlDK4XNcK22q0wSxudMJETBD92AUAB0b1s5q5hOWrSbtTBRWcfoyT</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /dA0qz/BtUjrOSH/sQIAE9sZVR/eSQOqkDQ14\n</data></match></read> <write echo="ascii"><data>NDIR\x30/0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW/r5Y3</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>NDIR\x25/dA0qz/BtUjrOSH/sQIAE9sZVR/LGofUjDcHS</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>NDIR\x26/0QRtoHxE6k/HSlf/inFaaRX2i1/1MNfbM40GO</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>RECV\x13/SSlo0RbJ/suS6T4Gi4</data></write> <read echo="ascii"><delim>\n</delim><match><data>[DATA] nwBZVbE6nb2vb8Wky0rV3YAHlxQmln42nRzqOkOoMbCbq7sQMNnzaEeatffk839OV\n</data></match></read> <write echo="ascii"><data>REPO\x14/SSlo0RbJ/pgqB/aBmfe</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] aBmfe removed\n</data></match></read> <write echo="ascii"><data>SEND\x36/0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW/r5Y3/UHq3F\x50\x00A6RrgXXVlReaDQ8PxAtPTl8uhehY5IJNoJ03icO9Ob4n6CaxcDO8D6WCpNO3uAarqYbUwwz8FNTKkAMK</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW/r5Y3/UHq3F\n</data></match></read> <write echo="ascii"><data>SEND\x21/dA0qz/BtUjrOSH/3g1xhcUW/SNJuhHk4\x31\x00amizvicV2VR1hqbwiOH4uutbuFHMHt0s0HulGD2im9IwdcJqT</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /dA0qz/BtUjrOSH/3g1xhcUW/SNJuhHk4\n</data></match></read> <write echo="ascii"><data>RECV\x1e/0QRtoHxE6k/HSlf/5az3QYg/5OQNl</data></write> <read echo="ascii"><delim>\n</delim><match><data>[DATA] xLBzbUMcY2bZq8HhskuvSgkIxM23NIBQFGTIyd0\n</data></match></read> <write echo="ascii"><data>SEND\x2c/0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/hbKRXD0EN\x2a\x00h7qobyHyTbASyOJ8QVKirPGPtMfCbADGhTCZT7jKOt</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/hbKRXD0EN\n</data></match></read> <write echo="ascii"><data>NDIR\x1c/SSlo0RbJ/pgqB/dqP1M/VXeq5FU</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>REPO\x36/0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW/r5Y3/UHq3F</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] UHq3F removed\n</data></match></read> <write echo="ascii"><data>SEND\x30/dA0qz/BtUjrOSH/sQIAE9sZVR/LGofUjDcHS/bmrENMHk9F\x25\x00Oj3ILY3HqidMY0AM4I1tYqKR6HxGDo9HNnANC</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /dA0qz/BtUjrOSH/sQIAE9sZVR/LGofUjDcHS/bmrENMHk9F\n</data></match></read> <write echo="ascii"><data>NDIR\x46/0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW/rjuCkPFhil/r37I/O90JRiodAg</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>NDIR\x3a/0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW/r5Y3/u0XsmXmYW</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>NDIR\x1d/SSlo0RbJ/pgqB/vpjPkL9Zc/IRsa</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>REPO\x18/0QRtoHxE6k/HSlf/y1lzPU5</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] y1lzPU5 removed\n</data></match></read> <write echo="ascii"><data>NDIR\x27/SSlo0RbJ/pgqB/vpjPkL9Zc/IRsa/jSQVb42D2</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>NDIR\x36/0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW/CepVOagE1V</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>SEND\x17/0QRtoHxE6k/HSlf/UW07De\x30\x00dfKgWu2gA9qg6voI8G8nhRCNR6Dd9hQ3VFYQnMPpavuJwwNI</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /0QRtoHxE6k/HSlf/UW07De\n</data></match></read> <write echo="ascii"><data>REPO\x0f/SSlo0RbJ/uE0Y3</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] uE0Y3 removed\n</data></match></read> <write echo="ascii"><data>RECV\x1d/0QRtoHxE6k/HSlf/5az3QYg/cUaf</data></write> <read echo="ascii"><delim>\n</delim><match><data>[DATA] KGGGIkiNWNTtyaneo8cL9YzHL\n</data></match></read> <write echo="ascii"><data>SEND\x1f/dA0qz/BtUjrOSH/sQIAE9sZVR/g8Od\x2f\x009KGclS5XLbDyxHWM3hJHoKaHbTyGjlUcHiZ86awVBzptH7g</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /dA0qz/BtUjrOSH/sQIAE9sZVR/g8Od\n</data></match></read> <write echo="ascii"><data>SEND\x17/SSlo0RbJ/k6Gxas/385xw0\x4d\x00Fy5HqUBJ95pLF6r0yOAa2U73uYu0YuKSQa6s9nGwyNpFL32fmcMdD5wIptcZKLaNDTs9d2M5bV8GN</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /SSlo0RbJ/k6Gxas/385xw0\n</data></match></read> <write echo="ascii"><data>SEND\x16/0QRtoHxE6k/HSlf/zjzmB\x2f\x00tWPIHj9FjToyK8NVlSLKoswfIjTR9aeY8FiZOoqmUZHNeTl</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /0QRtoHxE6k/HSlf/zjzmB\n</data></match></read> <write echo="ascii"><data>SEND\x1a/SSlo0RbJ/BJx7UL/hN0r5SgwD\x37\x008oNoh7dX2x5bzwU6SnDT1uDsCqTOX8IBvxU5CMaRDHSfiToC2hSgbio</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /SSlo0RbJ/BJx7UL/hN0r5SgwD\n</data></match></read> <write echo="ascii"><data>REPO\x23/SSlo0RbJ/pgqB/vpjPkL9Zc/XlRbTFuXZ2</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] XlRbTFuXZ2 removed\n</data></match></read> <write echo="ascii"><data>NDIR\x31/0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW/PVnSd</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>SEND\x08/d9lpkg6\x4d\x00LAlmzT0zjaZxBu3CjHghHbGXDzbpcfUvm6H4S2l3U80A7ylCMjDTKK1GhtaqdVnbzDKKA7M0jpdUk</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /d9lpkg6\n</data></match></read> <write echo="ascii"><data>SEND\x2a/dA0qz/BtUjrOSH/sQIAE9sZVR/LGofUjDcHS/Un7J\x38\x00oj0WI4kcIG3ECXFRKiKU4n8RaWKkRPSJjs20vRhHIpVSz3osyZYGXtaZ</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /dA0qz/BtUjrOSH/sQIAE9sZVR/LGofUjDcHS/Un7J\n</data></match></read> <write echo="ascii"><data>RECV\x1a/SSlo0RbJ/k6Gxas/XVdYY7C2b</data></write> <read echo="ascii"><delim>\n</delim><match><data>[DATA] Y8YExE4QtkrelpTulwwKCIkyqydxQMxPfs7868UGmGOSDXjxZc6JHbOqdI2r0yMbnhpTc6cHk8\n</data></match></read> <write echo="ascii"><data>REPO\x1a/SSlo0RbJ/BJx7UL/hN0r5SgwD</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] hN0r5SgwD removed\n</data></match></read> <write echo="ascii"><data>NDIR\x0e/dA0qz/8FUEA4x</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>SEND\x45/0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW/rjuCkPFhil/WiDkKNH/jUuy9b\x54\x00a7rX2E89HdxHCmWbHR0REG9V4cFQ1WKQ3dE00tNx2tyAISLAJlhnuXpdn59IzUgNVv0fxm90ZwDZBwf6Pygq</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW/rjuCkPFhil/WiDkKNH/jUuy9b\n</data></match></read> <write echo="ascii"><data>NDIR\x53/0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW/rjuCkPFhil/WiDkKNH/SvFCtb/HYzm/l2ihCHoX</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>REPO\x20/SSlo0RbJ/pgqB/ihrYUUF5/W8Rxpo8y</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] W8Rxpo8y removed\n</data></match></read> <write echo="ascii"><data>REPO\x16/0QRtoHxE6k/cfrbjW32YW</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] cfrbjW32YW removed\n</data></match></read> <write echo="ascii"><data>RECV\x1a/0QRtoHxE6k/HSlf/QLtXHil7a</data></write> <read echo="ascii"><delim>\n</delim><match><data>[DATA] gGS9GwgQ0HhZx371czCwzT260yhO1PMW5t7FhjYvTqceSNPBjTgwzMKNbN7Ede2t\n</data></match></read> <write echo="ascii"><data>SEND\x22/dA0qz/BtUjrOSH/3g1xhcUW/qLsjBbHxI\x1d\x006WDPfJikQTRrLPztp8ug7hGLBl5vm</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /dA0qz/BtUjrOSH/3g1xhcUW/qLsjBbHxI\n</data></match></read> <write echo="ascii"><data>NDIR\x1e/SSlo0RbJ/pgqB/vpjPkL9Zc/Y5xmc</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>NDIR\x3c/0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW/rjuCkPFhil/eN1p9</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>NDIR\x3c/0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW/PVnSd/44zBR8r1Rr</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>REPO\x0f/TG77Ugqn/YWIZd</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] YWIZd removed\n</data></match></read> <write echo="ascii"><data>SEND\x1b/0QRtoHxE6k/HSlf/ha1QYUGYxp\x39\x00BdbABYfK4tdPJ14bspwv8g4WuFKLvRwQX8Mhlc3R0Gbgq70cTE7Ucomxv</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /0QRtoHxE6k/HSlf/ha1QYUGYxp\n</data></match></read> <write echo="ascii"><data>REPO\x30/dA0qz/BtUjrOSH/sQIAE9sZVR/LGofUjDcHS/bmrENMHk9F</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] bmrENMHk9F removed\n</data></match></read> <write echo="ascii"><data>SEND\x3b/0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW/m6ec/OIrBo6myDF\x2b\x00sa4Omg9TVGdYxUGNaoLNuo9V7I8CCVtFchfwTmG7rmL</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW/m6ec/OIrBo6myDF\n</data></match></read> <write echo="ascii"><data>NDIR\x43/0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW/rjuCkPFhil/eN1p9/yZIm6W</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>RECV\x1d/0QRtoHxE6k/HSlf/5az3QYg/cUaf</data></write> <read echo="ascii"><delim>\n</delim><match><data>[DATA] KGGGIkiNWNTtyaneo8cL9YzHL\n</data></match></read> <write echo="ascii"><data>NDIR\x36/0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW/r5Y3/IPsfx</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>SEND\x51/0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW/rjuCkPFhil/WiDkKNH/SvFCtb/HYzm/MngOWc\x1d\x003p6eAexBE0VOBegvcmgoRWakOjZBc</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW/rjuCkPFhil/WiDkKNH/SvFCtb/HYzm/MngOWc\n</data></match></read> <write echo="ascii"><data>REPO\x2a/dA0qz/BtUjrOSH/sQIAE9sZVR/LGofUjDcHS/Un7J</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Un7J removed\n</data></match></read> <write echo="ascii"><data>SEND\x40/0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW/rjuCkPFhil/r37I/BVpO\x35\x00NB3mItkAPYcXpHQhFbA3s6qBKsWOGTpoM0YvaYOn2jbu9Kvq2wKnx</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW/rjuCkPFhil/r37I/BVpO\n</data></match></read> <write echo="ascii"><data>NDIR\x1a/TG77Ugqn/mOt8gKO/8X9oUKNu</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>RECV\x20/0QRtoHxE6k/HSlf/inFaaRX2i1/eTQe</data></write> <read echo="ascii"><delim>\n</delim><match><data>[DATA] 2ZdYsBNrtKStMboExxqv29mW7y2LMjT69y23296\n</data></match></read> <write echo="ascii"><data>NDIR\x27/SSlo0RbJ/pgqB/vpjPkL9Zc/IRsa/KXKhUHS8C</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read> <write echo="ascii"><data>REPO\x21/dA0qz/BtUjrOSH/3g1xhcUW/SNJuhHk4</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] SNJuhHk4 removed\n</data></match></read> <write echo="ascii"><data>REPO\x51/0QRtoHxE6k/HSlf/5az3QYg/Uufytd60v/MCn6gDJW/rjuCkPFhil/WiDkKNH/SvFCtb/HYzm/MngOWc</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] MngOWc removed\n</data></match></read> <write echo="ascii"><data>STOP</data></write> <read echo="ascii"><delim>\n</delim><match><data>[INFO] Terminating\n</data></match></read> </replay> </pov>
{ "pile_set_name": "Github" }
<snippet> <content><![CDATA[getContentScaleFactor()]]></content> <tabTrigger>getContentScaleFactor()</tabTrigger> <scope>source.lua</scope> <description>GLView</description> </snippet>
{ "pile_set_name": "Github" }
# -*- coding: utf-8 -*- from tornado import gen from tornado.web import HTTPError from young.handler import BaseHandler from app.user.document import UserDocument from app.community.document import TopicDocument from app.share.document import ShareDocument from app.search.form import SearchForm __all__ = ['SearchHandler'] class SearchHandler(BaseHandler): @gen.coroutine def get(self): form = SearchForm(self.request.arguments) if not form.validate(): raise HTTPError(404) category = form.category.data query = form.query.data response_data = [] if category == 'user': res = self.es.search( index="young", doc_type=UserDocument.meta['collection'], body={ "query": { "match": { "name": query } } } ) response_data = [ {'name': r["_source"]['name'], '_id': r["_id"]} for r in res["hits"]["hits"] ] elif category == 'topic': res = self.es.search( index="young", doc_type=TopicDocument.meta['collection'], body={ "query": { "match": { "title": query } } } ) response_data = [ {'title': r["_source"]['title'], '_id': r["_id"]} for r in res["hits"]["hits"] ] elif category == 'share': res = self.es.search( index="young", doc_type=ShareDocument.meta['collection'], body={ "query": { "match": { "title": query } } } ) response_data = [ {'title': r["_source"]['title'], '_id': r["_id"]} for r in res["hits"]["hits"] ] self.write_json(response_data)
{ "pile_set_name": "Github" }
<?php /** * PHPExcel * * Copyright (c) 2006 - 2014 PHPExcel * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * @category PHPExcel * @package PHPExcel_Writer_Excel2007 * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL * @version ##VERSION##, ##DATE## */ /** * PHPExcel_Writer_Excel2007_Rels * * @category PHPExcel * @package PHPExcel_Writer_Excel2007 * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) */ class PHPExcel_Writer_Excel2007_Rels extends PHPExcel_Writer_Excel2007_WriterPart { /** * Write relationships to XML format * * @param PHPExcel $pPHPExcel * @return string XML Output * @throws PHPExcel_Writer_Exception */ public function writeRelationships(PHPExcel $pPHPExcel = null) { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0','UTF-8','yes'); // Relationships $objWriter->startElement('Relationships'); $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships'); $customPropertyList = $pPHPExcel->getProperties()->getCustomProperties(); if (!empty($customPropertyList)) { // Relationship docProps/app.xml $this->_writeRelationship( $objWriter, 4, 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties', 'docProps/custom.xml' ); } // Relationship docProps/app.xml $this->_writeRelationship( $objWriter, 3, 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties', 'docProps/app.xml' ); // Relationship docProps/core.xml $this->_writeRelationship( $objWriter, 2, 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties', 'docProps/core.xml' ); // Relationship xl/workbook.xml $this->_writeRelationship( $objWriter, 1, 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument', 'xl/workbook.xml' ); // a custom UI in workbook ? if($pPHPExcel->hasRibbon()){ $this->_writeRelationShip( $objWriter, 5, 'http://schemas.microsoft.com/office/2006/relationships/ui/extensibility', $pPHPExcel->getRibbonXMLData('target') ); } $objWriter->endElement(); // Return return $objWriter->getData(); } /** * Write workbook relationships to XML format * * @param PHPExcel $pPHPExcel * @return string XML Output * @throws PHPExcel_Writer_Exception */ public function writeWorkbookRelationships(PHPExcel $pPHPExcel = null) { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0','UTF-8','yes'); // Relationships $objWriter->startElement('Relationships'); $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships'); // Relationship styles.xml $this->_writeRelationship( $objWriter, 1, 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles', 'styles.xml' ); // Relationship theme/theme1.xml $this->_writeRelationship( $objWriter, 2, 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme', 'theme/theme1.xml' ); // Relationship sharedStrings.xml $this->_writeRelationship( $objWriter, 3, 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings', 'sharedStrings.xml' ); // Relationships with sheets $sheetCount = $pPHPExcel->getSheetCount(); for ($i = 0; $i < $sheetCount; ++$i) { $this->_writeRelationship( $objWriter, ($i + 1 + 3), 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet', 'worksheets/sheet' . ($i + 1) . '.xml' ); } // Relationships for vbaProject if needed // id : just after the last sheet if($pPHPExcel->hasMacros()){ $this->_writeRelationShip( $objWriter, ($i + 1 + 3), 'http://schemas.microsoft.com/office/2006/relationships/vbaProject', 'vbaProject.bin' ); ++$i;//increment i if needed for an another relation } $objWriter->endElement(); // Return return $objWriter->getData(); } /** * Write worksheet relationships to XML format * * Numbering is as follows: * rId1 - Drawings * rId_hyperlink_x - Hyperlinks * * @param PHPExcel_Worksheet $pWorksheet * @param int $pWorksheetId * @param boolean $includeCharts Flag indicating if we should write charts * @return string XML Output * @throws PHPExcel_Writer_Exception */ public function writeWorksheetRelationships(PHPExcel_Worksheet $pWorksheet = null, $pWorksheetId = 1, $includeCharts = FALSE) { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0','UTF-8','yes'); // Relationships $objWriter->startElement('Relationships'); $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships'); // Write drawing relationships? $d = 0; if ($includeCharts) { $charts = $pWorksheet->getChartCollection(); } else { $charts = array(); } if (($pWorksheet->getDrawingCollection()->count() > 0) || (count($charts) > 0)) { $this->_writeRelationship( $objWriter, ++$d, 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing', '../drawings/drawing' . $pWorksheetId . '.xml' ); } // Write chart relationships? // $chartCount = 0; // $charts = $pWorksheet->getChartCollection(); // echo 'Chart Rels: ' , count($charts) , '<br />'; // if (count($charts) > 0) { // foreach($charts as $chart) { // $this->_writeRelationship( // $objWriter, // ++$d, // 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart', // '../charts/chart' . ++$chartCount . '.xml' // ); // } // } // // Write hyperlink relationships? $i = 1; foreach ($pWorksheet->getHyperlinkCollection() as $hyperlink) { if (!$hyperlink->isInternal()) { $this->_writeRelationship( $objWriter, '_hyperlink_' . $i, 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink', $hyperlink->getUrl(), 'External' ); ++$i; } } // Write comments relationship? $i = 1; if (count($pWorksheet->getComments()) > 0) { $this->_writeRelationship( $objWriter, '_comments_vml' . $i, 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing', '../drawings/vmlDrawing' . $pWorksheetId . '.vml' ); $this->_writeRelationship( $objWriter, '_comments' . $i, 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments', '../comments' . $pWorksheetId . '.xml' ); } // Write header/footer relationship? $i = 1; if (count($pWorksheet->getHeaderFooter()->getImages()) > 0) { $this->_writeRelationship( $objWriter, '_headerfooter_vml' . $i, 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing', '../drawings/vmlDrawingHF' . $pWorksheetId . '.vml' ); } $objWriter->endElement(); // Return return $objWriter->getData(); } /** * Write drawing relationships to XML format * * @param PHPExcel_Worksheet $pWorksheet * @param int &$chartRef Chart ID * @param boolean $includeCharts Flag indicating if we should write charts * @return string XML Output * @throws PHPExcel_Writer_Exception */ public function writeDrawingRelationships(PHPExcel_Worksheet $pWorksheet = null, &$chartRef, $includeCharts = FALSE) { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0','UTF-8','yes'); // Relationships $objWriter->startElement('Relationships'); $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships'); // Loop through images and write relationships $i = 1; $iterator = $pWorksheet->getDrawingCollection()->getIterator(); while ($iterator->valid()) { if ($iterator->current() instanceof PHPExcel_Worksheet_Drawing || $iterator->current() instanceof PHPExcel_Worksheet_MemoryDrawing) { // Write relationship for image drawing $this->_writeRelationship( $objWriter, $i, 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image', '../media/' . str_replace(' ', '', $iterator->current()->getIndexedFilename()) ); } $iterator->next(); ++$i; } if ($includeCharts) { // Loop through charts and write relationships $chartCount = $pWorksheet->getChartCount(); if ($chartCount > 0) { for ($c = 0; $c < $chartCount; ++$c) { $this->_writeRelationship( $objWriter, $i++, 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart', '../charts/chart' . ++$chartRef . '.xml' ); } } } $objWriter->endElement(); // Return return $objWriter->getData(); } /** * Write header/footer drawing relationships to XML format * * @param PHPExcel_Worksheet $pWorksheet * @return string XML Output * @throws PHPExcel_Writer_Exception */ public function writeHeaderFooterDrawingRelationships(PHPExcel_Worksheet $pWorksheet = null) { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0','UTF-8','yes'); // Relationships $objWriter->startElement('Relationships'); $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships'); // Loop through images and write relationships foreach ($pWorksheet->getHeaderFooter()->getImages() as $key => $value) { // Write relationship for image drawing $this->_writeRelationship( $objWriter, $key, 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image', '../media/' . $value->getIndexedFilename() ); } $objWriter->endElement(); // Return return $objWriter->getData(); } /** * Write Override content type * * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer * @param int $pId Relationship ID. rId will be prepended! * @param string $pType Relationship type * @param string $pTarget Relationship target * @param string $pTargetMode Relationship target mode * @throws PHPExcel_Writer_Exception */ private function _writeRelationship(PHPExcel_Shared_XMLWriter $objWriter = null, $pId = 1, $pType = '', $pTarget = '', $pTargetMode = '') { if ($pType != '' && $pTarget != '') { // Write relationship $objWriter->startElement('Relationship'); $objWriter->writeAttribute('Id', 'rId' . $pId); $objWriter->writeAttribute('Type', $pType); $objWriter->writeAttribute('Target', $pTarget); if ($pTargetMode != '') { $objWriter->writeAttribute('TargetMode', $pTargetMode); } $objWriter->endElement(); } else { throw new PHPExcel_Writer_Exception("Invalid parameters passed."); } } }
{ "pile_set_name": "Github" }
{ "name": "roadmap-next", "version": "1.0.0", "main": "index.js", "license": "BSD-4-Clause", "scripts": { "dev": "NODE_ENV=dev next", "serve:out": "serve out", "build": "./scripts/build.sh", "deploy": "NODE_DEBUG=gh-pages gh-pages -d out -t", "test": "jest", "test:watch": "jest --watch", "meta:sitemap": "node scripts/sitemap.js", "meta:roadmaps": "node scripts/roadmaps-meta.js", "meta": "yarn meta:roadmaps && yarn meta:sitemap" }, "dependencies": { "@fortawesome/fontawesome-svg-core": "^1.2.28", "@fortawesome/free-brands-svg-icons": "^5.13.0", "@fortawesome/free-solid-svg-icons": "^5.13.0", "@fortawesome/react-fontawesome": "^0.1.9", "@mapbox/rehype-prism": "^0.4.0", "@mdx-js/loader": "^1.5.8", "@mdx-js/react": "^1.5.8", "@next/mdx": "^9.3.2", "@svgr/webpack": "^5.3.0", "@zeit/next-css": "latest", "@zeit/next-sass": "^1.0.1", "autoprefixer": "^9.7.5", "bootstrap": "^4.4.1", "classnames": "^2.2.6", "date-fns": "^2.11.1", "font-awesome": "^4.7.0", "next": "^9.3.2", "node-sass": "^4.13.1", "postcss-css-variables": "^0.14.0", "prism-themes": "^1.3.0", "query-string": "^6.11.1", "react": "^16.13.1", "react-dom": "^16.13.1", "styled-components": "^5.0.1" }, "devDependencies": { "babel-plugin-styled-components": "^1.10.7", "gh-pages": "^2.2.0", "glob": "^7.1.6", "jest": "^25.2.3", "serve": "^11.3.0" } }
{ "pile_set_name": "Github" }
require 'active_support/core_ext' require 'netzke/core/ruby_ext' require 'netzke/core/client_code' require 'netzke/core/stylesheets' require 'netzke/core/services' require 'netzke/core/composition' require 'netzke/core/plugins' require 'netzke/core/configuration' require 'netzke/core/state' require 'netzke/core/embedding' require 'netzke/core/actions' require 'netzke/core/session' require 'netzke/core/core_i18n' require 'netzke/core/inheritance' require 'netzke/core/support' module Netzke # The base class for every Netzke component. Its main responsibilities include: # * Client class generation and inheritance (using Ext JS class system) which reflects the Ruby class inheritance (see {Netzke::Core::ClientCode}) # * Nesting and dynamic loading of child components (see {Netzke::Core::Composition}) # * Ruby-side action declaration (see {Netzke::Actions}) # * I18n # * Client-server communication (see {Netzke::Core::Services}) # * Session-based persistence (see {Netzke::Core::State}) # # Client-side methods are documented [here](http://api.netzke.org/client/classes/Netzke.Base.html). # # == Referring to JavaScript configuration methods from Ruby # # Netzke allows use Ruby symbols for referring to pre-defined pieces of configuration. Let's say for example, that a toolbar needs to nest a control more complex than a button (say, a date field), and a component should still make it possible to make it's presence and position in the toolbar configurable. We can implement it like this: # # action :do_something # # def configure(c) # super # c.tbar = [:do_something, :date_selector] # end # # While :do_something here is referring to a usual Netzke action, :date_selector is not declared in actions. If our JavaScript include file contains a method called `dateSelectorConfig`, it will be executed at the moment of configuring `tbar` at client side, and it's result, a config object, will substitute `date_selector`: # # { # dateSelectorConfig: function(config){ # return { # xtype: 'datefield' # } # } # } # # This doesn't necessarily have to be used in toolbars, but also in other places in config (i.e. layouts). class Base include Core::Session include Core::State include Core::Configuration include Core::ClientCode include Core::Services include Core::Composition include Core::Plugins include Core::Stylesheets include Core::Embedding include Core::Actions include Core::CoreI18n include Core::Inheritance # These are set during initialization mattr_accessor :session, :controller, :logger attr_reader :parent, :name, :item_id, :path # Instantiates a component instance. A parent can optionally be provided. def initialize(conf = {}, parent = nil) @passed_config = conf # parent component @parent = parent # name fo the component used in the +component+ DSL block, and is a part of component's +@path+ @name = conf[:name] || self.class.name.underscore # path down the composition hierarchy (composed of names) @path = parent.nil? ? @name : "#{parent.path}__#{@name}" # JS id in the scope of the parent component. Auto-generated when using multiple instance loading. # Full JS id will be built using these along the +@path+ @item_id = conf[:item_id] || @name # Make +client_config+ accessible in +configure+ before calling +super+ client_config = Netzke::Support.permit_hash_params(conf.delete(:client_config)) config.client_config = HashWithIndifferentAccess.new(client_config) # Build complete component configuration configure(config) # Check whether the config is valid (as specified in a custom override) validate_config(config) normalize_config config.deep_freeze end end end
{ "pile_set_name": "Github" }
// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !go1.7 package context import ( "errors" "fmt" "sync" "time" ) // An emptyCtx is never canceled, has no values, and has no deadline. It is not // struct{}, since vars of this type must have distinct addresses. type emptyCtx int func (*emptyCtx) Deadline() (deadline time.Time, ok bool) { return } func (*emptyCtx) Done() <-chan struct{} { return nil } func (*emptyCtx) Err() error { return nil } func (*emptyCtx) Value(key interface{}) interface{} { return nil } func (e *emptyCtx) String() string { switch e { case background: return "context.Background" case todo: return "context.TODO" } return "unknown empty Context" } var ( background = new(emptyCtx) todo = new(emptyCtx) ) // Canceled is the error returned by Context.Err when the context is canceled. var Canceled = errors.New("context canceled") // DeadlineExceeded is the error returned by Context.Err when the context's // deadline passes. var DeadlineExceeded = errors.New("context deadline exceeded") // WithCancel returns a copy of parent with a new Done channel. The returned // context's Done channel is closed when the returned cancel function is called // or when the parent context's Done channel is closed, whichever happens first. // // Canceling this context releases resources associated with it, so code should // call cancel as soon as the operations running in this Context complete. func WithCancel(parent Context) (ctx Context, cancel CancelFunc) { c := newCancelCtx(parent) propagateCancel(parent, c) return c, func() { c.cancel(true, Canceled) } } // newCancelCtx returns an initialized cancelCtx. func newCancelCtx(parent Context) *cancelCtx { return &cancelCtx{ Context: parent, done: make(chan struct{}), } } // propagateCancel arranges for child to be canceled when parent is. func propagateCancel(parent Context, child canceler) { if parent.Done() == nil { return // parent is never canceled } if p, ok := parentCancelCtx(parent); ok { p.mu.Lock() if p.err != nil { // parent has already been canceled child.cancel(false, p.err) } else { if p.children == nil { p.children = make(map[canceler]bool) } p.children[child] = true } p.mu.Unlock() } else { go func() { select { case <-parent.Done(): child.cancel(false, parent.Err()) case <-child.Done(): } }() } } // parentCancelCtx follows a chain of parent references until it finds a // *cancelCtx. This function understands how each of the concrete types in this // package represents its parent. func parentCancelCtx(parent Context) (*cancelCtx, bool) { for { switch c := parent.(type) { case *cancelCtx: return c, true case *timerCtx: return c.cancelCtx, true case *valueCtx: parent = c.Context default: return nil, false } } } // removeChild removes a context from its parent. func removeChild(parent Context, child canceler) { p, ok := parentCancelCtx(parent) if !ok { return } p.mu.Lock() if p.children != nil { delete(p.children, child) } p.mu.Unlock() } // A canceler is a context type that can be canceled directly. The // implementations are *cancelCtx and *timerCtx. type canceler interface { cancel(removeFromParent bool, err error) Done() <-chan struct{} } // A cancelCtx can be canceled. When canceled, it also cancels any children // that implement canceler. type cancelCtx struct { Context done chan struct{} // closed by the first cancel call. mu sync.Mutex children map[canceler]bool // set to nil by the first cancel call err error // set to non-nil by the first cancel call } func (c *cancelCtx) Done() <-chan struct{} { return c.done } func (c *cancelCtx) Err() error { c.mu.Lock() defer c.mu.Unlock() return c.err } func (c *cancelCtx) String() string { return fmt.Sprintf("%v.WithCancel", c.Context) } // cancel closes c.done, cancels each of c's children, and, if // removeFromParent is true, removes c from its parent's children. func (c *cancelCtx) cancel(removeFromParent bool, err error) { if err == nil { panic("context: internal error: missing cancel error") } c.mu.Lock() if c.err != nil { c.mu.Unlock() return // already canceled } c.err = err close(c.done) for child := range c.children { // NOTE: acquiring the child's lock while holding parent's lock. child.cancel(false, err) } c.children = nil c.mu.Unlock() if removeFromParent { removeChild(c.Context, c) } } // WithDeadline returns a copy of the parent context with the deadline adjusted // to be no later than d. If the parent's deadline is already earlier than d, // WithDeadline(parent, d) is semantically equivalent to parent. The returned // context's Done channel is closed when the deadline expires, when the returned // cancel function is called, or when the parent context's Done channel is // closed, whichever happens first. // // Canceling this context releases resources associated with it, so code should // call cancel as soon as the operations running in this Context complete. func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) { if cur, ok := parent.Deadline(); ok && cur.Before(deadline) { // The current deadline is already sooner than the new one. return WithCancel(parent) } c := &timerCtx{ cancelCtx: newCancelCtx(parent), deadline: deadline, } propagateCancel(parent, c) d := deadline.Sub(time.Now()) if d <= 0 { c.cancel(true, DeadlineExceeded) // deadline has already passed return c, func() { c.cancel(true, Canceled) } } c.mu.Lock() defer c.mu.Unlock() if c.err == nil { c.timer = time.AfterFunc(d, func() { c.cancel(true, DeadlineExceeded) }) } return c, func() { c.cancel(true, Canceled) } } // A timerCtx carries a timer and a deadline. It embeds a cancelCtx to // implement Done and Err. It implements cancel by stopping its timer then // delegating to cancelCtx.cancel. type timerCtx struct { *cancelCtx timer *time.Timer // Under cancelCtx.mu. deadline time.Time } func (c *timerCtx) Deadline() (deadline time.Time, ok bool) { return c.deadline, true } func (c *timerCtx) String() string { return fmt.Sprintf("%v.WithDeadline(%s [%s])", c.cancelCtx.Context, c.deadline, c.deadline.Sub(time.Now())) } func (c *timerCtx) cancel(removeFromParent bool, err error) { c.cancelCtx.cancel(false, err) if removeFromParent { // Remove this timerCtx from its parent cancelCtx's children. removeChild(c.cancelCtx.Context, c) } c.mu.Lock() if c.timer != nil { c.timer.Stop() c.timer = nil } c.mu.Unlock() } // WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)). // // Canceling this context releases resources associated with it, so code should // call cancel as soon as the operations running in this Context complete: // // func slowOperationWithTimeout(ctx context.Context) (Result, error) { // ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) // defer cancel() // releases resources if slowOperation completes before timeout elapses // return slowOperation(ctx) // } func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) { return WithDeadline(parent, time.Now().Add(timeout)) } // WithValue returns a copy of parent in which the value associated with key is // val. // // Use context Values only for request-scoped data that transits processes and // APIs, not for passing optional parameters to functions. func WithValue(parent Context, key interface{}, val interface{}) Context { return &valueCtx{parent, key, val} } // A valueCtx carries a key-value pair. It implements Value for that key and // delegates all other calls to the embedded Context. type valueCtx struct { Context key, val interface{} } func (c *valueCtx) String() string { return fmt.Sprintf("%v.WithValue(%#v, %#v)", c.Context, c.key, c.val) } func (c *valueCtx) Value(key interface{}) interface{} { if c.key == key { return c.val } return c.Context.Value(key) }
{ "pile_set_name": "Github" }
#!/usr/bin/env python # Copyright (C) 2015 Dmitry Rodionov # This software may be modified and distributed under the terms # of the MIT license. See the LICENSE file for details. from os import system from lib.core.packages import Package class Macho(Package): """ Mach-O executable analysys package. """ def prepare(self): # Make sure that our target is executable system("/bin/chmod +x \"%s\"" % self.target)
{ "pile_set_name": "Github" }
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package sqs import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/client" "github.com/aws/aws-sdk-go/aws/client/metadata" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/aws/signer/v4" "github.com/aws/aws-sdk-go/private/protocol/query" ) // SQS provides the API operation methods for making requests to // Amazon Simple Queue Service. See this package's package overview docs // for details on the service. // // SQS methods are safe to use concurrently. It is not safe to // modify mutate any of the struct's properties though. type SQS struct { *client.Client } // Used for custom client initialization logic var initClient func(*client.Client) // Used for custom request initialization logic var initRequest func(*request.Request) // Service information constants const ( ServiceName = "sqs" // Name of service. EndpointsID = ServiceName // ID to lookup a service endpoint with. ServiceID = "SQS" // ServiceID is a unique identifier of a specific service. ) // New creates a new instance of the SQS client with a session. // If additional configuration is needed for the client instance use the optional // aws.Config parameter to add your extra config. // // Example: // mySession := session.Must(session.NewSession()) // // // Create a SQS client from just a session. // svc := sqs.New(mySession) // // // Create a SQS client with additional configuration // svc := sqs.New(mySession, aws.NewConfig().WithRegion("us-west-2")) func New(p client.ConfigProvider, cfgs ...*aws.Config) *SQS { c := p.ClientConfig(EndpointsID, cfgs...) return newClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName) } // newClient creates, initializes and returns a new service client instance. func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *SQS { svc := &SQS{ Client: client.New( cfg, metadata.ClientInfo{ ServiceName: ServiceName, ServiceID: ServiceID, SigningName: signingName, SigningRegion: signingRegion, PartitionID: partitionID, Endpoint: endpoint, APIVersion: "2012-11-05", }, handlers, ), } // Handlers svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) svc.Handlers.Build.PushBackNamed(query.BuildHandler) svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) // Run custom client initialization if present if initClient != nil { initClient(svc.Client) } return svc } // newRequest creates a new request for a SQS operation and runs any // custom request initialization. func (c *SQS) newRequest(op *request.Operation, params, data interface{}) *request.Request { req := c.NewRequest(op, params, data) // Run custom request initialization if present if initRequest != nil { initRequest(req) } return req }
{ "pile_set_name": "Github" }
# Generated from 'AppleHelp.h' kAHInternalErr = -10790 kAHInternetConfigPrefErr = -10791 kAHTOCTypeUser = 0 kAHTOCTypeDeveloper = 1
{ "pile_set_name": "Github" }
// // GLProgram.h // CeedGL // // Created by Raphael Sebbe on 01/11/10. // Copyright (c) 2010 Creaceed. All rights reserved. // #import <Foundation/Foundation.h> #import <CeedGL/GLObject.h> @class GLShader; @interface GLProgram : GLObject { NSMutableDictionary *mAttachedShaders; // keys are the types as NSNumbers NSMutableDictionary *mUniformLookup; // {name: location} NSMutableDictionary *mAttribLookup; // {name: location} } + (instancetype)program; - (void)attachShader:(GLShader*)shader; - (void)detachShaderWithType:(GLenum)type; - (GLShader*)attachedShaderWithType:(GLenum)type; // Convenience - (GLShader*)vertexShader; - (GLShader*)fragmentShader; // Linking / Setting / Validate - (BOOL)link:(NSError**)error; - (void)use; - (BOOL)validate:(NSError**)error; // Variable Info (available after link) - (void)bindAttributeLocation:(GLint)loc forName:(NSString*)name; // before linking! - (NSArray*)allAttributeNames; - (BOOL)hasAttributeNamed:(NSString*)name; - (GLint)attributeLocationForName:(NSString*)name; - (NSArray*)allUniformNames; - (BOOL)hasUniformNamed:(NSString*)name; - (GLint)uniformLocationForName:(NSString*)name; @end
{ "pile_set_name": "Github" }
/* * Copyright (c) 2011 Apple Inc. All rights reserved. * * @APPLE_OSREFERENCE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. The rights granted to you under the License * may not be used to create, or enable the creation or redistribution of, * unlawful or unlicensed copies of an Apple operating system, or to * circumvent, violate, or enable the circumvention or violation of, any * terms of an Apple operating system software license agreement. * * Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_OSREFERENCE_LICENSE_HEADER_END@ */ #ifdef KERNEL_PRIVATE #ifndef _MACHINE_CPUID_H #define _MACHINE_CPUID_H #if defined (__arm__) #include <arm/machine_cpuid.h> #elif defined (__arm64__) #include <arm64/machine_cpuid.h> #else #error architecture not supported #endif #endif /* _MACHINE_CPUID_H */ #endif /* KERNEL_PRIVATE */
{ "pile_set_name": "Github" }
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>ip::basic_resolver_iterator::operator *</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="Asio"> <link rel="up" href="../ip__basic_resolver_iterator.html" title="ip::basic_resolver_iterator"> <link rel="prev" href="iterator_category.html" title="ip::basic_resolver_iterator::iterator_category"> <link rel="next" href="operator_not__eq_.html" title="ip::basic_resolver_iterator::operator!="> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr><td valign="top"><img alt="asio C++ library" width="250" height="60" src="../../../asio.png"></td></tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="iterator_category.html"><img src="../../../prev.png" alt="Prev"></a><a accesskey="u" href="../ip__basic_resolver_iterator.html"><img src="../../../up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../home.png" alt="Home"></a><a accesskey="n" href="operator_not__eq_.html"><img src="../../../next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h4 class="title"> <a name="asio.reference.ip__basic_resolver_iterator.operator__star_"></a><a class="link" href="operator__star_.html" title="ip::basic_resolver_iterator::operator *">ip::basic_resolver_iterator::operator *</a> </h4></div></div></div> <p> <a class="indexterm" name="asio.indexterm.ip__basic_resolver_iterator.operator__star_"></a> Dereference an iterator. </p> <pre class="programlisting">const basic_resolver_entry&lt; InternetProtocol &gt; &amp; operator *() const; </pre> </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; 2003-2018 Christopher M. Kohlhoff<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="iterator_category.html"><img src="../../../prev.png" alt="Prev"></a><a accesskey="u" href="../ip__basic_resolver_iterator.html"><img src="../../../up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../home.png" alt="Home"></a><a accesskey="n" href="operator_not__eq_.html"><img src="../../../next.png" alt="Next"></a> </div> </body> </html>
{ "pile_set_name": "Github" }
UPGRADE FROM 0.12 to 0.13 ======================= # Table of Contents - [Rename default_field config](#rename-default_field-config) - [Improve default field resolver](#improve-default-field-resolver) - [Use service tags to register resolver maps](#use-service-tags-to-register-resolver-maps) ### Rename default_field config ```diff overblog_graphql: definitions: - default_resolver: ~ + default_field_resolver: ~ ``` The new `default_field_resolver` config entry accepts callable service id. ### Improve default field resolver Stop using internally `symfony/property-access` package since it was a bottleneck to performance for large schema. Array access and camelize getter/isser are supported but hasser, jQuery style (e.g. `last()`) and "can" property accessors are no more supported out-of-the-box, please implement a custom resolver if these accessors are needed. Globally: ```yaml overblog_graphql: definitions: default_field_resolver: 'App\GraphQL\CustomResolver' ``` [see default field resolver for more details](https://webonyx.github.io/graphql-php/data-fetching/#default-field-resolver) Per Type: ```yaml MyType: type: object config: resolveField: 'App\GraphQL\MyTypeResolver::defaultFieldResolver' fields: name: {type: String} email: {type: String} ``` [see default Field Resolver per type for more details](https://webonyx.github.io/graphql-php/data-fetching/#default-field-resolver-per-type) ### Use service tags to register resolver maps The resolver maps used to be configured using the `overblog_graphql.definitions.schema.resolver_maps` option. This has been deprecated in favour of using service tags to register them. ```diff # config/graphql.yaml overblog_graphql: definitions: schema: # ... - resolver_maps: - - 'App\GraphQL\MyResolverMap' ``` ```diff # services/graphql.yaml services: - App\GraphQL\MyResolverMap: ~ + App\GraphQL\MyResolverMap: + tags: + - { name: overblog_graphql.resolver_map, schema: default } ```
{ "pile_set_name": "Github" }
# SPDX-License-Identifier: GPL-2.0-only config CODA_FS tristate "Coda file system support (advanced network fs)" depends on INET help Coda is an advanced network file system, similar to NFS in that it enables you to mount file systems of a remote server and access them with regular Unix commands as if they were sitting on your hard disk. Coda has several advantages over NFS: support for disconnected operation (e.g. for laptops), read/write server replication, security model for authentication and encryption, persistent client caches and write back caching. If you say Y here, your Linux box will be able to act as a Coda *client*. You will need user level code as well, both for the client and server. Servers are currently user level, i.e. they need no kernel support. Please read <file:Documentation/filesystems/coda.txt> and check out the Coda home page <http://www.coda.cs.cmu.edu/>. To compile the coda client support as a module, choose M here: the module will be called coda.
{ "pile_set_name": "Github" }
#!/bin/bash cd $SRC_DIR/bin binaries="\ gustaf \ gustaf_mate_joining \ " mkdir -p $PREFIX/bin for i in $binaries; do cp $SRC_DIR/bin/$i $PREFIX/bin/$i && chmod a+x $PREFIX/bin/$i; done
{ "pile_set_name": "Github" }
package com.moti.controller; import com.moti.entity.FileFolder; import com.moti.entity.FileStoreStatistics; import com.moti.entity.MyFile; import com.moti.utils.LogUtils; import org.slf4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; /** * @ClassName: SystemController * @Description: 系统页面跳转控制器 * @author: xw * @date 2020/2/25 22:02 * @Version: 1.0 **/ @Controller public class SystemController extends BaseController { Logger logger = LogUtils.getInstance(SystemController.class); /** * @return java.lang.String * @Description 前往我的网盘 * @Author xw * @Date 23:28 2020/2/10 * @Param [fId, fName, error, map] **/ @GetMapping("/files") public String toFileStorePage(Integer fId, String fName, Integer error, Map<String, Object> map) { //判断是否包含错误信息 if (error != null) { if (error == 1) { map.put("error", "添加失败!当前已存在同名文件夹"); } if (error == 2) { map.put("error", "重命名失败!文件夹已存在"); } } //包含的子文件夹 List<FileFolder> folders = null; //包含的文件 List<MyFile> files = null; //当前文件夹信息 FileFolder nowFolder = null; //当前文件夹的相对路径 List<FileFolder> location = new ArrayList<>(); if (fId == null || fId <= 0) { //代表当前为根目录 fId = 0; folders = fileFolderService.getRootFoldersByFileStoreId(loginUser.getFileStoreId()); files = myFileService.getRootFilesByFileStoreId(loginUser.getFileStoreId()); nowFolder = FileFolder.builder().fileFolderId(fId).build(); location.add(nowFolder); } else { //当前为具体目录,访问的文件夹不是当前登录用户所创建的文件夹 FileFolder folder = fileFolderService.getFileFolderByFileFolderId(fId); if (folder.getFileStoreId() - loginUser.getFileStoreId() != 0){ return "redirect:/error401Page"; } //当前为具体目录,访问的文件夹是当前登录用户所创建的文件夹 folders = fileFolderService.getFileFolderByParentFolderId(fId); files = myFileService.getFilesByParentFolderId(fId); nowFolder = fileFolderService.getFileFolderByFileFolderId(fId); //遍历查询当前目录 FileFolder temp = nowFolder; while (temp.getParentFolderId() != 0) { temp = fileFolderService.getFileFolderByFileFolderId(temp.getParentFolderId()); location.add(temp); } } Collections.reverse(location); //获得统计信息 FileStoreStatistics statistics = myFileService.getCountStatistics(loginUser.getFileStoreId()); map.put("statistics", statistics); map.put("permission", fileStoreService.getFileStoreByUserId(loginUser.getUserId()).getPermission()); map.put("folders", folders); map.put("files", files); map.put("nowFolder", nowFolder); map.put("location", location); logger.info("网盘页面域中的数据:" + map); return "u-admin/files"; } /** * @Description 前往文件上传页面 * @Author xw * @Date 15:16 2020/2/26 * @Param [fId, fName, map] * @return java.lang.String **/ @GetMapping("/upload") public String toUploadPage(Integer fId, String fName, Map<String, Object> map) { //包含的子文件夹 List<FileFolder> folders = null; //当前文件夹信息 FileFolder nowFolder = null; //当前文件夹的相对路径 List<FileFolder> location = new ArrayList<>(); if (fId == null || fId <= 0) { //代表当前为根目录 fId = 0; folders = fileFolderService.getRootFoldersByFileStoreId(loginUser.getFileStoreId()); nowFolder = FileFolder.builder().fileFolderId(fId).build(); location.add(nowFolder); } else { //当前为具体目录 folders = fileFolderService.getFileFolderByParentFolderId(fId); nowFolder = fileFolderService.getFileFolderByFileFolderId(fId); //遍历查询当前目录 FileFolder temp = nowFolder; while (temp.getParentFolderId() != 0) { temp = fileFolderService.getFileFolderByFileFolderId(temp.getParentFolderId()); location.add(temp); } } Collections.reverse(location); //获得统计信息 FileStoreStatistics statistics = myFileService.getCountStatistics(loginUser.getFileStoreId()); map.put("statistics", statistics); map.put("folders", folders); map.put("nowFolder", nowFolder); map.put("location", location); logger.info("网盘页面域中的数据:" + map); return "u-admin/upload"; } /** * @Description 前往所有文档页面 * @Author xw * @Date 10:26 2020/2/26 * @Param [map] * @return java.lang.String **/ @GetMapping("/doc-files") public String toDocFilePage( Map<String, Object> map) { List<MyFile> files = myFileService.getFilesByType(loginUser.getFileStoreId(),1); //获得统计信息 FileStoreStatistics statistics = myFileService.getCountStatistics(loginUser.getFileStoreId()); map.put("statistics", statistics); map.put("files", files); map.put("permission", fileStoreService.getFileStoreByUserId(loginUser.getUserId()).getPermission()); return "u-admin/doc-files"; } /** * @Description 前往所有图像页面 * @Author xw * @Date 10:26 2020/2/26 * @Param [map] * @return java.lang.String **/ @GetMapping("/image-files") public String toImageFilePage( Map<String, Object> map) { List<MyFile> files = myFileService.getFilesByType(loginUser.getFileStoreId(),2); //获得统计信息 FileStoreStatistics statistics = myFileService.getCountStatistics(loginUser.getFileStoreId()); map.put("statistics", statistics); map.put("files", files); map.put("permission", fileStoreService.getFileStoreByUserId(loginUser.getUserId()).getPermission()); return "u-admin/image-files"; } /** * @Description 前往所有视频页面 * @Author xw * @Date 10:26 2020/2/26 * @Param [map] * @return java.lang.String **/ @GetMapping("/video-files") public String toVideoFilePage( Map<String, Object> map) { List<MyFile> files = myFileService.getFilesByType(loginUser.getFileStoreId(),3); //获得统计信息 FileStoreStatistics statistics = myFileService.getCountStatistics(loginUser.getFileStoreId()); map.put("statistics", statistics); map.put("files", files); map.put("permission", fileStoreService.getFileStoreByUserId(loginUser.getUserId()).getPermission()); return "u-admin/video-files"; } /** * @Description 前往所有音频页面 * @Author xw * @Date 10:26 2020/2/26 * @Param [map] * @return java.lang.String **/ @GetMapping("/music-files") public String toMusicFilePage( Map<String, Object> map) { List<MyFile> files = myFileService.getFilesByType(loginUser.getFileStoreId(),4); //获得统计信息 FileStoreStatistics statistics = myFileService.getCountStatistics(loginUser.getFileStoreId()); map.put("statistics", statistics); map.put("files", files); map.put("permission", fileStoreService.getFileStoreByUserId(loginUser.getUserId()).getPermission()); return "u-admin/music-files"; } /** * @Description 前往其他文件页面 * @Author xw * @Date 10:26 2020/2/26 * @Param [map] * @return java.lang.String **/ @GetMapping("/other-files") public String toOtherFilePage( Map<String, Object> map) { List<MyFile> files = myFileService.getFilesByType(loginUser.getFileStoreId(),5); //获得统计信息 FileStoreStatistics statistics = myFileService.getCountStatistics(loginUser.getFileStoreId()); map.put("statistics", statistics); map.put("files", files); map.put("permission", fileStoreService.getFileStoreByUserId(loginUser.getUserId()).getPermission()); return "u-admin/other-files"; } /** * @Description 登录之后的用户主页 * @Author xw * @Date 10:28 2020/2/26 * @Param [map] * @return java.lang.String **/ @GetMapping("/index") public String index(Map<String, Object> map) { //获得统计信息 FileStoreStatistics statistics = myFileService.getCountStatistics(loginUser.getFileStoreId()); statistics.setFileStore(fileStoreService.getFileStoreById(loginUser.getFileStoreId())); map.put("statistics", statistics); return "u-admin/index"; } /** * @Description 前往帮助页面 * @Author xw * @Date 15:17 2020/2/26 * @Param [map] * @return java.lang.String **/ @GetMapping("/help") public String helpPage(Map<String, Object> map) { //获得统计信息 FileStoreStatistics statistics = myFileService.getCountStatistics(loginUser.getFileStoreId()); map.put("statistics", statistics); return "u-admin/help"; } }
{ "pile_set_name": "Github" }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Threading; using System.Threading.Tasks; using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.Dialogs; using Microsoft.Bot.Schema; namespace Microsoft.BotBuilderSamples { public class LogoutDialog : ComponentDialog { public LogoutDialog(string id, string connectionName) : base(id) { ConnectionName = connectionName; } protected string ConnectionName { get; } protected override async Task<DialogTurnResult> OnBeginDialogAsync(DialogContext innerDc, object options, CancellationToken cancellationToken = default(CancellationToken)) { var result = await InterruptAsync(innerDc, cancellationToken); if (result != null) { return result; } return await base.OnBeginDialogAsync(innerDc, options, cancellationToken); } protected override async Task<DialogTurnResult> OnContinueDialogAsync(DialogContext innerDc, CancellationToken cancellationToken = default(CancellationToken)) { var result = await InterruptAsync(innerDc, cancellationToken); if (result != null) { return result; } return await base.OnContinueDialogAsync(innerDc, cancellationToken); } private async Task<DialogTurnResult> InterruptAsync(DialogContext innerDc, CancellationToken cancellationToken = default(CancellationToken)) { if (innerDc.Context.Activity.Type == ActivityTypes.Message) { var text = innerDc.Context.Activity.Text.ToLowerInvariant(); // Allow logout anywhere in the command if (text.IndexOf("logout") >= 0) { // The bot adapter encapsulates the authentication processes. var botAdapter = (BotFrameworkAdapter)innerDc.Context.Adapter; await botAdapter.SignOutUserAsync(innerDc.Context, ConnectionName, null, cancellationToken); await innerDc.Context.SendActivityAsync(MessageFactory.Text("You have been signed out."), cancellationToken); return await innerDc.CancelAllDialogsAsync(cancellationToken); } } return null; } } }
{ "pile_set_name": "Github" }
// Copyright 2009 the Sputnik authors. All rights reserved. /** * Since applying the "call" method to Function constructor themself leads to creating a new function instance, the second argument must be a valid function body * * @path ch15/15.3/S15.3_A2_T1.js * @description Checking if executing "Function.call(this, "var x / = 1;")" fails */ //CHECK# try{ Function.call(this, "var x / = 1;"); } catch(e){ if (!(e instanceof SyntaxError)) { $ERROR('#1: function body must be valid'); } }
{ "pile_set_name": "Github" }
<?php /** * @package Joomla.Platform * @subpackage Language * * @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved. * @copyright Copyright (C) 2005 Richard Heyes (http://www.phpguru.org/). All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ defined('JPATH_PLATFORM') or die; /** * Porter English stemmer class. * * This class was adapted from one written by Richard Heyes. * See copyright and link information above. * * @package Joomla.Platform * @subpackage Language * @since 12.1 */ class JLanguageStemmerPorteren extends JLanguageStemmer { /** * Regex for matching a consonant. * * @var string * @since 12.1 */ private static $_regex_consonant = '(?:[bcdfghjklmnpqrstvwxz]|(?<=[aeiou])y|^y)'; /** * Regex for matching a vowel * @var string * @since 12.1 */ private static $_regex_vowel = '(?:[aeiou]|(?<![aeiou])y)'; /** * Method to stem a token and return the root. * * @param string $token The token to stem. * @param string $lang The language of the token. * * @return string The root token. * * @since 12.1 */ public function stem($token, $lang) { // Check if the token is long enough to merit stemming. if (strlen($token) <= 2) { return $token; } // Check if the language is English or All. if ($lang !== 'en') { return $token; } // Stem the token if it is not in the cache. if (!isset($this->cache[$lang][$token])) { // Stem the token. $result = $token; $result = self::_step1ab($result); $result = self::_step1c($result); $result = self::_step2($result); $result = self::_step3($result); $result = self::_step4($result); $result = self::_step5($result); // Add the token to the cache. $this->cache[$lang][$token] = $result; } return $this->cache[$lang][$token]; } /** * Step 1 * * @param string $word The token to stem. * * @return string * * @since 12.1 */ private static function _step1ab($word) { // Part a if (substr($word, -1) == 's') { self::_replace($word, 'sses', 'ss') or self::_replace($word, 'ies', 'i') or self::_replace($word, 'ss', 'ss') or self::_replace($word, 's', ''); } // Part b if (substr($word, -2, 1) != 'e' or !self::_replace($word, 'eed', 'ee', 0)) { // First rule $v = self::$_regex_vowel; // Check ing and ed // Note use of && and OR, for precedence reasons if (preg_match("#$v+#", substr($word, 0, -3)) && self::_replace($word, 'ing', '') or preg_match("#$v+#", substr($word, 0, -2)) && self::_replace($word, 'ed', '')) { // If one of above two test successful if (!self::_replace($word, 'at', 'ate') and !self::_replace($word, 'bl', 'ble') and !self::_replace($word, 'iz', 'ize')) { // Double consonant ending if (self::_doubleConsonant($word) and substr($word, -2) != 'll' and substr($word, -2) != 'ss' and substr($word, -2) != 'zz') { $word = substr($word, 0, -1); } elseif (self::_m($word) == 1 and self::_cvc($word)) { $word .= 'e'; } } } } return $word; } /** * Step 1c * * @param string $word The token to stem. * * @return string * * @since 12.1 */ private static function _step1c($word) { $v = self::$_regex_vowel; if (substr($word, -1) == 'y' && preg_match("#$v+#", substr($word, 0, -1))) { self::_replace($word, 'y', 'i'); } return $word; } /** * Step 2 * * @param string $word The token to stem. * * @return string * * @since 12.1 */ private static function _step2($word) { switch (substr($word, -2, 1)) { case 'a': self::_replace($word, 'ational', 'ate', 0) or self::_replace($word, 'tional', 'tion', 0); break; case 'c': self::_replace($word, 'enci', 'ence', 0) or self::_replace($word, 'anci', 'ance', 0); break; case 'e': self::_replace($word, 'izer', 'ize', 0); break; case 'g': self::_replace($word, 'logi', 'log', 0); break; case 'l': self::_replace($word, 'entli', 'ent', 0) or self::_replace($word, 'ousli', 'ous', 0) or self::_replace($word, 'alli', 'al', 0) or self::_replace($word, 'bli', 'ble', 0) or self::_replace($word, 'eli', 'e', 0); break; case 'o': self::_replace($word, 'ization', 'ize', 0) or self::_replace($word, 'ation', 'ate', 0) or self::_replace($word, 'ator', 'ate', 0); break; case 's': self::_replace($word, 'iveness', 'ive', 0) or self::_replace($word, 'fulness', 'ful', 0) or self::_replace($word, 'ousness', 'ous', 0) or self::_replace($word, 'alism', 'al', 0); break; case 't': self::_replace($word, 'biliti', 'ble', 0) or self::_replace($word, 'aliti', 'al', 0) or self::_replace($word, 'iviti', 'ive', 0); break; } return $word; } /** * Step 3 * * @param string $word The token to stem. * * @return string * * @since 12.1 */ private static function _step3($word) { switch (substr($word, -2, 1)) { case 'a': self::_replace($word, 'ical', 'ic', 0); break; case 's': self::_replace($word, 'ness', '', 0); break; case 't': self::_replace($word, 'icate', 'ic', 0) or self::_replace($word, 'iciti', 'ic', 0); break; case 'u': self::_replace($word, 'ful', '', 0); break; case 'v': self::_replace($word, 'ative', '', 0); break; case 'z': self::_replace($word, 'alize', 'al', 0); break; } return $word; } /** * Step 4 * * @param string $word The token to stem. * * @return string * * @since 12.1 */ private static function _step4($word) { switch (substr($word, -2, 1)) { case 'a': self::_replace($word, 'al', '', 1); break; case 'c': self::_replace($word, 'ance', '', 1) or self::_replace($word, 'ence', '', 1); break; case 'e': self::_replace($word, 'er', '', 1); break; case 'i': self::_replace($word, 'ic', '', 1); break; case 'l': self::_replace($word, 'able', '', 1) or self::_replace($word, 'ible', '', 1); break; case 'n': self::_replace($word, 'ant', '', 1) or self::_replace($word, 'ement', '', 1) or self::_replace($word, 'ment', '', 1) or self::_replace($word, 'ent', '', 1); break; case 'o': if (substr($word, -4) == 'tion' or substr($word, -4) == 'sion') { self::_replace($word, 'ion', '', 1); } else { self::_replace($word, 'ou', '', 1); } break; case 's': self::_replace($word, 'ism', '', 1); break; case 't': self::_replace($word, 'ate', '', 1) or self::_replace($word, 'iti', '', 1); break; case 'u': self::_replace($word, 'ous', '', 1); break; case 'v': self::_replace($word, 'ive', '', 1); break; case 'z': self::_replace($word, 'ize', '', 1); break; } return $word; } /** * Step 5 * * @param string $word The token to stem. * * @return string * * @since 12.1 */ private static function _step5($word) { // Part a if (substr($word, -1) == 'e') { if (self::_m(substr($word, 0, -1)) > 1) { self::_replace($word, 'e', ''); } elseif (self::_m(substr($word, 0, -1)) == 1) { if (!self::_cvc(substr($word, 0, -1))) { self::_replace($word, 'e', ''); } } } // Part b if (self::_m($word) > 1 and self::_doubleConsonant($word) and substr($word, -1) == 'l') { $word = substr($word, 0, -1); } return $word; } /** * Replaces the first string with the second, at the end of the string. If third * arg is given, then the preceding string must match that m count at least. * * @param string &$str String to check * @param string $check Ending to check for * @param string $repl Replacement string * @param integer $m Optional minimum number of m() to meet * * @return boolean Whether the $check string was at the end * of the $str string. True does not necessarily mean * that it was replaced. * * @since 12.1 */ private static function _replace(&$str, $check, $repl, $m = null) { $len = 0 - strlen($check); if (substr($str, $len) == $check) { $substr = substr($str, 0, $len); if (is_null($m) or self::_m($substr) > $m) { $str = $substr . $repl; } return true; } return false; } /** * m() measures the number of consonant sequences in $str. if c is * a consonant sequence and v a vowel sequence, and <..> indicates arbitrary * presence, * * <c><v> gives 0 * <c>vc<v> gives 1 * <c>vcvc<v> gives 2 * <c>vcvcvc<v> gives 3 * * @param string $str The string to return the m count for * * @return integer The m count * * @since 12.1 */ private static function _m($str) { $c = self::$_regex_consonant; $v = self::$_regex_vowel; $str = preg_replace("#^$c+#", '', $str); $str = preg_replace("#$v+$#", '', $str); preg_match_all("#($v+$c+)#", $str, $matches); return count($matches[1]); } /** * Returns true/false as to whether the given string contains two * of the same consonant next to each other at the end of the string. * * @param string $str String to check * * @return boolean Result * * @since 12.1 */ private static function _doubleConsonant($str) { $c = self::$_regex_consonant; return preg_match("#$c{2}$#", $str, $matches) and $matches[0]{0} == $matches[0]{1}; } /** * Checks for ending CVC sequence where second C is not W, X or Y * * @param string $str String to check * * @return boolean Result * * @since 12.1 */ private static function _cvc($str) { $c = self::$_regex_consonant; $v = self::$_regex_vowel; $result = preg_match("#($c$v$c)$#", $str, $matches) and strlen($matches[1]) == 3 and $matches[1]{2} != 'w' and $matches[1]{2} != 'x' and $matches[1]{2} != 'y'; return $result; } }
{ "pile_set_name": "Github" }
package com.itcast.day03 /** * ClassName:`14.多态` * 多态特点:通过父类接收 执行的是子类的方法 */ fun main(args: Array<String>) { //创建狗和猫的对象 val dog: Animal = Dog() val cat = Cat() dog.call() // cat.call() } //动物 abstract class Animal { var color: String = "" //行为 open fun call() { println("动物叫") } } //狗 class Dog : Animal() { override fun call() { println("狗汪汪叫") } } //猫 class Cat : Animal() { override fun call() { println("猫喵喵叫") } }
{ "pile_set_name": "Github" }
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef BASE_TASK_THREAD_POOL_THREAD_GROUP_IMPL_H_ #define BASE_TASK_THREAD_POOL_THREAD_GROUP_IMPL_H_ #include <stddef.h> #include <memory> #include <string> #include <vector> #include "base/base_export.h" #include "base/compiler_specific.h" #include "base/containers/stack.h" #include "base/gtest_prod_util.h" #include "base/logging.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/optional.h" #include "base/sequenced_task_runner.h" #include "base/strings/string_piece.h" #include "base/synchronization/condition_variable.h" #include "base/synchronization/waitable_event.h" #include "base/task/thread_pool/task.h" #include "base/task/thread_pool/task_source.h" #include "base/task/thread_pool/thread_group.h" #include "base/task/thread_pool/tracked_ref.h" #include "base/task/thread_pool/worker_thread.h" #include "base/task/thread_pool/worker_thread_stack.h" #include "base/time/time.h" namespace base { class HistogramBase; class WorkerThreadObserver; namespace internal { class TaskTracker; // A group of workers that run Tasks. // // The thread group doesn't create threads until Start() is called. Tasks can be // posted at any time but will not run until after Start() is called. // // This class is thread-safe. class BASE_EXPORT ThreadGroupImpl : public ThreadGroup { public: // Constructs a group without workers. // // |histogram_label| is used to label the thread group's histograms as // "ThreadPool." + histogram_name + "." + |histogram_label| + extra suffixes. // It must not be empty. |thread group_label| is used to label the thread // group's threads, it must not be empty. |priority_hint| is the preferred // thread priority; the actual thread priority depends on shutdown state and // platform capabilities. |task_tracker| keeps track of tasks. ThreadGroupImpl(StringPiece histogram_label, StringPiece thread_group_label, ThreadPriority priority_hint, TrackedRef<TaskTracker> task_tracker, TrackedRef<Delegate> delegate); // Creates threads, allowing existing and future tasks to run. The thread // group runs at most |max_tasks| / |max_best_effort_tasks| unblocked task // with any / BEST_EFFORT priority concurrently. It reclaims unused threads // after |suggested_reclaim_time|. It uses |service_thread_task_runner| to // monitor for blocked tasks. If specified, it notifies // |worker_thread_observer| when a worker enters and exits its main function // (the observer must not be destroyed before JoinForTesting() has returned). // |worker_environment| specifies the environment in which tasks are executed. // |may_block_threshold| is the timeout after which a task in a MAY_BLOCK // ScopedBlockingCall is considered blocked (the thread group will choose an // appropriate value if none is specified). Can only be called once. CHECKs on // failure. void Start(int max_tasks, int max_best_effort_tasks, TimeDelta suggested_reclaim_time, scoped_refptr<SequencedTaskRunner> service_thread_task_runner, WorkerThreadObserver* worker_thread_observer, WorkerEnvironment worker_environment, Optional<TimeDelta> may_block_threshold = Optional<TimeDelta>()); // Destroying a ThreadGroupImpl returned by Create() is not allowed in // production; it is always leaked. In tests, it can only be destroyed after // JoinForTesting() has returned. ~ThreadGroupImpl() override; // ThreadGroup: void JoinForTesting() override; size_t GetMaxConcurrentNonBlockedTasksDeprecated() const override; void ReportHeartbeatMetrics() const override; void DidUpdateCanRunPolicy() override; const HistogramBase* num_tasks_before_detach_histogram() const { return num_tasks_before_detach_histogram_; } // Waits until at least |n| workers are idle. Note that while workers are // disallowed from cleaning up during this call: tests using a custom // |suggested_reclaim_time_| need to be careful to invoke this swiftly after // unblocking the waited upon workers as: if a worker is already detached by // the time this is invoked, it will never make it onto the idle stack and // this call will hang. void WaitForWorkersIdleForTesting(size_t n); // Waits until at least |n| workers are idle. void WaitForWorkersIdleLockRequiredForTesting(size_t n) EXCLUSIVE_LOCKS_REQUIRED(lock_); // Waits until all workers are idle. void WaitForAllWorkersIdleForTesting(); // Waits until |n| workers have cleaned up (went through // WorkerThreadDelegateImpl::OnMainExit()) since the last call to // WaitForWorkersCleanedUpForTesting() (or Start() if that wasn't called yet). void WaitForWorkersCleanedUpForTesting(size_t n); // Returns the number of workers in this thread group. size_t NumberOfWorkersForTesting() const; // Returns |max_tasks_|. size_t GetMaxTasksForTesting() const; // Returns the number of workers that are idle (i.e. not running tasks). size_t NumberOfIdleWorkersForTesting() const; private: class ScopedCommandsExecutor; class WorkerThreadDelegateImpl; // Friend tests so that they can access |blocked_workers_poll_period| and // may_block_threshold(). friend class ThreadGroupImplBlockingTest; friend class ThreadGroupImplMayBlockTest; FRIEND_TEST_ALL_PREFIXES(ThreadGroupImplBlockingTest, ThreadBlockUnblockPremature); // ThreadGroup: void UpdateSortKey(TaskSource::Transaction transaction) override; void PushTaskSourceAndWakeUpWorkers( TransactionWithRegisteredTaskSource transaction_with_task_source) override; void EnsureEnoughWorkersLockRequired(BaseScopedCommandsExecutor* executor) override EXCLUSIVE_LOCKS_REQUIRED(lock_); // Creates a worker and schedules its start, if needed, to maintain one idle // worker, |max_tasks_| permitting. void MaintainAtLeastOneIdleWorkerLockRequired( ScopedCommandsExecutor* executor) EXCLUSIVE_LOCKS_REQUIRED(lock_); // Returns true if worker cleanup is permitted. bool CanWorkerCleanupForTestingLockRequired() EXCLUSIVE_LOCKS_REQUIRED(lock_); // Creates a worker, adds it to the thread group, schedules its start and // returns it. Cannot be called before Start(). scoped_refptr<WorkerThread> CreateAndRegisterWorkerLockRequired( ScopedCommandsExecutor* executor) EXCLUSIVE_LOCKS_REQUIRED(lock_); // Returns the number of workers that are awake (i.e. not on the idle stack). size_t GetNumAwakeWorkersLockRequired() const EXCLUSIVE_LOCKS_REQUIRED(lock_); // Returns the desired number of awake workers, given current workload and // concurrency limits. size_t GetDesiredNumAwakeWorkersLockRequired() const EXCLUSIVE_LOCKS_REQUIRED(lock_); // Examines the list of WorkerThreads and increments |max_tasks_| for each // worker that has been within the scope of a MAY_BLOCK ScopedBlockingCall for // more than BlockedThreshold(). Reschedules a call if necessary. void AdjustMaxTasks(); // Returns the threshold after which the max tasks is increased to compensate // for a worker that is within a MAY_BLOCK ScopedBlockingCall. TimeDelta may_block_threshold_for_testing() const { return after_start().may_block_threshold; } // Interval at which the service thread checks for workers in this thread // group that have been in a MAY_BLOCK ScopedBlockingCall for more than // may_block_threshold(). TimeDelta blocked_workers_poll_period_for_testing() const { return after_start().blocked_workers_poll_period; } // Starts calling AdjustMaxTasks() periodically on // |service_thread_task_runner_|. void ScheduleAdjustMaxTasks(); // Schedules AdjustMaxTasks() through |executor| if required. void MaybeScheduleAdjustMaxTasksLockRequired(ScopedCommandsExecutor* executor) EXCLUSIVE_LOCKS_REQUIRED(lock_); // Returns true if AdjustMaxTasks() should periodically be called on // |service_thread_task_runner_|. bool ShouldPeriodicallyAdjustMaxTasksLockRequired() EXCLUSIVE_LOCKS_REQUIRED(lock_); // Updates the minimum priority allowed to run below which tasks should yield. // This should be called whenever |num_running_tasks_| or |max_tasks| changes, // or when a new task is added to |priority_queue_|. void UpdateMinAllowedPriorityLockRequired() EXCLUSIVE_LOCKS_REQUIRED(lock_); // Increments/decrements the number of tasks of |priority| that are currently // running in this thread group. Must be invoked before/after running a task. void DecrementTasksRunningLockRequired(TaskPriority priority) EXCLUSIVE_LOCKS_REQUIRED(lock_); void IncrementTasksRunningLockRequired(TaskPriority priority) EXCLUSIVE_LOCKS_REQUIRED(lock_); // Increments/decrements the number of tasks that can run in this thread // group. May only be called in a scope where a task is running with // |priority|. void DecrementMaxTasksLockRequired(TaskPriority priority) EXCLUSIVE_LOCKS_REQUIRED(lock_); void IncrementMaxTasksLockRequired(TaskPriority priority) EXCLUSIVE_LOCKS_REQUIRED(lock_); // Values set at Start() and never modified afterwards. struct InitializedInStart { InitializedInStart(); ~InitializedInStart(); #if DCHECK_IS_ON() // Set after all members of this struct are set. bool initialized = false; #endif // Initial value of |max_tasks_|. size_t initial_max_tasks = 0; // Suggested reclaim time for workers. TimeDelta suggested_reclaim_time; // Environment to be initialized per worker. WorkerEnvironment worker_environment = WorkerEnvironment::NONE; scoped_refptr<SequencedTaskRunner> service_thread_task_runner; // Optional observer notified when a worker enters and exits its main. WorkerThreadObserver* worker_thread_observer = nullptr; bool may_block_without_delay; bool fixed_max_best_effort_tasks; // Threshold after which the max tasks is increased to compensate for a // worker that is within a MAY_BLOCK ScopedBlockingCall. TimeDelta may_block_threshold; // The period between calls to AdjustMaxTasks() when the thread group is at // capacity. TimeDelta blocked_workers_poll_period; } initialized_in_start_; InitializedInStart& in_start() { #if DCHECK_IS_ON() DCHECK(!initialized_in_start_.initialized); #endif return initialized_in_start_; } const InitializedInStart& after_start() const { #if DCHECK_IS_ON() DCHECK(initialized_in_start_.initialized); #endif return initialized_in_start_; } const std::string thread_group_label_; const ThreadPriority priority_hint_; // All workers owned by this thread group. std::vector<scoped_refptr<WorkerThread>> workers_ GUARDED_BY(lock_); // Maximum number of tasks of any priority / BEST_EFFORT priority that can run // concurrently in this thread group. size_t max_tasks_ GUARDED_BY(lock_) = 0; size_t max_best_effort_tasks_ GUARDED_BY(lock_) = 0; // Number of tasks of any priority / BEST_EFFORT priority that are currently // running in this thread group. size_t num_running_tasks_ GUARDED_BY(lock_) = 0; size_t num_running_best_effort_tasks_ GUARDED_BY(lock_) = 0; // Number of workers running a task of any priority / BEST_EFFORT priority // that are within the scope of a MAY_BLOCK ScopedBlockingCall but haven't // caused a max tasks increase yet. int num_unresolved_may_block_ GUARDED_BY(lock_) = 0; int num_unresolved_best_effort_may_block_ GUARDED_BY(lock_) = 0; // Stack of idle workers. Initially, all workers are on this stack. A worker // is removed from the stack before its WakeUp() function is called and when // it receives work from GetWork() (a worker calls GetWork() when its sleep // timeout expires, even if its WakeUp() method hasn't been called). A worker // is pushed on this stack when it receives nullptr from GetWork(). WorkerThreadStack idle_workers_stack_ GUARDED_BY(lock_); // Signaled when a worker is added to the idle workers stack. std::unique_ptr<ConditionVariable> idle_workers_stack_cv_for_testing_ GUARDED_BY(lock_); // Stack that contains the timestamps of when workers get cleaned up. // Timestamps get popped off the stack as new workers are added. base::stack<TimeTicks, std::vector<TimeTicks>> cleanup_timestamps_ GUARDED_BY(lock_); // Whether an AdjustMaxTasks() task was posted to the service thread. bool adjust_max_tasks_posted_ GUARDED_BY(lock_) = false; // Indicates to the delegates that workers are not permitted to cleanup. bool worker_cleanup_disallowed_for_testing_ GUARDED_BY(lock_) = false; // Counts the number of workers cleaned up (went through // WorkerThreadDelegateImpl::OnMainExit()) since the last call to // WaitForWorkersCleanedUpForTesting() (or Start() if that wasn't called yet). // |some_workers_cleaned_up_for_testing_| is true if this was ever // incremented. Tests with a custom |suggested_reclaim_time_| can wait on a // specific number of workers being cleaned up via // WaitForWorkersCleanedUpForTesting(). size_t num_workers_cleaned_up_for_testing_ GUARDED_BY(lock_) = 0; #if DCHECK_IS_ON() bool some_workers_cleaned_up_for_testing_ GUARDED_BY(lock_) = false; #endif // Signaled, if non-null, when |num_workers_cleaned_up_for_testing_| is // incremented. std::unique_ptr<ConditionVariable> num_workers_cleaned_up_for_testing_cv_ GUARDED_BY(lock_); // Set at the start of JoinForTesting(). bool join_for_testing_started_ GUARDED_BY(lock_) = false; // Cached HistogramBase pointers, can be accessed without // holding |lock_|. If |lock_| is held, add new samples using // ThreadGroupImpl::ScopedCommandsExecutor (increase // |scheduled_histogram_samples_| size as needed) to defer until after |lock_| // release, due to metrics system callbacks which may schedule tasks. // ThreadPool.DetachDuration.[thread group name] histogram. Intentionally // leaked. HistogramBase* const detach_duration_histogram_; // ThreadPool.NumTasksBeforeDetach.[thread group name] histogram. // Intentionally leaked. HistogramBase* const num_tasks_before_detach_histogram_; // ThreadPool.NumWorkers.[thread group name] histogram. // Intentionally leaked. HistogramBase* const num_workers_histogram_; // ThreadPool.NumActiveWorkers.[thread group name] histogram. // Intentionally leaked. HistogramBase* const num_active_workers_histogram_; // Ensures recently cleaned up workers (ref. // WorkerThreadDelegateImpl::CleanupLockRequired()) had time to exit as // they have a raw reference to |this| (and to TaskTracker) which can // otherwise result in racy use-after-frees per no longer being part of // |workers_| and hence not being explicitly joined in JoinForTesting(): // https://crbug.com/810464. Uses AtomicRefCount to make its only public // method thread-safe. TrackedRefFactory<ThreadGroupImpl> tracked_ref_factory_; DISALLOW_COPY_AND_ASSIGN(ThreadGroupImpl); }; } // namespace internal } // namespace base #endif // BASE_TASK_THREAD_POOL_THREAD_GROUP_IMPL_H_
{ "pile_set_name": "Github" }
(ns quo.react (:refer-clojure :exclude [ref]) (:require [oops.core :refer [oget oset!]] ["react" :as react]) (:require-macros [quo.react :refer [with-deps-check maybe-js-deps]])) (def create-ref react/createRef) (defn current-ref [ref] (oget ref "current")) ;; Inspired from UIX, Rum and Rumext (defn set-ref-val! [ref val] (oset! ref "current" val) val) (deftype StateHook [value set-value] cljs.core/IHash (-hash [o] (goog/getUid o)) cljs.core/IDeref (-deref [o] value) cljs.core/IReset (-reset! [o new-value] (set-value new-value)) cljs.core/ISwap (-swap! [o f] (set-value f)) (-swap! [o f a] (set-value #(f % a))) (-swap! [o f a b] (set-value #(f % a b))) (-swap! [o f a b xs] (set-value #(apply f % a b xs)))) (defn state [value] (let [[value set-value] (react/useState value) sh (react/useMemo #(StateHook. value set-value) #js [])] (react/useMemo (fn [] (set! (.-value sh) value) (set! (.-set-value sh) set-value) sh) #js [value set-value]))) (defn use-ref [val] (let [ref (react/useRef val)] (reify cljs.core/IHash (-hash [_] (goog/getUid ref)) cljs.core/IDeref (-deref [_] (current-ref ref)) cljs.core/IReset (-reset! [_ new-value] (set-ref-val! ref new-value)) cljs.core/ISwap (-swap! [_ f] (-reset! ref (f (current-ref ref)))) (-swap! [_ f a] (-reset! ref (f (current-ref ref) a))) (-swap! [_ f a b] (-reset! ref (f (current-ref ref) a b))) (-swap! [_ f a b xs] (-reset! ref (apply f (current-ref ref) a b xs)))))) (defn ref [value] (let [vref (use-ref value)] (react/useMemo (fn [] vref) #js []))) (defn effect! ([setup-fn] (react/useEffect #(let [ret (setup-fn)] (if (fn? ret) ret js/undefined)))) ([setup-fn deps] (with-deps-check [prev-deps*] (react/useEffect (fn [] (reset! prev-deps* deps) (let [ret (setup-fn)] (if (fn? ret) ret js/undefined))) (maybe-js-deps @prev-deps*)) deps))) (defn layout-effect! ([setup-fn] (react/useLayoutEffect #(let [ret (setup-fn)] (if (fn? ret) ret js/undefined)))) ([setup-fn deps] (with-deps-check [prev-deps*] (react/useLayoutEffect (fn [] (reset! prev-deps* deps) (let [ret (setup-fn)] (if (fn? ret) ret js/undefined))) (maybe-js-deps @prev-deps*)) deps))) (defn callback ([f] (react/useCallback f)) ([f deps] (with-deps-check [prev-deps*] (react/useCallback f (maybe-js-deps @prev-deps*)) deps))) (defn use-memo ([f] (react/useMemo f)) ([f deps] (with-deps-check [prev-deps*] (react/useMemo f (maybe-js-deps @prev-deps*)) deps))) (def memo react/memo) (defn get-children [^js children] (->> children (react/Children.toArray) (into [])))
{ "pile_set_name": "Github" }
/* * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.tests.server.netty import io.ktor.server.netty.* import io.ktor.server.testing.* class NettyStressTest : EngineStressSuite<NettyApplicationEngine, NettyApplicationEngine.Configuration>(Netty) { }
{ "pile_set_name": "Github" }
using System; using System.IO; using System.Reflection; using FluentAssertions; using Newtonsoft.Json.Linq; using Xunit; namespace Serilog.Sinks.Elasticsearch.Tests.Templating { public class TemplateMatchTests : ElasticsearchSinkTestsBase { private readonly Tuple<Uri, string> _templatePut; public TemplateMatchTests() { _options.AutoRegisterTemplate = true; _options.IndexFormat = "dailyindex-{0:yyyy.MM.dd}-mycompany"; _options.TemplateName = "dailyindex-logs-template"; var loggerConfig = new LoggerConfiguration() .MinimumLevel.Debug() .Enrich.WithMachineName() .WriteTo.ColoredConsole() .WriteTo.Elasticsearch(_options); var logger = loggerConfig.CreateLogger(); using (logger as IDisposable) { logger.Error("Test exception. Should not contain an embedded exception object."); } this._seenHttpPosts.Should().NotBeNullOrEmpty().And.HaveCount(1); this._seenHttpPuts.Should().NotBeNullOrEmpty().And.HaveCount(1); this._seenHttpHeads.Should().NotBeNullOrEmpty().And.HaveCount(1); _templatePut = this._seenHttpPuts[0]; } [Fact] public void TemplatePutToCorrectUrl() { var uri = this._templatePut.Item1; uri.AbsolutePath.Should().Be("/_template/dailyindex-logs-template"); } [Fact] public void TemplateMatchShouldReflectConfiguredIndexFormat() { var json = this._templatePut.Item2; json.Should().Contain(@"""template"":""dailyindex-*-mycompany"""); } } }
{ "pile_set_name": "Github" }
from ScoutSuite.providers.base.resources.base import Resources from ScoutSuite.providers.gcp.facade.base import GCPFacade class Firewalls(Resources): def __init__(self, facade: GCPFacade, project_id: str): super(Firewalls, self).__init__(facade) self.project_id = project_id async def fetch_all(self): raw_firewalls = await self.facade.gce.get_firewalls(self.project_id) for raw_firewall in raw_firewalls: firewall_id, firewall = self._parse_firewall(raw_firewall) self[firewall_id] = firewall def _parse_firewall(self, raw_firewall): firewall_dict = {} firewall_dict['id'] = raw_firewall['id'] firewall_dict['project_id'] = raw_firewall['selfLink'].split('/')[-4] firewall_dict['name'] = raw_firewall['name'] firewall_dict['description'] = self._get_description(raw_firewall) firewall_dict['creation_timestamp'] = raw_firewall['creationTimestamp'] firewall_dict['network'] = raw_firewall['network'].split('/')[-1] firewall_dict['network_url'] = raw_firewall['network'] firewall_dict['priority'] = raw_firewall['priority'] firewall_dict['source_ranges'] = raw_firewall.get('sourceRanges', []) firewall_dict['source_tags'] = raw_firewall.get('sourceTags', []) firewall_dict['target_tags'] = raw_firewall.get('targetTags', []) firewall_dict['direction'] = raw_firewall['direction'] firewall_dict['disabled'] = raw_firewall['disabled'] self._parse_firewall_rules(firewall_dict, raw_firewall) return firewall_dict['id'], firewall_dict def _parse_firewall_rules(self, firewall_dict, raw_firewall): for direction in ['allowed', 'denied']: direction_string = '%s_traffic' % direction firewall_dict[direction_string] = { 'tcp': [], 'udp': [], 'icmp': [] } if direction in raw_firewall: firewall_dict['action'] = direction for rule in raw_firewall[direction]: if rule['IPProtocol'] not in firewall_dict[direction_string]: firewall_dict[direction_string][rule['IPProtocol']] = ['*'] else: if rule['IPProtocol'] == 'all': for protocol in firewall_dict[direction_string]: firewall_dict[direction_string][protocol] = ['0-65535'] break else: if firewall_dict[direction_string][rule['IPProtocol']] != ['0-65535']: if 'ports' in rule: firewall_dict[direction_string][rule['IPProtocol']] += rule['ports'] else: firewall_dict[direction_string][rule['IPProtocol']] = ['0-65535'] def _get_description(self, raw_firewall): description = raw_firewall.get('description') return description if description else 'N/A'
{ "pile_set_name": "Github" }
package net.monitor.gather.traffic; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Date; import java.util.concurrent.atomic.AtomicBoolean; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.monitor.dao.dto.TrafficMonitorDTO; import net.monitor.dao.mapper.TrafficMonitorMapper; import net.monitor.utils.Config; import net.monitor.utils.DoubleUtils; import net.monitor.utils.MybatisUtils; import org.apache.ibatis.session.SqlSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TrafficMonitor implements Runnable { private static final Logger LOGGER = LoggerFactory.getLogger(TrafficMonitor.class); private static final AtomicBoolean RUNNING = new AtomicBoolean(true); private static final Pattern PATTERN = Pattern.compile("[^0-9]"); private final String localIp; public TrafficMonitor(String localIp) { this.localIp = localIp; } public void start() { File netfp = new File("/proc/net/dev"); if (!netfp.exists()) { LOGGER.error("Can't open /proc/net/dev"); } else { LOGGER.info("Open /proc/net/dev......[OK]"); } while (RUNNING.get()) { double[] preDatas = getTrafficDatas(netfp); try { Thread.sleep(Config.INTERVAL_TIME); } catch (InterruptedException e) { LOGGER.error("thread interrupted exception", e); } double[] curDatas = getTrafficDatas(netfp); computePersistence(preDatas, curDatas); System.arraycopy(curDatas, 0, preDatas, 0, preDatas.length); } } private void computePersistence(double[] preDatas, double[] curDatas) { double[] results = new double[6]; for (int i = 0; i < results.length; i++) { results[i] = ((curDatas[i] - preDatas[i])) / (Config.INTERVAL_TIME / 1000); } TrafficMonitorDTO trafficMonitorDTO = new TrafficMonitorDTO(); trafficMonitorDTO.setIp(localIp); trafficMonitorDTO.setNetworkCardName(Config.NETWORK_CARD_NAME); trafficMonitorDTO.setReceiveTraffic(DoubleUtils.round(results[0])); trafficMonitorDTO.setReceivePackets(DoubleUtils.round(results[1])); trafficMonitorDTO.setReceiveErrs(DoubleUtils.round(results[2])); trafficMonitorDTO.setTransmitTraffic(DoubleUtils.round(results[3])); trafficMonitorDTO.setTransmitPackets(DoubleUtils.round(results[4])); trafficMonitorDTO.setTransmitErrs(DoubleUtils.round(results[5])); trafficMonitorDTO.setGmtCreate(new Date()); insertSelective(trafficMonitorDTO); } private void insertSelective(TrafficMonitorDTO record) { try (SqlSession session = MybatisUtils.SQL_SESSION_FACTORY.openSession(Boolean.FALSE)) { TrafficMonitorMapper trafficMonitorMapper = session.getMapper(TrafficMonitorMapper.class); trafficMonitorMapper.insertSelective(record); session.commit(); } } private double[] getTrafficDatas(File netfp) { double[] datas = new double[6]; BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(netfp)); String tempString; while ((tempString = reader.readLine()) != null) { if (tempString.contains(Config.NETWORK_CARD_NAME)) { Matcher m = PATTERN.matcher(tempString); String str = m.replaceAll(" ").trim().replaceAll(" {2,}", " "); String[] array = str.split(" "); datas[0] += Double.parseDouble(array[1]); datas[1] += Double.parseDouble(array[2]); datas[2] += Double.parseDouble(array[3]); datas[3] += Double.parseDouble(array[9]); datas[4] += Double.parseDouble(array[10]); datas[5] += Double.parseDouble(array[11]); } } } catch (Exception e) { LOGGER.error(String.format("read file %s error.", netfp.getAbsolutePath()), e); } finally { try { if (reader != null) { reader.close(); } } catch (IOException e) { LOGGER.error(String.format("close file %s error.", netfp.getAbsolutePath()), e); } } return datas; } @Override public void run() { // TODO Auto-generated method stub start(); } }
{ "pile_set_name": "Github" }
<?php abstract class SyndicationFeedRenderer { const LEVEL_INDENTATION = ' '; protected $syndicationFeed; protected $syndicationFeedDB; protected $mimeType; public function init($syndicationFeed, $syndicationFeedDB, $mimeType) { $this->syndicationFeed = $syndicationFeed; $this->syndicationFeedDB = $syndicationFeedDB; $this->mimeType = $mimeType; } public function shouldEnableCache() { return true; } public abstract function handleHeader(); public abstract function handleBody($entry, $e = null, $flavorAssetUrl = null); public abstract function handleFooter(); /** * @return the HTTP header */ public function handleHttpHeader() { return "content-type: " . $this->syndicationFeedDB->getFeedContentTypeHeader(); } /** * Finalizes the object and format it to printable version * @param string $entryMrss Current mrss format * @param boolean $moreItems Whether this is the last entry * @return The formatted mrss */ public function finalize($entryMrss, $moreItems) { return $entryMrss; } protected function getPlayerUrl($entryId) { $url = requestUtils::getProtocol() . '://' . kConf::get('www_host'); $partnerId = $this->syndicationFeed->partnerId; if ( $this->syndicationFeedDB->getPlayerType() == PlayerType::HTML5Player ) { $isPlaykit = false; if ($this->syndicationFeed->playerUiconfId) { $dbUiConf = uiConfPeer::retrieveByPK( $this->syndicationFeed->playerUiconfId ); if($dbUiConf && strpos( $dbUiConf->getTags() , 'kalturaPlayerJs') !== false) { $isPlaykit = true; } } $uiconfId = ($this->syndicationFeed->playerUiconfId)? '/uiconf_id/'.$this->syndicationFeed->playerUiconfId: ''; if ($isPlaykit) { $url .= '/p/' .$partnerId.'/embedPlaykitJs' .$uiconfId. '?iframeembed=true&entry_id=' .$entryId; } else { $url .= '/p/' .$partnerId. '/sp/' .$partnerId. '00/embedIframeJs'.$uiconfId. '/partner_id/' .$partnerId.'?iframeembed=true&entry_id='.$entryId; } } else { $uiconfId = ($this->syndicationFeed->playerUiconfId)? '/ui_conf_id/'.$this->syndicationFeed->playerUiconfId: ''; $url .= '/kwidget/wid/_'.$partnerId. '/entry_id/'.$entryId.$uiconfId; } $url = htmlEntities($url); return $url; } // Writer functions protected function stringToSafeXml($string, $now = false) { $string = @iconv('utf-8', 'utf-8', $string); $safe = kString::xmlEncode($string); return $safe; } protected function writeFullXmlNode($nodeName, $value, $level, $attributes = array()) { $res = ''; $res .= $this->writeOpenXmlNode($nodeName, $level, $attributes, false); $res .= kString::xmlEncode(kString::xmlDecode("$value")); //to create a valid XML (without unescaped special chars) //we decode before encoding to avoid breaking an xml which its special chars had already been escaped $res .= $this->writeClosingXmlNode($nodeName, 0); return $res; } protected function writeOpenXmlNode($nodeName, $level, $attributes = array(), $eol = true) { $tag = $this->getSpacesForLevel($level)."<$nodeName"; if(count($attributes)) { foreach($attributes as $key => $val) { $tag .= ' '.$key.'="'.$val.'"'; } } $tag .= ">"; if($eol) $tag .= PHP_EOL; return $tag; } protected function writeClosingXmlNode($nodeName, $level = 0) { return $this->getSpacesForLevel($level)."</$nodeName>".PHP_EOL; } protected function getSpacesForLevel($level) { $spaces = ''; for($i=0;$i<$level;$i++) $spaces .= self::LEVEL_INDENTATION; return $spaces; } protected function secondsToWords($seconds) { /*** return value ***/ $ret = ""; /*** get the hours ***/ $hours = intval(intval($seconds) / 3600); if($hours > 0) { $ret .= "$hours:"; } /*** get the minutes ***/ $minutes = (intval($seconds) / 60)%60; $ret .= ($minutes >= 10 || $minutes == 0)? "$minutes:": "0$minutes:"; /*** get the seconds ***/ $seconds = intval($seconds)%60; $ret .= ($seconds >= 10)? "$seconds": "0$seconds"; return $ret; } }
{ "pile_set_name": "Github" }
import parakeet import parakeet.testing_helpers import numpy as np def matmult_high_level(X,Y): return np.array([[np.min(x+y) for y in Y.T] for x in X]) def test_matmult_tropical(): n, d = 4,5 m = 3 X = np.random.randn(m,d) Y = np.random.randn(d,n) parakeet.testing_helpers.expect(matmult_high_level, [X,Y], matmult_high_level(X,Y)) if __name__ == '__main__': parakeet.testing_helpers.run_local_tests()
{ "pile_set_name": "Github" }