text
stringlengths
10
99.9k
meta
dict
const nest = require('depnest') const Value = require('mutant/value') const onceTrue = require('mutant/once-true') const computed = require('mutant/computed') const resolve = require('mutant/resolve') const pull = require('pull-stream') const sorted = require('sorted-array-functions') const MutantPullCollection = require('../../mutant-pull-collection') exports.needs = nest({ 'sbot.pull.backlinks': 'first', 'sbot.obs.connection': 'first', 'message.sync.root': 'first', 'sbot.pull.stream': 'first', 'message.sync.timestamp': 'first' }) exports.gives = nest({ 'backlinks.obs.for': true, 'backlinks.obs.references': true, 'backlinks.obs.forks': true }) exports.create = function (api) { const cache = {} const collections = {} let loaded = false // cycle remove sets for fast cleanup let newRemove = new Set() let oldRemove = new Set() // run cache cleanup every 5 seconds // an item will be removed from cache between 5 - 10 seconds after release // this ensures that the data is still available for a page reload const timer = setInterval(() => { oldRemove.forEach(id => { if (cache[id]) { unsubscribe(id) delete collections[id] delete cache[id] } }) oldRemove.clear() // cycle const hold = oldRemove oldRemove = newRemove newRemove = hold }, 5e3) if (timer.unref) timer.unref() return nest({ 'backlinks.obs.for': (id) => backlinks(id), 'backlinks.obs.references': references, 'backlinks.obs.forks': forks }) function references (msg) { const id = msg.key return MutantPullCollection((lastMessage) => { return api.sbot.pull.stream((sbot) => sbot.patchwork.backlinks.referencesStream({ id, since: lastMessage && lastMessage.timestamp })) }) } function forks (msg) { const id = msg.key const rooted = !!api.message.sync.root(msg) if (rooted) { return MutantPullCollection((lastMessage) => { return api.sbot.pull.stream((sbot) => sbot.patchwork.backlinks.forksStream({ id, since: lastMessage && lastMessage.timestamp })) }) } else { return [] } } function backlinks (id) { load() if (!cache[id]) { const sync = Value(false) const collection = Value([]) subscribe(id) process.nextTick(() => { pull( api.sbot.pull.backlinks({ query: [{ $filter: { dest: id } }], index: 'DTA' // use asserted timestamps }), pull.drain((msg) => { const value = resolve(collection) sorted.add(value, msg, compareAsserted) collection.set(value) }, () => { sync.set(true) }) ) }) collections[id] = collection cache[id] = computed([collection], x => x, { onListen: () => use(id), onUnlisten: () => release(id) }) cache[id].sync = sync } return cache[id] } function load () { if (!loaded) { pull( api.sbot.pull.stream(sbot => sbot.patchwork.liveBacklinks.stream()), pull.drain(msg => { const collection = collections[msg.dest] if (collection) { const value = resolve(collection) sorted.add(value, msg, compareAsserted) collection.set(value) } }) ) loaded = true } } function use (id) { newRemove.delete(id) oldRemove.delete(id) } function release (id) { newRemove.add(id) } function subscribe (id) { onceTrue(api.sbot.obs.connection(), (sbot) => sbot.patchwork.liveBacklinks.subscribe(id)) } function unsubscribe (id) { onceTrue(api.sbot.obs.connection(), (sbot) => sbot.patchwork.liveBacklinks.unsubscribe(id)) } function compareAsserted (a, b) { if (isReplyTo(a, b)) { return -1 } else if (isReplyTo(b, a)) { return 1 } else { return api.message.sync.timestamp(a) - api.message.sync.timestamp(b) } } } function isReplyTo (maybeReply, msg) { return (includesOrEquals(maybeReply.branch, msg.key)) } function includesOrEquals (array, value) { if (Array.isArray(array)) { return array.includes(value) } else { return array === value } }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2004, PostgreSQL Global Development Group * See the LICENSE file in the project root for more information. */ package org.postgresql.ds; import org.postgresql.ds.common.BaseDataSource; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.sql.SQLException; import javax.sql.DataSource; /** * Simple DataSource which does not perform connection pooling. In order to use the DataSource, you * must set the property databaseName. The settings for serverName, portNumber, user, and password * are optional. Note: these properties are declared in the superclass. * * @author Aaron Mulder (ammulder@chariotsolutions.com) */ public class PGSimpleDataSource extends BaseDataSource implements DataSource, Serializable { /** * Gets a description of this DataSource. */ public String getDescription() { return "Non-Pooling DataSource from " + org.postgresql.util.DriverInfo.DRIVER_FULL_NAME; } private void writeObject(ObjectOutputStream out) throws IOException { writeBaseObject(out); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { readBaseObject(in); } public boolean isWrapperFor(Class<?> iface) throws SQLException { return iface.isAssignableFrom(getClass()); } public <T> T unwrap(Class<T> iface) throws SQLException { if (iface.isAssignableFrom(getClass())) { return iface.cast(this); } throw new SQLException("Cannot unwrap to " + iface.getName()); } }
{ "pile_set_name": "Github" }
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.psi.impl.source.resolve.reference.impl.manipulators; import com.intellij.openapi.editor.Document; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiPlainTextFile; import com.intellij.psi.AbstractElementManipulator; import com.intellij.util.IncorrectOperationException; import javax.annotation.Nonnull; /** * Created by IntelliJ IDEA. * User: ik * Date: 09.12.2003 * Time: 14:10:35 * To change this template use Options | File Templates. */ public class PlainFileManipulator extends AbstractElementManipulator<PsiPlainTextFile> { @Override public PsiPlainTextFile handleContentChange(@Nonnull PsiPlainTextFile file, @Nonnull TextRange range, String newContent) throws IncorrectOperationException { final Document document = FileDocumentManager.getInstance().getDocument(file.getVirtualFile()); document.replaceString(range.getStartOffset(), range.getEndOffset(), newContent); PsiDocumentManager.getInstance(file.getProject()).commitDocument(document); return file; } }
{ "pile_set_name": "Github" }
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. module internal FSharp.Compiler.InnerLambdasToTopLevelFuncs open FSharp.Compiler open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL.Internal.Library open FSharp.Compiler.AbstractIL.Diagnostics open FSharp.Compiler.CompilerGlobalState open FSharp.Compiler.ErrorLogger open FSharp.Compiler.Detuple.GlobalUsageAnalysis open FSharp.Compiler.Layout open FSharp.Compiler.Lib open FSharp.Compiler.SyntaxTree open FSharp.Compiler.TypedTree open FSharp.Compiler.TypedTreeBasics open FSharp.Compiler.TypedTreeOps open FSharp.Compiler.TypedTreeOps.DebugPrint open FSharp.Compiler.TcGlobals open FSharp.Compiler.XmlDoc let verboseTLR = false //------------------------------------------------------------------------- // library helpers //------------------------------------------------------------------------- let internalError str = dprintf "Error: %s\n" str;raise (Failure str) module Zmap = let force k mp (str, soK) = try Zmap.find k mp with e -> dprintf "Zmap.force: %s %s\n" str (soK k) PreserveStackTrace e raise e //------------------------------------------------------------------------- // misc //------------------------------------------------------------------------- /// tree, used to store dec sequence type Tree<'T> = | TreeNode of Tree<'T> list | LeafNode of 'T let fringeTR tr = let rec collect tr acc = match tr with | TreeNode subts -> List.foldBack collect subts acc | LeafNode x -> x :: acc collect tr [] let emptyTR = TreeNode[] //------------------------------------------------------------------------- // misc //------------------------------------------------------------------------- /// Collapse reclinks on app and combine apps if possible /// recursive ids are inside reclinks and maybe be type instanced with a Expr.App // CLEANUP NOTE: mkApps ensures applications are kept in a collapsed // and combined form, so this function should not be needed let destApp (f, fty, tys, args, m) = match stripExpr f with | Expr.App (f2, fty2, tys2, [], _) -> (f2, fty2, tys2 @ tys, args, m) | Expr.App _ -> (f, fty, tys, args, m) (* has args, so not combine ty args *) | f -> (f, fty, tys, args, m) #if DEBUG let showTyparSet tps = showL (commaListL (List.map typarL (Zset.elements tps))) #endif // CLEANUP NOTE: don't like the look of this function - this distinction // should never be needed let isDelayedRepr (f: Val) e = let _tps, vss, _b, _rty = stripTopLambda (e, f.Type) List.length vss>0 // REVIEW: these should just be replaced by direct calls to mkLocal, mkCompGenLocal etc. // REVIEW: However these set an arity whereas the others don't let mkLocalNameTypeArity compgen m name ty topValInfo = Construct.NewVal(name, m, None, ty, Immutable, compgen, topValInfo, taccessPublic, ValNotInRecScope, None, NormalVal, [], ValInline.Optional, XmlDoc.Empty, false, false, false, false, false, false, None, ParentNone) //------------------------------------------------------------------------- // definitions: TLR, arity, arity-met, arity-short // // DEFN: An f is TLR with arity wf if // (a) it's repr is "LAM tps. lam x1...xN. body" and have N<=wf (i.e. have enough args) // (b) it has no free tps // (c) for g: freevars(repr), both // (1) g is TLR with arity wg, and // (2) g occurs in arity-met occurrence. // (d) if N=0, then further require that body be a TLR-constant. // // Conditions (a-c) are required if f is to have a static method/field representation. // Condition (d) chooses which constants can be lifted. (no effects, non-trivial). // // DEFN: An arity-met occurrence of g is a g application with enough args supplied, // ie. (g tps args) where wg <= |args|. // // DEFN: An arity-short occurrence does not have enough args. // // DEFN: A TLR-constant: // - can have constructors (tuples, datatype, records, exn). // - should be non-trivial (says, causes allocation). // - if calls are allowed, they must be effect free (since eval point is moving). //------------------------------------------------------------------------- //------------------------------------------------------------------------- // OVERVIEW // Overview of passes (over term) and steps (not over term): // // pass1 - decide which f will be TLR and determine their arity. // pass2 - what closures are needed? Finds reqdTypars(f) and reqdItems(f) for TLR f. // Depends on the arity choice, so must follow pass1. // step3 - choose env packing, create fHats. // pass4 - rewrite term fixing up definitions and callsites. // Depends on closure and env packing, so must follow pass2 (and step 3). // pass5 - copyExpr call to topexpr to ensure all bound ids are unique. // For complexity reasons, better to re-recurse over expr once. // pass6 - sanity check, confirm that all TLR marked bindings meet DEFN. // //------------------------------------------------------------------------- //------------------------------------------------------------------------- // pass1: GetValsBoundUnderMustInline (see comment further below) //------------------------------------------------------------------------- let GetValsBoundUnderMustInline xinfo = let accRejectFrom (v: Val) repr rejectS = if v.InlineInfo = ValInline.PseudoVal then Zset.union (GetValsBoundInExpr repr) rejectS else rejectS let rejectS = Zset.empty valOrder let rejectS = Zmap.fold accRejectFrom xinfo.Defns rejectS rejectS //------------------------------------------------------------------------- // pass1: IsRefusedTLR //------------------------------------------------------------------------- let IsRefusedTLR g (f: Val) = let mutableVal = f.IsMutable // things marked ValInline.Never are special let dllImportStubOrOtherNeverInline = (f.InlineInfo = ValInline.Never) // Cannot have static fields of byref type let byrefVal = isByrefLikeTy g f.Range f.Type // Special values are instance methods etc. on .NET types. For now leave these alone let specialVal = f.MemberInfo.IsSome let alreadyChosen = f.ValReprInfo.IsSome let refuseTest = alreadyChosen || mutableVal || byrefVal || specialVal || dllImportStubOrOtherNeverInline refuseTest let IsMandatoryTopLevel (f: Val) = let specialVal = f.MemberInfo.IsSome let isModulBinding = f.IsMemberOrModuleBinding specialVal || isModulBinding let IsMandatoryNonTopLevel g (f: Val) = let byrefVal = isByrefLikeTy g f.Range f.Type byrefVal //------------------------------------------------------------------------- // pass1: decide which f are to be TLR? and if so, arity(f) //------------------------------------------------------------------------- module Pass1_DetermineTLRAndArities = let GetMaxNumArgsAtUses xinfo f = match Zmap.tryFind f xinfo.Uses with | None -> 0 (* no call sites *) | Some sites -> sites |> List.map (fun (_accessors, _tinst, args) -> List.length args) |> List.max let SelectTLRVals g xinfo f e = if IsRefusedTLR g f then None // Exclude values bound in a decision tree else if Zset.contains f xinfo.DecisionTreeBindings then None else // Could the binding be TLR? with what arity? let atTopLevel = Zset.contains f xinfo.TopLevelBindings let tps, vss, _b, _rty = stripTopLambda (e, f.Type) let nFormals = vss.Length let nMaxApplied = GetMaxNumArgsAtUses xinfo f let arity = Operators.min nFormals nMaxApplied if atTopLevel || arity<>0 || not (isNil tps) then Some (f, arity) else None /// Check if f involves any value recursion (so can skip those). /// ValRec considered: recursive && some f in mutual binding is not bound to a lambda let IsValueRecursionFree xinfo f = let hasDelayedRepr f = isDelayedRepr f (Zmap.force f xinfo.Defns ("IsValueRecursionFree - hasDelayedRepr", nameOfVal)) let isRecursive, mudefs = Zmap.force f xinfo.RecursiveBindings ("IsValueRecursionFree", nameOfVal) not isRecursive || List.forall hasDelayedRepr mudefs let DumpArity arityM = let dump f n = dprintf "tlr: arity %50s = %d\n" (showL (valL f)) n Zmap.iter dump arityM let DetermineTLRAndArities g expr = let xinfo = GetUsageInfoOfImplFile g expr let fArities = Zmap.chooseL (SelectTLRVals g xinfo) xinfo.Defns let fArities = List.filter (fst >> IsValueRecursionFree xinfo) fArities // Do not TLR v if it is bound under a mustinline defn // There is simply no point - the original value will be duplicated and TLR'd anyway let rejectS = GetValsBoundUnderMustInline xinfo let fArities = List.filter (fun (v, _) -> not (Zset.contains v rejectS)) fArities (*-*) let tlrS = Zset.ofList valOrder (List.map fst fArities) let topValS = xinfo.TopLevelBindings (* genuinely top level *) let topValS = Zset.filter (IsMandatoryNonTopLevel g >> not) topValS (* restrict *) (* REPORT MISSED CASES *) #if DEBUG if verboseTLR then let missed = Zset.diff xinfo.TopLevelBindings tlrS missed |> Zset.iter (fun v -> dprintf "TopLevel but not TLR = %s\n" v.LogicalName) #endif (* REPORT OVER *) let arityM = Zmap.ofList valOrder fArities #if DEBUG if verboseTLR then DumpArity arityM #endif tlrS, topValS, arityM (* NOTES: For constants, Want to fold in a declaration order, so can make decisions about TLR given TLR-knowledge about prior constants. Assuming ilxgen will fix up initialisations. So, Results to be extended to include some scoping representation. Maybe a telescope tree which can be walked over. *) //------------------------------------------------------------------------- // pass2: determine reqdTypars(f) and envreq(f) - notes //------------------------------------------------------------------------- /// What are the closing types/values for {f1, f2...} mutually defined? /// // Note: arity-met g-applications (g TLR) will translated as: // [[g @ tps ` args]] -> gHAT @ reqdTypars(g) tps ` env(g) args // so they require availability of closing types/values for g. // // If g is free wrt f1, f2... then g's closure must be included. // // Note: mutual definitions have a common closure. // // For f1, f2, ... = fBody1, fbody2... mutual bindings: // // DEFN: The reqdVals0 are the free-values of fBody1, fBody2... // // What are the closure equations? // // reqdTypars(f1, f2..) includes free-tps(f) // reqdTypars(f1, f2..) includes reqdTypars(g) if fBody has arity-met g-occurrence (g TLR). // // reqdItems(f1, f2...) includes ReqdSubEnv(g) if fBody has arity-met g-occurrence (g TLR) // reqdItems(f1, f2...) includes ReqdVal(g) if fBody has arity-short g-occurrence (g TLR) // reqdItems(f1, f2...) includes ReqdVal(g) if fBody has g-occurrence (g not TLR) // // and only collect requirements if g is a generator (see next notes). // // Note: "env-availability" // In the translated code, env(h) will be defined at the h definition point. // So, where-ever h could be called (recursive or not), // the env(h) will be available (in scope). // // Note (subtle): "sub-env-requirement-only-for-reqdVals0" // If have an arity-met call to h inside fBody, but h is not a freevar for f, // then h does not contribute env(h) to env(f), the closure for f. // It is true that env(h) will be required at the h call-site, // but the env(h) will be available there (by "env-availability"), // since h must be bound inside the fBody since h was not a freevar for f. // . // [note, f and h may mutually recurse and formals of f may be in env(h), // so env(f) may be properly inside env(h), // so better not have env(h) in env(f)!!!]. /// The subset of ids from a mutal binding that are chosen to be TLR. /// They share a common env. /// [Each fclass has an env, the fclass are the handles to envs.] type BindingGroupSharingSameReqdItems(bindings: Bindings) = let vals = valsOfBinds bindings let vset = Zset.addList vals (Zset.empty valOrder) member fclass.Vals = vals member fclass.Contains (v: Val) = vset.Contains v member fclass.IsEmpty = isNil vals member fclass.Pairs = vals |> List.map (fun f -> (f, fclass)) override fclass.ToString() = "+" + String.concat "+" (List.map nameOfVal vals) let fclassOrder = Order.orderOn (fun (b: BindingGroupSharingSameReqdItems) -> b.Vals) (List.order valOrder) /// It is required to make the TLR closed wrt it's freevars (the env reqdVals0). /// For gv a generator, /// An arity-met gv occurrence contributes the env required for that gv call. /// Other occurrences contribute the value gv. type ReqdItem = | ReqdSubEnv of Val | ReqdVal of Val override i.ToString() = match i with | ReqdSubEnv f -> "&" + f.LogicalName | ReqdVal f -> f.LogicalName let reqdItemOrder = let rep = function | ReqdSubEnv v -> true, v | ReqdVal v -> false, v Order.orderOn rep (Pair.order (Bool.order, valOrder)) /// An env says what is needed to close the corresponding defn(s). /// The reqdTypars are the free reqdTypars of the defns, and those required by any direct TLR arity-met calls. /// The reqdItems are the ids/subEnvs required from calls to freeVars. type ReqdItemsForDefn = { reqdTypars: Zset<Typar> reqdItems: Zset<ReqdItem> m: Range.range } member env.ReqdSubEnvs = [ for x in env.reqdItems do match x with | ReqdSubEnv f -> yield f | ReqdVal _ -> () ] member env.ReqdVals = [ for x in env.reqdItems do match x with | ReqdSubEnv _ -> () | ReqdVal v -> yield v ] member env.Extend (typars, items) = {env with reqdTypars = Zset.addList typars env.reqdTypars reqdItems = Zset.addList items env.reqdItems} static member Initial typars m = {reqdTypars = Zset.addList typars (Zset.empty typarOrder) reqdItems = Zset.empty reqdItemOrder m = m } override env.ToString() = (showL (commaListL (List.map typarL (Zset.elements env.reqdTypars)))) + "--" + (String.concat ", " (List.map string (Zset.elements env.reqdItems))) (*--debug-stuff--*) //------------------------------------------------------------------------- // pass2: collector - state //------------------------------------------------------------------------- type Generators = Zset<Val> /// check a named function value applied to sufficient arguments let IsArityMet (vref: ValRef) wf (tys: TypeInst) args = (tys.Length = vref.Typars.Length) && (wf <= List.length args) module Pass2_DetermineReqdItems = // IMPLEMENTATION PLAN: // // fold over expr. // // - at an instance g, // - (a) g arity-met, LogRequiredFrom g - ReqdSubEnv(g) -- direct call will require env(g) and reqdTypars(g) // - (b) g arity-short, LogRequiredFrom g - ReqdVal(g) -- remains g call // - (c) g non-TLR, LogRequiredFrom g - ReqdVal(g) -- remains g // where // LogRequiredFrom g ... = logs info into (reqdVals0, env) if g in reqdVals0. // // - at some mu-bindings, f1, f2... = fBody1, fBody2, ... // "note reqdVals0, push (reqdVals0, env), fold-over bodies, pop, fold rest" // // - let fclass = ff1, ... be the fi which are being made TLR. // - required to find an env for these. // - start a new envCollector: // freetps = freetypars of (fBody1, fBody2, ...) // freevs = freevars of .. // initialise: // reqdTypars = freetps // reqdItems = [] -- info collected from generator occurrences in bindings // reqdVals0 = freevs // - fold bodies, collecting info for reqdVals0. // - pop and save env. // - note: - reqdTypars(fclass) are only the freetps // - they need to include reqdTypars(g) for each direct call to g (g a generator for fclass) // - the reqdTypars(g) may not yet be known, // e.g. if we are inside the definition of g and had recursively called it. // - so need to FIX up the reqdTypars(-) function when collected info for all fclass. // - fold rest (after binding) // // fix up reqdTypars(-) according to direct call dependencies. // /// This state collects: /// reqdItemsMap - fclass -> env /// fclassM - f -> fclass /// declist - fclass list /// recShortCallS - the f which are "recursively-called" in arity short instance. /// /// When walking expr, at each mutual binding site, /// push a (generator, env) collector frame on stack. /// If occurrences in body are relevant (for a generator) then it's contribution is logged. /// /// recShortCalls to f will require a binding for f in terms of fHat within the fHatBody. type state = { stack: (BindingGroupSharingSameReqdItems * Generators * ReqdItemsForDefn) list reqdItemsMap: Zmap<BindingGroupSharingSameReqdItems, ReqdItemsForDefn> fclassM: Zmap<Val, BindingGroupSharingSameReqdItems> revDeclist: BindingGroupSharingSameReqdItems list recShortCallS: Zset<Val> } let state0 = { stack = [] reqdItemsMap = Zmap.empty fclassOrder fclassM = Zmap.empty valOrder revDeclist = [] recShortCallS = Zset.empty valOrder } /// PUSH = start collecting for fclass let PushFrame (fclass: BindingGroupSharingSameReqdItems) (reqdTypars0, reqdVals0, m) state = if fclass.IsEmpty then state else {state with revDeclist = fclass :: state.revDeclist stack = (let env = ReqdItemsForDefn.Initial reqdTypars0 m in (fclass, reqdVals0, env) :: state.stack) } /// POP & SAVE = end collecting for fclass and store let SaveFrame (fclass: BindingGroupSharingSameReqdItems) state = if verboseTLR then dprintf "SaveFrame: %A\n" fclass if fclass.IsEmpty then state else match state.stack with | [] -> internalError "trl: popFrame has empty stack" | (fclass, _reqdVals0, env) :: stack -> (* ASSERT: same fclass *) {state with stack = stack reqdItemsMap = Zmap.add fclass env state.reqdItemsMap fclassM = List.fold (fun mp (k, v) -> Zmap.add k v mp) state.fclassM fclass.Pairs } /// Log requirements for gv in the relevant stack frames let LogRequiredFrom gv items state = let logIntoFrame (fclass, reqdVals0: Zset<Val>, env: ReqdItemsForDefn) = let env = if reqdVals0.Contains gv then env.Extend ([], items) else env fclass, reqdVals0, env {state with stack = List.map logIntoFrame state.stack} let LogShortCall gv state = if state.stack |> List.exists (fun (fclass, _reqdVals0, _env) -> fclass.Contains gv) then if verboseTLR then dprintf "shortCall: rec: %s\n" gv.LogicalName // Have short call to gv within it's (mutual) definition(s) {state with recShortCallS = Zset.add gv state.recShortCallS} else if verboseTLR then dprintf "shortCall: not-rec: %s\n" gv.LogicalName state let FreeInBindings bs = List.fold (foldOn (freeInBindingRhs CollectTyparsAndLocals) unionFreeVars) emptyFreeVars bs /// Intercepts selected exprs. /// "letrec f1, f2, ... = fBody1, fBody2, ... in rest" - /// "val v" - free occurrence /// "app (f, tps, args)" - occurrence /// /// On intercepted nodes, must recurseF fold to collect from subexpressions. let ExprEnvIntercept (tlrS, arityM) recurseF noInterceptF z expr = let accInstance z (fvref: ValRef, tps, args) = let f = fvref.Deref match Zmap.tryFind f arityM with | Some wf -> // f is TLR with arity wf if IsArityMet fvref wf tps args then // arity-met call to a TLR g LogRequiredFrom f [ReqdSubEnv f] z else // arity-short instance let z = LogRequiredFrom f [ReqdVal f] z // LogShortCall - logs recursive short calls let z = LogShortCall f z z | None -> // f is non-TLR LogRequiredFrom f [ReqdVal f] z let accBinds m z (binds: Bindings) = let tlrBs, nonTlrBs = binds |> List.partition (fun b -> Zset.contains b.Var tlrS) // For bindings marked TLR, collect implied env let fclass = BindingGroupSharingSameReqdItems tlrBs // what determines env? let frees = FreeInBindings tlrBs // put in env let reqdTypars0 = frees.FreeTyvars.FreeTypars |> Zset.elements // occurrences contribute to env let reqdVals0 = frees.FreeLocals |> Zset.elements // tlrBs are not reqdVals0 for themselves let reqdVals0 = reqdVals0 |> List.filter (fun gv -> not (fclass.Contains gv)) let reqdVals0 = reqdVals0 |> Zset.ofList valOrder // collect into env over bodies let z = PushFrame fclass (reqdTypars0, reqdVals0,m) z let z = (z, tlrBs) ||> List.fold (foldOn (fun b -> b.Expr) recurseF) let z = SaveFrame fclass z // for bindings not marked TRL, collect let z = (z, nonTlrBs) ||> List.fold (foldOn (fun b -> b.Expr) recurseF) z match expr with | Expr.Val (v, _, _) -> accInstance z (v, [], []) | Expr.Op (TOp.LValueOp (_, v), _tys, args, _) -> let z = accInstance z (v, [], []) List.fold recurseF z args | Expr.App (f, fty, tys, args, m) -> let f, _fty, tys, args, _m = destApp (f, fty, tys, args, m) match f with | Expr.Val (f, _, _) -> // YES: APP vspec tps args - log let z = accInstance z (f, tys, args) List.fold recurseF z args | _ -> // NO: app, but function is not val - no log noInterceptF z expr | Expr.LetRec (binds, body, m, _) -> let z = accBinds m z binds recurseF z body | Expr.Let (bind,body,m,_) -> let z = accBinds m z [bind] // tailcall for linear sequences recurseF z body | _ -> noInterceptF z expr /// Initially, reqdTypars(fclass) = freetps(bodies). /// For each direct call to a gv, a generator for fclass, /// Required to include the reqdTypars(gv) in reqdTypars(fclass). let CloseReqdTypars fclassM reqdItemsMap = if verboseTLR then dprintf "CloseReqdTypars------\n" let closeStep reqdItemsMap changed fc (env: ReqdItemsForDefn) = let directCallReqdEnvs = env.ReqdSubEnvs let directCallReqdTypars = directCallReqdEnvs |> List.map (fun f -> let fc = Zmap.force f fclassM ("reqdTyparsFor", nameOfVal) let env = Zmap.force fc reqdItemsMap ("reqdTyparsFor", string) env.reqdTypars) let reqdTypars0 = env.reqdTypars let reqdTypars = List.fold Zset.union reqdTypars0 directCallReqdTypars let changed = changed || (not (Zset.equal reqdTypars0 reqdTypars)) let env = {env with reqdTypars = reqdTypars} #if DEBUG if verboseTLR then dprintf "closeStep: fc=%30A nSubs=%d reqdTypars0=%s reqdTypars=%s\n" fc directCallReqdEnvs.Length (showTyparSet reqdTypars0) (showTyparSet reqdTypars) directCallReqdEnvs |> List.iter (fun f -> dprintf "closeStep: dcall f=%s\n" f.LogicalName) directCallReqdEnvs |> List.iter (fun f -> dprintf "closeStep: dcall fc=%A\n" (Zmap.find f fclassM)) directCallReqdTypars |> List.iter (fun _reqdTypars -> dprintf "closeStep: dcall reqdTypars=%s\n" (showTyparSet reqdTypars0)) #else ignore fc #endif changed, env let rec fixpoint reqdItemsMap = let changed = false let changed, reqdItemsMap = Zmap.foldMap (closeStep reqdItemsMap) changed reqdItemsMap if changed then fixpoint reqdItemsMap else reqdItemsMap fixpoint reqdItemsMap #if DEBUG let DumpReqdValMap reqdItemsMap = for KeyValue(fc, env) in reqdItemsMap do dprintf "CLASS=%A\n env=%A\n" fc env #endif let DetermineReqdItems (tlrS, arityM) expr = if verboseTLR then dprintf "DetermineReqdItems------\n" let folder = {ExprFolder0 with exprIntercept = ExprEnvIntercept (tlrS, arityM)} let z = state0 // Walk the entire assembly let z = FoldImplFile folder z expr // project results from the state let reqdItemsMap = z.reqdItemsMap let fclassM = z.fclassM let declist = List.rev z.revDeclist let recShortCallS = z.recShortCallS // diagnostic dump #if DEBUG if verboseTLR then DumpReqdValMap reqdItemsMap #endif // close the reqdTypars under the subEnv reln let reqdItemsMap = CloseReqdTypars fclassM reqdItemsMap // filter out trivial fclass - with no TLR defns let reqdItemsMap = Zmap.remove (BindingGroupSharingSameReqdItems List.empty) reqdItemsMap // restrict declist to those with reqdItemsMap bindings (the non-trivial ones) let declist = List.filter (Zmap.memberOf reqdItemsMap) declist #if DEBUG // diagnostic dump if verboseTLR then DumpReqdValMap reqdItemsMap declist |> List.iter (fun fc -> dprintf "Declist: %A\n" fc) recShortCallS |> Zset.iter (fun f -> dprintf "RecShortCall: %s\n" f.LogicalName) #endif reqdItemsMap, fclassM, declist, recShortCallS //------------------------------------------------------------------------- // step3: PackedReqdItems //------------------------------------------------------------------------- /// Each env is represented by some carrier values, the aenvs. /// An env packing defines these, and the pack/unpack bindings. /// The bindings are in terms of the fvs directly. /// /// When defining a new TLR f definition, /// the fvs will become bound by the unpack bindings, /// the aenvs will become bound by the new lam, and /// the reqdTypars will become bound by the new LAM. /// For uniqueness of bound ids, /// all these ids (Typar/Val) will need to be freshened up. /// It is OK to break the uniqueness-of-bound-ids rule during the rw, /// provided it is fixed up via a copyExpr call on the final expr. type PackedReqdItems = { /// The actual typars ep_etps: Typars /// The actual env carrier values ep_aenvs: Val list /// Sequentially define the aenvs in terms of the fvs ep_pack: Bindings /// Sequentially define the fvs in terms of the aenvs ep_unpack: Bindings } //------------------------------------------------------------------------- // step3: FlatEnvPacks //------------------------------------------------------------------------- exception AbortTLR of Range.range /// A naive packing of environments. /// Chooses to pass all env values as explicit args (no tupling). /// Note, tupling would cause an allocation, /// so, unless arg lists get very long, this flat packing will be preferable. /// Given (fclass, env). /// Have env = ReqdVal vj, ReqdSubEnv subEnvk -- ranging over j, k /// Define vals(env) = {vj}|j union vals(subEnvk)|k -- trans closure of vals of env. /// Define <vi, aenvi> for each vi in vals(env). /// This is the cmap for the env. /// reqdTypars = env.reqdTypars /// carriers = aenvi|i /// pack = TBIND(aenvi = vi) for each (aenvi, vi) in cmap /// unpack = TBIND(vj = aenvFor(vj)) for each vj in reqvals(env). /// and TBIND(asubEnvi = aenvFor(v)) for each (asubEnvi, v) in cmap(subEnvk) ranging over required subEnvk. /// where /// aenvFor(v) = aenvi where (v, aenvi) in cmap. let FlatEnvPacks g fclassM topValS declist (reqdItemsMap: Zmap<BindingGroupSharingSameReqdItems, ReqdItemsForDefn>) = let fclassOf f = Zmap.force f fclassM ("fclassM", nameOfVal) let packEnv carrierMaps (fc: BindingGroupSharingSameReqdItems) = if verboseTLR then dprintf "\ntlr: packEnv fc=%A\n" fc let env = Zmap.force fc reqdItemsMap ("packEnv", string) // carrierMaps = (fclass, (v, aenv)map)map let carrierMapFor f = Zmap.force (fclassOf f) carrierMaps ("carrierMapFor", string) let valsSubEnvFor f = Zmap.keys (carrierMapFor f) // determine vals(env) - transclosure let vals = env.ReqdVals @ List.collect valsSubEnvFor env.ReqdSubEnvs // list, with repeats let vals = vals |> List.distinctBy (fun v -> v.Stamp) // Remove genuinely toplevel, no need to close over these let vals = vals |> List.filter (IsMandatoryTopLevel >> not) // Remove byrefs, no need to close over these, and would be invalid to do so since their values can change. // // Note that it is normally not OK to skip closing over values, since values given (method) TLR must have implementations // which are truly closed. However, byref values never escape into any lambdas, so are never used in anything // for which we will choose a method TLR. // // For example, consider this (FSharp 1.0 bug 5578): // // let mutable a = 1 // // let resutl1 = // let x = &a // This is NOT given TLR, because it is byref // x <- 111 // let temp = x // This is given a static field TLR, not a method TLR // // let f () = x // This is not allowed, can't capture x // x <- 999 // temp // // Compare with this: // let mutable a = 1 // // let result2 = // let x = a // this is given static field TLR // a <- 111 // let temp = a // let f () = x // This is not allowed, and is given a method TLR // a <- 999 // temp let vals = vals |> List.filter (fun v -> not (isByrefLikeTy g v.Range v.Type)) // Remove values which have been labelled TLR, no need to close over these let vals = vals |> List.filter (Zset.memberOf topValS >> not) // Carrier sets cannot include constrained polymorphic values. We can't just take such a value out, so for the moment // we'll just abandon TLR altogether and give a warning about this condition. match vals |> List.tryFind (IsGenericValWithGenericConstraints g) with | None -> () | Some v -> raise (AbortTLR v.Range) // build cmap for env let cmapPairs = vals |> List.map (fun v -> (v, (mkCompGenLocal env.m v.LogicalName v.Type |> fst))) let cmap = Zmap.ofList valOrder cmapPairs let aenvFor v = Zmap.force v cmap ("aenvFor", nameOfVal) let aenvExprFor v = exprForVal env.m (aenvFor v) // build PackedReqdItems let reqdTypars = env.reqdTypars let aenvs = Zmap.values cmap let pack = cmapPairs |> List.map (fun (v, aenv) -> mkInvisibleBind aenv (exprForVal env.m v)) let unpack = let unpackCarrier (v, aenv) = mkInvisibleBind (setValHasNoArity v) (exprForVal env.m aenv) let unpackSubenv f = let subCMap = carrierMapFor f let vaenvs = Zmap.toList subCMap vaenvs |> List.map (fun (subv, subaenv) -> mkBind NoDebugPointAtInvisibleBinding subaenv (aenvExprFor subv)) List.map unpackCarrier (Zmap.toList cmap) @ List.collect unpackSubenv env.ReqdSubEnvs // extend carrierMaps let carrierMaps = Zmap.add fc cmap carrierMaps // dump if verboseTLR then let bindingL bind = bindingL g bind dprintf "tlr: packEnv envVals =%s\n" (showL (listL valL env.ReqdVals)) dprintf "tlr: packEnv envSubs =%s\n" (showL (listL valL env.ReqdSubEnvs)) dprintf "tlr: packEnv vals =%s\n" (showL (listL valL vals)) dprintf "tlr: packEnv aenvs =%s\n" (showL (listL valL aenvs)) dprintf "tlr: packEnv pack =%s\n" (showL (listL bindingL pack)) dprintf "tlr: packEnv unpack =%s\n" (showL (listL bindingL unpack)) // result (fc, { ep_etps = Zset.elements reqdTypars ep_aenvs = aenvs ep_pack = pack ep_unpack = unpack}), carrierMaps let carriedMaps = Zmap.empty fclassOrder let envPacks, _carriedMaps = List.mapFold packEnv carriedMaps declist (* List.mapFold in dec order *) let envPacks = Zmap.ofList fclassOrder envPacks envPacks //------------------------------------------------------------------------- // step3: chooseEnvPacks //------------------------------------------------------------------------- #if DEBUG let DumpEnvPackM g envPackM = let bindingL bind = bindingL g bind for KeyValue(fc, packedReqdItems) in envPackM do dprintf "packedReqdItems: fc = %A\n" fc dprintf " reqdTypars = %s\n" (showL (commaListL (List.map typarL packedReqdItems.ep_etps))) dprintf " aenvs = %s\n" (showL (commaListL (List.map valL packedReqdItems.ep_aenvs))) dprintf " pack = %s\n" (showL (semiListL (List.map bindingL packedReqdItems.ep_pack))) dprintf " unpack = %s\n" (showL (semiListL (List.map bindingL packedReqdItems.ep_unpack))) dprintf "\n" #endif /// For each fclass, have an env. /// Required to choose an PackedReqdItems, /// e.g. deciding whether to tuple up the environment or not. /// e.g. deciding whether to use known values for required sub environments. /// /// Scope for optimization env packing here. /// For now, pass all environments via arguments since aiming to eliminate allocations. /// Later, package as tuples if arg lists get too long. let ChooseReqdItemPackings g fclassM topValS declist reqdItemsMap = if verboseTLR then dprintf "ChooseReqdItemPackings------\n" let envPackM = FlatEnvPacks g fclassM topValS declist reqdItemsMap #if DEBUG if verboseTLR then DumpEnvPackM g envPackM #endif envPackM //------------------------------------------------------------------------- // step3: CreateNewValuesForTLR //------------------------------------------------------------------------- /// arity info where nothing is untupled // REVIEW: could do better here by preserving names let MakeSimpleArityInfo tps n = ValReprInfo (ValReprInfo.InferTyparInfo tps, List.replicate n ValReprInfo.unnamedTopArg, ValReprInfo.unnamedRetVal) let CreateNewValuesForTLR g tlrS arityM fclassM envPackM = if verboseTLR then dprintf "CreateNewValuesForTLR------\n" let createFHat (f: Val) = let wf = Zmap.force f arityM ("createFHat - wf", (fun v -> showL (valL v))) let fc = Zmap.force f fclassM ("createFHat - fc", nameOfVal) let envp = Zmap.force fc envPackM ("CreateNewValuesForTLR - envp", string) let name = f.LogicalName (* + "_TLR_" + string wf *) let m = f.Range let tps, tau = f.TypeScheme let argtys, res = stripFunTy g tau let newTps = envp.ep_etps @ tps let fHatTy = let newArgtys = List.map typeOfVal envp.ep_aenvs @ argtys mkLambdaTy newTps newArgtys res let fHatArity = MakeSimpleArityInfo newTps (envp.ep_aenvs.Length + wf) let fHatName = // Ensure that we have an g.CompilerGlobalState assert(g.CompilerGlobalState |> Option.isSome) g.CompilerGlobalState.Value.NiceNameGenerator.FreshCompilerGeneratedName(name, m) let fHat = mkLocalNameTypeArity f.IsCompilerGenerated m fHatName fHatTy (Some fHatArity) fHat let fs = Zset.elements tlrS let ffHats = List.map (fun f -> f, createFHat f) fs let fHatM = Zmap.ofList valOrder ffHats fHatM //------------------------------------------------------------------------- // pass4: rewrite - penv //------------------------------------------------------------------------- module Pass4_RewriteAssembly = [<NoEquality; NoComparison>] type RewriteContext = { ccu: CcuThunk g: TcGlobals tlrS: Zset<Val> topValS: Zset<Val> arityM: Zmap<Val, int> fclassM: Zmap<Val, BindingGroupSharingSameReqdItems> recShortCallS: Zset<Val> envPackM: Zmap<BindingGroupSharingSameReqdItems, PackedReqdItems> /// The mapping from 'f' values to 'fHat' values fHatM: Zmap<Val, Val> } //------------------------------------------------------------------------- // pass4: rwstate (z state) //------------------------------------------------------------------------- type IsRecursive = IsRec | NotRec type LiftedDeclaration = IsRecursive * Bindings (* where bool=true if letrec *) /// This state is related to lifting to top-level (which is actually disabled right now) /// This is to ensure the TLR constants get initialised once. /// /// Top-level status ends when stepping inside a lambda, where a lambda is: /// Expr.TyLambda, Expr.Lambda, Expr.Obj (and tmethods). /// [... also, try_catch handlers, and switch targets...] /// /// Top* repr bindings already at top-level do not need moving... /// [and should not be, since they may lift over unmoved defns on which they depend]. /// Any TLR repr bindings under lambdas can be filtered out (and collected), /// giving pre-declarations to insert before the outermost lambda expr. type RewriteState = { rws_mustinline: bool /// counts level of enclosing "lambdas" rws_innerLevel: int /// collected preDecs (fringe is in-order) rws_preDecs: Tree<LiftedDeclaration> } let rewriteState0 = {rws_mustinline=false;rws_innerLevel=0;rws_preDecs=emptyTR} // move in/out of lambdas (or lambda containing construct) let EnterInner z = {z with rws_innerLevel = z.rws_innerLevel + 1} let ExitInner z = {z with rws_innerLevel = z.rws_innerLevel - 1} let EnterMustInline b z f = let orig = z.rws_mustinline let x, z' = f (if b then {z with rws_mustinline = true } else z) {z' with rws_mustinline = orig }, x /// extract PreDecs (iff at top-level) let ExtractPreDecs z = // If level=0, so at top-level, then pop decs, // else keep until get back to a top-level point. if z.rws_innerLevel=0 then // at top-level, extract preDecs let preDecs = fringeTR z.rws_preDecs preDecs, {z with rws_preDecs=emptyTR} else // not yet top-level, keep decs [], z /// pop and set preDecs as "LiftedDeclaration tree" let PopPreDecs z = {z with rws_preDecs=emptyTR}, z.rws_preDecs let SetPreDecs z pdt = {z with rws_preDecs=pdt} /// collect Top* repr bindings - if needed... let LiftTopBinds _isRec _penv z binds = z, binds /// Wrap preDecs (in order) over an expr - use letrec/let as approp let MakePreDec m (isRec, binds: Bindings) expr = if isRec=IsRec then // By definition top level bindings don't refer to non-top level bindings, so we can build them in two parts let topLevelBinds, nonTopLevelBinds = binds |> List.partition (fun bind -> bind.Var.IsCompiledAsTopLevel) mkLetRecBinds m topLevelBinds (mkLetRecBinds m nonTopLevelBinds expr) else mkLetsFromBindings m binds expr /// Must MakePreDecs around every construct that could do EnterInner (which filters TLR decs). /// i.e. let, letrec (bind may...), ilobj, lambda, tlambda. let MakePreDecs m preDecs expr = List.foldBack (MakePreDec m) preDecs expr let RecursivePreDecs pdsA pdsB = let pds = fringeTR (TreeNode[pdsA;pdsB]) let decs = pds |> List.collect snd LeafNode (IsRec, decs) //------------------------------------------------------------------------- // pass4: lowertop - convert_vterm_bind on TopLevel binds //------------------------------------------------------------------------- let ConvertBind g (TBind(v, repr, _) as bind) = match v.ValReprInfo with | None -> v.SetValReprInfo (Some (InferArityOfExprBinding g AllowTypeDirectedDetupling.Yes v repr )) | Some _ -> () bind //------------------------------------------------------------------------- // pass4: transBind (translate) //------------------------------------------------------------------------- // Transform // let f<tps> vss = f_body[<f_freeTypars>, f_freeVars] // To // let f<tps> vss = fHat<f_freeTypars> f_freeVars vss // let fHat<tps> f_freeVars vss = f_body[<f_freeTypars>, f_freeVars] let TransTLRBindings penv (binds: Bindings) = if isNil binds then List.empty, List.empty else let fc = BindingGroupSharingSameReqdItems binds let envp = Zmap.force fc penv.envPackM ("TransTLRBindings", string) let fRebinding (TBind(fOrig, b, letSeqPtOpt)) = let m = fOrig.Range let tps, vss, _b, rty = stripTopLambda (b, fOrig.Type) let aenvExprs = envp.ep_aenvs |> List.map (exprForVal m) let vsExprs = vss |> List.map (mkRefTupledVars penv.g m) let fHat = Zmap.force fOrig penv.fHatM ("fRebinding", nameOfVal) (* REVIEW: is this mutation really, really necessary? *) (* Why are we applying TLR if the thing already has an arity? *) let fOrig = setValHasNoArity fOrig let fBind = mkMultiLambdaBind fOrig letSeqPtOpt m tps vss (mkApps penv.g ((exprForVal m fHat, fHat.Type), [List.map mkTyparTy (envp.ep_etps @ tps)], aenvExprs @ vsExprs, m), rty) fBind let fHatNewBinding (shortRecBinds: Bindings) (TBind(f, b, letSeqPtOpt)) = let wf = Zmap.force f penv.arityM ("fHatNewBinding - arityM", nameOfVal) let fHat = Zmap.force f penv.fHatM ("fHatNewBinding - fHatM", nameOfVal) // Take off the variables let tps, vss, b, rty = stripTopLambda (b, f.Type) // Don't take all the variables - only up to length wf let vssTake, vssDrop = List.splitAt wf vss // put the variables back on let b, rty = mkMultiLambdasCore b.Range vssDrop (b, rty) // fHat, args let m = fHat.Range // Add the type variables to the front let fHat_tps = envp.ep_etps @ tps // Add the 'aenv' and original taken variables to the front let fHat_args = List.map List.singleton envp.ep_aenvs @ vssTake let fHat_body = mkLetsFromBindings m envp.ep_unpack b let fHat_body = mkLetsFromBindings m shortRecBinds fHat_body // bind "f" if have short recursive calls (somewhere) // fHat binding, f rebinding let fHatBind = mkMultiLambdaBind fHat letSeqPtOpt m fHat_tps fHat_args (fHat_body, rty) fHatBind let rebinds = binds |> List.map fRebinding let shortRecBinds = rebinds |> List.filter (fun b -> penv.recShortCallS.Contains(b.Var)) let newBinds = binds |> List.map (fHatNewBinding shortRecBinds) newBinds, rebinds let GetAEnvBindings penv fc = match Zmap.tryFind fc penv.envPackM with | None -> List.empty // no env for this mutual binding | Some envp -> envp.ep_pack // environment pack bindings let TransBindings xisRec penv (binds: Bindings) = let tlrBs, nonTlrBs = binds |> List.partition (fun b -> Zset.contains b.Var penv.tlrS) let fclass = BindingGroupSharingSameReqdItems tlrBs // Trans each TLR f binding into fHat and f rebind let newTlrBinds, tlrRebinds = TransTLRBindings penv tlrBs let aenvBinds = GetAEnvBindings penv fclass // lower nonTlrBs if they are GTL // QUERY: we repeat this logic in LowerCallsAndSeqs. Do we really need to do this here? // QUERY: yes and no - if we don't, we have an unrealizable term, and many decisions must // QUERY: correlate with LowerCallsAndSeqs. let forceTopBindToHaveArity (bind: Binding) = if penv.topValS.Contains(bind.Var) then ConvertBind penv.g bind else bind let nonTlrBs = nonTlrBs |> List.map forceTopBindToHaveArity let tlrRebinds = tlrRebinds |> List.map forceTopBindToHaveArity // assemble into replacement bindings let bindAs, rebinds = match xisRec with | IsRec -> newTlrBinds @ tlrRebinds @ nonTlrBs @ aenvBinds, [] (* note: aenv last, order matters in letrec! *) | NotRec -> aenvBinds @ newTlrBinds, tlrRebinds @ nonTlrBs (* note: aenv go first, they may be used *) bindAs, rebinds //------------------------------------------------------------------------- // pass4: TransApp (translate) //------------------------------------------------------------------------- let TransApp penv (fx, fty, tys, args, m) = // Is it a val app, where the val f is TLR with arity wf? // CLEANUP NOTE: should be using a mkApps to make all applications match fx with | Expr.Val (fvref: ValRef, _, m) when (Zset.contains fvref.Deref penv.tlrS) && (let wf = Zmap.force fvref.Deref penv.arityM ("TransApp - wf", nameOfVal) IsArityMet fvref wf tys args) -> let f = fvref.Deref (* replace by direct call to corresponding fHat (and additional closure args) *) let fc = Zmap.force f penv.fclassM ("TransApp - fc", nameOfVal) let envp = Zmap.force fc penv.envPackM ("TransApp - envp", string) let fHat = Zmap.force f penv.fHatM ("TransApp - fHat", nameOfVal) let tys = (List.map mkTyparTy envp.ep_etps) @ tys let aenvExprs = List.map (exprForVal m) envp.ep_aenvs let args = aenvExprs @ args mkApps penv.g ((exprForVal m fHat, fHat.Type), [tys], args, m) (* change, direct fHat call with closure (reqdTypars, aenvs) *) | _ -> if isNil tys && isNil args then fx else Expr.App (fx, fty, tys, args, m) (* no change, f is expr *) //------------------------------------------------------------------------- // pass4: pass (over expr) //------------------------------------------------------------------------- /// At bindings, fixup any TLR bindings. /// At applications, fixup calls if they are arity-met instances of TLR. /// At free vals, fixup 0-call if it is an arity-met constant. /// Other cases rewrite structurally. let rec TransExpr (penv: RewriteContext) (z: RewriteState) expr: Expr * RewriteState = match expr with // Use TransLinearExpr with a rebuild-continuation for some forms to avoid stack overflows on large terms | LinearOpExpr _ | LinearMatchExpr _ | Expr.LetRec _ // note, Expr.LetRec not normally considered linear, but keeping it here as it's always been here | Expr.Let _ | Expr.Sequential _ -> TransLinearExpr penv z expr (fun res -> res) // app - call sites may require z. // - match the app (collapsing reclinks and type instances). // - patch it. | Expr.App (f, fty, tys, args, m) -> // pass over f, args subexprs let f, z = TransExpr penv z f let args, z = List.mapFold (TransExpr penv) z args // match app, and fixup if needed let f, fty, tys, args, m = destApp (f, fty, tys, args, m) let expr = TransApp penv (f, fty, tys, args, m) expr, z | Expr.Val (v, _, m) -> // consider this a trivial app let fx, fty = expr, v.Type let expr = TransApp penv (fx, fty, [], [], m) expr, z // reclink - suppress | Expr.Link r -> TransExpr penv z (!r) // ilobj - has implicit lambda exprs and recursive/base references | Expr.Obj (_, ty, basev, basecall, overrides, iimpls, m) -> let basecall, z = TransExpr penv z basecall let overrides, z = List.mapFold (TransMethod penv) z overrides let iimpls, z = (z, iimpls) ||> List.mapFold (fun z (tType, objExprs) -> let objExprs', z' = List.mapFold (TransMethod penv) z objExprs (tType, objExprs'), z') let expr = Expr.Obj (newUnique(), ty, basev, basecall, overrides, iimpls, m) let pds, z = ExtractPreDecs z MakePreDecs m pds expr, z (* if TopLevel, lift preDecs over the ilobj expr *) // lambda, tlambda - explicit lambda terms | Expr.Lambda (_, ctorThisValOpt, baseValOpt, argvs, body, m, rty) -> let z = EnterInner z let body, z = TransExpr penv z body let z = ExitInner z let pds, z = ExtractPreDecs z MakePreDecs m pds (rebuildLambda m ctorThisValOpt baseValOpt argvs (body, rty)), z | Expr.TyLambda (_, argtyvs, body, m, rty) -> let z = EnterInner z let body, z = TransExpr penv z body let z = ExitInner z let pds, z = ExtractPreDecs z MakePreDecs m pds (mkTypeLambda m argtyvs (body, rty)), z /// Lifting TLR out over constructs (disabled) /// Lift minimally to ensure the defn is not lifted up and over defns on which it depends (disabled) | Expr.Match (spBind, exprm, dtree, targets, m, ty) -> let targets = Array.toList targets let dtree, z = TransDecisionTree penv z dtree let targets, z = List.mapFold (TransDecisionTreeTarget penv) z targets // TransDecisionTreeTarget wraps EnterInner/exitInnter, so need to collect any top decs let pds,z = ExtractPreDecs z MakePreDecs m pds (mkAndSimplifyMatch spBind exprm m ty dtree targets), z // all others - below - rewrite structurally - so boiler plate code after this point... | Expr.Const _ -> expr,z | Expr.Quote (a,dataCell,isFromQueryExpression,m,ty) -> let doData (typeDefs,argTypes,argExprs,data) z = let argExprs,z = List.mapFold (TransExpr penv) z argExprs (typeDefs,argTypes,argExprs,data), z let data, z = match !dataCell with | Some (data1, data2) -> let data1, z = doData data1 z let data2, z = doData data2 z Some (data1, data2), z | None -> None, z Expr.Quote (a,ref data,isFromQueryExpression,m,ty),z | Expr.Op (c,tyargs,args,m) -> let args,z = List.mapFold (TransExpr penv) z args Expr.Op (c,tyargs,args,m),z | Expr.StaticOptimization (constraints,e2,e3,m) -> let e2,z = TransExpr penv z e2 let e3,z = TransExpr penv z e3 Expr.StaticOptimization (constraints,e2,e3,m),z | Expr.TyChoose (_,_,m) -> error(Error(FSComp.SR.tlrUnexpectedTExpr(),m)) | Expr.WitnessArg (_witnessInfo, _m) -> expr, z /// Walk over linear structured terms in tail-recursive loop, using a continuation /// to represent the rebuild-the-term stack and TransLinearExpr penv z expr (contf: Expr * RewriteState -> Expr * RewriteState) = match expr with | Expr.Sequential (e1, e2, dir, spSeq, m) -> let e1, z = TransExpr penv z e1 TransLinearExpr penv z e2 (contf << (fun (e2, z) -> Expr.Sequential (e1, e2, dir, spSeq, m), z)) // letrec - pass_recbinds does the work | Expr.LetRec (binds, e, m, _) -> let z = EnterInner z // For letrec, preDecs from RHS must mutually recurse with those from the bindings let z, pdsPrior = PopPreDecs z let binds, z = List.mapFold (TransBindingRhs penv) z binds let z, pdsRhs = PopPreDecs z let binds, rebinds = TransBindings IsRec penv binds let z, binds = LiftTopBinds IsRec penv z binds (* factor Top* repr binds *) let z, rebinds = LiftTopBinds IsRec penv z rebinds let z, pdsBind = PopPreDecs z let z = SetPreDecs z (TreeNode [pdsPrior;RecursivePreDecs pdsBind pdsRhs]) let z = ExitInner z let pds, z = ExtractPreDecs z // tailcall TransLinearExpr penv z e (contf << (fun (e, z) -> let e = mkLetsFromBindings m rebinds e MakePreDecs m pds (Expr.LetRec (binds, e, m, Construct.NewFreeVarsCache())), z)) // let - can consider the mu-let bindings as mu-letrec bindings - so like as above | Expr.Let (bind, e, m, _) -> // For let, preDecs from RHS go before those of bindings, which is collection order let bind, z = TransBindingRhs penv z bind let binds, rebinds = TransBindings NotRec penv [bind] // factor Top* repr binds let z, binds = LiftTopBinds NotRec penv z binds let z, rebinds = LiftTopBinds NotRec penv z rebinds // any lifted PreDecs from binding, if so wrap them... let pds, z = ExtractPreDecs z // tailcall TransLinearExpr penv z e (contf << (fun (e, z) -> let e = mkLetsFromBindings m rebinds e MakePreDecs m pds (mkLetsFromBindings m binds e), z)) | LinearMatchExpr (spBind, exprm, dtree, tg1, e2, sp2, m2, ty) -> let dtree, z = TransDecisionTree penv z dtree let tg1, z = TransDecisionTreeTarget penv z tg1 // tailcall TransLinearExpr penv z e2 (contf << (fun (e2, z) -> rebuildLinearMatchExpr (spBind, exprm, dtree, tg1, e2, sp2, m2, ty), z)) | LinearOpExpr (op, tyargs, argsHead, argLast, m) -> let argsHead,z = List.mapFold (TransExpr penv) z argsHead // tailcall TransLinearExpr penv z argLast (contf << (fun (argLast, z) -> rebuildLinearOpExpr (op, tyargs, argsHead, argLast, m), z)) | _ -> // not a linear expression contf (TransExpr penv z expr) and TransMethod penv (z: RewriteState) (TObjExprMethod(slotsig, attribs, tps, vs, e, m)) = let z = EnterInner z let e, z = TransExpr penv z e let z = ExitInner z TObjExprMethod(slotsig, attribs, tps, vs, e, m), z and TransBindingRhs penv z (TBind(v, e, letSeqPtOpt)) : Binding * RewriteState = let mustInline = v.MustInline let z, e = EnterMustInline mustInline z (fun z -> TransExpr penv z e) TBind (v, e, letSeqPtOpt), z and TransDecisionTree penv z x: DecisionTree * RewriteState = match x with | TDSuccess (es, n) -> let es, z = List.mapFold (TransExpr penv) z es TDSuccess(es, n), z | TDBind (bind, rest) -> let bind, z = TransBindingRhs penv z bind let rest, z = TransDecisionTree penv z rest TDBind(bind, rest), z | TDSwitch (e, cases, dflt, m) -> let e, z = TransExpr penv z e let TransDecisionTreeCase penv z (TCase (discrim, dtree)) = let dtree, z = TransDecisionTree penv z dtree TCase(discrim, dtree), z let cases, z = List.mapFold (TransDecisionTreeCase penv) z cases let dflt, z = Option.mapFold (TransDecisionTree penv) z dflt TDSwitch (e, cases, dflt, m), z and TransDecisionTreeTarget penv z (TTarget(vs, e, spTarget)) = let z = EnterInner z let e, z = TransExpr penv z e let z = ExitInner z TTarget(vs, e, spTarget), z and TransValBinding penv z bind = TransBindingRhs penv z bind and TransValBindings penv z binds = List.mapFold (TransValBinding penv) z binds and TransModuleExpr penv z x = match x with | ModuleOrNamespaceExprWithSig(mty, def, m) -> let def, z = TransModuleDef penv z def ModuleOrNamespaceExprWithSig(mty, def, m), z and TransModuleDefs penv z x = List.mapFold (TransModuleDef penv) z x and TransModuleDef penv (z: RewriteState) x: ModuleOrNamespaceExpr * RewriteState = match x with | TMDefRec(isRec, tycons, mbinds, m) -> let mbinds, z = TransModuleBindings penv z mbinds TMDefRec(isRec, tycons, mbinds, m), z | TMDefLet(bind, m) -> let bind, z = TransValBinding penv z bind TMDefLet(bind, m), z | TMDefDo(e, m) -> let _bind, z = TransExpr penv z e TMDefDo(e, m), z | TMDefs defs -> let defs, z = TransModuleDefs penv z defs TMDefs defs, z | TMAbstract mexpr -> let mexpr, z = TransModuleExpr penv z mexpr TMAbstract mexpr, z and TransModuleBindings penv z binds = List.mapFold (TransModuleBinding penv) z binds and TransModuleBinding penv z x = match x with | ModuleOrNamespaceBinding.Binding bind -> let bind, z = TransValBinding penv z bind ModuleOrNamespaceBinding.Binding bind, z | ModuleOrNamespaceBinding.Module(nm, rhs) -> let rhs, z = TransModuleDef penv z rhs ModuleOrNamespaceBinding.Module(nm, rhs), z let TransImplFile penv z (TImplFile (fragName, pragmas, moduleExpr, hasExplicitEntryPoint, isScript, anonRecdTypes)) = let moduleExpr, z = TransModuleExpr penv z moduleExpr (TImplFile (fragName, pragmas, moduleExpr, hasExplicitEntryPoint, isScript, anonRecdTypes)), z //------------------------------------------------------------------------- // pass5: copyExpr //------------------------------------------------------------------------- let RecreateUniqueBounds g expr = copyImplFile g OnlyCloneExprVals expr //------------------------------------------------------------------------- // entry point //------------------------------------------------------------------------- let MakeTLRDecisions ccu g expr = try // pass1: choose the f to be TLR with arity(f) let tlrS, topValS, arityM = Pass1_DetermineTLRAndArities.DetermineTLRAndArities g expr // pass2: determine the typar/freevar closures, f->fclass and fclass declist let reqdItemsMap, fclassM, declist, recShortCallS = Pass2_DetermineReqdItems.DetermineReqdItems (tlrS, arityM) expr // pass3 let envPackM = ChooseReqdItemPackings g fclassM topValS declist reqdItemsMap let fHatM = CreateNewValuesForTLR g tlrS arityM fclassM envPackM // pass4: rewrite if verboseTLR then dprintf "TransExpr(rw)------\n" let expr, _ = let penv: Pass4_RewriteAssembly.RewriteContext = {ccu=ccu; g=g; tlrS=tlrS; topValS=topValS; arityM=arityM; fclassM=fclassM; recShortCallS=recShortCallS; envPackM=envPackM; fHatM=fHatM} let z = Pass4_RewriteAssembly.rewriteState0 Pass4_RewriteAssembly.TransImplFile penv z expr // pass5: copyExpr to restore "each bound is unique" property // aka, copyExpr if verboseTLR then dprintf "copyExpr------\n" let expr = RecreateUniqueBounds g expr if verboseTLR then dprintf "TLR-done------\n" // Summary: // GTL = genuine top-level // TLR = TopLevelRep = identified by this pass // Note, some GTL are skipped until sort out the initial env... // if verboseTLR then dprintf "note: tlr = %d inner-TLR + %d GenuineTopLevel-TLR + %d GenuineTopLevel skipped TLR (public)\n" // (lengthS (Zset.diff tlrS topValS)) // (lengthS (Zset.inter topValS tlrS)) // (lengthS (Zset.diff topValS tlrS)) // DONE expr with AbortTLR m -> warning(Error(FSComp.SR.tlrLambdaLiftingOptimizationsNotApplied(), m)) expr
{ "pile_set_name": "Github" }
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import <NewsUI2/_TtC7NewsUI217NoopAudioAssembly.h> @interface _TtC7NewsUI217NoopAudioAssembly (NewsUI2) - (void)loadInRegistry:(id)arg1; @end
{ "pile_set_name": "Github" }
/* * Copyright (C) 2004, 2005 Nikolas Zimmermann <zimmermann@kde.org> * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org> * Copyright (C) 2006 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ interface SVGTransform { // Transform Types const unsigned short SVG_TRANSFORM_UNKNOWN = 0; const unsigned short SVG_TRANSFORM_MATRIX = 1; const unsigned short SVG_TRANSFORM_TRANSLATE = 2; const unsigned short SVG_TRANSFORM_SCALE = 3; const unsigned short SVG_TRANSFORM_ROTATE = 4; const unsigned short SVG_TRANSFORM_SKEWX = 5; const unsigned short SVG_TRANSFORM_SKEWY = 6; readonly attribute unsigned short type; [ImplementedAs=svgMatrix] readonly attribute SVGMatrix matrix; readonly attribute unrestricted float angle; [StrictTypeChecking] void setMatrix(SVGMatrix matrix); [StrictTypeChecking] void setTranslate(unrestricted float tx, unrestricted float ty); [StrictTypeChecking] void setScale(unrestricted float sx, unrestricted float sy); [StrictTypeChecking] void setRotate(unrestricted float angle, unrestricted float cx, unrestricted float cy); [StrictTypeChecking] void setSkewX(unrestricted float angle); [StrictTypeChecking] void setSkewY(unrestricted float angle); };
{ "pile_set_name": "Github" }
def safe_remove(f): import os try: os.remove(f) except OSError: pass """ Basic logger functionality; replace this with a real logger of your choice """ import imp import sys class VPLogger: def debug(self, s): print '[DEBUG] %s' % s def info(self, s): print '[INFO] %s' % s def warning(self, s): print '[WARNING] %s' % s def error(self, s): print '[ERROR] %s' % s def import_non_local(name, custom_name=None): """Import when you have conflicting names""" custom_name = custom_name or name f, pathname, desc = imp.find_module(name, sys.path[1:]) module = imp.load_module(custom_name, f, pathname, desc) if f: f.close() return module
{ "pile_set_name": "Github" }
import { IScheduler } from '../Scheduler'; import { Observable } from '../Observable'; import { Subscriber } from '../Subscriber'; import { TeardownLogic } from '../Subscription'; /** * We need this JSDoc comment for affecting ESDoc. * @extends {Ignored} * @hide true */ export declare class ScalarObservable<T> extends Observable<T> { value: T; private scheduler; static create<T>(value: T, scheduler?: IScheduler): ScalarObservable<T>; static dispatch(state: any): void; _isScalar: boolean; constructor(value: T, scheduler?: IScheduler); protected _subscribe(subscriber: Subscriber<T>): TeardownLogic; }
{ "pile_set_name": "Github" }
package ezy.sdk3rd.social.sdk; /** * Created by ezy on 17/3/18. */ public interface OnSucceed<T> { void onSucceed(T result); }
{ "pile_set_name": "Github" }
package jsoniter import ( "encoding/json" "io" "reflect" "sync" "unsafe" "github.com/modern-go/concurrent" "github.com/modern-go/reflect2" ) // Config customize how the API should behave. // The API is created from Config by Froze. type Config struct { IndentionStep int MarshalFloatWith6Digits bool EscapeHTML bool SortMapKeys bool UseNumber bool DisallowUnknownFields bool TagKey string OnlyTaggedField bool ValidateJsonRawMessage bool ObjectFieldMustBeSimpleString bool CaseSensitive bool } // API the public interface of this package. // Primary Marshal and Unmarshal. type API interface { IteratorPool StreamPool MarshalToString(v interface{}) (string, error) Marshal(v interface{}) ([]byte, error) MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) UnmarshalFromString(str string, v interface{}) error Unmarshal(data []byte, v interface{}) error Get(data []byte, path ...interface{}) Any NewEncoder(writer io.Writer) *Encoder NewDecoder(reader io.Reader) *Decoder Valid(data []byte) bool RegisterExtension(extension Extension) DecoderOf(typ reflect2.Type) ValDecoder EncoderOf(typ reflect2.Type) ValEncoder } // ConfigDefault the default API var ConfigDefault = Config{ EscapeHTML: true, }.Froze() // ConfigCompatibleWithStandardLibrary tries to be 100% compatible with standard library behavior var ConfigCompatibleWithStandardLibrary = Config{ EscapeHTML: true, SortMapKeys: true, ValidateJsonRawMessage: true, }.Froze() // ConfigFastest marshals float with only 6 digits precision var ConfigFastest = Config{ EscapeHTML: false, MarshalFloatWith6Digits: true, // will lose precession ObjectFieldMustBeSimpleString: true, // do not unescape object field }.Froze() type frozenConfig struct { configBeforeFrozen Config sortMapKeys bool indentionStep int objectFieldMustBeSimpleString bool onlyTaggedField bool disallowUnknownFields bool decoderCache *concurrent.Map encoderCache *concurrent.Map encoderExtension Extension decoderExtension Extension extraExtensions []Extension streamPool *sync.Pool iteratorPool *sync.Pool caseSensitive bool } func (cfg *frozenConfig) initCache() { cfg.decoderCache = concurrent.NewMap() cfg.encoderCache = concurrent.NewMap() } func (cfg *frozenConfig) addDecoderToCache(cacheKey uintptr, decoder ValDecoder) { cfg.decoderCache.Store(cacheKey, decoder) } func (cfg *frozenConfig) addEncoderToCache(cacheKey uintptr, encoder ValEncoder) { cfg.encoderCache.Store(cacheKey, encoder) } func (cfg *frozenConfig) getDecoderFromCache(cacheKey uintptr) ValDecoder { decoder, found := cfg.decoderCache.Load(cacheKey) if found { return decoder.(ValDecoder) } return nil } func (cfg *frozenConfig) getEncoderFromCache(cacheKey uintptr) ValEncoder { encoder, found := cfg.encoderCache.Load(cacheKey) if found { return encoder.(ValEncoder) } return nil } var cfgCache = concurrent.NewMap() func getFrozenConfigFromCache(cfg Config) *frozenConfig { obj, found := cfgCache.Load(cfg) if found { return obj.(*frozenConfig) } return nil } func addFrozenConfigToCache(cfg Config, frozenConfig *frozenConfig) { cfgCache.Store(cfg, frozenConfig) } // Froze forge API from config func (cfg Config) Froze() API { api := &frozenConfig{ sortMapKeys: cfg.SortMapKeys, indentionStep: cfg.IndentionStep, objectFieldMustBeSimpleString: cfg.ObjectFieldMustBeSimpleString, onlyTaggedField: cfg.OnlyTaggedField, disallowUnknownFields: cfg.DisallowUnknownFields, caseSensitive: cfg.CaseSensitive, } api.streamPool = &sync.Pool{ New: func() interface{} { return NewStream(api, nil, 512) }, } api.iteratorPool = &sync.Pool{ New: func() interface{} { return NewIterator(api) }, } api.initCache() encoderExtension := EncoderExtension{} decoderExtension := DecoderExtension{} if cfg.MarshalFloatWith6Digits { api.marshalFloatWith6Digits(encoderExtension) } if cfg.EscapeHTML { api.escapeHTML(encoderExtension) } if cfg.UseNumber { api.useNumber(decoderExtension) } if cfg.ValidateJsonRawMessage { api.validateJsonRawMessage(encoderExtension) } api.encoderExtension = encoderExtension api.decoderExtension = decoderExtension api.configBeforeFrozen = cfg return api } func (cfg Config) frozeWithCacheReuse(extraExtensions []Extension) *frozenConfig { api := getFrozenConfigFromCache(cfg) if api != nil { return api } api = cfg.Froze().(*frozenConfig) for _, extension := range extraExtensions { api.RegisterExtension(extension) } addFrozenConfigToCache(cfg, api) return api } func (cfg *frozenConfig) validateJsonRawMessage(extension EncoderExtension) { encoder := &funcEncoder{func(ptr unsafe.Pointer, stream *Stream) { rawMessage := *(*json.RawMessage)(ptr) iter := cfg.BorrowIterator([]byte(rawMessage)) defer cfg.ReturnIterator(iter) iter.Read() if iter.Error != nil && iter.Error != io.EOF { stream.WriteRaw("null") } else { stream.WriteRaw(string(rawMessage)) } }, func(ptr unsafe.Pointer) bool { return len(*((*json.RawMessage)(ptr))) == 0 }} extension[reflect2.TypeOfPtr((*json.RawMessage)(nil)).Elem()] = encoder extension[reflect2.TypeOfPtr((*RawMessage)(nil)).Elem()] = encoder } func (cfg *frozenConfig) useNumber(extension DecoderExtension) { extension[reflect2.TypeOfPtr((*interface{})(nil)).Elem()] = &funcDecoder{func(ptr unsafe.Pointer, iter *Iterator) { exitingValue := *((*interface{})(ptr)) if exitingValue != nil && reflect.TypeOf(exitingValue).Kind() == reflect.Ptr { iter.ReadVal(exitingValue) return } if iter.WhatIsNext() == NumberValue { *((*interface{})(ptr)) = json.Number(iter.readNumberAsString()) } else { *((*interface{})(ptr)) = iter.Read() } }} } func (cfg *frozenConfig) getTagKey() string { tagKey := cfg.configBeforeFrozen.TagKey if tagKey == "" { return "json" } return tagKey } func (cfg *frozenConfig) RegisterExtension(extension Extension) { cfg.extraExtensions = append(cfg.extraExtensions, extension) copied := cfg.configBeforeFrozen cfg.configBeforeFrozen = copied } type lossyFloat32Encoder struct { } func (encoder *lossyFloat32Encoder) Encode(ptr unsafe.Pointer, stream *Stream) { stream.WriteFloat32Lossy(*((*float32)(ptr))) } func (encoder *lossyFloat32Encoder) IsEmpty(ptr unsafe.Pointer) bool { return *((*float32)(ptr)) == 0 } type lossyFloat64Encoder struct { } func (encoder *lossyFloat64Encoder) Encode(ptr unsafe.Pointer, stream *Stream) { stream.WriteFloat64Lossy(*((*float64)(ptr))) } func (encoder *lossyFloat64Encoder) IsEmpty(ptr unsafe.Pointer) bool { return *((*float64)(ptr)) == 0 } // EnableLossyFloatMarshalling keeps 10**(-6) precision // for float variables for better performance. func (cfg *frozenConfig) marshalFloatWith6Digits(extension EncoderExtension) { // for better performance extension[reflect2.TypeOfPtr((*float32)(nil)).Elem()] = &lossyFloat32Encoder{} extension[reflect2.TypeOfPtr((*float64)(nil)).Elem()] = &lossyFloat64Encoder{} } type htmlEscapedStringEncoder struct { } func (encoder *htmlEscapedStringEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { str := *((*string)(ptr)) stream.WriteStringWithHTMLEscaped(str) } func (encoder *htmlEscapedStringEncoder) IsEmpty(ptr unsafe.Pointer) bool { return *((*string)(ptr)) == "" } func (cfg *frozenConfig) escapeHTML(encoderExtension EncoderExtension) { encoderExtension[reflect2.TypeOfPtr((*string)(nil)).Elem()] = &htmlEscapedStringEncoder{} } func (cfg *frozenConfig) cleanDecoders() { typeDecoders = map[string]ValDecoder{} fieldDecoders = map[string]ValDecoder{} *cfg = *(cfg.configBeforeFrozen.Froze().(*frozenConfig)) } func (cfg *frozenConfig) cleanEncoders() { typeEncoders = map[string]ValEncoder{} fieldEncoders = map[string]ValEncoder{} *cfg = *(cfg.configBeforeFrozen.Froze().(*frozenConfig)) } func (cfg *frozenConfig) MarshalToString(v interface{}) (string, error) { stream := cfg.BorrowStream(nil) defer cfg.ReturnStream(stream) stream.WriteVal(v) if stream.Error != nil { return "", stream.Error } return string(stream.Buffer()), nil } func (cfg *frozenConfig) Marshal(v interface{}) ([]byte, error) { stream := cfg.BorrowStream(nil) defer cfg.ReturnStream(stream) stream.WriteVal(v) if stream.Error != nil { return nil, stream.Error } result := stream.Buffer() copied := make([]byte, len(result)) copy(copied, result) return copied, nil } func (cfg *frozenConfig) MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { if prefix != "" { panic("prefix is not supported") } for _, r := range indent { if r != ' ' { panic("indent can only be space") } } newCfg := cfg.configBeforeFrozen newCfg.IndentionStep = len(indent) return newCfg.frozeWithCacheReuse(cfg.extraExtensions).Marshal(v) } func (cfg *frozenConfig) UnmarshalFromString(str string, v interface{}) error { data := []byte(str) iter := cfg.BorrowIterator(data) defer cfg.ReturnIterator(iter) iter.ReadVal(v) c := iter.nextToken() if c == 0 { if iter.Error == io.EOF { return nil } return iter.Error } iter.ReportError("Unmarshal", "there are bytes left after unmarshal") return iter.Error } func (cfg *frozenConfig) Get(data []byte, path ...interface{}) Any { iter := cfg.BorrowIterator(data) defer cfg.ReturnIterator(iter) return locatePath(iter, path) } func (cfg *frozenConfig) Unmarshal(data []byte, v interface{}) error { iter := cfg.BorrowIterator(data) defer cfg.ReturnIterator(iter) iter.ReadVal(v) c := iter.nextToken() if c == 0 { if iter.Error == io.EOF { return nil } return iter.Error } iter.ReportError("Unmarshal", "there are bytes left after unmarshal") return iter.Error } func (cfg *frozenConfig) NewEncoder(writer io.Writer) *Encoder { stream := NewStream(cfg, writer, 512) return &Encoder{stream} } func (cfg *frozenConfig) NewDecoder(reader io.Reader) *Decoder { iter := Parse(cfg, reader, 512) return &Decoder{iter} } func (cfg *frozenConfig) Valid(data []byte) bool { iter := cfg.BorrowIterator(data) defer cfg.ReturnIterator(iter) iter.Skip() return iter.Error == nil }
{ "pile_set_name": "Github" }
ο»Ώ#region Copyright notice and license // Copyright 2019 The gRPC Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using Microsoft.Extensions.DependencyInjection; namespace Grpc.AspNetCore.Server.Internal { /// <summary> /// A marker class used to determine if all the required gRPC services were added /// to the <see cref="IServiceCollection"/>. /// </summary> internal class GrpcMarkerService { } }
{ "pile_set_name": "Github" }
'use strict'; module.exports = function (str, sep) { if (typeof str !== 'string') { throw new TypeError('Expected a string'); } sep = typeof sep === 'undefined' ? '_' : sep; return str .replace(/([a-z\d])([A-Z])/g, '$1' + sep + '$2') .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + sep + '$2') .toLowerCase(); };
{ "pile_set_name": "Github" }
<?php /* * Copyright 2016 Google 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. */ class Google_Service_Spanner_Binding extends Google_Collection { protected $collection_key = 'members'; public $members; public $role; public function setMembers($members) { $this->members = $members; } public function getMembers() { return $this->members; } public function setRole($role) { $this->role = $role; } public function getRole() { return $this->role; } }
{ "pile_set_name": "Github" }
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import <SAObjects/AceObject.h> #import <SAObjects/SAAceSerializable-Protocol.h> @class NSString; @interface SAUITemplateEdgeInsets : AceObject <SAAceSerializable> { } + (id)edgeInsetsWithDictionary:(id)arg1 context:(id)arg2; + (id)edgeInsets; @property(nonatomic) float top; @property(nonatomic) float right; @property(nonatomic) float left; @property(nonatomic) float bottom; - (id)encodedClassName; - (id)groupIdentifier; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end
{ "pile_set_name": "Github" }
/* * Copyright 2019 Google, 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. */ package com.netflix.spinnaker.orca.igor.model; public interface RetryableStageDefinition { int getConsecutiveErrors(); }
{ "pile_set_name": "Github" }
# -*- coding: utf-8 -*- from globaleaks.handlers.admin import l10n as admin_l10n from globaleaks.tests import helpers from twisted.internet.defer import inlineCallbacks empty_texts = {} custom_texts1 = { '12345': '54321' } custom_texts2 = { '12345': '54321' } class TestAdminL10NHandler(helpers.TestHandler): _handler = admin_l10n.AdminL10NHandler @inlineCallbacks def test_get(self): handler = self.request(role='admin') response = yield handler.get(lang=u'en') self.assertEqual(response, {}) @inlineCallbacks def test_put(self): check = yield admin_l10n.get(1, 'en') self.assertEqual(empty_texts, check) handler = self.request(custom_texts1, role='admin') yield handler.put(lang=u'en') check = yield admin_l10n.get(1, 'en') self.assertEqual(custom_texts1, check) handler = self.request(custom_texts1, role='admin') yield handler.put(lang=u'en') check = yield admin_l10n.get(1, 'en') self.assertEqual(custom_texts2, check) @inlineCallbacks def test_delete(self): yield self.test_put() check = yield admin_l10n.get(1, 'en') self.assertEqual(custom_texts1, check) handler = self.request({}, role='admin') handler.delete(lang=u'en') check = yield admin_l10n.get(1, 'en') self.assertEqual(empty_texts, check)
{ "pile_set_name": "Github" }
#%RAML 0.8 title: test API traits: - tr: body: application/json: schemas: - MyType: | { "$schema": "http://json-schema.org/draft-04/", "type": "object", "properties": { "arrayProp": { "items": { "type": "object", "properties": { "prop1": { "type": "number" }, "prop2": { "type": "boolean" } }, "additionalProperties": false } } } } /res1: post: body: application/json: schema: MyType example: | { "arrayProp": [ { "prop1": 13, "prop2" : true }, { "prop1": 13, "prop2": false } ] } /res2: post: body: application/json: schema: MyType example: | { "arrayProp": [ { "prop1": 13 "prop2": false } , { "prop1": 13, "prop2": false } ] }
{ "pile_set_name": "Github" }
#!/usr/bin/env python # -*- coding: utf-8 -*- import six from bson import ObjectId from easydict import EasyDict as edict from tornado.concurrent import return_future from motorengine import ASCENDING from motorengine.query_builder.transform import update class BaseAggregation(object): def __init__(self, field, alias): self._field = field self.alias = alias @property def field(self): return self._field class PipelineOperation(object): def __init__(self, aggregation): self.aggregation = aggregation def to_query(self): return {} class GroupBy(PipelineOperation): def __init__(self, aggregation, first_group_by, *groups): super(GroupBy, self).__init__(aggregation) self.first_group_by = first_group_by self.groups = groups def to_query(self): group_obj = {'$group': {'_id': {}}} for group in self.groups: if isinstance(group, BaseAggregation): group_obj['$group'].update(group.to_query(self.aggregation)) continue if isinstance(group, six.string_types): field_name = group else: field_name = self.aggregation.get_field(group).db_field if self.first_group_by: group_obj['$group']['_id'][field_name] = "$%s" % field_name else: group_obj['$group']['_id'][field_name] = "$_id.%s" % field_name return group_obj class Match(PipelineOperation): def __init__(self, aggregation, **filters): super(Match, self).__init__(aggregation) self.filters = filters def to_query(self): from motorengine import Q match_obj = {'$match': {}} query = self.aggregation.queryset.get_query_from_filters(Q(**self.filters)) update(match_obj['$match'], query) return match_obj class Unwind(PipelineOperation): def __init__(self, aggregation, field): super(Unwind, self).__init__(aggregation) self.field = self.aggregation.get_field(field) def to_query(self): return {'$unwind': '$%s' % self.field.db_field} class OrderBy(PipelineOperation): def __init__(self, aggregation, field, direction): super(OrderBy, self).__init__(aggregation) self.field = self.aggregation.get_field(field) self.direction = direction def to_query(self): return {'$sort': {self.field.db_field: self.direction}} class Aggregation(object): def __init__(self, queryset): self.first_group_by = True self.queryset = queryset self.pipeline = [] self.ids = [] self.raw_query = None def get_field_name(self, field): if isinstance(field, six.string_types): return field return field.db_field def get_field(self, field): return field def raw(self, steps): self.raw_query = steps return self def group_by(self, *args): self.pipeline.append(GroupBy(self, self.first_group_by, *args)) self.first_group_by = False return self def match(self, **kw): self.pipeline.append(Match(self, **kw)) return self def unwind(self, field): self.pipeline.append(Unwind(self, field)) return self def order_by(self, field, direction=ASCENDING): self.pipeline.append(OrderBy(self, field, direction)) return self def fill_ids(self, item): if not '_id' in item: return if isinstance(item['_id'], (dict,)): for id_name, id_value in list(item['_id'].items()): item[id_name] = id_value def get_instance(self, item): return self.queryset.__klass__.from_son(item) def handle_aggregation(self, callback): def handle(*arguments, **kw): if arguments[1]: raise RuntimeError('Aggregation failed due to: %s' % str(arguments[1])) results = [] for item in arguments[0]: self.fill_ids(item) results.append(edict(item)) callback(results) return handle @return_future def fetch(self, callback=None, alias=None): coll = self.queryset.coll(alias) coll.aggregate(self.to_query()).to_list(None, callback=self.handle_aggregation(callback)) @classmethod def avg(cls, field, alias=None): from motorengine.aggregation.avg import AverageAggregation return AverageAggregation(field, alias) @classmethod def sum(cls, field, alias=None): from motorengine.aggregation.sum import SumAggregation return SumAggregation(field, alias) def to_query(self): if self.raw_query is not None: return self.raw_query query = [] for pipeline_step in self.pipeline: query_steps = pipeline_step.to_query() if isinstance(query_steps, (tuple, set, list)): for step in query_steps: query.append(step) else: query.append(query_steps) return query
{ "pile_set_name": "Github" }
package org.intellij.markdown.parser.sequentialparsers.impl import org.intellij.markdown.MarkdownElementTypes import org.intellij.markdown.MarkdownTokenTypes import org.intellij.markdown.parser.sequentialparsers.LocalParsingResult import org.intellij.markdown.parser.sequentialparsers.RangesListBuilder import org.intellij.markdown.parser.sequentialparsers.SequentialParser import org.intellij.markdown.parser.sequentialparsers.TokensCache class ReferenceLinkParser : SequentialParser { override fun parse(tokens: TokensCache, rangesToGlue: List<IntRange>): SequentialParser.ParsingResult { var result = SequentialParser.ParsingResultBuilder() val delegateIndices = RangesListBuilder() var iterator: TokensCache.Iterator = tokens.RangesListIterator(rangesToGlue) while (iterator.type != null) { if (iterator.type == MarkdownTokenTypes.LBRACKET) { val referenceLink = parseReferenceLink(iterator) if (referenceLink != null) { iterator = referenceLink.iteratorPosition.advance() result = result.withOtherParsingResult(referenceLink) continue } } delegateIndices.put(iterator.index) iterator = iterator.advance() } return result.withFurtherProcessing(delegateIndices.get()) } companion object { fun parseReferenceLink(iterator: TokensCache.Iterator): LocalParsingResult? { return parseFullReferenceLink(iterator) ?: parseShortReferenceLink(iterator) } private fun parseFullReferenceLink(iterator: TokensCache.Iterator): LocalParsingResult? { val startIndex = iterator.index val linkText = LinkParserUtil.parseLinkText(iterator) ?: return null var it = linkText.iteratorPosition.advance() if (it.type == MarkdownTokenTypes.EOL) { it = it.advance() } val linkLabel = LinkParserUtil.parseLinkLabel(it) ?: return null it = linkLabel.iteratorPosition return LocalParsingResult(it, linkText.parsedNodes + linkLabel.parsedNodes + SequentialParser.Node(startIndex..it.index + 1, MarkdownElementTypes.FULL_REFERENCE_LINK), linkText.rangesToProcessFurther + linkLabel.rangesToProcessFurther) } private fun parseShortReferenceLink(iterator: TokensCache.Iterator): LocalParsingResult? { val startIndex = iterator.index val linkLabel = LinkParserUtil.parseLinkLabel(iterator) ?: return null var it = linkLabel.iteratorPosition val shortcutLinkEnd = it it = it.advance() if (it.type == MarkdownTokenTypes.EOL) { it = it.advance() } if (it.type == MarkdownTokenTypes.LBRACKET && it.rawLookup(1) == MarkdownTokenTypes.RBRACKET) { it = it.advance() } else { it = shortcutLinkEnd } return LocalParsingResult(it, linkLabel.parsedNodes + SequentialParser.Node(startIndex..it.index + 1, MarkdownElementTypes.SHORT_REFERENCE_LINK), linkLabel.rangesToProcessFurther) } } }
{ "pile_set_name": "Github" }
var mkdirp = require('../'); var path = require('path'); var fs = require('fs'); var test = require('tap').test; test('root', function (t) { // '/' on unix, 'c:/' on windows. var file = path.resolve('/'); mkdirp(file, 0755, function (err) { if (err) throw err fs.stat(file, function (er, stat) { if (er) throw er t.ok(stat.isDirectory(), 'target is a directory'); t.end(); }) }); });
{ "pile_set_name": "Github" }
<#-- /** * Copyright 2000-present Liferay, 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. */ --> <#assign aui = PortletJspTagLibs["/META-INF/liferay-aui.tld"] /> <#assign liferay_portlet = PortletJspTagLibs["/META-INF/liferay-portlet-ext.tld"] /> <#assign liferay_security = PortletJspTagLibs["/META-INF/liferay-security.tld"] /> <#assign liferay_theme = PortletJspTagLibs["/META-INF/liferay-theme.tld"] /> <#assign liferay_ui = PortletJspTagLibs["/META-INF/liferay-ui.tld"] /> <#assign liferay_util = PortletJspTagLibs["/META-INF/liferay-util.tld"] /> <#assign portlet = PortletJspTagLibs["/META-INF/liferay-portlet.tld"] /> <@liferay_theme["defineObjects"] /> <@portlet["defineObjects"] />
{ "pile_set_name": "Github" }
#ifndef PARDENSEMATRIX_H #define PARDENSEMATRIX_H #include "MatrixDef.h" #include "DenseMatrix.h" #include "DenseVector.h" #include "MPI_Wrappers.h" #include "ATC_Error.h" using ATC::ATC_Error; #include <algorithm> #include <sstream> namespace ATC_matrix { /** * @class ParDenseMatrix * @brief Parallelized version of DenseMatrix class. */ template <typename T> class ParDenseMatrix : public DenseMatrix<T> { public: MPI_Comm _comm; ParDenseMatrix(MPI_Comm comm, INDEX rows=0, INDEX cols=0, bool z=1) : DenseMatrix<T>(rows, cols, z), _comm(comm) {} ParDenseMatrix(MPI_Comm comm, const DenseMatrix<T>& c) : DenseMatrix<T>(c), _comm(comm) {} ParDenseMatrix(MPI_Comm comm, const SparseMatrix<T>& c) : DenseMatrix<T>(c), _comm(comm) {} ParDenseMatrix(MPI_Comm comm, const Matrix<T>& c) : DenseMatrix<T>(c), _comm(comm) {} ////////////////////////////////////////////////////////////////////////////// //* performs a matrix-vector multiply void ParMultMv(const Vector<T> &v, DenseVector<T> &c, const bool At, T a, T b) { // We can't generically support parallel multiplication because the data // types must be specified when using MPI MultMv(*this, v, c, At, a, b); } }; template<> class ParDenseMatrix<double> : public DenseMatrix<double> { public: MPI_Comm _comm; ParDenseMatrix(MPI_Comm comm, INDEX rows=0, INDEX cols=0, bool z=1) : DenseMatrix<double>(rows, cols, z), _comm(comm) {} ParDenseMatrix(MPI_Comm comm, const DenseMatrix<double>& c) : DenseMatrix<double>(c), _comm(comm) {} ParDenseMatrix(MPI_Comm comm, const SparseMatrix<double>& c) : DenseMatrix<double>(c), _comm(comm) {} ParDenseMatrix(MPI_Comm comm, const Matrix<double>& c) : DenseMatrix<double>(c), _comm(comm) {} void ParMultMv(const Vector<double> &v, DenseVector<double> &c, const bool At, double a, double b) const { // We don't support parallel vec-Mat multiplication yet if (At) { MultMv(*this, v, c, At, a, b); return; } const INDEX nRows = this->nRows(); const INDEX nCols = this->nCols(); if (c.size() != nRows) { c.resize(nRows); // set size of C c.zero(); // do not add result to C } else c *= b; // Determine how many rows will be handled on each processor int nProcs = MPI_Wrappers::size(_comm); int myRank = MPI_Wrappers::rank(_comm); int *majorCounts = new int[nProcs]; int *offsets = new int[nProcs]; #ifdef COL_STORAGE // Column-major storage int nMajor = nCols; int nMinor = nRows; int ParDenseMatrix::*majorField = &ParDenseMatrix::_nCols; int ParDenseMatrix::*minorField = &ParDenseMatrix::_nRows; #else // Row-major storage int nMajor = nRows; int nMinor = nCols; int ParDenseMatrix::*majorField = &ParDenseMatrix::_nRows; int ParDenseMatrix::*minorField = &ParDenseMatrix::_nCols; #endif for (int i = 0; i < nProcs; i++) { // If we have an uneven row-or-col/processors number, or too few rows // or cols, some processors will need to receive fewer rows/cols. offsets[i] = (i * nMajor) / nProcs; majorCounts[i] = (((i + 1) * nMajor) / nProcs) - offsets[i]; } int myNMajor = majorCounts[myRank]; int myMajorOffset = offsets[myRank]; // Take data from an offset version of A ParDenseMatrix<double> A_local(_comm); A_local._data = this->_data + myMajorOffset * nMinor; A_local.*majorField = myNMajor; A_local.*minorField = nMinor; #ifdef COL_STORAGE // Column-major storage // When splitting by columns, we split the vector as well, and sum the // results. DenseVector<double> v_local(myNMajor); for (int i = 0; i < myNMajor; i++) v_local(i) = v(myMajorOffset + i); // Store results in a local vector DenseVector<double> c_local = A_local * v_local; // Sum all vectors onto each processor MPI_Wrappers::allsum(_comm, c_local.ptr(), c.ptr(), c_local.size()); #else // Row-major storage // When splitting by rows, we use the whole vector and concatenate the // results. // Store results in a small local vector DenseVector<double> c_local(myNMajor); for (int i = 0; i < myNMajor; i++) c_local(i) = c(myMajorOffset + i); MultMv(A_local, v, c_local, At, a, b); // Gather the results onto each processor allgatherv(_comm, c_local.ptr(), c_local.size(), c.ptr(), majorCounts, offsets); #endif // Clear out the local matrix's pointer so we don't double-free A_local._data = nullptr; delete [] majorCounts; delete [] offsets; } }; // Operator for dense Matrix - dense vector product template<typename T> DenseVector<T> operator*(const ParDenseMatrix<T> &A, const Vector<T> &b) { DenseVector<T> c; A.ParMultMv(b, c, 0, 1.0, 0.0); return c; } } // end namespace #endif
{ "pile_set_name": "Github" }
// Copyright (C) 2014 Yasuhiro Matsumoto <mattn.jp@gmail.com>. // Copyright (C) 2018 G.J.R. Timmer <gjr.timmer@gmail.com>. // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. // +build sqlite_secure_delete_fast package sqlite3 /* #cgo CFLAGS: -DSQLITE_SECURE_DELETE=FAST #cgo LDFLAGS: -lm */ import "C"
{ "pile_set_name": "Github" }
# -*- coding: utf-8 -*- from .common import *
{ "pile_set_name": "Github" }
sizeof_1_ = 8; aggr _1_ { 'U' 0 lo; 'U' 4 hi; }; defn _1_(addr) { complex _1_ addr; print(" lo ", addr.lo, "\n"); print(" hi ", addr.hi, "\n"); }; sizeofFPdbleword = 8; aggr FPdbleword { 'F' 0 x; { 'U' 0 lo; 'U' 4 hi; }; }; defn FPdbleword(addr) { complex FPdbleword addr; print(" x ", addr.x, "\n"); print("_1_ {\n"); _1_(addr+0); print("}\n"); }; UTFmax = 3; Runesync = 128; Runeself = 128; Runeerror = 128; sizeofFmt = 48; aggr Fmt { 'b' 0 runes; 'X' 4 start; 'X' 8 to; 'X' 12 stop; 'X' 16 flush; 'X' 20 farg; 'D' 24 nfmt; 'X' 28 args; 'D' 32 r; 'D' 36 width; 'D' 40 prec; 'U' 44 flags; }; defn Fmt(addr) { complex Fmt addr; print(" runes ", addr.runes, "\n"); print(" start ", addr.start\X, "\n"); print(" to ", addr.to\X, "\n"); print(" stop ", addr.stop\X, "\n"); print(" flush ", addr.flush\X, "\n"); print(" farg ", addr.farg\X, "\n"); print(" nfmt ", addr.nfmt, "\n"); print(" args ", addr.args\X, "\n"); print(" r ", addr.r, "\n"); print(" width ", addr.width, "\n"); print(" prec ", addr.prec, "\n"); print(" flags ", addr.flags, "\n"); }; FmtWidth = 1; FmtLeft = 2; FmtPrec = 4; FmtSharp = 8; FmtSpace = 16; FmtSign = 32; FmtZero = 64; FmtUnsigned = 128; FmtShort = 256; FmtLong = 512; FmtVLong = 1024; FmtComma = 2048; FmtByte = 4096; FmtFlag = 8192; sizeofTm = 40; aggr Tm { 'D' 0 sec; 'D' 4 min; 'D' 8 hour; 'D' 12 mday; 'D' 16 mon; 'D' 20 year; 'D' 24 wday; 'D' 28 yday; 'a' 32 zone; 'D' 36 tzoff; }; defn Tm(addr) { complex Tm addr; print(" sec ", addr.sec, "\n"); print(" min ", addr.min, "\n"); print(" hour ", addr.hour, "\n"); print(" mday ", addr.mday, "\n"); print(" mon ", addr.mon, "\n"); print(" year ", addr.year, "\n"); print(" wday ", addr.wday, "\n"); print(" yday ", addr.yday, "\n"); print(" zone ", addr.zone, "\n"); print(" tzoff ", addr.tzoff, "\n"); }; PNPROC = 1; PNGROUP = 2; sizeofLock = 4; aggr Lock { 'D' 0 val; }; defn Lock(addr) { complex Lock addr; print(" val ", addr.val, "\n"); }; sizeofQLp = 12; aggr QLp { 'D' 0 inuse; 'A' QLp 4 next; 'C' 8 state; }; defn QLp(addr) { complex QLp addr; print(" inuse ", addr.inuse, "\n"); print(" next ", addr.next\X, "\n"); print(" state ", addr.state, "\n"); }; sizeofQLock = 16; aggr QLock { Lock 0 lock; 'D' 4 locked; 'A' QLp 8 $head; 'A' QLp 12 $tail; }; defn QLock(addr) { complex QLock addr; print("Lock lock {\n"); Lock(addr.lock); print("}\n"); print(" locked ", addr.locked, "\n"); print(" $head ", addr.$head\X, "\n"); print(" $tail ", addr.$tail\X, "\n"); }; sizeofRWLock = 20; aggr RWLock { Lock 0 lock; 'D' 4 readers; 'D' 8 writer; 'A' QLp 12 $head; 'A' QLp 16 $tail; }; defn RWLock(addr) { complex RWLock addr; print("Lock lock {\n"); Lock(addr.lock); print("}\n"); print(" readers ", addr.readers, "\n"); print(" writer ", addr.writer, "\n"); print(" $head ", addr.$head\X, "\n"); print(" $tail ", addr.$tail\X, "\n"); }; sizeofRendez = 12; aggr Rendez { 'A' QLock 0 l; 'A' QLp 4 $head; 'A' QLp 8 $tail; }; defn Rendez(addr) { complex Rendez addr; print(" l ", addr.l\X, "\n"); print(" $head ", addr.$head\X, "\n"); print(" $tail ", addr.$tail\X, "\n"); }; sizeofNetConnInfo = 28; aggr NetConnInfo { 'X' 0 dir; 'X' 4 root; 'X' 8 spec; 'X' 12 lsys; 'X' 16 lserv; 'X' 20 rsys; 'X' 24 rserv; }; defn NetConnInfo(addr) { complex NetConnInfo addr; print(" dir ", addr.dir\X, "\n"); print(" root ", addr.root\X, "\n"); print(" spec ", addr.spec\X, "\n"); print(" lsys ", addr.lsys\X, "\n"); print(" lserv ", addr.lserv\X, "\n"); print(" rsys ", addr.rsys\X, "\n"); print(" rserv ", addr.rserv\X, "\n"); }; RFNAMEG = 1; RFENVG = 2; RFFDG = 4; RFNOTEG = 8; RFPROC = 16; RFMEM = 32; RFNOWAIT = 64; RFCNAMEG = 1024; RFCENVG = 2048; RFCFDG = 4096; RFREND = 8192; RFNOMNT = 16384; sizeofQid = 16; aggr Qid { 'W' 0 path; 'U' 8 vers; 'b' 12 type; }; defn Qid(addr) { complex Qid addr; print(" path ", addr.path, "\n"); print(" vers ", addr.vers, "\n"); print(" type ", addr.type, "\n"); }; sizeofDir = 60; aggr Dir { 'u' 0 type; 'U' 4 dev; Qid 8 qid; 'U' 24 mode; 'U' 28 atime; 'U' 32 mtime; 'V' 36 length; 'X' 44 name; 'X' 48 uid; 'X' 52 gid; 'X' 56 muid; }; defn Dir(addr) { complex Dir addr; print(" type ", addr.type, "\n"); print(" dev ", addr.dev, "\n"); print("Qid qid {\n"); Qid(addr.qid); print("}\n"); print(" mode ", addr.mode, "\n"); print(" atime ", addr.atime, "\n"); print(" mtime ", addr.mtime, "\n"); print(" length ", addr.length, "\n"); print(" name ", addr.name\X, "\n"); print(" uid ", addr.uid\X, "\n"); print(" gid ", addr.gid\X, "\n"); print(" muid ", addr.muid\X, "\n"); }; sizeofWaitmsg = 20; aggr Waitmsg { 'D' 0 pid; 'a' 4 time; 'X' 16 msg; }; defn Waitmsg(addr) { complex Waitmsg addr; print(" pid ", addr.pid, "\n"); print(" time ", addr.time, "\n"); print(" msg ", addr.msg\X, "\n"); }; sizeofIOchunk = 8; aggr IOchunk { 'X' 0 addr; 'U' 4 len; }; defn IOchunk(addr) { complex IOchunk addr; print(" addr ", addr.addr\X, "\n"); print(" len ", addr.len, "\n"); }; MaxFragSize = 9216; VtScoreSize = 20; VtMaxStringSize = 1024; VtMaxFileSize = 281474976710655; VtMaxLumpSize = 57344; VtPointerDepth = 7; VtDataType = 0; VtDirType = 8; VtRootType = 16; VtMaxType = 17; VtTypeDepthMask = 7; VtEntryActive = 1; VtEntryDir = 2; VtEntryDepthShift = 2; VtEntryDepthMask = 28; VtEntryLocal = 32; VtEntrySize = 40; sizeofVtEntry = 40; aggr VtEntry { 'U' 0 gen; 'u' 4 psize; 'u' 6 dsize; 'b' 8 type; 'b' 9 flags; 'W' 12 size; 'a' 20 score; }; defn VtEntry(addr) { complex VtEntry addr; print(" gen ", addr.gen, "\n"); print(" psize ", addr.psize, "\n"); print(" dsize ", addr.dsize, "\n"); print(" type ", addr.type, "\n"); print(" flags ", addr.flags, "\n"); print(" size ", addr.size, "\n"); print(" score ", addr.score, "\n"); }; sizeofVtRoot = 300; aggr VtRoot { 'a' 0 name; 'a' 128 type; 'a' 256 score; 'u' 276 blocksize; 'a' 278 prev; }; defn VtRoot(addr) { complex VtRoot addr; print(" name ", addr.name, "\n"); print(" type ", addr.type, "\n"); print(" score ", addr.score, "\n"); print(" blocksize ", addr.blocksize, "\n"); print(" prev ", addr.prev, "\n"); }; VtRootSize = 300; VtRootVersion = 2; VtCryptoStrengthNone = 0; VtCryptoStrengthAuth = 1; VtCryptoStrengthWeak = 2; VtCryptoStrengthStrong = 3; VtCryptoNone = 0; VtCryptoSSL3 = 1; VtCryptoTLS1 = 2; VtCryptoMax = 3; VtCodecNone = 0; VtCodecDeflate = 1; VtCodecThwack = 2; VtCodecMax = 3; VtRerror = 1; VtTping = 2; VtRping = 3; VtThello = 4; VtRhello = 5; VtTgoodbye = 6; VtRgoodbye = 7; VtTauth0 = 8; VtRauth0 = 9; VtTauth1 = 10; VtRauth1 = 11; VtTread = 12; VtRread = 13; VtTwrite = 14; VtRwrite = 15; VtTsync = 16; VtRsync = 17; VtTmax = 18; sizeofVtFcall = 80; aggr VtFcall { 'b' 0 type; 'b' 1 tag; 'X' 4 error; 'X' 8 version; 'X' 12 uid; 'b' 16 strength; 'X' 20 crypto; 'U' 24 ncrypto; 'X' 28 codec; 'U' 32 ncodec; 'X' 36 sid; 'b' 40 rcrypto; 'b' 41 rcodec; 'X' 44 auth; 'U' 48 nauth; 'a' 52 score; 'b' 72 dtype; 'u' 74 count; 'X' 76 data; }; defn VtFcall(addr) { complex VtFcall addr; print(" type ", addr.type, "\n"); print(" tag ", addr.tag, "\n"); print(" error ", addr.error\X, "\n"); print(" version ", addr.version\X, "\n"); print(" uid ", addr.uid\X, "\n"); print(" strength ", addr.strength, "\n"); print(" crypto ", addr.crypto\X, "\n"); print(" ncrypto ", addr.ncrypto, "\n"); print(" codec ", addr.codec\X, "\n"); print(" ncodec ", addr.ncodec, "\n"); print(" sid ", addr.sid\X, "\n"); print(" rcrypto ", addr.rcrypto, "\n"); print(" rcodec ", addr.rcodec, "\n"); print(" auth ", addr.auth\X, "\n"); print(" nauth ", addr.nauth, "\n"); print(" score ", addr.score, "\n"); print(" dtype ", addr.dtype, "\n"); print(" count ", addr.count, "\n"); print(" data ", addr.data\X, "\n"); }; VtStateAlloc = 0; VtStateConnected = 1; VtStateClosed = 2; sizeofVtConn = 1148; aggr VtConn { QLock 0 lk; QLock 16 inlk; QLock 32 outlk; 'D' 48 debug; 'D' 52 infd; 'D' 56 outfd; 'D' 60 muxer; 'X' 64 writeq; 'X' 68 readq; 'D' 72 state; 'a' 76 wait; 'U' 1100 ntag; 'U' 1104 nsleep; 'X' 1108 part; Rendez 1112 tagrend; Rendez 1124 rpcfork; 'X' 1136 version; 'X' 1140 uid; 'X' 1144 sid; }; defn VtConn(addr) { complex VtConn addr; print("QLock lk {\n"); QLock(addr.lk); print("}\n"); print("QLock inlk {\n"); QLock(addr.inlk); print("}\n"); print("QLock outlk {\n"); QLock(addr.outlk); print("}\n"); print(" debug ", addr.debug, "\n"); print(" infd ", addr.infd, "\n"); print(" outfd ", addr.outfd, "\n"); print(" muxer ", addr.muxer, "\n"); print(" writeq ", addr.writeq\X, "\n"); print(" readq ", addr.readq\X, "\n"); print(" state ", addr.state, "\n"); print(" wait ", addr.wait, "\n"); print(" ntag ", addr.ntag, "\n"); print(" nsleep ", addr.nsleep, "\n"); print(" part ", addr.part\X, "\n"); print("Rendez tagrend {\n"); Rendez(addr.tagrend); print("}\n"); print("Rendez rpcfork {\n"); Rendez(addr.rpcfork); print("}\n"); print(" version ", addr.version\X, "\n"); print(" uid ", addr.uid\X, "\n"); print(" sid ", addr.sid\X, "\n"); }; NilBlock = -1; sizeofVtBlock = 88; aggr VtBlock { 'X' 0 c; QLock 4 lk; 'X' 20 data; 'a' 24 score; 'b' 44 type; 'D' 48 nlock; 'D' 52 iostate; 'D' 56 ref; 'U' 60 heap; 'A' VtBlock 64 next; 'A' VtBlock 68 prev; 'U' 72 used; 'U' 76 used2; 'U' 80 addr; 'D' 84 decrypted; }; defn VtBlock(addr) { complex VtBlock addr; print(" c ", addr.c\X, "\n"); print("QLock lk {\n"); QLock(addr.lk); print("}\n"); print(" data ", addr.data\X, "\n"); print(" score ", addr.score, "\n"); print(" type ", addr.type, "\n"); print(" nlock ", addr.nlock, "\n"); print(" iostate ", addr.iostate, "\n"); print(" ref ", addr.ref, "\n"); print(" heap ", addr.heap, "\n"); print(" next ", addr.next\X, "\n"); print(" prev ", addr.prev\X, "\n"); print(" used ", addr.used, "\n"); print(" used2 ", addr.used2, "\n"); print(" addr ", addr.addr, "\n"); print(" decrypted ", addr.decrypted, "\n"); }; VtOREAD = 0; VtOWRITE = 1; VtORDWR = 2; VtOCREATE = 256; BioLocal = 1; BioVenti = 2; BioReading = 3; BioWriting = 4; BioEmpty = 5; BioVentiError = 6; BadHeap = -1; sizeofVtCache = 60; aggr VtCache { QLock 0 lk; 'A' VtConn 16 z; 'U' 20 blocksize; 'U' 24 now; 'A' VtBlock 28 hash; 'D' 32 nhash; 'A' VtBlock 36 heap; 'D' 40 nheap; 'A' VtBlock 44 block; 'D' 48 nblock; 'X' 52 mem; 'D' 56 mode; }; defn VtCache(addr) { complex VtCache addr; print("QLock lk {\n"); QLock(addr.lk); print("}\n"); print(" z ", addr.z\X, "\n"); print(" blocksize ", addr.blocksize, "\n"); print(" now ", addr.now, "\n"); print(" hash ", addr.hash\X, "\n"); print(" nhash ", addr.nhash, "\n"); print(" heap ", addr.heap\X, "\n"); print(" nheap ", addr.nheap, "\n"); print(" block ", addr.block\X, "\n"); print(" nblock ", addr.nblock, "\n"); print(" mem ", addr.mem\X, "\n"); print(" mode ", addr.mode, "\n"); }; complex VtConn vtcachealloc:z; complex VtCache vtcachealloc:c; complex VtBlock vtcachealloc:b; complex VtCache vtcachefree:c; complex VtCache vtcachedump:c; complex VtBlock vtcachedump:b; complex VtCache cachecheck:c; complex VtBlock cachecheck:b; complex VtBlock upheap:b; complex VtBlock upheap:bb; complex VtCache upheap:c; complex VtBlock downheap:b; complex VtBlock downheap:bb; complex VtCache downheap:c; complex VtBlock heapdel:b; complex VtCache heapdel:c; complex VtBlock heapins:b; complex VtCache vtcachebumpblock:c; complex VtBlock vtcachebumpblock:b; complex VtCache vtcachelocal:c; complex VtBlock vtcachelocal:b; complex VtCache vtcacheallocblock:c; complex VtBlock vtcacheallocblock:b; complex VtCache vtcacheglobal:c; complex VtBlock vtcacheglobal:b; complex VtBlock vtblockduplock:b; complex VtBlock vtblockput:b; complex VtCache vtblockput:c; complex VtBlock vtblockwrite:b; complex VtCache vtblockwrite:c; complex VtCache vtcacheblocksize:c; complex VtBlock vtblockcopy:b; complex VtBlock vtblockcopy:bb;
{ "pile_set_name": "Github" }
ο»Ώ@using System.Globalization @using Microsoft.Azure.Devices.Applications.RemoteMonitoring.Common.Extensions @using Microsoft.Azure.Devices.Applications.RemoteMonitoring.Common.Helpers @using Microsoft.Azure.Devices.Applications.RemoteMonitoring.DeviceAdmin.Infrastructure.Models @using Microsoft.Azure.Devices.Applications.RemoteMonitoring.DeviceAdmin.Web.Helpers @using GlobalResources @model Microsoft.Azure.Devices.Applications.RemoteMonitoring.DeviceAdmin.Web.Models.DeviceDetailModel @{ DateTime? resolvedDate; var tags = Model.DevicePropertyValueModels.Where(m => m.Name.StartsWith("tags.") && !m.Name.IsReservedTwinName()); var desiredProperties = Model.DevicePropertyValueModels.Where(m => m.Name.StartsWith("properties.desired.") && !m.Name.IsReservedTwinName()); var reportedProperties = Model.DevicePropertyValueModels.Where(m => m.Name.StartsWith("properties.reported.") && !m.Name.IsReservedTwinName()); var deviceProperties = Model.DevicePropertyValueModels.Except(tags).Except(desiredProperties).Except(reportedProperties).Where(m => !m.Name.IsReservedTwinName()); var utcNow = DateTime.UtcNow; } <div class="header_grid header_grid_general"> <h3 class="grid_subheadhead_detail grid_subheadhead">@Strings.DeviceTwin</h3> <img src="~/Content/img/icon_info_gray.svg" class="details_grid_info" title="@Strings.DeviceTwinHeader" /> @Html.ActionLink(@Strings.DownloadTwinJson, "DownloadTwinJson", "Device", new { deviceId = Model.DeviceID }, new { id = "download_link", @class = "link_grid_subheadhead_detail", @style = "margin-top: 1ch;" }) </div> <hr class="details_grid_twin_begin_line" /> <div class="header_grid_left_space"> <div class="header_grid header_grid_general"> <img id="tagClose" src="~/Content/img/expanded.svg" class="details_grid_info pull-left cursor_pointer tag_toggle_target tag_toggle_source" /> <img id="tagOpen" src="~/Content/img/collapsed.svg" class="details_grid_info pull-left cursor_pointer display_none tag_toggle_target tag_toggle_source" /> <h3 class="grid_subheadhead_detail_collapsable cursor_pointer tag_toggle_source">@Strings.Tags</h3> @if (Model.IsDeviceEditEnabled) { @Html.ActionLink(@Strings.Edit, "EditTags", "Device", new { deviceId = Model.DeviceID }, new { id = "edit_tags_link", @class = "link_grid_subheadhead_detail", }) } </div> <section class="details_grid_general tag_toggle_target" id="tagsGrid"> @if (tags.Any()) { foreach (var val in tags) { <h4 class="grid_subhead_detail_label">@val.Name.Substring(5)</h4> if (val.PropertyType == PropertyType.DateTime && (resolvedDate = DynamicValuesHelper.ConvertToDateTime(CultureInfo.InvariantCulture, val.Value)).HasValue) { <p class="grid_detail_value" name="tagField_@val.Name">@resolvedDate.Value.ToString()</p> } else { <p class="grid_detail_value" name="tagField_@val.Name">@val.Value</p> } } } else { <p class="grid_detail_value">@Strings.NoTags</p> } </section> <div class="header_grid header_grid_general"> <img id="desiredPropertyClose" src="~/Content/img/expanded.svg" class="details_grid_info pull-left cursor_pointer desiredproperty_toggle_target desiredproperty_toggle_source" /> <img id="desiredPropertyOpen" src="~/Content/img/collapsed.svg" class="details_grid_info pull-left cursor_pointer display_none desiredproperty_toggle_target desiredproperty_toggle_source" /> <h3 class="grid_subheadhead_detail_collapsable cursor_pointer desiredproperty_toggle_source">@Strings.DesiredProperties</h3> @if (Model.IsDeviceEditEnabled) { @Html.ActionLink(@Strings.Edit, "EditDesiredProperties", "Device", new { deviceId = Model.DeviceID }, new { id = "edit_desiredProperties_link", @class = "link_grid_subheadhead_detail", }) } </div> <section class="details_grid_general desiredproperty_toggle_target" id="desiredPropertiesGrid"> @if (desiredProperties.Any()) { foreach (var val in desiredProperties) { <h4 class="grid_subhead_detail_label">@val.Name.Substring(19)</h4> <div> <p class="grid_detail_value" name="desiredPropertyField_@val.Name"> @if (val.PropertyType == PropertyType.DateTime && (resolvedDate = DynamicValuesHelper.ConvertToDateTime(CultureInfo.InvariantCulture, val.Value)).HasValue) { @resolvedDate.Value.ToString() } else { @val.Value } <span class="grid_detail_lastUpdated pull-right" name="desiredPropertyField_lastUpdated_@val.Name">@TimeSpanExtension.ToFloorShortString(utcNow - val.LastUpdatedUtc, Strings.LastUpdatedFormatString)</span> </p> </div> } } else { <p class="grid_detail_value">@Strings.NoDesiredProperties</p> } </section> @if (reportedProperties.Any()) { <div class="header_grid header_grid_general"> <img id="reportedPropertyClose" src="~/Content/img/expanded.svg" class="details_grid_info pull-left cursor_pointer reportedproperty_toggle_target reportedproperty_toggle_source" /> <img id="reportedPropertyOpen" src="~/Content/img/collapsed.svg" class="details_grid_info pull-left cursor_pointer display_none reportedproperty_toggle_target reportedproperty_toggle_source" /> <h3 class="grid_subheadhead_detail_collapsable cursor_pointer reportedproperty_toggle_source">@Strings.ReportedProperties</h3> </div> <section class="details_grid_general reportedproperty_toggle_target" id="reportedPropertiesGrid"> @foreach (var val in reportedProperties) { <h4 class="grid_subhead_detail_label">@val.Name.Substring(20)</h4> <div> <p class="grid_detail_value" name="reportedPropertyField_@val.Name"> @if (val.PropertyType == PropertyType.DateTime && (resolvedDate = DynamicValuesHelper.ConvertToDateTime(CultureInfo.InvariantCulture, val.Value)).HasValue) { @resolvedDate.Value.ToString() } else { @val.Value } <span class="grid_detail_lastUpdated pull-right" name="reportedPropertyField_lastUpdated_@val.Name">@TimeSpanExtension.ToFloorShortString(utcNow - val.LastUpdatedUtc, Strings.LastUpdatedFormatString)</span> </p> </div> } </section> } </div> <hr class="details_grid_twin_end_line" /> <div class="grid_subheadhead_left_space"> <div class="header_grid header_grid_general"> <img id="deviceDetailsClose" src="~/Content/img/expanded.svg" class="details_grid_info cursor_pointer devicedetails_toggle_target devicedetails_toggle_source" /> <img id="deviceDetailsOpen" src="~/Content/img/collapsed.svg" class="details_grid_info cursor_pointer display_none devicedetails_toggle_target devicedetails_toggle_source" /> <h3 class="grid_subheadhead cursor_pointer devicedetails_toggle_source">@Strings.DeviceProperties</h3> </div> <section class="details_grid_general devicedetails_toggle_target" id="deviceDetailsGrid"> @foreach (var propVal in deviceProperties) { <h4 class="grid_subhead_detail_label">@DeviceDisplayHelper.GetDevicePropertyFieldLocalName(propVal.Name)</h4> if (DeviceDisplayHelper.GetIsCopyControlPropertyName(propVal.Name)) { string classname = "text_copy_container__input--details_grid"; string class_styles_modifier = "text_copy_container--details_grid"; string button_style_modifier = "details_grid_general__copy_button"; @IoTHelpers.TextCopy(propVal.Name, classname, propVal.Value, class_styles_modifier, button_style_modifier); } else { if ((propVal.PropertyType == PropertyType.DateTime) && (resolvedDate = DynamicValuesHelper.ConvertToDateTime(CultureInfo.InvariantCulture, propVal.Value)).HasValue) { <p class="grid_detail_value" name="deviceField_@propVal.Name">@resolvedDate.Value.ToString()</p> } else { <p class="grid_detail_value" name="deviceField_@propVal.Name">@propVal.Value</p> } } } @if (Model.HasKeyViewingPerm) { <p class="grid_detail_value"> <a href="#" id="deviceExplorer_authKeys" class="not_disable">@Strings.ViewAuthenticationKeys</a> </p> } </section> <div class="header_grid header_grid_general"> <img id="jobClose" src="~/Content/img/expanded.svg" class="details_grid_info cursor_pointer job_toggle_target job_toggle_source" /> <img id="jobOpen" src="~/Content/img/collapsed.svg" class="details_grid_info cursor_pointer display_none job_toggle_target job_toggle_source" /> <h3 class="grid_subheadhead cursor_pointer job_toggle_source">@Strings.RecentJobs</h3> </div> <section class="details_grid_general job_toggle_target" id="deviceJobGrid"> <div id="deviceJobLoadingElement" class="loader_container_panel"> <div class="loader_container__loader loader_container__loader--large_top_margin" /> </div> </section> </div> <script type="text/javascript"> (function () { 'use strict'; IoTApp.DeviceDetails.loadDeviceJobs("@Model.DeviceID"); })(); </script>
{ "pile_set_name": "Github" }
<!DOCTYPE HTML> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (11.0.3) on Sun Mar 29 22:42:10 IST 2020 --> <title>Uses of Class com.googlecode.cqengine.quantizer.BigDecimalQuantizer (CQEngine 3.5.0 API)</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="dc.created" content="2020-03-29"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <link rel="stylesheet" type="text/css" href="../../../../../jquery/jquery-ui.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> <script type="text/javascript" src="../../../../../jquery/jszip/dist/jszip.min.js"></script> <script type="text/javascript" src="../../../../../jquery/jszip-utils/dist/jszip-utils.min.js"></script> <!--[if IE]> <script type="text/javascript" src="../../../../../jquery/jszip-utils/dist/jszip-utils-ie.min.js"></script> <![endif]--> <script type="text/javascript" src="../../../../../jquery/jquery-3.3.1.js"></script> <script type="text/javascript" src="../../../../../jquery/jquery-migrate-3.0.1.js"></script> <script type="text/javascript" src="../../../../../jquery/jquery-ui.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class com.googlecode.cqengine.quantizer.BigDecimalQuantizer (CQEngine 3.5.0 API)"; } } catch(err) { } //--> var pathtoroot = "../../../../../"; var useModuleDirectories = true; loadScripts(document, 'script');</script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <header role="banner"> <nav role="navigation"> <div class="fixedNav"> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a id="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a id="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../index.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../BigDecimalQuantizer.html" title="class in com.googlecode.cqengine.quantizer">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses.html">All&nbsp;Classes</a></li> </ul> <ul class="navListSearch"> <li><label for="search">SEARCH:</label> <input type="text" id="search" value="search" disabled="disabled"> <input type="reset" id="reset" value="reset" disabled="disabled"> </li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> </div> <a id="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> </div> <div class="navPadding">&nbsp;</div> <script type="text/javascript"><!-- $('.navPadding').css('padding-top', $('.fixedNav').css("height")); //--> </script> </nav> </header> <main role="main"> <div class="header"> <h2 title="Uses of Class com.googlecode.cqengine.quantizer.BigDecimalQuantizer" class="title">Uses of Class<br>com.googlecode.cqengine.quantizer.BigDecimalQuantizer</h2> </div> <div class="classUseContainer">No usage of com.googlecode.cqengine.quantizer.BigDecimalQuantizer</div> </main> <footer role="contentinfo"> <nav role="navigation"> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a id="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a id="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../index.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../BigDecimalQuantizer.html" title="class in com.googlecode.cqengine.quantizer">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> </div> <a id="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </nav> <p class="legalCopy"><small>Copyright &#169; 2020. All rights reserved.</small></p> </footer> </body> </html>
{ "pile_set_name": "Github" }
require 'sass/script' require 'sass/script/css_lexer' module Sass module Script # This is a subclass of {Parser} for use in parsing plain CSS properties. # # @see Sass::SCSS::CssParser class CssParser < Parser private # @private def lexer_class; CssLexer; end # We need a production that only does /, # since * and % aren't allowed in plain CSS production :div, :unary_plus, :div def string tok = try_tok(:string) return number unless tok unless @lexer.peek && @lexer.peek.type == :begin_interpolation return literal_node(tok.value, tok.source_range) end end # Short-circuit all the SassScript-only productions alias_method :interpolation, :space alias_method :or_expr, :div alias_method :unary_div, :ident alias_method :paren, :string end end end
{ "pile_set_name": "Github" }
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package workqueue import ( "container/heap" "sync" "time" "k8s.io/apimachinery/pkg/util/clock" utilruntime "k8s.io/apimachinery/pkg/util/runtime" ) // DelayingInterface is an Interface that can Add an item at a later time. This makes it easier to // requeue items after failures without ending up in a hot-loop. type DelayingInterface interface { Interface // AddAfter adds an item to the workqueue after the indicated duration has passed AddAfter(item interface{}, duration time.Duration) } // NewDelayingQueue constructs a new workqueue with delayed queuing ability func NewDelayingQueue() DelayingInterface { return NewDelayingQueueWithCustomClock(clock.RealClock{}, "") } // NewNamedDelayingQueue constructs a new named workqueue with delayed queuing ability func NewNamedDelayingQueue(name string) DelayingInterface { return NewDelayingQueueWithCustomClock(clock.RealClock{}, name) } // NewDelayingQueueWithCustomClock constructs a new named workqueue // with ability to inject real or fake clock for testing purposes func NewDelayingQueueWithCustomClock(clock clock.Clock, name string) DelayingInterface { ret := &delayingType{ Interface: NewNamed(name), clock: clock, heartbeat: clock.NewTicker(maxWait), stopCh: make(chan struct{}), waitingForAddCh: make(chan *waitFor, 1000), metrics: newRetryMetrics(name), } go ret.waitingLoop() return ret } // delayingType wraps an Interface and provides delayed re-enquing type delayingType struct { Interface // clock tracks time for delayed firing clock clock.Clock // stopCh lets us signal a shutdown to the waiting loop stopCh chan struct{} // stopOnce guarantees we only signal shutdown a single time stopOnce sync.Once // heartbeat ensures we wait no more than maxWait before firing heartbeat clock.Ticker // waitingForAddCh is a buffered channel that feeds waitingForAdd waitingForAddCh chan *waitFor // metrics counts the number of retries metrics retryMetrics } // waitFor holds the data to add and the time it should be added type waitFor struct { data t readyAt time.Time // index in the priority queue (heap) index int } // waitForPriorityQueue implements a priority queue for waitFor items. // // waitForPriorityQueue implements heap.Interface. The item occurring next in // time (i.e., the item with the smallest readyAt) is at the root (index 0). // Peek returns this minimum item at index 0. Pop returns the minimum item after // it has been removed from the queue and placed at index Len()-1 by // container/heap. Push adds an item at index Len(), and container/heap // percolates it into the correct location. type waitForPriorityQueue []*waitFor func (pq waitForPriorityQueue) Len() int { return len(pq) } func (pq waitForPriorityQueue) Less(i, j int) bool { return pq[i].readyAt.Before(pq[j].readyAt) } func (pq waitForPriorityQueue) Swap(i, j int) { pq[i], pq[j] = pq[j], pq[i] pq[i].index = i pq[j].index = j } // Push adds an item to the queue. Push should not be called directly; instead, // use `heap.Push`. func (pq *waitForPriorityQueue) Push(x interface{}) { n := len(*pq) item := x.(*waitFor) item.index = n *pq = append(*pq, item) } // Pop removes an item from the queue. Pop should not be called directly; // instead, use `heap.Pop`. func (pq *waitForPriorityQueue) Pop() interface{} { n := len(*pq) item := (*pq)[n-1] item.index = -1 *pq = (*pq)[0:(n - 1)] return item } // Peek returns the item at the beginning of the queue, without removing the // item or otherwise mutating the queue. It is safe to call directly. func (pq waitForPriorityQueue) Peek() interface{} { return pq[0] } // ShutDown stops the queue. After the queue drains, the returned shutdown bool // on Get() will be true. This method may be invoked more than once. func (q *delayingType) ShutDown() { q.stopOnce.Do(func() { q.Interface.ShutDown() close(q.stopCh) q.heartbeat.Stop() }) } // AddAfter adds the given item to the work queue after the given delay func (q *delayingType) AddAfter(item interface{}, duration time.Duration) { // don't add if we're already shutting down if q.ShuttingDown() { return } q.metrics.retry() // immediately add things with no delay if duration <= 0 { q.Add(item) return } select { case <-q.stopCh: // unblock if ShutDown() is called case q.waitingForAddCh <- &waitFor{data: item, readyAt: q.clock.Now().Add(duration)}: } } // maxWait keeps a max bound on the wait time. It's just insurance against weird things happening. // Checking the queue every 10 seconds isn't expensive and we know that we'll never end up with an // expired item sitting for more than 10 seconds. const maxWait = 10 * time.Second // waitingLoop runs until the workqueue is shutdown and keeps a check on the list of items to be added. func (q *delayingType) waitingLoop() { defer utilruntime.HandleCrash() // Make a placeholder channel to use when there are no items in our list never := make(<-chan time.Time) // Make a timer that expires when the item at the head of the waiting queue is ready var nextReadyAtTimer clock.Timer waitingForQueue := &waitForPriorityQueue{} heap.Init(waitingForQueue) waitingEntryByData := map[t]*waitFor{} for { if q.Interface.ShuttingDown() { return } now := q.clock.Now() // Add ready entries for waitingForQueue.Len() > 0 { entry := waitingForQueue.Peek().(*waitFor) if entry.readyAt.After(now) { break } entry = heap.Pop(waitingForQueue).(*waitFor) q.Add(entry.data) delete(waitingEntryByData, entry.data) } // Set up a wait for the first item's readyAt (if one exists) nextReadyAt := never if waitingForQueue.Len() > 0 { if nextReadyAtTimer != nil { nextReadyAtTimer.Stop() } entry := waitingForQueue.Peek().(*waitFor) nextReadyAtTimer = q.clock.NewTimer(entry.readyAt.Sub(now)) nextReadyAt = nextReadyAtTimer.C() } select { case <-q.stopCh: return case <-q.heartbeat.C(): // continue the loop, which will add ready items case <-nextReadyAt: // continue the loop, which will add ready items case waitEntry := <-q.waitingForAddCh: if waitEntry.readyAt.After(q.clock.Now()) { insert(waitingForQueue, waitingEntryByData, waitEntry) } else { q.Add(waitEntry.data) } drained := false for !drained { select { case waitEntry := <-q.waitingForAddCh: if waitEntry.readyAt.After(q.clock.Now()) { insert(waitingForQueue, waitingEntryByData, waitEntry) } else { q.Add(waitEntry.data) } default: drained = true } } } } } // insert adds the entry to the priority queue, or updates the readyAt if it already exists in the queue func insert(q *waitForPriorityQueue, knownEntries map[t]*waitFor, entry *waitFor) { // if the entry already exists, update the time only if it would cause the item to be queued sooner existing, exists := knownEntries[entry.data] if exists { if existing.readyAt.After(entry.readyAt) { existing.readyAt = entry.readyAt heap.Fix(q, existing.index) } return } heap.Push(q, entry) knownEntries[entry.data] = entry }
{ "pile_set_name": "Github" }
// Copyright 2012 Citrix Systems, Inc. Licensed under the // Apache License, Version 2.0 (the "License"); you may not use this // file except in compliance with the License. Citrix Systems, Inc. // reserves all rights not expressly granted by 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. // // Automatically generated by addcopyright.py at 04/03/2012 package com.cloud.test.stress; import java.util.Arrays; import java.util.Iterator; import java.util.List; import org.apache.log4j.Logger; import com.trilead.ssh2.Connection; import com.trilead.ssh2.Session; public class SshTest { public static final Logger s_logger = Logger.getLogger(SshTest.class.getName()); public static String host = ""; public static String password = "password"; public static String url = "http://google.com"; public static void main (String[] args) { // Parameters List<String> argsList = Arrays.asList(args); Iterator<String> iter = argsList.iterator(); while (iter.hasNext()) { String arg = iter.next(); if (arg.equals("-h")) { host = iter.next(); } if (arg.equals("-p")) { password = iter.next(); } if (arg.equals("-u")) { url = iter.next(); } } if (host == null || host.equals("")) { s_logger.info("Did not receive a host back from test, ignoring ssh test"); System.exit(2); } if (password == null){ s_logger.info("Did not receive a password back from test, ignoring ssh test"); System.exit(2); } try { s_logger.info("Attempting to SSH into host " + host); Connection conn = new Connection(host); conn.connect(null, 60000, 60000); s_logger.info("User + ssHed successfully into host " + host); boolean isAuthenticated = conn.authenticateWithPassword("root", password); if (isAuthenticated == false) { s_logger.info("Authentication failed for root with password" + password); System.exit(2); } String linuxCommand = "wget " + url; Session sess = conn.openSession(); sess.execCommand(linuxCommand); sess.close(); conn.close(); } catch (Exception e) { s_logger.error("SSH test fail with error", e); System.exit(2); } } }
{ "pile_set_name": "Github" }
{ "acno": "D40572", "acquisitionYear": 1856, "additionalImages": [ { "copyright": null, "creativeCommons": null, "filenameBase": "D40572", "sizes": [ { "caption": "Enhanced image", "cleared": true, "file": "enhanced_images/D405/D40572_E.jpg", "height": 337, "resolution": 512, "size": "large", "width": 512 } ] } ], "all_artists": "Joseph Mallord William Turner", "catTextResId": 1129878, "catalogueGroup": { "accessionRanges": "D05491-D05617; D40568-D40574; D41505", "completeStatus": "COMPLETE", "finbergNumber": "XC", "groupType": "Turner Sketchbook", "id": 65737, "shortTitle": "Studies for Pictures: Isleworth Sketchbook" }, "classification": "on paper, unique", "contributorCount": 1, "contributors": [ { "birthYear": 1775, "date": "1775\u20131851", "displayOrder": 1, "fc": "Joseph Mallord William Turner", "gender": "Male", "id": 558, "mda": "Turner, Joseph Mallord William", "role": "artist", "startLetter": "T" } ], "creditLine": "Accepted by the nation as part of the Turner Bequest 1856", "dateRange": { "endYear": 1805, "startYear": 1805, "text": "1805" }, "dateText": "1805", "depth": "", "dimensions": "support: 150 x 258 mm", "finberg": null, "foreignTitle": null, "groupTitle": "Studies for Pictures: Isleworth Sketchbook", "height": "258", "id": 64321, "inscription": null, "medium": "Pen and ink on paper", "movementCount": 0, "pageNumber": 98, "subjectCount": 1, "subjects": { "children": [ { "children": [ { "children": [ { "id": 1827, "name": "tree" } ], "id": 1809, "name": "trees" } ], "id": 60, "name": "nature" } ], "id": 1, "name": "subject" }, "thumbnailCopyright": null, "thumbnailUrl": "http://www.tate.org.uk/art/images/work/D/D40/D40572_8.jpg", "title": "A View on the Thames", "units": "mm", "url": "http://www.tate.org.uk/art/artworks/turner-a-view-on-the-thames-d40572", "width": "150" }
{ "pile_set_name": "Github" }
'use strict'; module.exports = function(Chart) { var helpers = Chart.helpers; Chart.scaleService = { // Scale registration object. Extensions can register new scale types (such as log or DB scales) and then // use the new chart options to grab the correct scale constructors: {}, // Use a registration function so that we can move to an ES6 map when we no longer need to support // old browsers // Scale config defaults defaults: {}, registerScaleType: function(type, scaleConstructor, defaults) { this.constructors[type] = scaleConstructor; this.defaults[type] = helpers.clone(defaults); }, getScaleConstructor: function(type) { return this.constructors.hasOwnProperty(type) ? this.constructors[type] : undefined; }, getScaleDefaults: function(type) { // Return the scale defaults merged with the global settings so that we always use the latest ones return this.defaults.hasOwnProperty(type) ? helpers.scaleMerge(Chart.defaults.scale, this.defaults[type]) : {}; }, updateScaleDefaults: function(type, additions) { var defaults = this.defaults; if (defaults.hasOwnProperty(type)) { defaults[type] = helpers.extend(defaults[type], additions); } }, addScalesToLayout: function(chart) { // Adds each scale to the chart.boxes array to be sized accordingly helpers.each(chart.scales, function(scale) { // Set ILayoutItem parameters for backwards compatibility scale.fullWidth = scale.options.fullWidth; scale.position = scale.options.position; scale.weight = scale.options.weight; Chart.layoutService.addBox(chart, scale); }); } }; };
{ "pile_set_name": "Github" }
describe Wordmove::Doctor::Mysql do let(:movefile_name) { 'multi_environments' } let(:movefile_dir) { "spec/fixtures/movefiles" } let(:doctor) { described_class.new(movefile_name, movefile_dir) } context ".new" do it "implements #check! method" do expect_any_instance_of(described_class).to receive(:check!) silence_stream(STDOUT) { doctor.check! } end it "calls mysql client check" do expect(doctor).to receive(:mysql_client_doctor) silence_stream(STDOUT) { doctor.check! } end it "calls mysqldump check" do expect(doctor).to receive(:mysqldump_doctor) silence_stream(STDOUT) { doctor.check! } end it "calls mysql server check" do expect(doctor).to receive(:mysql_server_doctor) silence_stream(STDOUT) { doctor.check! } end it "calls mysql database check" do # expect(doctor).to receive(:mysql_database_doctor) silence_stream(STDOUT) { doctor.check! } end end end
{ "pile_set_name": "Github" }
package mirror.android.os; import android.os.Parcel; import mirror.RefClass; import mirror.RefObject; public class BundleICS { public static Class<?> TYPE = RefClass.load(BundleICS.class, "android.os.Bundle"); public static RefObject<Parcel> mParcelledData; }
{ "pile_set_name": "Github" }
/* * Copyright 2011 David Jurgens * * This file is part of the S-Space package and is covered under the terms and * conditions therein. * * The S-Space package 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 and distributed hereunder to you. * * THIS SOFTWARE IS PROVIDED "AS IS" AND NO REPRESENTATIONS OR WARRANTIES, * EXPRESS OR IMPLIED ARE MADE. BY WAY OF EXAMPLE, BUT NOT LIMITATION, WE MAKE * NO REPRESENTATIONS OR WARRANTIES OF MERCHANT- ABILITY OR FITNESS FOR ANY * PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE OR DOCUMENTATION * WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER * RIGHTS. * * 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 edu.ucla.sspace.graph; import java.util.*; import edu.ucla.sspace.util.OpenIntSet; import org.junit.Ignore; import org.junit.Test; import static org.junit.Assert.*; /** * */ public class DirectedMultigraphTests { @Test public void testConstructor() { Set<Integer> vertices = new HashSet<Integer>(); DirectedMultigraph<String> g = new DirectedMultigraph<String>(); assertEquals(0, g.order()); assertEquals(0, g.size()); } @Test(expected=NullPointerException.class) public void testConstructor2NullArg() { Graph<Edge> g = new SparseUndirectedGraph((Graph<DirectedTypedEdge<String>>)null); } @Test public void testAdd() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); assertTrue(g.add(0)); assertEquals(1, g.order()); assertTrue(g.contains(0)); // second add should have no effect assertFalse(g.add(0)); assertEquals(1, g.order()); assertTrue(g.contains(0)); assertTrue(g.add(1)); assertEquals(2, g.order()); assertTrue(g.contains(1)); } @Test public void testEquals() { DirectedMultigraph<String> g1 = new DirectedMultigraph<String>(); DirectedMultigraph<String> g2 = new DirectedMultigraph<String>(); for (int i = 0; i < 10; ++i) { for (int j = i + 1; j < 10; ++j) { g1.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); g2.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } } assertEquals(g1, g2); g1 = new DirectedMultigraph<String>(); g2 = new DirectedMultigraph<String>(); for (int i = 0; i < 10; ++i) { for (int j = i + 1; j < 10; ++j) { g1.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); g2.add(new SimpleDirectedTypedEdge<String>("type-1",j, i)); } } assertFalse(g1.equals(g2)); assertFalse(g2.equals(g1)); } @Test public void testEqualGeneric() { DirectedMultigraph<String> g1 = new DirectedMultigraph<String>(); Graph<DirectedTypedEdge<String>> g2 = new GenericGraph<DirectedTypedEdge<String>>(); for (int i = 0; i < 10; ++i) { for (int j = i + 1; j < 10; ++j) { g1.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); g2.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } } assertEquals(g1, g2); } @Test public void testContainsEdge() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 0; i < 100; ++i) for (int j = i + 1; j < 100; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); for (int i = 0; i < 100; ++i) { for (int j = i + 1; j < 100; ++j) { g.contains(new SimpleDirectedTypedEdge<String>("type-1",i, j)); g.contains(new SimpleDirectedTypedEdge<String>("type-1",j, i)); g.contains(i, j); g.contains(j, i); } } } @Test public void testAddEdge() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); assertEquals(2, g.order()); assertEquals(1, g.size()); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); g.add(new SimpleDirectedTypedEdge<String>("type-1",0, 2)); assertEquals(3, g.order()); assertEquals(2, g.size()); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 2))); g.add(new SimpleDirectedTypedEdge<String>("type-1",3, 4)); assertEquals(5, g.order()); assertEquals(3, g.size()); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-1",3, 4))); } @Test public void testRemoveLesserVertexWithEdges() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 1; i < 100; ++i) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, i); g.add(e); } assertTrue(g.contains(0)); assertTrue(g.remove(0)); assertEquals(99, g.order()); assertEquals(0, g.size()); } @Test public void testRemoveHigherVertexWithEdges() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 0; i < 99; ++i) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",100, i); g.add(e); } assertTrue(g.contains(100)); assertTrue(g.remove(100)); assertEquals(99, g.order()); assertEquals(0, g.size()); } @Test public void testRemoveVertex() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 0; i < 100; ++i) { g.add(i); } for (int i = 99; i >= 0; --i) { assertTrue(g.remove(i)); assertEquals(i, g.order()); assertFalse(g.contains(i)); assertFalse(g.remove(i)); } } @Test public void testRemoveEdge() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 1; i < 100; ++i) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, i); g.add(e); } for (int i = 99; i > 0; --i) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, i); assertTrue(g.remove(e)); assertEquals(i-1, g.size()); assertFalse(g.contains(e)); assertFalse(g.remove(e)); } } @Test public void testVertexIterator() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<Integer> control = new HashSet<Integer>(); for (int i = 0; i < 100; ++i) { g.add(i); control.add(i); } assertEquals(control.size(), g.order()); for (Integer i : g.vertices()) assertTrue(control.contains(i)); } @Test public void testEdgeIterator() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<DirectedTypedEdge<String>> control = new HashSet<DirectedTypedEdge<String>>(); for (int i = 1; i <= 100; ++i) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, i); g.add(e); control.add(e); } assertEquals(control.size(), g.size()); assertEquals(control.size(), g.edges().size()); int returned = 0; for (Edge e : g.edges()) { assertTrue(control.remove(e)); returned++; } assertEquals(g.size(), returned); assertEquals(0, control.size()); } @Test public void testEdgeIteratorSmall() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<DirectedTypedEdge<String>> control = new HashSet<DirectedTypedEdge<String>>(); for (int i = 1; i <= 5; ++i) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, i); assertTrue(g.add(e)); control.add(e); } assertEquals(control.size(), g.size()); assertEquals(control.size(), g.edges().size()); int returned = 0; for (Edge e : g.edges()) { System.out.println(e); assertTrue(control.contains(e)); returned++; } assertEquals(control.size(), returned); } @Test public void testEdgeIteratorSmallReverse() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<DirectedTypedEdge<String>> control = new HashSet<DirectedTypedEdge<String>>(); for (int i = 1; i <= 5; ++i) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, 0); g.add(e); control.add(e); } assertEquals(control.size(), g.size()); assertEquals(control.size(), g.edges().size()); int returned = 0; for (Edge e : g.edges()) { System.out.println(e); assertTrue(control.contains(e)); returned++; } assertEquals(control.size(), returned); } @Test public void testAdjacentEdges() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<DirectedTypedEdge<String>> control = new HashSet<DirectedTypedEdge<String>>(); for (int i = 1; i <= 100; ++i) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, i); g.add(e); control.add(e); } Set<DirectedTypedEdge<String>> test = g.getAdjacencyList(0); assertEquals(control, test); } @Test public void testAdjacencyListSize() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<DirectedTypedEdge<String>> adjList = g.getAdjacencyList(0); assertEquals(9, adjList.size()); adjList = g.getAdjacencyList(1); assertEquals(9, adjList.size()); adjList = g.getAdjacencyList(2); assertEquals(9, adjList.size()); adjList = g.getAdjacencyList(3); assertEquals(9, adjList.size()); adjList = g.getAdjacencyList(5); assertEquals(9, adjList.size()); } @Test public void testAdjacentEdgesRemove() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<DirectedTypedEdge<String>> control = new HashSet<DirectedTypedEdge<String>>(); for (int i = 1; i <= 100; ++i) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, i); g.add(e); control.add(e); } Set<DirectedTypedEdge<String>> test = g.getAdjacencyList(0); assertEquals(control, test); Edge removed = new SimpleDirectedTypedEdge<String>("type-1",0, 1); assertTrue(test.remove(removed)); assertTrue(control.remove(removed)); assertEquals(control, test); assertEquals(99, g.size()); } @Test public void testAdjacentEdgesAdd() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<DirectedTypedEdge<String>> control = new HashSet<DirectedTypedEdge<String>>(); for (int i = 1; i <= 100; ++i) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, i); g.add(e); control.add(e); } Set<DirectedTypedEdge<String>> test = g.getAdjacencyList(0); assertEquals(control, test); DirectedTypedEdge<String> added = new SimpleDirectedTypedEdge<String>("type-1",0, 101); assertTrue(test.add(added)); assertTrue(control.add(added)); assertEquals(control, test); assertEquals(101, g.size()); assertTrue(g.contains(added)); assertTrue(g.contains(101)); assertEquals(102, g.order()); } @Test public void testClear() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); g.clear(); assertEquals(0, g.size()); assertEquals(0, g.order()); assertEquals(0, g.vertices().size()); assertEquals(0, g.edges().size()); // Error checking case for double-clear g.clear(); } @Test public void testClearEdges() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); g.clearEdges(); assertEquals(0, g.size()); assertEquals(10, g.order()); assertEquals(10, g.vertices().size()); assertEquals(0, g.edges().size()); // Error checking case for double-clear g.clearEdges(); } @Test public void testToString() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 0; i < 10; ++i) for (int j = i + 1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); g.toString(); // only vertices g.clearEdges(); g.toString(); // empty graph g.clear(); g.toString(); } /****************************************************************** * * * VertexSet tests * * ******************************************************************/ @Test(expected=UnsupportedOperationException.class) public void testVertexSetAdd() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<Integer> control = new HashSet<Integer>(); for (int i = 0; i < 100; ++i) { g.add(i); control.add(i); } Set<Integer> vertices = g.vertices(); assertEquals(control.size(), vertices.size()); assertTrue(vertices.add(100)); assertTrue(g.contains(100)); assertEquals(101, vertices.size()); assertEquals(101, g.order()); // dupe assertFalse(vertices.add(100)); assertEquals(101, vertices.size()); } @Test(expected=UnsupportedOperationException.class) public void testVertexSetAddFromGraph() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<Integer> control = new HashSet<Integer>(); for (int i = 0; i < 100; ++i) { g.add(i); control.add(i); } Set<Integer> vertices = g.vertices(); assertEquals(control.size(), vertices.size()); assertTrue(g.add(100)); assertTrue(g.contains(100)); assertTrue(vertices.contains(100)); assertEquals(101, vertices.size()); assertEquals(101, g.order()); // dupe assertFalse(vertices.add(100)); assertEquals(101, vertices.size()); } @Test(expected=UnsupportedOperationException.class) public void testVertexSetRemove() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<Integer> control = new HashSet<Integer>(); for (int i = 0; i < 100; ++i) { g.add(i); control.add(i); } Set<Integer> vertices = g.vertices(); assertEquals(control.size(), vertices.size()); assertTrue(g.contains(99)); assertTrue(vertices.remove(99)); assertFalse(g.contains(99)); assertEquals(99, vertices.size()); assertEquals(99, g.order()); // dupe assertFalse(vertices.remove(99)); assertEquals(99, vertices.size()); } @Test public void testVertexSetRemoveFromGraph() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<Integer> control = new HashSet<Integer>(); for (int i = 0; i < 100; ++i) { g.add(i); control.add(i); } Set<Integer> vertices = g.vertices(); assertEquals(control.size(), vertices.size()); assertTrue(g.remove(99)); assertFalse(g.contains(99)); assertFalse(vertices.contains(99)); assertEquals(99, vertices.size()); assertEquals(99, g.order()); } @Test(expected=UnsupportedOperationException.class) public void testVertexSetIteratorRemove() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<Integer> control = new HashSet<Integer>(); for (int i = 0; i < 100; ++i) { g.add(i); control.add(i); } Set<Integer> vertices = g.vertices(); assertEquals(control.size(), vertices.size()); Iterator<Integer> iter = vertices.iterator(); assertTrue(iter.hasNext()); Integer toRemove = iter.next(); assertTrue(g.contains(toRemove)); assertTrue(vertices.contains(toRemove)); iter.remove(); assertFalse(g.contains(toRemove)); assertFalse(vertices.contains(toRemove)); assertEquals(g.order(), vertices.size()); } @Test(expected=NoSuchElementException.class) public void testVertexSetIteratorTooFar() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<Integer> control = new HashSet<Integer>(); for (int i = 0; i < 100; ++i) { g.add(i); control.add(i); } Set<Integer> vertices = g.vertices(); Iterator<Integer> iter = vertices.iterator(); int i = 0; while (iter.hasNext()) { i++; iter.next(); } assertEquals(vertices.size(), i); iter.next(); } @Test(expected=UnsupportedOperationException.class) public void testVertexSetIteratorRemoveTwice() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<Integer> control = new HashSet<Integer>(); for (int i = 0; i < 100; ++i) { g.add(i); control.add(i); } Set<Integer> vertices = g.vertices(); Iterator<Integer> iter = vertices.iterator(); assertTrue(iter.hasNext()); Integer toRemove = iter.next(); assertTrue(g.contains(toRemove)); assertTrue(vertices.contains(toRemove)); iter.remove(); iter.remove(); } @Test(expected=UnsupportedOperationException.class) public void testVertexSetIteratorRemoveEarly() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<Integer> control = new HashSet<Integer>(); for (int i = 0; i < 100; ++i) { g.add(i); control.add(i); } Set<Integer> vertices = g.vertices(); Iterator<Integer> iter = vertices.iterator(); iter.remove(); } /****************************************************************** * * * EdgeView tests * * ******************************************************************/ @Test public void testEdgeViewAdd() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<DirectedTypedEdge<String>> edges = g.edges(); assertEquals(g.size(), edges.size()); edges.add(new SimpleDirectedTypedEdge<String>("type-1",0, 1)); assertEquals(2, g.order()); assertEquals(1, g.size()); assertEquals(1, edges.size()); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); assertTrue(edges.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); } @Test public void testEdgeViewRemove() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<DirectedTypedEdge<String>> edges = g.edges(); assertEquals(g.size(), edges.size()); edges.add(new SimpleDirectedTypedEdge<String>("type-1",0, 1)); edges.remove(new SimpleDirectedTypedEdge<String>("type-1",0, 1)); assertEquals(2, g.order()); assertEquals(0, g.size()); assertEquals(0, edges.size()); assertFalse(g.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); assertFalse(edges.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); } @Test public void testEdgeViewIterator() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<DirectedTypedEdge<String>> edges = g.edges(); Set<DirectedTypedEdge<String>> control = new HashSet<DirectedTypedEdge<String>>(); for (int i = 0; i < 100; i += 2) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, i+1); g.add(e); // all disconnected control.add(e); } assertEquals(100, g.order()); assertEquals(50, g.size()); assertEquals(50, edges.size()); Set<DirectedTypedEdge<String>> test = new HashSet<DirectedTypedEdge<String>>(); for (DirectedTypedEdge<String> e : edges) test.add(e); assertEquals(control.size(), test.size()); for (Edge e : test) assertTrue(control.contains(e)); } @Test public void testEdgeViewIteratorRemove() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<DirectedTypedEdge<String>> edges = g.edges(); Set<DirectedTypedEdge<String>> control = new HashSet<DirectedTypedEdge<String>>(); for (int i = 0; i < 10; i += 2) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, i+1); g.add(e); // all disconnected control.add(e); } assertEquals(10, g.order()); assertEquals(5, g.size()); assertEquals(5, edges.size()); Iterator<DirectedTypedEdge<String>> iter = edges.iterator(); while (iter.hasNext()) { iter.next(); iter.remove(); } assertEquals(0, g.size()); assertFalse(g.edges().iterator().hasNext()); assertEquals(0, edges.size()); assertEquals(10, g.order()); } /****************************************************************** * * * AdjacencyListView tests * * ******************************************************************/ @Test public void testAdjacencyList() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 0; i < 10; ++i) for (int j = i + 1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); for (int i = 0; i < 10; ++i) { Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(i); assertEquals(9, adjacencyList.size()); for (int j = 0; j < 10; ++j) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j); if (i >= j) assertFalse(adjacencyList.contains(e)); else assertTrue(adjacencyList.contains(e)); } } } @Test public void testAdjacencyListRemoveEdge() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 0; i < 10; ++i) for (int j = i + 1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(0); Edge e = new SimpleDirectedTypedEdge<String>("type-1",0, 1); assertTrue(adjacencyList.contains(e)); assertTrue(adjacencyList.remove(e)); assertEquals(8, adjacencyList.size()); assertEquals( (10 * 9) / 2 - 1, g.size()); } public void testAdjacencyListAddEdge() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 0; i < 10; ++i) for (int j = i + 2; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); assertEquals( (10 * 9) / 2 - 9, g.size()); Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(0); DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, 1); assertFalse(adjacencyList.contains(e)); assertFalse(g.contains(e)); assertTrue(adjacencyList.add(e)); assertTrue(g.contains(e)); assertEquals(9, adjacencyList.size()); assertEquals( (10 * 9) / 2 - 8, g.size()); } @Test public void testAdjacencyListIterator() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 0; i < 10; ++i) { for (int j = i + 1; j < 10; ++j) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j); g.add(e); } } Set<DirectedTypedEdge<String>> test = new HashSet<DirectedTypedEdge<String>>(); Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(0); assertEquals(9, adjacencyList.size()); Iterator<DirectedTypedEdge<String>> it = adjacencyList.iterator(); int i = 0; while (it.hasNext()) assertTrue(test.add(it.next())); assertEquals(9, test.size()); } @Test public void testAdjacencyListNoVertex() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(0); assertEquals(0, adjacencyList.size()); } @Test(expected=NoSuchElementException.class) public void testAdjacencyListIteratorNextOffEnd() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 0; i < 10; ++i) { for (int j = i + 1; j < 10; ++j) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j); g.add(e); } } Set<DirectedTypedEdge<String>> test = new HashSet<DirectedTypedEdge<String>>(); Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(0); assertEquals(9, adjacencyList.size()); Iterator<DirectedTypedEdge<String>> it = adjacencyList.iterator(); int i = 0; while (it.hasNext()) assertTrue(test.add(it.next())); assertEquals(9, test.size()); it.next(); } @Test(expected=UnsupportedOperationException.class) public void testAdjacencyListIteratorRemove() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 0; i < 10; ++i) { for (int j = i + 1; j < 10; ++j) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j); g.add(e); } } Set<DirectedTypedEdge<String>> test = new HashSet<DirectedTypedEdge<String>>(); Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(0); assertEquals(9, adjacencyList.size()); Iterator<DirectedTypedEdge<String>> it = adjacencyList.iterator(); assertTrue(it.hasNext()); Edge e = it.next(); it.remove(); assertFalse(adjacencyList.contains(e)); assertEquals(8, adjacencyList.size()); assertFalse(g.contains(e)); assertEquals( (10 * 9) / 2 - 1, g.size()); } @Test(expected=UnsupportedOperationException.class) public void testAdjacencyListIteratorRemoveFirst() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 0; i < 10; ++i) { for (int j = i + 1; j < 10; ++j) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j); g.add(e); } } Set<DirectedTypedEdge<String>> test = new HashSet<DirectedTypedEdge<String>>(); Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(0); assertEquals(9, adjacencyList.size()); Iterator<DirectedTypedEdge<String>> it = adjacencyList.iterator(); it.remove(); } @Test(expected=UnsupportedOperationException.class) public void testAdjacencyListIteratorRemoveTwice() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 0; i < 10; ++i) { for (int j = i + 1; j < 10; ++j) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j); g.add(e); } } Set<DirectedTypedEdge<String>> test = new HashSet<DirectedTypedEdge<String>>(); Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(0); assertEquals(9, adjacencyList.size()); Iterator<DirectedTypedEdge<String>> it = adjacencyList.iterator(); assertTrue(it.hasNext()); it.next(); it.remove(); it.remove(); } /****************************************************************** * * * AdjacentVerticesView tests * * ******************************************************************/ @Test public void testAdjacentVertices() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 0; i < 10; ++i) { for (int j = i + 1; j < 10; ++j) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j); g.add(e); } } Set<Integer> test = new HashSet<Integer>(); Set<Integer> adjacent = g.getNeighbors(0); assertEquals(9, adjacent.size()); for (int i = 1; i < 10; ++i) assertTrue(adjacent.contains(i)); assertFalse(adjacent.contains(0)); assertFalse(adjacent.contains(10)); } @Test(expected=UnsupportedOperationException.class) public void testAdjacentVerticesAdd() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 0; i < 10; ++i) { for (int j = i + 1; j < 10; ++j) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j); g.add(e); } } Set<Integer> test = new HashSet<Integer>(); Set<Integer> adjacent = g.getNeighbors(0); adjacent.add(1); } @Test(expected=UnsupportedOperationException.class) public void testAdjacentVerticesRemove() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 0; i < 10; ++i) { for (int j = i + 1; j < 10; ++j) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j); g.add(e); } } Set<Integer> test = new HashSet<Integer>(); Set<Integer> adjacent = g.getNeighbors(0); adjacent.remove(1); } @Test public void testAdjacentVerticesIterator() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 0; i < 10; ++i) { for (int j = i + 1; j < 10; ++j) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j); g.add(e); } } Set<Integer> test = new HashSet<Integer>(); Set<Integer> adjacent = g.getNeighbors(0); Iterator<Integer> it = adjacent.iterator(); while (it.hasNext()) assertTrue(test.add(it.next())); assertEquals(9, test.size()); } @Test(expected=UnsupportedOperationException.class) public void testAdjacentVerticesIteratorRemove() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 0; i < 10; ++i) { for (int j = i + 1; j < 10; ++j) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j); g.add(e); } } Set<Integer> test = new HashSet<Integer>(); Set<Integer> adjacent = g.getNeighbors(0); Iterator<Integer> it = adjacent.iterator(); assertTrue(it.hasNext()); it.next(); it.remove(); } /****************************************************************** * * * Subgraph tests * * ******************************************************************/ @Test public void testSubgraph() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); assertEquals(5, subgraph.order()); assertEquals( (5 * 4) / 2, subgraph.size()); } @Test public void testSubgraphContainsVertex() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); assertEquals(5, subgraph.order()); assertEquals( (5 * 4) / 2, subgraph.size()); for (int i = 0; i < 5; ++i) assertTrue(subgraph.contains(i)); for (int i = 5; i < 10; ++i) { assertTrue(g.contains(i)); assertFalse(subgraph.contains(i)); } } @Test public void testSubgraphContainsEdge() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); assertEquals(5, subgraph.order()); assertEquals( (5 * 4) / 2, subgraph.size()); for (int i = 0; i < 5; ++i) { for (int j = i+1; j < 5; ++j) { assertTrue(subgraph.contains(new SimpleDirectedTypedEdge<String>("type-1",i, j))); } } for (int i = 5; i < 10; ++i) { for (int j = i+1; j < 10; ++j) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j); assertTrue(g.contains(e)); assertFalse(subgraph.contains(e)); } } } @Test public void testSubgraphAddEdge() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < i+2 && j < 10; ++j) assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j))); } assertEquals(9, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); assertEquals(5, subgraph.order()); assertEquals(4, subgraph.size()); // Add an edge to a new vertex assertTrue(subgraph.add(new SimpleDirectedTypedEdge<String>("type-1", 1, 0))); assertEquals(5, subgraph.size()); assertEquals(5, subgraph.order()); assertEquals(10, g.size()); } @Test(expected=UnsupportedOperationException.class) public void testSubgraphAddEdgeNewVertex() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); assertEquals(5, subgraph.order()); assertEquals( (5 * 4) / 2, subgraph.size()); // Add an edge to a new vertex assertTrue(subgraph.add(new SimpleDirectedTypedEdge<String>("type-1",0, 5))); assertEquals( (5 * 4) / 2 + 1, subgraph.size()); assertEquals(6, subgraph.order()); assertEquals(11, g.order()); assertEquals( (9*10)/2 + 1, g.size()); } @Test public void testSubgraphRemoveEdge() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); assertEquals(5, subgraph.order()); assertEquals( (5 * 4) / 2, subgraph.size()); // Remove an existing edge assertTrue(subgraph.remove(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); assertEquals( (5 * 4) / 2 - 1, subgraph.size()); assertEquals(5, subgraph.order()); assertEquals(10, g.order()); assertEquals( (9*10)/2 - 1, g.size()); // Remove a non-existent edge, which should have no effect even though // the edge is present in the backing graph assertFalse(subgraph.remove(new SimpleDirectedTypedEdge<String>("type-1",0, 6))); assertEquals( (5 * 4) / 2 - 1, subgraph.size()); assertEquals(5, subgraph.order()); assertEquals(10, g.order()); assertEquals( (9*10)/2 - 1, g.size()); } /****************************************************************** * * * SubgraphVertexView tests * * ******************************************************************/ @Test(expected=UnsupportedOperationException.class) public void testSubgraphVerticesAdd() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); assertEquals(5, subgraph.order()); assertEquals( (5 * 4) / 2, subgraph.size()); Set<Integer> test = subgraph.vertices(); assertEquals(5, test.size()); // Add a vertex assertTrue(test.add(5)); assertEquals(6, test.size()); assertEquals(6, subgraph.order()); assertEquals(11, g.order()); assertEquals( (5*4)/2, subgraph.size()); } @Test(expected=UnsupportedOperationException.class) public void testSubgraphVerticesRemove() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); assertEquals(5, subgraph.order()); assertEquals( (5 * 4) / 2, subgraph.size()); Set<Integer> test = subgraph.vertices(); assertEquals(5, test.size()); // Add a vertex assertTrue(test.remove(0)); assertEquals(4, test.size()); assertEquals(4, subgraph.order()); assertEquals(9, g.order()); assertEquals( (4*3)/2, subgraph.size()); } @Test(expected=UnsupportedOperationException.class) public void testSubgraphVerticesIteratorRemove() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); assertEquals(5, subgraph.order()); assertEquals( (5 * 4) / 2, subgraph.size()); Set<Integer> test = subgraph.vertices(); assertEquals(5, test.size()); Iterator<Integer> it = test.iterator(); assertTrue(it.hasNext()); // Remove the first vertex returned it.next(); it.remove(); assertEquals(4, test.size()); assertEquals(4, subgraph.order()); assertEquals(9, g.order()); assertEquals( (4*3)/2, subgraph.size()); } /****************************************************************** * * * SubgraphEdgeView tests * * ******************************************************************/ @Test public void testSubgraphEdges() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { g.add(i); } g.add(new SimpleDirectedTypedEdge<String>("type-1",0, 1)); g.add(new SimpleDirectedTypedEdge<String>("type-1",0, 2)); g.add(new SimpleDirectedTypedEdge<String>("type-1",1, 2)); assertEquals(3, g.size()); Set<Integer> verts = new HashSet<Integer>(); for (int i = 0; i < 3; ++i) verts.add(i); DirectedMultigraph<String> sub = g.subgraph(verts); assertEquals(3, sub.order()); assertEquals(3, sub.size()); Set<DirectedTypedEdge<String>> edges = sub.edges(); assertEquals(3, edges.size()); int j = 0; Iterator<DirectedTypedEdge<String>> iter = edges.iterator(); while (iter.hasNext()) { iter.next(); j++; } assertEquals(3, j); verts.clear(); for (int i = 3; i < 6; ++i) verts.add(i); sub = g.subgraph(verts); assertEquals(3, sub.order()); assertEquals(0, sub.size()); edges = sub.edges(); assertEquals(0, edges.size()); iter = edges.iterator(); assertFalse(iter.hasNext()); } /****************************************************************** * * * SubgraphAdjacencyListView tests * * ******************************************************************/ @Test public void testSubgraphAdjacencyListContains() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); Set<DirectedTypedEdge<String>> adjList = subgraph.getAdjacencyList(0); for (int i = 1; i < 5; ++i) assertTrue(adjList.contains(new SimpleDirectedTypedEdge<String>("type-1",0, i))); for (int i = 5; i < 10; ++i) assertFalse(adjList.contains(new SimpleDirectedTypedEdge<String>("type-1",0, i))); } @Test public void testSubgraphAdjacencyListSize() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); Set<DirectedTypedEdge<String>> adjList = subgraph.getAdjacencyList(0); assertEquals(4, adjList.size()); adjList = subgraph.getAdjacencyList(1); assertEquals(4, adjList.size()); adjList = subgraph.getAdjacencyList(2); assertEquals(4, adjList.size()); adjList = subgraph.getAdjacencyList(3); assertEquals(4, adjList.size()); adjList = subgraph.getAdjacencyList(4); assertEquals(4, adjList.size()); } @Test(expected=UnsupportedOperationException.class) public void testSubgraphAdjacencyListAddNewVertex() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); Set<DirectedTypedEdge<String>> adjList = subgraph.getAdjacencyList(0); // Add an edge to a new vertex assertTrue(adjList.add(new SimpleDirectedTypedEdge<String>("type-1",0, 5))); } /****************************************************************** * * * SubgraphAdjacentVerticesView tests * * ******************************************************************/ @Test public void testSubgraphAdjacentVertices() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); Set<Integer> adjacent = subgraph.getNeighbors(0); assertEquals(4, adjacent.size()); // check contents for (int i = 1; i < 5; ++i) assertTrue(adjacent.contains(i)); adjacent = subgraph.getNeighbors(1); assertEquals(4, adjacent.size()); adjacent = subgraph.getNeighbors(2); assertEquals(4, adjacent.size()); adjacent = subgraph.getNeighbors(3); assertEquals(4, adjacent.size()); adjacent = subgraph.getNeighbors(4); assertEquals(4, adjacent.size()); adjacent = subgraph.getNeighbors(5); assertEquals(0, adjacent.size()); } @Test(expected=UnsupportedOperationException.class) public void testSubgraphAdjacentVerticesAdd() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); Set<Integer> adjacent = subgraph.getNeighbors(0); adjacent.add(0); } @Test(expected=UnsupportedOperationException.class) public void testSubgraphAdjacentVerticesRemove() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); Set<Integer> adjacent = subgraph.getNeighbors(0); adjacent.remove(0); } @Test public void testSubgraphAdjacentVerticesIterator() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); vertices.remove(0); // now is the adjacent vertices of 0 Set<Integer> adjacent = subgraph.getNeighbors(0); assertEquals(vertices, adjacent); Iterator<Integer> it = adjacent.iterator(); int i = 0; while (it.hasNext()) { i++; vertices.remove(it.next()); } assertEquals(4, i); assertEquals(0, vertices.size()); } @Test(expected=UnsupportedOperationException.class) public void testSubgraphAdjacentVerticesIteratorRemove() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); vertices.remove(0); // now is the adjacent vertices of 0 Set<Integer> adjacent = subgraph.getNeighbors(0); assertEquals(vertices, adjacent); Iterator<Integer> it = adjacent.iterator(); assertTrue(it.hasNext()); it.next(); it.remove(); } /****************************************************************** * * * Tests that create a subgraph and then modify the backing graph * * ******************************************************************/ @Test public void testSubgraphWhenVerticesRemovedFromBacking() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); g.remove(0); assertEquals(4, subgraph.order()); assertEquals((3 * 4) / 2, subgraph.size()); g.remove(1); assertFalse(subgraph.contains(1)); g.remove(2); assertFalse(subgraph.contains(new SimpleDirectedTypedEdge<String>("type-1",2,3))); } @Test public void testSubgraphVertexIteratorWhenVerticesRemovedFromBacking() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); g.remove(0); Iterator<Integer> it = subgraph.vertices().iterator(); int i = 0; while (it.hasNext()) { assertTrue(0 != it.next()); i++; } assertEquals(4, i); } @Test public void testSubgraphEdgesWhenVerticesRemovedFromBacking() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); Set<DirectedTypedEdge<String>> edges = subgraph.edges(); g.remove(0); assertEquals((4 * 3) / 2, edges.size()); assertFalse(edges.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); } /**************** * * * Tests on graphs with multiple edge types * * ****************/ @Test public void testAddTypedEdges() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); assertEquals(2, g.order()); assertEquals(1, g.size()); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); assertEquals(1, g.edgeTypes().size()); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-2",0, 1))); assertEquals(2, g.order()); assertEquals(2, g.size()); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-2",0, 1))); assertEquals(2, g.edgeTypes().size()); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-3", 3, 4))); assertEquals(4, g.order()); assertEquals(3, g.size()); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-3",3, 4))); assertEquals(3, g.edgeTypes().size()); } @Test public void testNeighborsOfDifferentTypes() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1", 0, 1))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-2", 0, 2))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-3", 0, 3))); Set<Integer> neighbors = g.getNeighbors(0); assertEquals(3, g.size()); assertEquals(3, neighbors.size()); assertTrue(neighbors.contains(1)); assertTrue(neighbors.contains(2)); assertTrue(neighbors.contains(3)); // Test bi-directional case assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1", 1, 0))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-2", 2, 0))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-3", 3, 0))); neighbors = g.getNeighbors(0); assertEquals(3, neighbors.size()); assertEquals(6, g.size()); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1", 4, 0))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-2", 5, 0))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-3", 6, 0))); neighbors = g.getNeighbors(0); assertEquals(6, neighbors.size()); assertEquals(9, g.size()); for (int i = 1; i <= 6; ++i) assertTrue(neighbors.contains(i)); } @Test public void testSubgraphOfSubtype() { // set up the network DirectedMultigraph<String> g = new DirectedMultigraph<String>(); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1", 0, 1))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1", 1, 3))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1", 1, 2))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-2", 0, 1))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-3", 3, 4))); Set<Integer> verts = new HashSet<Integer>(); verts.add(0); verts.add(1); Set<String> types = Collections.singleton("type-1"); DirectedMultigraph<String> sub = g.subgraph(g.vertices(), types); assertEquals(1, sub.edgeTypes().size()); assertEquals(3, sub.size()); assertEquals(g.order(), sub.order()); assertFalse(sub.contains(new SimpleDirectedTypedEdge<String>("type-2", 0, 1))); } /**************** * * * Tests for copy() * * ****************/ @Test public void testCopyAllVertices() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-2",0, 1))); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-2",0, 1))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-3", 3, 4))); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-3",3, 4))); DirectedMultigraph<String> copy = g.copy(g.vertices()); assertEquals(g.order(), copy.order()); assertEquals(g.size(), copy.size()); assertEquals(g, copy); copy.remove(4); assertEquals(4, g.order()); assertEquals(3, copy.order()); } @Test public void testCopy1vertex() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-2",0, 1))); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-2",0, 1))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-3", 3, 4))); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-3",3, 4))); DirectedMultigraph<String> copy = g.copy(Collections.singleton(1)); assertEquals(1, copy.order()); assertEquals(0, copy.size()); } @Test public void testCopy2vertex() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-2",0, 1))); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-2",0, 1))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-3", 3, 4))); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-3",3, 4))); Set<Integer> verts = new HashSet<Integer>(); Collections.addAll(verts, 0, 1); DirectedMultigraph<String> copy = g.copy(verts); assertEquals(2, copy.order()); assertEquals(2, copy.size()); } @Test public void testCopy3vertexTriangle() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1", 0, 1))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-2", 0, 1))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1", 1, 2))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-2", 1, 2))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-3", 1, 2))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1", 0, 2))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-2", 2, 0))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1", 2, 3))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-3", 3, 4))); Set<Integer> verts = new HashSet<Integer>(); Collections.addAll(verts, 0, 1, 2); DirectedMultigraph<String> copy = g.copy(verts); assertEquals(3, copy.order()); assertEquals(7, copy.size()); } @Test public void testCopy3vertexVee() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1", 0, 1))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-2", 0, 1))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1", 1, 2))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-2", 1, 2))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-3", 1, 2))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1", 2, 3))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-3", 3, 4))); Set<Integer> verts = new HashSet<Integer>(); Collections.addAll(verts, 0, 1, 2); DirectedMultigraph<String> copy = g.copy(verts); assertEquals(3, copy.order()); assertEquals(5, copy.size()); } @Test public void testEmptyCopy() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-2",0, 1))); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-2",0, 1))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-3", 3, 4))); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-3",3, 4))); DirectedMultigraph<String> copy = g.copy(Collections.<Integer>emptySet()); assertEquals(0, copy.order()); assertEquals(0, copy.size()); assertEquals(new DirectedMultigraph<String>(), copy); copy.add(5); assertTrue(copy.contains(5)); assertFalse(g.contains(5)); } /* * To test: * * - remove vertex causes edge type to no longer be present (graph + subgraph) * - remove a vertex and then add the vertex back in (not present in subgraph) * - all of the DirectedGraph methods * */ }
{ "pile_set_name": "Github" }
package org.matomo.sdk.dispatcher; import androidx.annotation.Nullable; public enum DispatchMode { /** * Dispatch always (default) */ ALWAYS("always"), /** * Dispatch only on WIFI */ WIFI_ONLY("wifi_only"), /** * The dispatcher will assume being offline. This is not persisted and will revert on app restart. * Ensures no information is lost when tracking exceptions. See #247 */ EXCEPTION("exception"); private final String key; DispatchMode(String key) {this.key = key;} @Override public String toString() { return key; } @Nullable public static DispatchMode fromString(String raw) { for (DispatchMode mode : DispatchMode.values()) { if (mode.key.equals(raw)) return mode; } return null; } }
{ "pile_set_name": "Github" }
{ "name": "volumetric_lighting_scattering.comp", "properties": { "name": "volumetric_lighting_scattering.comp", "gpuProgramName": "volumetric_lighting_scattering.comp.glsl", "entryPoint": "main", "preprocessorDefines": "", "gpuProgramType": 3 } }
{ "pile_set_name": "Github" }
/* Copyright The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Code generated by informer-gen. DO NOT EDIT. package v1 import ( "context" time "time" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" watch "k8s.io/apimachinery/pkg/watch" internalinterfaces "k8s.io/client-go/informers/internalinterfaces" kubernetes "k8s.io/client-go/kubernetes" v1 "k8s.io/client-go/listers/core/v1" cache "k8s.io/client-go/tools/cache" ) // PersistentVolumeInformer provides access to a shared informer and lister for // PersistentVolumes. type PersistentVolumeInformer interface { Informer() cache.SharedIndexInformer Lister() v1.PersistentVolumeLister } type persistentVolumeInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc } // NewPersistentVolumeInformer constructs a new informer for PersistentVolume type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. func NewPersistentVolumeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewFilteredPersistentVolumeInformer(client, resyncPeriod, indexers, nil) } // NewFilteredPersistentVolumeInformer constructs a new informer for PersistentVolume type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. func NewFilteredPersistentVolumeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { return cache.NewSharedIndexInformer( &cache.ListWatch{ ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { tweakListOptions(&options) } return client.CoreV1().PersistentVolumes().List(context.TODO(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } return client.CoreV1().PersistentVolumes().Watch(context.TODO(), options) }, }, &corev1.PersistentVolume{}, resyncPeriod, indexers, ) } func (f *persistentVolumeInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { return NewFilteredPersistentVolumeInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) } func (f *persistentVolumeInformer) Informer() cache.SharedIndexInformer { return f.factory.InformerFor(&corev1.PersistentVolume{}, f.defaultInformer) } func (f *persistentVolumeInformer) Lister() v1.PersistentVolumeLister { return v1.NewPersistentVolumeLister(f.Informer().GetIndexer()) }
{ "pile_set_name": "Github" }
/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package v1beta1 import ( "errors" "k8s.io/apimachinery/pkg/util/json" ) var jsTrue = []byte("true") var jsFalse = []byte("false") func (s JSONSchemaPropsOrBool) MarshalJSON() ([]byte, error) { if s.Schema != nil { return json.Marshal(s.Schema) } if s.Schema == nil && !s.Allows { return jsFalse, nil } return jsTrue, nil } func (s *JSONSchemaPropsOrBool) UnmarshalJSON(data []byte) error { var nw JSONSchemaPropsOrBool switch { case len(data) == 0: case data[0] == '{': var sch JSONSchemaProps if err := json.Unmarshal(data, &sch); err != nil { return err } nw.Allows = true nw.Schema = &sch case len(data) == 4 && string(data) == "true": nw.Allows = true case len(data) == 5 && string(data) == "false": nw.Allows = false default: return errors.New("boolean or JSON schema expected") } *s = nw return nil } func (s JSONSchemaPropsOrStringArray) MarshalJSON() ([]byte, error) { if len(s.Property) > 0 { return json.Marshal(s.Property) } if s.Schema != nil { return json.Marshal(s.Schema) } return []byte("null"), nil } func (s *JSONSchemaPropsOrStringArray) UnmarshalJSON(data []byte) error { var first byte if len(data) > 1 { first = data[0] } var nw JSONSchemaPropsOrStringArray if first == '{' { var sch JSONSchemaProps if err := json.Unmarshal(data, &sch); err != nil { return err } nw.Schema = &sch } if first == '[' { if err := json.Unmarshal(data, &nw.Property); err != nil { return err } } *s = nw return nil } func (s JSONSchemaPropsOrArray) MarshalJSON() ([]byte, error) { if len(s.JSONSchemas) > 0 { return json.Marshal(s.JSONSchemas) } return json.Marshal(s.Schema) } func (s *JSONSchemaPropsOrArray) UnmarshalJSON(data []byte) error { var nw JSONSchemaPropsOrArray var first byte if len(data) > 1 { first = data[0] } if first == '{' { var sch JSONSchemaProps if err := json.Unmarshal(data, &sch); err != nil { return err } nw.Schema = &sch } if first == '[' { if err := json.Unmarshal(data, &nw.JSONSchemas); err != nil { return err } } *s = nw return nil } func (s JSON) MarshalJSON() ([]byte, error) { if len(s.Raw) > 0 { return s.Raw, nil } return []byte("null"), nil } func (s *JSON) UnmarshalJSON(data []byte) error { if len(data) > 0 && string(data) != "null" { s.Raw = data } return nil }
{ "pile_set_name": "Github" }
/** * Returns a Buffer from a "ff 00 ff"-type hex string. */ getBufferFromHexString = function(byteStr) { var bytes = byteStr.split(' '); var buf = new Buffer(bytes.length); for (var i = 0; i < bytes.length; ++i) { buf[i] = parseInt(bytes[i], 16); } return buf; } /** * Returns a hex string from a Buffer. */ getHexStringFromBuffer = function(data) { var s = ''; for (var i = 0; i < data.length; ++i) { s += padl(data[i].toString(16), 2, '0') + ' '; } return s.trim(); } /** * Splits a buffer in two parts. */ splitBuffer = function(buffer) { var b1 = new Buffer(Math.ceil(buffer.length / 2)); buffer.copy(b1, 0, 0, b1.length); var b2 = new Buffer(Math.floor(buffer.length / 2)); buffer.copy(b2, 0, b1.length, b1.length + b2.length); return [b1, b2]; } /** * Performs hybi07+ type masking on a hex string or buffer. */ mask = function(buf, maskString) { if (typeof buf == 'string') buf = new Buffer(buf); var mask = getBufferFromHexString(maskString || '34 83 a8 68'); for (var i = 0; i < buf.length; ++i) { buf[i] ^= mask[i % 4]; } return buf; } /** * Returns a hex string representing the length of a message */ getHybiLengthAsHexString = function(len, masked) { if (len < 126) { var buf = new Buffer(1); buf[0] = (masked ? 0x80 : 0) | len; } else if (len < 65536) { var buf = new Buffer(3); buf[0] = (masked ? 0x80 : 0) | 126; getBufferFromHexString(pack(4, len)).copy(buf, 1); } else { var buf = new Buffer(9); buf[0] = (masked ? 0x80 : 0) | 127; getBufferFromHexString(pack(16, len)).copy(buf, 1); } return getHexStringFromBuffer(buf); } /** * Unpacks a Buffer into a number. */ unpack = function(buffer) { var n = 0; for (var i = 0; i < buffer.length; ++i) { n = (i == 0) ? buffer[i] : (n * 256) + buffer[i]; } return n; } /** * Returns a hex string, representing a specific byte count 'length', from a number. */ pack = function(length, number) { return padl(number.toString(16), length, '0').replace(/([0-9a-f][0-9a-f])/gi, '$1 ').trim(); } /** * Left pads the string 's' to a total length of 'n' with char 'c'. */ padl = function(s, n, c) { return new Array(1 + n - s.length).join(c) + s; }
{ "pile_set_name": "Github" }
// // NSImage+Thumbnail.swift // WWDC // // Created by Guilherme Rambo on 21/05/17. // Copyright Β© 2017 Guilherme Rambo. All rights reserved. // import Cocoa extension NSImage { static func thumbnailImage(with url: URL, maxWidth: CGFloat) -> NSImage? { guard let inputImage = NSImage(contentsOf: url) else { return nil } let aspectRatio = inputImage.size.width / inputImage.size.height let thumbSize = NSSize(width: maxWidth, height: maxWidth * aspectRatio) let outputImage = NSImage(size: thumbSize) outputImage.lockFocus() inputImage.draw(in: NSRect(x: 0, y: 0, width: thumbSize.width, height: thumbSize.height), from: .zero, operation: .sourceOver, fraction: 1) outputImage.unlockFocus() return outputImage } } extension NSImage { func makeFreestandingTemplate(outputSize: NSSize) -> NSImage { let insetPercentage: CGFloat = 0.25 var insetSize = outputSize let widthInset = outputSize.width * insetPercentage let heightInset = outputSize.height * insetPercentage insetSize.width -= 2 * widthInset insetSize.height -= 2 * heightInset let destinationRect = NSRect(origin: CGPoint(x: widthInset, y: heightInset), size: insetSize) // Circle Template let circle = CAShapeLayer() circle.path = CGPath(ellipseIn: CGRect(origin: .zero, size: outputSize), transform: nil) // New image let newImage = NSImage(size: outputSize) newImage.lockFocus() // Render both into new image let ctx = NSGraphicsContext.current!.cgContext circle.render(in: ctx) draw(in: destinationRect, from: .zero, operation: .xor, fraction: 1) newImage.unlockFocus() newImage.isTemplate = true return newImage } }
{ "pile_set_name": "Github" }
/* * Copyright 2003-2018 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jetbrains.mps.idea.java.psi; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiCodeBlock; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiExpression; import com.intellij.psi.PsiField; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFileSystemItem; import com.intellij.psi.PsiJavaFile; import com.intellij.psi.PsiMethod; import com.intellij.psi.PsiModifier; import com.intellij.psi.PsiModifierList; import com.intellij.psi.PsiParameter; import com.intellij.psi.PsiParameterList; import com.intellij.psi.PsiReferenceList; import com.intellij.psi.PsiTreeChangeEvent; import com.intellij.psi.PsiTypeParameter; import com.intellij.psi.PsiTypeParameterList; import com.intellij.psi.PsiWhiteSpace; import jetbrains.mps.ide.platform.watching.ReloadParticipant; import jetbrains.mps.idea.java.psi.JavaPsiListener.FSMove; import jetbrains.mps.idea.java.psi.JavaPsiListener.FSRename; import jetbrains.mps.idea.java.psi.JavaPsiListener.PsiEvent; import org.jetbrains.annotations.NotNull; import org.jetbrains.mps.openapi.util.ProgressMonitor; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * danilla 5/25/13 */ public class PsiChangeProcessor extends ReloadParticipant { // Per project change data // The thing is there's only one instance of reload participant for a given participant class, // whereas PsiChangesWatcher is a project component (as PsiManager) private Map<Project, PsiChangeData> changeData = new HashMap<Project, PsiChangeData>(); public PsiChangeProcessor() { } @Override public boolean wantsToShowProgress() { // we'll not request progress indicator for psi updates return false; } // TODO look with what locks is it called @Override public void update(ProgressMonitor monitor) { monitor.start("PSI update", changeData.size() + 1); try { for (Entry<Project, PsiChangeData> e : changeData.entrySet()) { final Project project = e.getKey(); final PsiChangeData change = e.getValue(); // we do update asynchronously, so we want to check if project is live yet if (project.isDisposed()) { continue; } project.getComponent(PsiChangesWatcher.class).notifyListeners(change); monitor.advance(1); } } finally { // clean-up changeData = new HashMap<>(); } monitor.done(); } @Override public boolean isEmpty() { for (PsiChangeData data : changeData.values()) { if (data.isNotEmpty()) { return false; } } return true; } // The following methods are called by PsiChangesWatcher when it receives a PSI event // We're not PsiTreeChangeAdapter ourselves for a reason: // we're a ReloadParticipant => we can be instantiated by ReloadManager itself and there's only // one instance of us per application, whereas psi listeners exist per project (as well as PsiManager) // todo filter out changes not related to stub structure /*package*/ void childAdded(final PsiTreeChangeEvent event) { if (!filter(event.getChild())) return; PsiChangeData data = projectData(event.getChild()); PsiElement elem = event.getChild(); if (elem instanceof PsiFileSystemItem) { data.created.add((PsiFileSystemItem) elem); } else { data.changed.add(elem.getContainingFile()); } } /*package*/ void childRemoved(PsiTreeChangeEvent event) { if (!(event.getChild() instanceof PsiFileSystemItem) && !filter(event.getParent())) { // can't use getChild() here as it's not valid any longer return; } // so, if fs item or passed filtering then proceed PsiChangeData data = projectData(event.getParent()); PsiElement elem = event.getChild(); if (elem instanceof PsiFileSystemItem) { data.removed.add((PsiFileSystemItem) elem); } else { // todo fix is parent is a file itself data.changed.add(event.getParent().getContainingFile()); } } /*package*/ void childReplaced(PsiTreeChangeEvent event) { // if both are uninteresting, only then ignore if (!filter(event.getOldChild()) && !filter(event.getNewChild())) return; PsiChangeData data = projectData(event.getNewChild()); // todo Q: should we check if it's PsiFile? data.changed.add(event.getNewChild().getContainingFile()); } /*package*/ void childrenChanged(PsiTreeChangeEvent event) { if (!filter(event.getParent())) return; if (event.getParent() instanceof PsiFile) { // it's some generic notification, we don't need it // (don't remember already what that means) return; } PsiChangeData data = projectData(event.getParent()); data.changed.add(event.getParent().getContainingFile()); } /*package*/ void childMoved(@NotNull PsiTreeChangeEvent event) { if (!filter(event.getChild())) return; PsiChangeData data = projectData(event.getChild()); PsiElement elem = event.getChild(); if (elem instanceof PsiFileSystemItem) { // file item; data.moved.add(new FSMove((PsiFileSystemItem) elem, (PsiFileSystemItem) event.getOldParent(), (PsiFileSystemItem) event.getNewParent())); } else { // todo what if old/new parent is PsiFileSystemItem ? data.changed.add(event.getOldParent().getContainingFile()); data.changed.add(event.getNewParent().getContainingFile()); } } /*package*/ void propertyChanged(@NotNull PsiTreeChangeEvent event) { if (!(event.getElement() instanceof PsiFileSystemItem && (PsiTreeChangeEvent.PROP_FILE_NAME.equals(event.getPropertyName()) || PsiTreeChangeEvent.PROP_DIRECTORY_NAME.equals(event.getPropertyName()))) ) { return; } PsiChangeData data = projectData(event.getElement()); FSRename rename = new FSRename((PsiFileSystemItem) event.getElement(), (String) event.getOldValue()); data.renamed.add(rename); } private PsiChangeData projectData(PsiElement subject) { Project project = subject.getProject(); PsiChangeData data = changeData.get(project); if (data == null) { data = new PsiChangeData(); changeData.put(project, data); } return data; } private boolean filter(PsiElement elem) { if (elem == null || elem instanceof PsiWhiteSpace) { return false; } if (elem instanceof PsiJavaFile || elem instanceof PsiDirectory) { return true; } PsiElement e = elem; do { if (interesting(e)) { return true; } if (notInteresting(e)) { return false; } e = e.getParent(); } while (e != null); return false; } private boolean interesting(PsiElement elem) { if (elem instanceof PsiClass || elem instanceof PsiMethod || elem instanceof PsiField || elem instanceof PsiParameterList || elem instanceof PsiParameter || elem instanceof PsiReferenceList // but not PsiReference ! || elem instanceof PsiModifierList || elem instanceof PsiModifier || elem instanceof PsiTypeParameterList || elem instanceof PsiTypeParameter) { return true; } return false; } private boolean notInteresting(PsiElement elem) { return elem instanceof PsiCodeBlock || elem instanceof PsiExpression; } } class PsiChangeData implements PsiEvent { Set<PsiFileSystemItem> created = new HashSet<PsiFileSystemItem>(); Set<PsiFileSystemItem> removed = new HashSet<PsiFileSystemItem>(); Set<FSMove> moved = new HashSet<FSMove>(); Set<FSRename> renamed = new HashSet<FSRename>(); Set<PsiFile> changed = new HashSet<PsiFile>(); @Override public Iterable<PsiFileSystemItem> getCreated() { return created; } @Override public Iterable<PsiFileSystemItem> getRemoved() { return removed; } @Override public Iterable<FSMove> getMoved() { return moved; } @Override public Iterable<FSRename> getRenamed() { return renamed; } @Override public Set<PsiFile> getChanged() { return changed; } boolean isNotEmpty() { return !(changed.isEmpty() && created.isEmpty() && renamed.isEmpty() && moved.isEmpty() && removed.isEmpty()); } }
{ "pile_set_name": "Github" }
// RUN: %clang_cc1 -verify -fopenmp %s // RUN: %clang_cc1 -verify -fopenmp-simd %s void foo() { } bool foobool(int argc) { return argc; } struct S1; // expected-note 2 {{declared here}} expected-note 2 {{forward declaration of 'S1'}} extern S1 a; class S2 { mutable int a; public: S2() : a(0) {} }; const S2 b; const S2 ba[5]; class S3 { int a; public: S3() : a(0) {} }; const S3 ca[5]; class S4 { int a; S4(); // expected-note {{implicitly declared private here}} public: S4(int v) : a(v) { #pragma omp parallel for private(a) private(this->a) for (int k = 0; k < v; ++k) ++this->a; } }; class S5 { int a; S5() : a(0) {} // expected-note {{implicitly declared private here}} public: S5(int v) : a(v) {} S5 &operator=(S5 &s) { #pragma omp parallel for private(a) private(this->a) private(s.a) // expected-error {{expected variable name or data member of current class}} for (int k = 0; k < s.a; ++k) ++s.a; return *this; } }; template <typename T> class S6 { public: T a; S6() : a(0) {} S6(T v) : a(v) { #pragma omp parallel for private(a) private(this->a) for (int k = 0; k < v; ++k) ++this->a; } S6 &operator=(S6 &s) { #pragma omp parallel for private(a) private(this->a) private(s.a) // expected-error {{expected variable name or data member of current class}} for (int k = 0; k < s.a; ++k) ++s.a; return *this; } }; template <typename T> class S7 : public T { T a; S7() : a(0) {} public: S7(T v) : a(v) { #pragma omp parallel for private(a) private(this->a) private(T::a) for (int k = 0; k < a.a; ++k) ++this->a.a; } S7 &operator=(S7 &s) { #pragma omp parallel for private(a) private(this->a) private(s.a) private(s.T::a) // expected-error 2 {{expected variable name or data member of current class}} for (int k = 0; k < s.a.a; ++k) ++s.a.a; return *this; } }; S3 h; #pragma omp threadprivate(h) // expected-note 2 {{defined as threadprivate or thread local}} template <class I, class C> int foomain(I argc, C **argv) { I e(4); I g(5); int i; int &j = i; #pragma omp parallel for private // expected-error {{expected '(' after 'private'}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private() // expected-error {{expected expression}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(argc // expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(argc, // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(argc > 0 ? argv[1] : argv[2]) // expected-error {{expected variable name}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(argc) for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(S1) // expected-error {{'S1' does not refer to a value}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(a, b) // expected-error {{private variable with incomplete type 'S1'}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(argv[1]) // expected-error {{expected variable name}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(e, g) for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(h) // expected-error {{threadprivate or thread local variable cannot be private}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for nowait // expected-error {{unexpected OpenMP clause 'nowait' in directive '#pragma omp parallel for'}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel { int v = 0; int i; #pragma omp parallel for private(i) for (int k = 0; k < argc; ++k) { i = k; v += i; } } #pragma omp parallel shared(i) #pragma omp parallel private(i) #pragma omp parallel for private(j) for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(i) for (int k = 0; k < argc; ++k) ++k; return 0; } namespace A { double x; #pragma omp threadprivate(x) // expected-note {{defined as threadprivate or thread local}} } namespace B { using A::x; } int main(int argc, char **argv) { S4 e(4); S5 g(5); S6<float> s6(0.0) , s6_0(1.0); S7<S6<float> > s7(0.0) , s7_0(1.0); int i; int &j = i; #pragma omp parallel for private // expected-error {{expected '(' after 'private'}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private() // expected-error {{expected expression}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(argc // expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(argc, // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(argc > 0 ? argv[1] : argv[2]) // expected-error {{expected variable name}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(argc) for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(S1) // expected-error {{'S1' does not refer to a value}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(a, b) // expected-error {{private variable with incomplete type 'S1'}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(argv[1]) // expected-error {{expected variable name}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(e, g) // expected-error {{calling a private constructor of class 'S4'}} expected-error {{calling a private constructor of class 'S5'}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(h, B::x) // expected-error 2 {{threadprivate or thread local variable cannot be private}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for nowait // expected-error {{unexpected OpenMP clause 'nowait' in directive '#pragma omp parallel for'}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel { int i; #pragma omp parallel for private(i) for (int k = 0; k < argc; ++k) ++k; } #pragma omp parallel shared(i) #pragma omp parallel private(i) #pragma omp parallel for private(j) for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(i) for (int k = 0; k < argc; ++k) ++k; static int m; #pragma omp parallel for private(m) for (int k = 0; k < argc; ++k) m = k + 2; s6 = s6_0; // expected-note {{in instantiation of member function 'S6<float>::operator=' requested here}} s7 = s7_0; // expected-note {{in instantiation of member function 'S7<S6<float> >::operator=' requested here}} return foomain(argc, argv); // expected-note {{in instantiation of function template specialization 'foomain<int, char>' requested here}} }
{ "pile_set_name": "Github" }
import 'reflect-metadata' import 'react-dates/initialize' import 'map.prototype.tojson' // to visualize Map in Redux Dev Tools import 'set.prototype.tojson' // to visualize Set in Redux Dev Tools import 'src/helpers/errorPrototypeTojson' // to visualize Error in Redux Dev Tools import { enableES5 } from 'immer' import React, { useEffect, useState, Suspense } from 'react' import { AppProps } from 'next/app' import { I18nextProvider } from 'react-i18next' import type { Store } from 'redux' import { ConnectedRouter } from 'connected-next-router' import type { Persistor } from 'redux-persist' import { Layout } from 'src/components/Layout/Layout' import { ThemeProvider } from 'styled-components' import { Provider } from 'react-redux' import { PersistGate } from 'redux-persist/integration/react' import { MDXProvider } from '@mdx-js/react' import { initialize } from 'src/initialize' import { init } from 'src/state/app/init.actions' import i18n from 'src/i18n/i18n' import Loading from 'src/components/Loading/Loading' import { LinkExternal } from 'src/components/Link/LinkExternal' import { SEO } from 'src/components/Common/SEO' import { theme } from 'src/theme' import 'src/styles/global.scss' enableES5() export interface AppState { persistor: Persistor store: Store } export default function MyApp({ Component, pageProps, router }: AppProps) { const [state, setState] = useState<AppState | undefined>() useEffect(() => { initialize({ router }) // eslint-disable-next-line promise/always-return .then((state: AppState) => { setState(state) state.store.dispatch(init()) }) .catch((error: Error) => { throw error }) }, [router]) if (!state) { return <Loading /> } const { store, persistor } = state return ( <Suspense fallback={<Loading />}> <Provider store={store}> <ConnectedRouter> <ThemeProvider theme={theme}> <I18nextProvider i18n={i18n}> <MDXProvider components={{ a: LinkExternal }}> <PersistGate loading={<Loading />} persistor={persistor}> <SEO /> <Layout> <Component {...pageProps} /> </Layout> </PersistGate> </MDXProvider> </I18nextProvider> </ThemeProvider> </ConnectedRouter> </Provider> </Suspense> ) }
{ "pile_set_name": "Github" }
/* * Copyright (C) 2016 Apple Inc. 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. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. */ #include "config.h" #include "TypedArrayCTest.h" #include "JavaScript.h" #include <limits.h> #include <math.h> #include <stdio.h> #include <wtf/Assertions.h> extern "C" void JSSynchronousGarbageCollectForDebugging(JSContextRef); static void id(void*, void*) { } static void freePtr(void* ptr, void*) { free(ptr); } static const unsigned numLengths = 3; static const unsigned lengths[numLengths] = { 0, 1, 10, }; static const unsigned byteSizes[kJSTypedArrayTypeArrayBuffer] = { 1, // kJSTypedArrayTypeInt8Array 2, // kJSTypedArrayTypeInt16Array 4, // kJSTypedArrayTypeInt32Array 1, // kJSTypedArrayTypeUint8Array 1, // kJSTypedArrayTypeUint8ClampedArray 2, // kJSTypedArrayTypeUint16Array 4, // kJSTypedArrayTypeUint32Array 4, // kJSTypedArrayTypeFloat32Array 8, // kJSTypedArrayTypeFloat64Array }; static const char* typeToString[kJSTypedArrayTypeArrayBuffer] = { "kJSTypedArrayTypeInt8Array", "kJSTypedArrayTypeInt16Array", "kJSTypedArrayTypeInt32Array", "kJSTypedArrayTypeUint8Array", "kJSTypedArrayTypeUint8ClampedArray", "kJSTypedArrayTypeUint16Array", "kJSTypedArrayTypeUint32Array", "kJSTypedArrayTypeFloat32Array", "kJSTypedArrayTypeFloat64Array", }; inline int unexpectedException(const char* name) { fprintf(stderr, "%s FAILED: unexpected exception\n", name); return 1; } static int assertEqualsAsNumber(JSGlobalContextRef context, JSValueRef value, double expectedValue) { double number = JSValueToNumber(context, value, nullptr); if (number != expectedValue && !(isnan(number) && isnan(expectedValue))) { fprintf(stderr, "assertEqualsAsNumber FAILED: %p, %lf\n", value, expectedValue); return 1; } return 0; } static int testAccess(JSGlobalContextRef context, JSObjectRef typedArray, JSTypedArrayType type, unsigned elementLength, void* expectedPtr = nullptr, JSObjectRef expectedBuffer = nullptr, unsigned expectedOffset = 0) { JSValueRef exception = nullptr; // Test typedArray basic functions. JSTypedArrayType actualType = JSValueGetTypedArrayType(context, typedArray, &exception); if (type != actualType || exception) { fprintf(stderr, "TypedArray type FAILED: %p, got: %s, expected: %s\n", typedArray, typeToString[actualType], typeToString[type]); return 1; } unsigned length = JSObjectGetTypedArrayLength(context, typedArray, &exception); if (elementLength != length || exception) { fprintf(stderr, "TypedArray length FAILED: %p (%s), got: %d, expected: %d\n", typedArray, typeToString[type], length, elementLength); return 1; } unsigned byteLength = JSObjectGetTypedArrayByteLength(context, typedArray, &exception); unsigned expectedLength = byteSizes[type] * elementLength; if (byteLength != expectedLength || exception) { fprintf(stderr, "TypedArray byteLength FAILED: %p (%s), got: %d, expected: %d\n", typedArray, typeToString[type], byteLength, expectedLength); return 1; } unsigned offset = JSObjectGetTypedArrayByteOffset(context, typedArray, &exception); if (expectedOffset != offset || exception) { fprintf(stderr, "TypedArray byteOffset FAILED: %p (%s), got: %d, expected: %d\n", typedArray, typeToString[type], offset, expectedOffset); return 1; } void* ptr = JSObjectGetTypedArrayBytesPtr(context, typedArray, &exception); if (exception) return unexpectedException("TypedArray get bytes ptr"); JSObjectRef buffer = JSObjectGetTypedArrayBuffer(context, typedArray, &exception); if (exception) return unexpectedException("TypedArray get buffer"); void* bufferPtr = JSObjectGetArrayBufferBytesPtr(context, buffer, &exception); if (exception) return unexpectedException("ArrayBuffer get bytes ptr"); if (bufferPtr != ptr) { fprintf(stderr, "FAIL: TypedArray bytes ptr and ArrayBuffer byte ptr were not the same: %p (%s) TypedArray: %p, ArrayBuffer: %p\n", typedArray, typeToString[type], ptr, bufferPtr); return 1; } if (expectedPtr && ptr != expectedPtr) { fprintf(stderr, "FAIL: TypedArray bytes ptr and the ptr used to construct the array were not the same: %p (%s) TypedArray: %p, bytes ptr: %p\n", typedArray, typeToString[type], ptr, expectedPtr); return 1; } if (expectedBuffer && expectedBuffer != buffer) { fprintf(stderr, "FAIL: TypedArray buffer and the ArrayBuffer buffer used to construct the array were not the same: %p (%s) TypedArray buffer: %p, data: %p\n", typedArray, typeToString[type], buffer, expectedBuffer); return 1; } return 0; } static int testConstructors(JSGlobalContextRef context, JSTypedArrayType type, unsigned length) { int failed = 0; JSValueRef exception = nullptr; JSObjectRef typedArray; // Test create with length. typedArray = JSObjectMakeTypedArray(context, type, length, &exception); failed = failed || exception || testAccess(context, typedArray, type, length); void* ptr = calloc(length, byteSizes[type]); // This is to be freed by data JSObjectRef data = JSObjectMakeArrayBufferWithBytesNoCopy(context, ptr, length * byteSizes[type], freePtr, nullptr, &exception); failed = failed || exception; // Test create with existing ptr. typedArray = JSObjectMakeTypedArrayWithBytesNoCopy(context, type, ptr, length * byteSizes[type], id, nullptr, &exception); failed = failed || exception || testAccess(context, typedArray, type, length, ptr); // Test create with existing ArrayBuffer. typedArray = JSObjectMakeTypedArrayWithArrayBuffer(context, type, data, &exception); failed = failed || exception || testAccess(context, typedArray, type, length, ptr, data); // Test create with existing ArrayBuffer and offset. typedArray = JSObjectMakeTypedArrayWithArrayBufferAndOffset(context, type, data, 0, length, &exception); failed = failed || exception || testAccess(context, typedArray, type, length, ptr, data); typedArray = JSObjectMakeTypedArrayWithArrayBufferAndOffset(context, type, data, byteSizes[type], length-1, &exception); if (!length) failed = failed || !exception; else failed = failed || testAccess(context, typedArray, type, length-1, ptr, data, byteSizes[type]) || exception; exception = nullptr; typedArray = JSObjectMakeTypedArrayWithArrayBufferAndOffset(context, type, data, byteSizes[type], 3, &exception); if (length < 2) failed = failed || !exception; else failed = failed || testAccess(context, typedArray, type, 3, ptr, data, byteSizes[type]) || exception; if (byteSizes[type] > 1) { exception = nullptr; typedArray = JSObjectMakeTypedArrayWithArrayBufferAndOffset(context, type, data, 1, length-1, &exception); failed = failed || !exception; } typedArray = JSObjectMakeTypedArrayWithArrayBufferAndOffset(context, type, data, byteSizes[type], length, &exception); failed = failed || !exception; exception = nullptr; typedArray = JSObjectMakeTypedArrayWithArrayBufferAndOffset(context, type, data, byteSizes[type], 0, &exception); if (!length) failed = failed || !exception; else failed = failed || testAccess(context, typedArray, type, 0, ptr, data, byteSizes[type]) || exception; return failed; } template <typename Functor> static int forEachTypedArrayType(const Functor& functor) { int failed = 0; for (unsigned i = 0; i < kJSTypedArrayTypeArrayBuffer; i++) failed = failed || functor(static_cast<JSTypedArrayType>(i)); return failed; } int testTypedArrayCAPI() { int failed = 0; JSGlobalContextRef context = JSGlobalContextCreate(nullptr); failed = failed || forEachTypedArrayType([&](JSTypedArrayType type) { int failed = 0; for (unsigned i = 0; i < numLengths; i++) failed = failed || testConstructors(context, type, lengths[i]); return failed; }); // Test making a typedArray from scratch length. volatile JSObjectRef typedArray = JSObjectMakeTypedArray(context, kJSTypedArrayTypeUint32Array, 10, nullptr); JSObjectRef data = JSObjectGetTypedArrayBuffer(context, typedArray, nullptr); unsigned* buffer = static_cast<unsigned*>(JSObjectGetArrayBufferBytesPtr(context, data, nullptr)); ASSERT(JSObjectGetTypedArrayLength(context, typedArray, nullptr) == 10); // Test buffer is connected to typedArray. buffer[1] = 1; JSValueRef v = JSObjectGetPropertyAtIndex(context, typedArray, 1, nullptr); failed = failed || assertEqualsAsNumber(context, v, 1); // Test passing a buffer from a new array to an old array typedArray = JSObjectMakeTypedArrayWithBytesNoCopy(context, kJSTypedArrayTypeUint32Array, buffer, 40, id, nullptr, nullptr); buffer = static_cast<unsigned*>(JSObjectGetTypedArrayBytesPtr(context, typedArray, nullptr)); ASSERT(buffer[1] == 1); buffer[1] = 20; ASSERT(((unsigned*)JSObjectGetArrayBufferBytesPtr(context, data, nullptr))[1] == 20); // Test constructing with data and the data returned are the same even with an offset. typedArray = JSObjectMakeTypedArrayWithArrayBufferAndOffset(context, kJSTypedArrayTypeUint32Array, data, 4, 9, nullptr); failed = failed || assertEqualsAsNumber(context, JSObjectGetPropertyAtIndex(context, typedArray, 0, nullptr), 20); ASSERT(data == JSObjectGetTypedArrayBuffer(context, typedArray, nullptr)); // Test attempting to allocate an array too big for memory. forEachTypedArrayType([&](JSTypedArrayType type) { JSValueRef exception = nullptr; JSObjectMakeTypedArray(context, type, UINT_MAX, &exception); return !exception; }); JSGlobalContextRelease(context); if (!failed) printf("PASS: Typed Array C API Tests.\n"); else printf("FAIL: Some Typed Array C API Tests failed.\n"); return failed; }
{ "pile_set_name": "Github" }
'use strict' var consoleControl = require('console-control-strings') var ThemeSet = require('./theme-set.js') var themes = module.exports = new ThemeSet() themes.addTheme('ASCII', { preProgressbar: '[', postProgressbar: ']', progressbarTheme: { complete: '#', remaining: '.' }, activityIndicatorTheme: '-\\|/', preSubsection: '>' }) themes.addTheme('colorASCII', themes.getTheme('ASCII'), { progressbarTheme: { preComplete: consoleControl.color('inverse'), complete: ' ', postComplete: consoleControl.color('stopInverse'), preRemaining: consoleControl.color('brightBlack'), remaining: '.', postRemaining: consoleControl.color('reset') } }) themes.addTheme('brailleSpinner', { preProgressbar: 'βΈ¨', postProgressbar: 'βΈ©', progressbarTheme: { complete: 'β–‘', remaining: 'β ‚' }, activityIndicatorTheme: '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏', preSubsection: '>' }) themes.addTheme('colorBrailleSpinner', themes.getTheme('brailleSpinner'), { progressbarTheme: { preComplete: consoleControl.color('inverse'), complete: ' ', postComplete: consoleControl.color('stopInverse'), preRemaining: consoleControl.color('brightBlack'), remaining: 'β–‘', postRemaining: consoleControl.color('reset') } }) themes.setDefault({}, 'ASCII') themes.setDefault({hasColor: true}, 'colorASCII') themes.setDefault({platform: 'darwin', hasUnicode: true}, 'brailleSpinner') themes.setDefault({platform: 'darwin', hasUnicode: true, hasColor: true}, 'colorBrailleSpinner')
{ "pile_set_name": "Github" }
{ "pagination": { "GetBotAliases": { "input_token": "nextToken", "output_token": "nextToken", "limit_key": "maxResults" }, "GetBotChannelAssociations": { "input_token": "nextToken", "output_token": "nextToken", "limit_key": "maxResults" }, "GetBotVersions": { "input_token": "nextToken", "output_token": "nextToken", "limit_key": "maxResults" }, "GetBots": { "input_token": "nextToken", "output_token": "nextToken", "limit_key": "maxResults" }, "GetBuiltinIntents": { "input_token": "nextToken", "output_token": "nextToken", "limit_key": "maxResults" }, "GetBuiltinSlotTypes": { "input_token": "nextToken", "output_token": "nextToken", "limit_key": "maxResults" }, "GetIntentVersions": { "input_token": "nextToken", "output_token": "nextToken", "limit_key": "maxResults" }, "GetIntents": { "input_token": "nextToken", "output_token": "nextToken", "limit_key": "maxResults" }, "GetSlotTypeVersions": { "input_token": "nextToken", "output_token": "nextToken", "limit_key": "maxResults" }, "GetSlotTypes": { "input_token": "nextToken", "output_token": "nextToken", "limit_key": "maxResults" } } }
{ "pile_set_name": "Github" }
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "prije podne", "popodne" ], "DAY": [ "nedjelja", "ponedjeljak", "utorak", "srijeda", "\u010detvrtak", "petak", "subota" ], "ERANAMES": [ "Prije nove ere", "Nove ere" ], "ERAS": [ "p. n. e.", "n. e." ], "FIRSTDAYOFWEEK": 0, "MONTH": [ "januar", "februar", "mart", "april", "maj", "juni", "juli", "august", "septembar", "oktobar", "novembar", "decembar" ], "SHORTDAY": [ "ned", "pon", "uto", "sri", "\u010det", "pet", "sub" ], "SHORTMONTH": [ "jan", "feb", "mar", "apr", "maj", "jun", "jul", "aug", "sep", "okt", "nov", "dec" ], "STANDALONEMONTH": [ "januar", "februar", "mart", "april", "maj", "juni", "juli", "august", "septembar", "oktobar", "novembar", "decembar" ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE, dd. MMMM y.", "longDate": "dd. MMMM y.", "medium": "dd. MMM. y. HH:mm:ss", "mediumDate": "dd. MMM. y.", "mediumTime": "HH:mm:ss", "short": "dd.MM.yy. HH:mm", "shortDate": "dd.MM.yy.", "shortTime": "HH:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "KM", "DECIMAL_SEP": ",", "GROUP_SEP": ".", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-", "negSuf": "\u00a0\u00a4", "posPre": "", "posSuf": "\u00a0\u00a4" } ] }, "id": "bs", "localeID": "bs", "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (vf.v == 0 && i % 10 == 1 && i % 100 != 11 || vf.f % 10 == 1 && vf.f % 100 != 11) { return PLURAL_CATEGORY.ONE; } if (vf.v == 0 && i % 10 >= 2 && i % 10 <= 4 && (i % 100 < 12 || i % 100 > 14) || vf.f % 10 >= 2 && vf.f % 10 <= 4 && (vf.f % 100 < 12 || vf.f % 100 > 14)) { return PLURAL_CATEGORY.FEW; } return PLURAL_CATEGORY.OTHER;} }); }]);
{ "pile_set_name": "Github" }
// Copyright (C) 2002-2014 Nikolaus Gebhardt // This file is part of the "irrKlang" library. // For conditions of distribution and use, see copyright notice in irrKlang.h #ifndef __I_IRRKLANG_AUDIO_STREAM_H_INCLUDED__ #define __I_IRRKLANG_AUDIO_STREAM_H_INCLUDED__ #include "ik_IRefCounted.h" #include "ik_SAudioStreamFormat.h" namespace irrklang { //! Reads and decodes audio data into an usable audio stream for the ISoundEngine class IAudioStream : public IRefCounted { public: //! destructor virtual ~IAudioStream() {}; //! returns format of the audio stream virtual SAudioStreamFormat getFormat() = 0; //! sets the position of the audio stream. /** For example to let the stream be read from the beginning of the file again, setPosition(0) would be called. This is usually done be the sound engine to loop a stream after if has reached the end. Return true if sucessful and 0 if not. \param pos: Position in frames.*/ virtual bool setPosition(ik_s32 pos) = 0; //! returns true if the audio stream is seekable /* Some file formats like (MODs) don't support seeking */ virtual bool getIsSeekingSupported() { return true; } //! tells the audio stream to read frameCountToRead audio frames into the specified buffer /** \param target: Target data buffer to the method will write the read frames into. The specified buffer will be at least getFormat().getFrameSize()*frameCountToRead bytes big. \param frameCountToRead: amount of frames to be read. \returns Returns amount of frames really read. Should be frameCountToRead in most cases. */ virtual ik_s32 readFrames(void* target, ik_s32 frameCountToRead) = 0; }; } // end namespace irrklang #endif
{ "pile_set_name": "Github" }
var baseClamp = require('./_baseClamp'), baseToString = require('./_baseToString'), toInteger = require('./toInteger'), toString = require('./toString'); /** * Checks if `string` starts with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=0] The position to search from. * @returns {boolean} Returns `true` if `string` starts with `target`, * else `false`. * @example * * _.startsWith('abc', 'a'); * // => true * * _.startsWith('abc', 'b'); * // => false * * _.startsWith('abc', 'b', 1); * // => true */ function startsWith(string, target, position) { string = toString(string); position = position == null ? 0 : baseClamp(toInteger(position), 0, string.length); target = baseToString(target); return string.slice(position, position + target.length) == target; } module.exports = startsWith;
{ "pile_set_name": "Github" }
export { default } from './checkout-confirmation'
{ "pile_set_name": "Github" }
<?php /** * Efficiently run operations on batches of results for any function * that supports an options array. * * This is usually used with elgg_get_entities() and friends, * elgg_get_annotations(), and elgg_get_metadata(). * * If you pass a valid PHP callback, all results will be run through that * callback. You can still foreach() through the result set after. Valid * PHP callbacks can be a string, an array, or a closure. * {@link http://php.net/manual/en/language.pseudo-types.php} * * The callback function must accept 3 arguments: an entity, the getter * used, and the options used. * * Results from the callback are stored in callbackResult. If the callback * returns only booleans, callbackResults will be the combined result of * all calls. If no entities are processed, callbackResults will be null. * * If the callback returns anything else, callbackresult will be an indexed * array of whatever the callback returns. If returning error handling * information, you should include enough information to determine which * result you're referring to. * * Don't combine returning bools and returning something else. * * Note that returning false will not stop the foreach. * * @warning If your callback or foreach loop deletes or disable entities * you MUST call setIncrementOffset(false) or set that when instantiating. * This forces the offset to stay what it was in the $options array. * * @example * <code> * // using foreach * $batch = new ElggBatch('elgg_get_entities', array()); * $batch->setIncrementOffset(false); * * foreach ($batch as $entity) { * $entity->disable(); * } * * // using both a callback * $callback = function($result, $getter, $options) { * var_dump("Looking at annotation id: $result->id"); * return true; * } * * $batch = new ElggBatch('elgg_get_annotations', array('guid' => 2), $callback); * </code> * * @package Elgg.Core * @subpackage DataModel * @link http://docs.elgg.org/DataModel/ElggBatch * @since 1.8 */ class ElggBatch implements Iterator { /** * The objects to interator over. * * @var array */ private $results = array(); /** * The function used to get results. * * @var mixed A string, array, or closure, or lamda function */ private $getter = null; /** * The number of results to grab at a time. * * @var int */ private $chunkSize = 25; /** * A callback function to pass results through. * * @var mixed A string, array, or closure, or lamda function */ private $callback = null; /** * Start after this many results. * * @var int */ private $offset = 0; /** * Stop after this many results. * * @var int */ private $limit = 0; /** * Number of processed results. * * @var int */ private $retrievedResults = 0; /** * The index of the current result within the current chunk * * @var int */ private $resultIndex = 0; /** * The index of the current chunk * * @var int */ private $chunkIndex = 0; /** * The number of results iterated through * * @var int */ private $processedResults = 0; /** * Is the getter a valid callback * * @var bool */ private $validGetter = null; /** * The result of running all entities through the callback function. * * @var mixed */ public $callbackResult = null; /** * If false, offset will not be incremented. This is used for callbacks/loops that delete. * * @var bool */ private $incrementOffset = true; /** * Batches operations on any elgg_get_*() or compatible function that supports * an options array. * * Instead of returning all objects in memory, it goes through $chunk_size * objects, then requests more from the server. This avoids OOM errors. * * @param string $getter The function used to get objects. Usually * an elgg_get_*() function, but can be any valid PHP callback. * @param array $options The options array to pass to the getter function. If limit is * not set, 10 is used as the default. In most cases that is not * what you want. * @param mixed $callback An optional callback function that all results will be passed * to upon load. The callback needs to accept $result, $getter, * $options. * @param int $chunk_size The number of entities to pull in before requesting more. * You have to balance this between running out of memory in PHP * and hitting the db server too often. * @param bool $inc_offset Increment the offset on each fetch. This must be false for * callbacks that delete rows. You can set this after the * object is created with {@see ElggBatch::setIncrementOffset()}. */ public function __construct($getter, $options, $callback = null, $chunk_size = 25, $inc_offset = true) { $this->getter = $getter; $this->options = $options; $this->callback = $callback; $this->chunkSize = $chunk_size; $this->setIncrementOffset($inc_offset); if ($this->chunkSize <= 0) { $this->chunkSize = 25; } // store these so we can compare later $this->offset = elgg_extract('offset', $options, 0); $this->limit = elgg_extract('limit', $options, 10); // if passed a callback, create a new ElggBatch with the same options // and pass each to the callback. if ($callback && is_callable($callback)) { $batch = new ElggBatch($getter, $options, null, $chunk_size, $inc_offset); $all_results = null; foreach ($batch as $result) { if (is_string($callback)) { $result = $callback($result, $getter, $options); } else { $result = call_user_func_array($callback, array($result, $getter, $options)); } if (!isset($all_results)) { if ($result === true || $result === false || $result === null) { $all_results = $result; } else { $all_results = array(); } } if (($result === true || $result === false || $result === null) && !is_array($all_results)) { $all_results = $result && $all_results; } else { $all_results[] = $result; } } $this->callbackResult = $all_results; } } /** * Fetches the next chunk of results * * @return bool */ private function getNextResultsChunk() { // reset memory caches after first chunk load if ($this->chunkIndex > 0) { global $DB_QUERY_CACHE, $ENTITY_CACHE; $DB_QUERY_CACHE = $ENTITY_CACHE = array(); } // always reset results. $this->results = array(); if (!isset($this->validGetter)) { $this->validGetter = is_callable($this->getter); } if (!$this->validGetter) { return false; } $limit = $this->chunkSize; // if someone passed limit = 0 they want everything. if ($this->limit != 0) { if ($this->retrievedResults >= $this->limit) { return false; } // if original limit < chunk size, set limit to original limit // else if the number of results we'll fetch if greater than the original limit if ($this->limit < $this->chunkSize) { $limit = $this->limit; } elseif ($this->retrievedResults + $this->chunkSize > $this->limit) { // set the limit to the number of results remaining in the original limit $limit = $this->limit - $this->retrievedResults; } } if ($this->incrementOffset) { $offset = $this->offset + $this->retrievedResults; } else { $offset = $this->offset; } $current_options = array( 'limit' => $limit, 'offset' => $offset ); $options = array_merge($this->options, $current_options); $getter = $this->getter; if (is_string($getter)) { $this->results = $getter($options); } else { $this->results = call_user_func_array($getter, array($options)); } if ($this->results) { $this->chunkIndex++; $this->resultIndex = 0; $this->retrievedResults += count($this->results); return true; } else { return false; } } /** * Increment the offset from the original options array? Setting to * false is required for callbacks that delete rows. * * @param bool $increment Set to false when deleting data * @return void */ public function setIncrementOffset($increment = true) { $this->incrementOffset = (bool) $increment; } /** * Implements Iterator */ /** * PHP Iterator Interface * * @see Iterator::rewind() * @return void */ public function rewind() { $this->resultIndex = 0; $this->retrievedResults = 0; $this->processedResults = 0; // only grab results if we haven't yet or we're crossing chunks if ($this->chunkIndex == 0 || $this->limit > $this->chunkSize) { $this->chunkIndex = 0; $this->getNextResultsChunk(); } } /** * PHP Iterator Interface * * @see Iterator::current() * @return mixed */ public function current() { return current($this->results); } /** * PHP Iterator Interface * * @see Iterator::key() * @return int */ public function key() { return $this->processedResults; } /** * PHP Iterator Interface * * @see Iterator::next() * @return mixed */ public function next() { // if we'll be at the end. if (($this->processedResults + 1) >= $this->limit && $this->limit > 0) { $this->results = array(); return false; } // if we'll need new results. if (($this->resultIndex + 1) >= $this->chunkSize) { if (!$this->getNextResultsChunk()) { $this->results = array(); return false; } $result = current($this->results); } else { // the function above resets the indexes, so only inc if not // getting new set $this->resultIndex++; $result = next($this->results); } $this->processedResults++; return $result; } /** * PHP Iterator Interface * * @see Iterator::valid() * @return bool */ public function valid() { if (!is_array($this->results)) { return false; } $key = key($this->results); return ($key !== NULL && $key !== FALSE); } }
{ "pile_set_name": "Github" }
// Copyright (c) 2012-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2018 The Luxcore developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_RPCSERVER_H #define BITCOIN_RPCSERVER_H #include "amount.h" #include "rpcprotocol.h" #include "uint256.h" #include <list> #include <map> #include <stdint.h> #include <string> #include <httpserver.h> #include <boost/function.hpp> #include "univalue/univalue.h" class CRPCCommand; namespace RPCServer { void OnStarted(boost::function<void ()> slot); void OnStopped(boost::function<void ()> slot); void OnPreCommand(boost::function<void (const CRPCCommand&)> slot); void OnPostCommand(boost::function<void (const CRPCCommand&)> slot); } class CBlockIndex; class CNetAddr; /** Wrapper for UniValue::VType, which includes typeAny: * Used to denote don't care type. Only used by RPCTypeCheckObj */ struct UniValueType { UniValueType(UniValue::VType _type) : typeAny(false), type(_type) {} UniValueType() : typeAny(true) {} bool typeAny; UniValue::VType type; }; class JSONRequest { public: UniValue id; std::string strMethod; UniValue params; bool isLongPolling; /** * If using batch JSON request, this object won't get the underlying HTTPRequest. */ JSONRequest() { id = NullUniValue; params = NullUniValue; req = NULL; isLongPolling = false; }; JSONRequest(HTTPRequest *req); /** * Start long-polling */ void PollStart(); /** * Ping long-poll connection with an empty character to make sure it's still alive. */ void PollPing(); /** * Returns whether the underlying long-poll connection is still alive. */ bool PollAlive(); /** * End a long poll request. */ void PollCancel(); /** * Return the JSON result of a long poll request */ void PollReply(const UniValue& result); void parse(const UniValue& valRequest); // FIXME: make this private? HTTPRequest *req; }; class JSONRPCRequest { public: UniValue id; std::string strMethod; UniValue params; bool fHelp; std::string URI; std::string authUser; bool isLongPolling; /** * If using batch JSON request, this object won't get the underlying HTTPRequest. */ JSONRPCRequest() { id = NullUniValue; params = NullUniValue; fHelp = false; req = NULL; isLongPolling = false; }; JSONRPCRequest(HTTPRequest *_req); /** * Start long-polling */ void PollStart(); /** * Ping long-poll connection with an empty character to make sure it's still alive. */ void PollPing(); /** * Returns whether the underlying long-poll connection is still alive. */ bool PollAlive(); /** * End a long poll request. */ void PollCancel(); /** * Return the JSON result of a long poll request */ void PollReply(const UniValue& result); void parse(const UniValue& valRequest); // FIXME: make this private? HTTPRequest *req; }; /** Query whether RPC is running */ bool IsRPCRunning(); /** * Set * the RPC warmup status. When this is done, all RPC calls will error out * immediately with RPC_IN_WARMUP. */ void SetRPCWarmupStatus(const std::string& newStatus); /* Mark warmup as done. RPC calls will be processed from now on. */ void SetRPCWarmupFinished(); /* returns the current warmup state. */ bool RPCIsInWarmup(std::string* statusOut); /** * Type-check arguments; throws JSONRPCError if wrong type given. Does not check that * the right number of arguments are passed, just that any passed are the correct type. * Use like: RPCTypeCheck(params, boost::assign::list_of(str_type)(int_type)(obj_type)); */ void RPCTypeCheck(const UniValue& params, const std::list<UniValue::VType>& typesExpected, bool fAllowNull = false); /** * Check for expected keys/value types in an Object. * Use like: RPCTypeCheck(object, boost::assign::map_list_of("name", str_type)("value", int_type)); */ void RPCTypeCheckObj(const UniValue& o, const std::map<std::string, UniValueType>& typesExpected, bool fAllowNull = false); /** Opaque base class for timers returned by NewTimerFunc. * This provides no methods at the moment, but makes sure that delete * cleans up the whole state. */ class RPCTimerBase { public: virtual ~RPCTimerBase() {} }; /** * RPC timer "driver". */ class RPCTimerInterface { public: virtual ~RPCTimerInterface() {} /** Implementation name */ virtual const char *Name() = 0; /** Factory function for timers. * RPC will call the function to create a timer that will call func in *millis* milliseconds. * @note As the RPC mechanism is backend-neutral, it can use different implementations of timers. * This is needed to cope with the case in which there is no HTTP server, but * only GUI RPC console, and to break the dependency of pcserver on httprpc. */ virtual RPCTimerBase* NewTimer(boost::function<void(void)>& func, int64_t millis) = 0; }; /** Set the factory function for timers */ void RPCSetTimerInterface(RPCTimerInterface *iface); /** Set the factory function for timer, but only, if unset */ void RPCSetTimerInterfaceIfUnset(RPCTimerInterface *iface); /** Unset factory function for timers */ void RPCUnsetTimerInterface(RPCTimerInterface *iface); /** * Run func nSeconds from now. * Overrides previous timer <name> (if any). */ void RPCRunLater(const std::string& name, boost::function<void(void)> func, int64_t nSeconds); typedef UniValue(*rpcfn_type)(const UniValue& params, bool fHelp); class CRPCCommand { public: std::string category; std::string name; rpcfn_type actor; bool okSafeMode; bool threadSafe; bool reqWallet; }; /** * LUX RPC command dispatcher. */ class CRPCTable { private: std::map<std::string, const CRPCCommand*> mapCommands; public: CRPCTable(); const CRPCCommand* operator[](const std::string& name) const; std::string help(std::string name) const; /** * Execute a method. * @param method Method to execute * @param params Array of arguments (JSON objects) * @returns Result of the call. * @throws an exception (UniValue) when an error happens. */ UniValue execute(const std::string& method, const UniValue& params) const; /** * Returns a list of registered commands * @returns List of registered commands. */ std::vector<std::string> listCommands() const; }; extern const CRPCTable tableRPC; /** * Utilities: convert hex-encoded Values * (throws error if not hex). */ extern uint256 ParseHashV(const UniValue& v, std::string strName); extern uint256 ParseHashO(const UniValue& o, std::string strKey); extern std::vector<unsigned char> ParseHexV(const UniValue& v, std::string strName); extern std::vector<unsigned char> ParseHexO(const UniValue& o, std::string strKey); extern int64_t nWalletUnlockTime; extern CAmount AmountFromValue(const UniValue& value); extern double GetDifficulty(const CBlockIndex* blockindex = NULL); extern CBlockIndex* GetLastBlockOfType(const int nPoS); double GetPoWMHashPS(); double GetPoSKernelPS(); extern std::string HelpRequiringPassphrase(); extern std::string HelpExampleCli(std::string methodname, std::string args); extern std::string HelpExampleRpc(std::string methodname, std::string args); extern void EnsureWalletIsUnlocked(); extern UniValue getconnectioncount(const UniValue& params, bool fHelp); // in rpcnet.cpp extern UniValue getpeerinfo(const UniValue& params, bool fHelp); extern UniValue ping(const UniValue& params, bool fHelp); extern UniValue addnode(const UniValue& params, bool fHelp); //extern UniValue disconnectnode(const UniValue& params, bool fHelp); extern UniValue getaddednodeinfo(const UniValue& params, bool fHelp); extern UniValue getnettotals(const UniValue& params, bool fHelp); extern UniValue setban(const UniValue& params, bool fHelp); extern UniValue listbanned(const UniValue& params, bool fHelp); extern UniValue clearbanned(const UniValue& params, bool fHelp); extern UniValue dumpprivkey(const UniValue& params, bool fHelp); // in rpcdump.cpp extern UniValue importprivkey(const UniValue& params, bool fHelp); extern UniValue importaddress(const UniValue& params, bool fHelp); extern UniValue importpubkey(const UniValue& params, bool fHelp); extern UniValue dumphdinfo(const UniValue& params, bool fHelp); extern UniValue dumpwallet(const UniValue& params, bool fHelp); extern UniValue importwallet(const UniValue& params, bool fHelp); extern UniValue bip38encrypt(const UniValue& params, bool fHelp); extern UniValue bip38decrypt(const UniValue& params, bool fHelp); extern UniValue importprunedfunds(const UniValue& params, bool fHelp); extern UniValue removeprunedfunds(const UniValue& params, bool fHelp); extern UniValue dumpprivkey(const UniValue& params, bool fHelp); // in rpcdump.cpp extern UniValue importprivkey(const UniValue& params, bool fHelp); extern UniValue importaddress(const UniValue& params, bool fHelp); extern UniValue dumpwallet(const UniValue& params, bool fHelp); extern UniValue importwallet(const UniValue& params, bool fHelp); extern UniValue bip38encrypt(const UniValue& params, bool fHelp); extern UniValue bip38decrypt(const UniValue& params, bool fHelp); extern UniValue setstakesplitthreshold(const UniValue& params, bool fHelp); extern UniValue getstakesplitthreshold(const UniValue& params, bool fHelp); extern UniValue getgenerate(const UniValue& params, bool fHelp); // in rpcmining.cpp extern UniValue setgenerate(const UniValue& params, bool fHelp); extern UniValue getnetworkhashps(const UniValue& params, bool fHelp); extern UniValue gethashespersec(const UniValue& params, bool fHelp); extern UniValue getmininginfo(const UniValue& params, bool fHelp); extern UniValue prioritisetransaction(const UniValue& params, bool fHelp); extern UniValue getblocktemplate(const UniValue& params, bool fHelp); extern UniValue getwork(const UniValue& params, bool fHelp); extern UniValue submitblock(const UniValue& params, bool fHelp); extern UniValue estimatefee(const UniValue& params, bool fHelp); extern UniValue estimatepriority(const UniValue& params, bool fHelp); extern UniValue estimatesmartfee(const UniValue& params, bool fHelp); extern UniValue estimatesmartpriority(const UniValue& params, bool fHelp); extern UniValue getnewaddress(const UniValue& params, bool fHelp); // in rpcwallet.cpp extern UniValue getaccountaddress(const UniValue& params, bool fHelp); extern UniValue getrawchangeaddress(const UniValue& params, bool fHelp); extern UniValue setaccount(const UniValue& params, bool fHelp); extern UniValue getaccount(const UniValue& params, bool fHelp); extern UniValue getaddressesbyaccount(const UniValue& params, bool fHelp); extern UniValue sendtoaddress(const UniValue& params, bool fHelp); extern UniValue sendtoaddressix(const UniValue& params, bool fHelp); extern UniValue signmessage(const UniValue& params, bool fHelp); extern UniValue verifymessage(const UniValue& params, bool fHelp); extern UniValue getreceivedbyaddress(const UniValue& params, bool fHelp); extern UniValue getreceivedbyaccount(const UniValue& params, bool fHelp); extern UniValue getbalance(const UniValue& params, bool fHelp); extern UniValue getunconfirmedbalance(const UniValue& params, bool fHelp); extern UniValue movecmd(const UniValue& params, bool fHelp); extern UniValue sendfrom(const UniValue& params, bool fHelp); extern UniValue sendmany(const UniValue& params, bool fHelp); extern UniValue addmultisigaddress(const UniValue& params, bool fHelp); extern UniValue createmultisig(const UniValue& params, bool fHelp); extern UniValue createwitnessaddress(const UniValue& params, bool fHelp); extern UniValue listreceivedbyaddress(const UniValue& params, bool fHelp); extern UniValue listreceivedbyaccount(const UniValue& params, bool fHelp); extern UniValue listtransactions(const UniValue& params, bool fHelp); extern UniValue listaddressgroupings(const UniValue& params, bool fHelp); extern UniValue listaddressbalances(const UniValue& params, bool fHelp); extern UniValue listaccounts(const UniValue& params, bool fHelp); extern UniValue listsinceblock(const UniValue& params, bool fHelp); extern UniValue gettransaction(const UniValue& params, bool fHelp); extern UniValue abandontransaction(const UniValue& params, bool fHelp); extern UniValue backupwallet(const UniValue& params, bool fHelp); extern UniValue keypoolrefill(const UniValue& params, bool fHelp); extern UniValue walletpassphrase(const UniValue& params, bool fHelp); extern UniValue walletpassphrasechange(const UniValue& params, bool fHelp); extern UniValue walletlock(const UniValue& params, bool fHelp); extern UniValue encryptwallet(const UniValue& params, bool fHelp); extern UniValue validateaddress(const UniValue& params, bool fHelp); extern UniValue getaddressmempool(const UniValue& params, bool fHelp); extern UniValue getaddressutxos(const UniValue& params, bool fHelp); extern UniValue getaddressdeltas(const UniValue& params, bool fHelp); extern UniValue getaddresstxids(const UniValue& params, bool fHelp); extern UniValue getaddressbalance(const UniValue& params, bool fHelp); extern UniValue getspentinfo(const UniValue& params, bool fHelp); extern UniValue purgetxindex(const UniValue& params, bool fHelp); extern UniValue getinfo(const UniValue& params, bool fHelp); extern UniValue getstateinfo(const UniValue& params, bool fHelp); extern UniValue getwalletinfo(const UniValue& params, bool fHelp); extern UniValue getblockchaininfo(const UniValue& params, bool fHelp); extern UniValue getnetworkinfo(const UniValue& params, bool fHelp); extern UniValue setmocktime(const UniValue& params, bool fHelp); extern UniValue reservebalance(const UniValue& params, bool fHelp); extern UniValue multisend(const UniValue& params, bool fHelp); extern UniValue autocombinerewards(const UniValue& params, bool fHelp); extern UniValue getstakingstatus(const UniValue& params, bool fHelp); extern UniValue callcontract(const UniValue& params, bool fHelp); extern UniValue createcontract(const UniValue& params, bool fHelp); extern UniValue sendtocontract(const UniValue& params, bool fHelp); extern UniValue getrawtransaction(const UniValue& params, bool fHelp); // in rcprawtransaction.cpp extern UniValue listunspent(const UniValue& params, bool fHelp); extern UniValue lockunspent(const UniValue& params, bool fHelp); extern UniValue listlockunspent(const UniValue& params, bool fHelp); extern UniValue createrawtransaction(const UniValue& params, bool fHelp); extern UniValue fundrawtransaction(const UniValue& params, bool fHelp); extern UniValue decoderawtransaction(const UniValue& params, bool fHelp); extern UniValue decodescript(const UniValue& params, bool fHelp); extern UniValue signrawtransaction(const UniValue& params, bool fHelp); extern UniValue sendrawtransaction(const UniValue& params, bool fHelp); extern UniValue gethexaddress(const UniValue& params, bool fHelp); extern UniValue fromhexaddress(const UniValue& params, bool fHelp); extern UniValue getblockcount(const UniValue& params, bool fHelp); // in rpcblockchain.cpp extern UniValue getblockhashes(const UniValue& params, bool fHelp); extern UniValue getbestblockhash(const UniValue& params, bool fHelp); extern UniValue getdifficulty(const UniValue& params, bool fHelp); extern UniValue settxfee(const UniValue& params, bool fHelp); extern UniValue getmempoolinfo(const UniValue& params, bool fHelp); extern UniValue getrawmempool(const UniValue& params, bool fHelp); extern UniValue getblockhash(const UniValue& params, bool fHelp); extern UniValue getblock(const UniValue& params, bool fHelp); extern UniValue getblockheader(const UniValue& params, bool fHelp); extern UniValue gettxoutsetinfo(const UniValue& params, bool fHelp); extern UniValue gettxout(const UniValue& params, bool fHelp); extern UniValue verifychain(const UniValue& params, bool fHelp); extern UniValue getchaintips(const UniValue& params, bool fHelp); extern UniValue getchaintxstats(const UniValue& params, bool fHelp); extern UniValue switchnetwork(const UniValue& params, bool fHelp); extern UniValue invalidateblock(const UniValue& params, bool fHelp); extern UniValue reconsiderblock(const UniValue& params, bool fHelp); extern UniValue darksend(const UniValue& params, bool fHelp); extern UniValue spork(const UniValue& params, bool fHelp); extern UniValue masternode(const UniValue& params, bool fHelp); extern UniValue getaccountinfo(const UniValue& params, bool fHelp); //extern UniValue masternodelist(const UniValue& params, bool fHelp); //extern UniValue mnbudget(const UniValue& params, bool fHelp); //extern UniValue mnbudgetvoteraw(const UniValue& params, bool fHelp); //extern UniValue mnfinalbudget(const UniValue& params, bool fHelp); //extern UniValue mnsync(const UniValue& params, bool fHelp); extern UniValue generate(const UniValue& params, bool fHelp); extern UniValue getstorage(const UniValue& params, bool fHelp); extern UniValue listcontracts(const UniValue& params, bool fHelp); extern UniValue gettransactionreceipt(const UniValue& params, bool fHelp); extern UniValue searchlogs(const UniValue& params, bool fHelp); extern UniValue waitforlogs(const UniValue& params, bool fHelp); extern UniValue pruneblockchain(const UniValue& params, bool fHelp); bool StartRPC(); void InterruptRPC(); void StopRPC(); std::string JSONRPCExecBatch(const UniValue& vReq); void RPCNotifyBlockChange(bool ibd, const CBlockIndex* pindex); #endif // BITCOIN_RPCSERVER_H
{ "pile_set_name": "Github" }
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.fresco.samples.showcase.drawee; import android.graphics.drawable.Animatable; import android.net.Uri; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.Nullable; import com.facebook.common.references.CloseableReference; import com.facebook.datasource.RetainingDataSourceSupplier; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.drawee.controller.BaseControllerListener; import com.facebook.drawee.controller.ControllerListener; import com.facebook.drawee.view.SimpleDraweeView; import com.facebook.fresco.samples.showcase.BaseShowcaseFragment; import com.facebook.fresco.samples.showcase.R; import com.facebook.imagepipeline.image.CloseableImage; import com.facebook.imagepipeline.image.ImageInfo; import com.facebook.imagepipeline.request.ImageRequest; import java.util.List; public class RetainingDataSourceSupplierFragment extends BaseShowcaseFragment { private List<Uri> mSampleUris; private int mUriIndex = 0; private ControllerListener controllerListener = new BaseControllerListener<ImageInfo>() { @Override public void onFinalImageSet( String id, @Nullable ImageInfo imageInfo, @Nullable Animatable anim) { if (anim != null) { // app-specific logic to enable animation starting anim.start(); } } }; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mSampleUris = sampleUris().getSampleGifUris(); } @Nullable @Override public View onCreateView( LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_drawee_retaining_supplier, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { final SimpleDraweeView simpleDraweeView = view.findViewById(R.id.drawee_view); final RetainingDataSourceSupplier<CloseableReference<CloseableImage>> retainingSupplier = new RetainingDataSourceSupplier<>(); simpleDraweeView.setController( Fresco.newDraweeControllerBuilder() .setDataSourceSupplier(retainingSupplier) .setControllerListener(controllerListener) .build()); replaceImage(retainingSupplier); simpleDraweeView.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { replaceImage(retainingSupplier); } }); } @Override public int getTitleId() { return R.string.drawee_retaining_supplier_title; } private void replaceImage( RetainingDataSourceSupplier<CloseableReference<CloseableImage>> retainingSupplier) { retainingSupplier.replaceSupplier( Fresco.getImagePipeline() .getDataSourceSupplier( ImageRequest.fromUri(getNextUri()), null, ImageRequest.RequestLevel.FULL_FETCH)); } private synchronized Uri getNextUri() { int previousIndex = mUriIndex; mUriIndex = (mUriIndex + 1) % mSampleUris.size(); return mSampleUris.get(previousIndex); } }
{ "pile_set_name": "Github" }
import { IconDefinition, IconPrefix, IconName } from "@fortawesome/fontawesome-common-types"; export const definition: IconDefinition; export const faPinterest: IconDefinition; export const prefix: IconPrefix; export const iconName: IconName; export const width: number; export const height: number; export const ligatures: string[]; export const unicode: string; export const svgPathData: string;
{ "pile_set_name": "Github" }
// // bind/bind_mf2_cc.hpp - member functions, type<> syntax // // Do not include this header directly. // // Copyright (c) 2001 Peter Dimov and Multi Media Ltd. // Copyright (c) 2008 Peter Dimov // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // // See http://www.boost.org/libs/bind/bind.html for documentation. // // 0 template<class Rt2, class R, class T, class A1> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(mf0)<R, T>, typename _bi::list_av_1<A1>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) (), A1 a1) { typedef _mfi::BOOST_BIND_MF_NAME(mf0)<R, T> F; typedef typename _bi::list_av_1<A1>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1)); } template<class Rt2, class R, class T, class A1> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(cmf0)<R, T>, typename _bi::list_av_1<A1>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) () const, A1 a1) { typedef _mfi::BOOST_BIND_MF_NAME(cmf0)<R, T> F; typedef typename _bi::list_av_1<A1>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1)); } // 1 template<class Rt2, class R, class T, class B1, class A1, class A2> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(mf1)<R, T, B1>, typename _bi::list_av_2<A1, A2>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) (B1), A1 a1, A2 a2) { typedef _mfi::BOOST_BIND_MF_NAME(mf1)<R, T, B1> F; typedef typename _bi::list_av_2<A1, A2>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1, a2)); } template<class Rt2, class R, class T, class B1, class A1, class A2> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(cmf1)<R, T, B1>, typename _bi::list_av_2<A1, A2>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) (B1) const, A1 a1, A2 a2) { typedef _mfi::BOOST_BIND_MF_NAME(cmf1)<R, T, B1> F; typedef typename _bi::list_av_2<A1, A2>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1, a2)); } // 2 template<class Rt2, class R, class T, class B1, class B2, class A1, class A2, class A3> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(mf2)<R, T, B1, B2>, typename _bi::list_av_3<A1, A2, A3>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) (B1, B2), A1 a1, A2 a2, A3 a3) { typedef _mfi::BOOST_BIND_MF_NAME(mf2)<R, T, B1, B2> F; typedef typename _bi::list_av_3<A1, A2, A3>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1, a2, a3)); } template<class Rt2, class R, class T, class B1, class B2, class A1, class A2, class A3> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(cmf2)<R, T, B1, B2>, typename _bi::list_av_3<A1, A2, A3>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) (B1, B2) const, A1 a1, A2 a2, A3 a3) { typedef _mfi::BOOST_BIND_MF_NAME(cmf2)<R, T, B1, B2> F; typedef typename _bi::list_av_3<A1, A2, A3>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1, a2, a3)); } // 3 template<class Rt2, class R, class T, class B1, class B2, class B3, class A1, class A2, class A3, class A4> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(mf3)<R, T, B1, B2, B3>, typename _bi::list_av_4<A1, A2, A3, A4>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) (B1, B2, B3), A1 a1, A2 a2, A3 a3, A4 a4) { typedef _mfi::BOOST_BIND_MF_NAME(mf3)<R, T, B1, B2, B3> F; typedef typename _bi::list_av_4<A1, A2, A3, A4>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1, a2, a3, a4)); } template<class Rt2, class R, class T, class B1, class B2, class B3, class A1, class A2, class A3, class A4> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(cmf3)<R, T, B1, B2, B3>, typename _bi::list_av_4<A1, A2, A3, A4>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) (B1, B2, B3) const, A1 a1, A2 a2, A3 a3, A4 a4) { typedef _mfi::BOOST_BIND_MF_NAME(cmf3)<R, T, B1, B2, B3> F; typedef typename _bi::list_av_4<A1, A2, A3, A4>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1, a2, a3, a4)); } // 4 template<class Rt2, class R, class T, class B1, class B2, class B3, class B4, class A1, class A2, class A3, class A4, class A5> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(mf4)<R, T, B1, B2, B3, B4>, typename _bi::list_av_5<A1, A2, A3, A4, A5>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) (B1, B2, B3, B4), A1 a1, A2 a2, A3 a3, A4 a4, A5 a5) { typedef _mfi::BOOST_BIND_MF_NAME(mf4)<R, T, B1, B2, B3, B4> F; typedef typename _bi::list_av_5<A1, A2, A3, A4, A5>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1, a2, a3, a4, a5)); } template<class Rt2, class R, class T, class B1, class B2, class B3, class B4, class A1, class A2, class A3, class A4, class A5> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(cmf4)<R, T, B1, B2, B3, B4>, typename _bi::list_av_5<A1, A2, A3, A4, A5>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) (B1, B2, B3, B4) const, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5) { typedef _mfi::BOOST_BIND_MF_NAME(cmf4)<R, T, B1, B2, B3, B4> F; typedef typename _bi::list_av_5<A1, A2, A3, A4, A5>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1, a2, a3, a4, a5)); } // 5 template<class Rt2, class R, class T, class B1, class B2, class B3, class B4, class B5, class A1, class A2, class A3, class A4, class A5, class A6> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(mf5)<R, T, B1, B2, B3, B4, B5>, typename _bi::list_av_6<A1, A2, A3, A4, A5, A6>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) (B1, B2, B3, B4, B5), A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6) { typedef _mfi::BOOST_BIND_MF_NAME(mf5)<R, T, B1, B2, B3, B4, B5> F; typedef typename _bi::list_av_6<A1, A2, A3, A4, A5, A6>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1, a2, a3, a4, a5, a6)); } template<class Rt2, class R, class T, class B1, class B2, class B3, class B4, class B5, class A1, class A2, class A3, class A4, class A5, class A6> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(cmf5)<R, T, B1, B2, B3, B4, B5>, typename _bi::list_av_6<A1, A2, A3, A4, A5, A6>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) (B1, B2, B3, B4, B5) const, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6) { typedef _mfi::BOOST_BIND_MF_NAME(cmf5)<R, T, B1, B2, B3, B4, B5> F; typedef typename _bi::list_av_6<A1, A2, A3, A4, A5, A6>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1, a2, a3, a4, a5, a6)); } // 6 template<class Rt2, class R, class T, class B1, class B2, class B3, class B4, class B5, class B6, class A1, class A2, class A3, class A4, class A5, class A6, class A7> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(mf6)<R, T, B1, B2, B3, B4, B5, B6>, typename _bi::list_av_7<A1, A2, A3, A4, A5, A6, A7>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) (B1, B2, B3, B4, B5, B6), A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7) { typedef _mfi::BOOST_BIND_MF_NAME(mf6)<R, T, B1, B2, B3, B4, B5, B6> F; typedef typename _bi::list_av_7<A1, A2, A3, A4, A5, A6, A7>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1, a2, a3, a4, a5, a6, a7)); } template<class Rt2, class R, class T, class B1, class B2, class B3, class B4, class B5, class B6, class A1, class A2, class A3, class A4, class A5, class A6, class A7> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(cmf6)<R, T, B1, B2, B3, B4, B5, B6>, typename _bi::list_av_7<A1, A2, A3, A4, A5, A6, A7>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) (B1, B2, B3, B4, B5, B6) const, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7) { typedef _mfi::BOOST_BIND_MF_NAME(cmf6)<R, T, B1, B2, B3, B4, B5, B6> F; typedef typename _bi::list_av_7<A1, A2, A3, A4, A5, A6, A7>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1, a2, a3, a4, a5, a6, a7)); } // 7 template<class Rt2, class R, class T, class B1, class B2, class B3, class B4, class B5, class B6, class B7, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(mf7)<R, T, B1, B2, B3, B4, B5, B6, B7>, typename _bi::list_av_8<A1, A2, A3, A4, A5, A6, A7, A8>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) (B1, B2, B3, B4, B5, B6, B7), A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8) { typedef _mfi::BOOST_BIND_MF_NAME(mf7)<R, T, B1, B2, B3, B4, B5, B6, B7> F; typedef typename _bi::list_av_8<A1, A2, A3, A4, A5, A6, A7, A8>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1, a2, a3, a4, a5, a6, a7, a8)); } template<class Rt2, class R, class T, class B1, class B2, class B3, class B4, class B5, class B6, class B7, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(cmf7)<R, T, B1, B2, B3, B4, B5, B6, B7>, typename _bi::list_av_8<A1, A2, A3, A4, A5, A6, A7, A8>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) (B1, B2, B3, B4, B5, B6, B7) const, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8) { typedef _mfi::BOOST_BIND_MF_NAME(cmf7)<R, T, B1, B2, B3, B4, B5, B6, B7> F; typedef typename _bi::list_av_8<A1, A2, A3, A4, A5, A6, A7, A8>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1, a2, a3, a4, a5, a6, a7, a8)); } // 8 template<class Rt2, class R, class T, class B1, class B2, class B3, class B4, class B5, class B6, class B7, class B8, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(mf8)<R, T, B1, B2, B3, B4, B5, B6, B7, B8>, typename _bi::list_av_9<A1, A2, A3, A4, A5, A6, A7, A8, A9>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) (B1, B2, B3, B4, B5, B6, B7, B8), A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8, A9 a9) { typedef _mfi::BOOST_BIND_MF_NAME(mf8)<R, T, B1, B2, B3, B4, B5, B6, B7, B8> F; typedef typename _bi::list_av_9<A1, A2, A3, A4, A5, A6, A7, A8, A9>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1, a2, a3, a4, a5, a6, a7, a8, a9)); } template<class Rt2, class R, class T, class B1, class B2, class B3, class B4, class B5, class B6, class B7, class B8, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(cmf8)<R, T, B1, B2, B3, B4, B5, B6, B7, B8>, typename _bi::list_av_9<A1, A2, A3, A4, A5, A6, A7, A8, A9>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) (B1, B2, B3, B4, B5, B6, B7, B8) const, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8, A9 a9) { typedef _mfi::BOOST_BIND_MF_NAME(cmf8)<R, T, B1, B2, B3, B4, B5, B6, B7, B8> F; typedef typename _bi::list_av_9<A1, A2, A3, A4, A5, A6, A7, A8, A9>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
{ "pile_set_name": "Github" }
// Load modules var Url = require('url'); var Code = require('code'); var Hawk = require('../lib'); var Lab = require('lab'); // Declare internals var internals = {}; // Test shortcuts var lab = exports.lab = Lab.script(); var describe = lab.experiment; var it = lab.test; var expect = Code.expect; describe('Hawk', function () { var credentialsFunc = function (id, callback) { var credentials = { id: id, key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', algorithm: (id === '1' ? 'sha1' : 'sha256'), user: 'steve' }; return callback(null, credentials); }; it('generates a header then successfully parse it (configuration)', function (done) { var req = { method: 'GET', url: '/resource/4?filter=a', host: 'example.com', port: 8080 }; credentialsFunc('123456', function (err, credentials1) { req.authorization = Hawk.client.header(Url.parse('http://example.com:8080/resource/4?filter=a'), req.method, { credentials: credentials1, ext: 'some-app-data' }).field; expect(req.authorization).to.exist(); Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) { expect(err).to.not.exist(); expect(credentials2.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); done(); }); }); }); it('generates a header then successfully parse it (node request)', function (done) { var req = { method: 'POST', url: '/resource/4?filter=a', headers: { host: 'example.com:8080', 'content-type': 'text/plain;x=y' } }; var payload = 'some not so random text'; credentialsFunc('123456', function (err, credentials1) { var reqHeader = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] }); req.headers.authorization = reqHeader.field; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) { expect(err).to.not.exist(); expect(credentials2.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); expect(Hawk.server.authenticatePayload(payload, credentials2, artifacts, req.headers['content-type'])).to.equal(true); var res = { headers: { 'content-type': 'text/plain' } }; res.headers['server-authorization'] = Hawk.server.header(credentials2, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' }); expect(res.headers['server-authorization']).to.exist(); expect(Hawk.client.authenticate(res, credentials2, artifacts, { payload: 'some reply' })).to.equal(true); done(); }); }); }); it('generates a header then successfully parse it (absolute request uri)', function (done) { var req = { method: 'POST', url: 'http://example.com:8080/resource/4?filter=a', headers: { host: 'example.com:8080', 'content-type': 'text/plain;x=y' } }; var payload = 'some not so random text'; credentialsFunc('123456', function (err, credentials1) { var reqHeader = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] }); req.headers.authorization = reqHeader.field; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) { expect(err).to.not.exist(); expect(credentials2.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); expect(Hawk.server.authenticatePayload(payload, credentials2, artifacts, req.headers['content-type'])).to.equal(true); var res = { headers: { 'content-type': 'text/plain' } }; res.headers['server-authorization'] = Hawk.server.header(credentials2, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' }); expect(res.headers['server-authorization']).to.exist(); expect(Hawk.client.authenticate(res, credentials2, artifacts, { payload: 'some reply' })).to.equal(true); done(); }); }); }); it('generates a header then successfully parse it (no server header options)', function (done) { var req = { method: 'POST', url: '/resource/4?filter=a', headers: { host: 'example.com:8080', 'content-type': 'text/plain;x=y' } }; var payload = 'some not so random text'; credentialsFunc('123456', function (err, credentials1) { var reqHeader = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] }); req.headers.authorization = reqHeader.field; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) { expect(err).to.not.exist(); expect(credentials2.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); expect(Hawk.server.authenticatePayload(payload, credentials2, artifacts, req.headers['content-type'])).to.equal(true); var res = { headers: { 'content-type': 'text/plain' } }; res.headers['server-authorization'] = Hawk.server.header(credentials2, artifacts); expect(res.headers['server-authorization']).to.exist(); expect(Hawk.client.authenticate(res, credentials2, artifacts)).to.equal(true); done(); }); }); }); it('generates a header then fails to parse it (missing server header hash)', function (done) { var req = { method: 'POST', url: '/resource/4?filter=a', headers: { host: 'example.com:8080', 'content-type': 'text/plain;x=y' } }; var payload = 'some not so random text'; credentialsFunc('123456', function (err, credentials1) { var reqHeader = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] }); req.headers.authorization = reqHeader.field; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) { expect(err).to.not.exist(); expect(credentials2.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); expect(Hawk.server.authenticatePayload(payload, credentials2, artifacts, req.headers['content-type'])).to.equal(true); var res = { headers: { 'content-type': 'text/plain' } }; res.headers['server-authorization'] = Hawk.server.header(credentials2, artifacts); expect(res.headers['server-authorization']).to.exist(); expect(Hawk.client.authenticate(res, credentials2, artifacts, { payload: 'some reply' })).to.equal(false); done(); }); }); }); it('generates a header then successfully parse it (with hash)', function (done) { var req = { method: 'GET', url: '/resource/4?filter=a', host: 'example.com', port: 8080 }; credentialsFunc('123456', function (err, credentials1) { req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, payload: 'hola!', ext: 'some-app-data' }).field; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) { expect(err).to.not.exist(); expect(credentials2.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); done(); }); }); }); it('generates a header then successfully parse it then validate payload', function (done) { var req = { method: 'GET', url: '/resource/4?filter=a', host: 'example.com', port: 8080 }; credentialsFunc('123456', function (err, credentials1) { req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, payload: 'hola!', ext: 'some-app-data' }).field; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) { expect(err).to.not.exist(); expect(credentials2.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); expect(Hawk.server.authenticatePayload('hola!', credentials2, artifacts)).to.be.true(); expect(Hawk.server.authenticatePayload('hello!', credentials2, artifacts)).to.be.false(); done(); }); }); }); it('generates a header then successfully parses and validates payload', function (done) { var req = { method: 'GET', url: '/resource/4?filter=a', host: 'example.com', port: 8080 }; credentialsFunc('123456', function (err, credentials1) { req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, payload: 'hola!', ext: 'some-app-data' }).field; Hawk.server.authenticate(req, credentialsFunc, { payload: 'hola!' }, function (err, credentials2, artifacts) { expect(err).to.not.exist(); expect(credentials2.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); done(); }); }); }); it('generates a header then successfully parse it (app)', function (done) { var req = { method: 'GET', url: '/resource/4?filter=a', host: 'example.com', port: 8080 }; credentialsFunc('123456', function (err, credentials1) { req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', app: 'asd23ased' }).field; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) { expect(err).to.not.exist(); expect(credentials2.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); expect(artifacts.app).to.equal('asd23ased'); done(); }); }); }); it('generates a header then successfully parse it (app, dlg)', function (done) { var req = { method: 'GET', url: '/resource/4?filter=a', host: 'example.com', port: 8080 }; credentialsFunc('123456', function (err, credentials1) { req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', app: 'asd23ased', dlg: '23434szr3q4d' }).field; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) { expect(err).to.not.exist(); expect(credentials2.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); expect(artifacts.app).to.equal('asd23ased'); expect(artifacts.dlg).to.equal('23434szr3q4d'); done(); }); }); }); it('generates a header then fail authentication due to bad hash', function (done) { var req = { method: 'GET', url: '/resource/4?filter=a', host: 'example.com', port: 8080 }; credentialsFunc('123456', function (err, credentials1) { req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, payload: 'hola!', ext: 'some-app-data' }).field; Hawk.server.authenticate(req, credentialsFunc, { payload: 'byebye!' }, function (err, credentials2, artifacts) { expect(err).to.exist(); expect(err.output.payload.message).to.equal('Bad payload hash'); done(); }); }); }); it('generates a header for one resource then fail to authenticate another', function (done) { var req = { method: 'GET', url: '/resource/4?filter=a', host: 'example.com', port: 8080 }; credentialsFunc('123456', function (err, credentials1) { req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data' }).field; req.url = '/something/else'; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) { expect(err).to.exist(); expect(credentials2).to.exist(); done(); }); }); }); });
{ "pile_set_name": "Github" }
/* * Copyright (c) Enalean, 2019-Present. All Rights Reserved. * * This file is a part of Tuleap. * * Tuleap is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Tuleap 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 Tuleap. If not, see <http://www.gnu.org/licenses/>. */ import Vue from "vue"; import { Component, Prop } from "vue-property-decorator"; import { ColumnDefinition } from "../../../../../type"; @Component export default class ClassesForCollapsedColumnMixin extends Vue { @Prop({ required: true }) readonly column!: ColumnDefinition; get classes(): string[] { if (!this.column.is_collapsed) { return []; } const classes = ["taskboard-cell-collapsed"]; if (this.column.has_hover) { classes.push("taskboard-cell-collapsed-hover"); } return classes; } }
{ "pile_set_name": "Github" }
// Copyright 2019 The MediaPipe Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "mediapipe/gpu/gl_context.h" #include <sys/types.h> #include <cmath> #include <memory> #include <string> #include <utility> #include "absl/base/dynamic_annotations.h" #include "absl/memory/memory.h" #include "absl/synchronization/mutex.h" #include "mediapipe/framework/port/logging.h" #include "mediapipe/framework/port/ret_check.h" #include "mediapipe/framework/port/status.h" #include "mediapipe/framework/port/status_builder.h" #include "mediapipe/gpu/gl_context_internal.h" #ifndef __EMSCRIPTEN__ #include "absl/debugging/leak_check.h" #include "mediapipe/gpu/gl_thread_collector.h" #endif #ifndef GL_MAJOR_VERSION #define GL_MAJOR_VERSION 0x821B #endif #ifndef GL_MINOR_VERSION #define GL_MINOR_VERSION 0x821C #endif namespace mediapipe { static void SetThreadName(const char* name) { #if defined(__GLIBC_PREREQ) #define LINUX_STYLE_SETNAME_NP __GLIBC_PREREQ(2, 12) #elif defined(__BIONIC__) #define LINUX_STYLE_SETNAME_NP 1 #endif // __GLIBC_PREREQ #if LINUX_STYLE_SETNAME_NP char thread_name[16]; // Linux requires names (with nul) fit in 16 chars strncpy(thread_name, name, sizeof(thread_name)); thread_name[sizeof(thread_name) - 1] = '\0'; int res = pthread_setname_np(pthread_self(), thread_name); if (res != 0) { LOG_FIRST_N(INFO, 1) << "Can't set pthread names: name: \"" << name << "\"; error: " << res; } #elif __APPLE__ pthread_setname_np(name); #endif ANNOTATE_THREAD_NAME(name); } GlContext::DedicatedThread::DedicatedThread() { CHECK_EQ(pthread_create(&gl_thread_id_, nullptr, ThreadBody, this), 0); } GlContext::DedicatedThread::~DedicatedThread() { if (IsCurrentThread()) { CHECK(self_destruct_); CHECK_EQ(pthread_detach(gl_thread_id_), 0); } else { // Give an invalid job to signal termination. PutJob({}); CHECK_EQ(pthread_join(gl_thread_id_, nullptr), 0); } } void GlContext::DedicatedThread::SelfDestruct() { self_destruct_ = true; // Give an invalid job to signal termination. PutJob({}); } GlContext::DedicatedThread::Job GlContext::DedicatedThread::GetJob() { absl::MutexLock lock(&mutex_); while (jobs_.empty()) { has_jobs_cv_.Wait(&mutex_); } Job job = std::move(jobs_.front()); jobs_.pop_front(); return job; } void GlContext::DedicatedThread::PutJob(Job job) { absl::MutexLock lock(&mutex_); jobs_.push_back(std::move(job)); has_jobs_cv_.SignalAll(); } void* GlContext::DedicatedThread::ThreadBody(void* instance) { DedicatedThread* thread = static_cast<DedicatedThread*>(instance); thread->ThreadBody(); return nullptr; } #ifdef __APPLE__ #define AUTORELEASEPOOL @autoreleasepool #else #define AUTORELEASEPOOL #endif // __APPLE__ void GlContext::DedicatedThread::ThreadBody() { SetThreadName("mediapipe_gl_runner"); #ifndef __EMSCRIPTEN__ GlThreadCollector::ThreadStarting(); #endif // The dedicated GL thread is not meant to be used on Apple platforms, but // in case it is, the use of an autorelease pool here will reap each task's // temporary allocations. while (true) AUTORELEASEPOOL { Job job = GetJob(); // Lack of a job means termination. Or vice versa. if (!job) { break; } job(); } if (self_destruct_) { delete this; } #ifndef __EMSCRIPTEN__ GlThreadCollector::ThreadEnding(); #endif } ::mediapipe::Status GlContext::DedicatedThread::Run(GlStatusFunction gl_func) { // Neither ENDO_SCOPE nor ENDO_TASK seem to work here. if (IsCurrentThread()) { return gl_func(); } bool done = false; // Guarded by mutex_ after initialization. ::mediapipe::Status status; PutJob([this, gl_func, &done, &status]() { status = gl_func(); absl::MutexLock lock(&mutex_); done = true; gl_job_done_cv_.SignalAll(); }); absl::MutexLock lock(&mutex_); while (!done) { gl_job_done_cv_.Wait(&mutex_); } return status; } void GlContext::DedicatedThread::RunWithoutWaiting(GlVoidFunction gl_func) { // Note: this is invoked by GlContextExecutor. To avoid starvation of // non-calculator tasks in the presence of GL source calculators, calculator // tasks must always be scheduled as new tasks, or another solution needs to // be set up to avoid starvation. See b/78522434. CHECK(gl_func); PutJob(std::move(gl_func)); } bool GlContext::DedicatedThread::IsCurrentThread() { return pthread_equal(gl_thread_id_, pthread_self()); } bool GlContext::ParseGlVersion(absl::string_view version_string, GLint* major, GLint* minor) { size_t pos = version_string.find('.'); if (pos == absl::string_view::npos || pos < 1) { return false; } // GL_VERSION is supposed to start with the version number; see, e.g., // https://www.khronos.org/registry/OpenGL-Refpages/es3/html/glGetString.xhtml // https://www.khronos.org/opengl/wiki/OpenGL_Context#OpenGL_version_number // However, in rare cases one will encounter non-conforming configurations // that have some prefix before the number. To deal with that, we walk // backwards from the dot. size_t start = pos - 1; while (start > 0 && isdigit(version_string[start - 1])) --start; if (!absl::SimpleAtoi(version_string.substr(start, (pos - start)), major)) { return false; } auto rest = version_string.substr(pos + 1); pos = rest.find(' '); size_t pos2 = rest.find('.'); if (pos == absl::string_view::npos || (pos2 != absl::string_view::npos && pos2 < pos)) { pos = pos2; } if (!absl::SimpleAtoi(rest.substr(0, pos), minor)) { return false; } return true; } bool GlContext::HasGlExtension(absl::string_view extension) const { return gl_extensions_.find(extension) != gl_extensions_.end(); } // Function for GL3.0+ to query for and store all of our available GL extensions // in an easily-accessible set. The glGetString call is actually *not* required // to work with GL_EXTENSIONS for newer GL versions, so we must maintain both // variations of this function. ::mediapipe::Status GlContext::GetGlExtensions() { gl_extensions_.clear(); // glGetStringi only introduced in GL 3.0+; so we exit out this function if // we don't have that function defined, regardless of version number reported. // The function itself is also fully stubbed out if we're linking against an // API version without a glGetStringi declaration. Although Emscripten // sometimes provides this function, its default library implementation // appears to only provide glGetString, so we skip this for Emscripten // platforms to avoid possible undefined symbol or runtime errors. #if (GL_VERSION_3_0 || GL_ES_VERSION_3_0) && !defined(__EMSCRIPTEN__) if (!SymbolAvailable(&glGetStringi)) { LOG(ERROR) << "GL major version > 3.0 indicated, but glGetStringi not " << "defined. Falling back to deprecated GL extensions querying " << "method."; return ::mediapipe::InternalError("glGetStringi not defined, but queried"); } int num_extensions = 0; glGetIntegerv(GL_NUM_EXTENSIONS, &num_extensions); if (glGetError() != 0) { return ::mediapipe::InternalError( "Error querying for number of extensions"); } for (int i = 0; i < num_extensions; ++i) { const GLubyte* res = glGetStringi(GL_EXTENSIONS, i); if (glGetError() != 0 || res == nullptr) { return ::mediapipe::InternalError( "Error querying for an extension by index"); } const char* signed_res = reinterpret_cast<const char*>(res); gl_extensions_.insert(signed_res); } return ::mediapipe::OkStatus(); #else return ::mediapipe::InternalError("GL version mismatch in GlGetExtensions"); #endif // (GL_VERSION_3_0 || GL_ES_VERSION_3_0) && !defined(__EMSCRIPTEN__) } // Same as GetGlExtensions() above, but for pre-GL3.0, where glGetStringi did // not exist. ::mediapipe::Status GlContext::GetGlExtensionsCompat() { gl_extensions_.clear(); const GLubyte* res = glGetString(GL_EXTENSIONS); if (glGetError() != 0 || res == nullptr) { LOG(ERROR) << "Error querying for GL extensions"; return ::mediapipe::InternalError("Error querying for GL extensions"); } const char* signed_res = reinterpret_cast<const char*>(res); gl_extensions_ = absl::StrSplit(signed_res, ' '); return ::mediapipe::OkStatus(); } ::mediapipe::Status GlContext::FinishInitialization(bool create_thread) { if (create_thread) { thread_ = absl::make_unique<GlContext::DedicatedThread>(); MP_RETURN_IF_ERROR(thread_->Run([this] { return EnterContext(nullptr); })); } return Run([this]() -> ::mediapipe::Status { // Clear any GL errors at this point: as this is a fresh context // there shouldn't be any, but if we adopted an existing context (e.g. in // some Emscripten cases), there might be some existing tripped error. ForceClearExistingGlErrors(); absl::string_view version_string( reinterpret_cast<const char*>(glGetString(GL_VERSION))); // We will decide later whether we want to use the version numbers we query // for, or instead derive that information from the context creation result, // which we cache here. GLint gl_major_version_from_context_creation = gl_major_version_; // Let's try getting the numeric version if possible. glGetIntegerv(GL_MAJOR_VERSION, &gl_major_version_); GLenum err = glGetError(); if (err == GL_NO_ERROR) { glGetIntegerv(GL_MINOR_VERSION, &gl_minor_version_); } else { // GL_MAJOR_VERSION is not supported on GL versions below 3. We have to // parse the version std::string. if (!ParseGlVersion(version_string, &gl_major_version_, &gl_minor_version_)) { LOG(WARNING) << "invalid GL_VERSION format: '" << version_string << "'; assuming 2.0"; gl_major_version_ = 2; gl_minor_version_ = 0; } } // If our platform-specific CreateContext already set a major GL version, // then we use that. Otherwise, we use the queried-for result. We do this // as a workaround for a Swiftshader on Android bug where the ES2 context // can report major version 3 instead of 2 when queried. Therefore we trust // the result from context creation more than from query. See b/152519932 // for more details. if (gl_major_version_from_context_creation > 0 && gl_major_version_ != gl_major_version_from_context_creation) { LOG(WARNING) << "Requested a context with major GL version " << gl_major_version_from_context_creation << " but context reports major version " << gl_major_version_ << ". Setting to " << gl_major_version_from_context_creation << ".0"; gl_major_version_ = gl_major_version_from_context_creation; gl_minor_version_ = 0; } LOG(INFO) << "GL version: " << gl_major_version_ << "." << gl_minor_version_ << " (" << glGetString(GL_VERSION) << ")"; if (gl_major_version_ >= 3) { auto status = GetGlExtensions(); if (status.ok()) { return ::mediapipe::OkStatus(); } } return GetGlExtensionsCompat(); }); } GlContext::GlContext() {} GlContext::~GlContext() { // Note: on Apple platforms, this object contains Objective-C objects. // The destructor will release them, but ARC must be on. #ifdef __OBJC__ #if !__has_feature(objc_arc) #error This file must be built with ARC. #endif #endif // __OBJC__ if (thread_) { auto status = thread_->Run([this] { if (profiling_helper_) { profiling_helper_->LogAllTimestamps(); } return ExitContext(nullptr); }); LOG_IF(ERROR, !status.ok()) << "Failed to deactivate context on thread: " << status; if (thread_->IsCurrentThread()) { thread_.release()->SelfDestruct(); } } DestroyContext(); } void GlContext::SetProfilingContext( std::shared_ptr<mediapipe::ProfilingContext> profiling_context) { // Create the GlProfilingHelper if it is uninitialized. if (!profiling_helper_ && profiling_context) { profiling_helper_ = profiling_context->CreateGlProfilingHelper(); } } ::mediapipe::Status GlContext::SwitchContextAndRun(GlStatusFunction gl_func) { ContextBinding saved_context; MP_RETURN_IF_ERROR(EnterContext(&saved_context)) << " (entering GL context)"; auto status = gl_func(); LogUncheckedGlErrors(CheckForGlErrors()); MP_RETURN_IF_ERROR(ExitContext(&saved_context)) << " (exiting GL context)"; return status; } ::mediapipe::Status GlContext::Run(GlStatusFunction gl_func, int node_id, Timestamp input_timestamp) { ::mediapipe::Status status; if (profiling_helper_) { gl_func = [=] { profiling_helper_->MarkTimestamp(node_id, input_timestamp, /*is_finish=*/false); auto status = gl_func(); profiling_helper_->MarkTimestamp(node_id, input_timestamp, /*is_finish=*/true); return status; }; } if (thread_) { bool had_gl_errors = false; status = thread_->Run([this, gl_func, &had_gl_errors] { auto status = gl_func(); had_gl_errors = CheckForGlErrors(); return status; }); LogUncheckedGlErrors(had_gl_errors); } else { status = SwitchContextAndRun(gl_func); } return status; } void GlContext::RunWithoutWaiting(GlVoidFunction gl_func) { if (thread_) { // Add ref to keep the context alive while the task is executing. auto context = shared_from_this(); thread_->RunWithoutWaiting([this, context, gl_func] { gl_func(); LogUncheckedGlErrors(CheckForGlErrors()); }); } else { // TODO: queue up task instead. auto status = SwitchContextAndRun([gl_func] { gl_func(); return ::mediapipe::OkStatus(); }); if (!status.ok()) { LOG(ERROR) << "Error in RunWithoutWaiting: " << status; } } } std::weak_ptr<GlContext>& GlContext::CurrentContext() { // Workaround for b/67878799. #ifndef __EMSCRIPTEN__ absl::LeakCheckDisabler disable_leak_check; #endif ABSL_CONST_INIT thread_local std::weak_ptr<GlContext> current_context; return current_context; } ::mediapipe::Status GlContext::SwitchContext(ContextBinding* saved_context, const ContextBinding& new_context) ABSL_NO_THREAD_SAFETY_ANALYSIS { std::shared_ptr<GlContext> old_context_obj = CurrentContext().lock(); std::shared_ptr<GlContext> new_context_obj = new_context.context_object.lock(); if (saved_context) { saved_context->context_object = old_context_obj; GetCurrentContextBinding(saved_context); } // Check that the context object is consistent with the native context. if (old_context_obj && saved_context) { DCHECK(old_context_obj->context_ == saved_context->context); } if (new_context_obj) { DCHECK(new_context_obj->context_ == new_context.context); } if (new_context_obj && (old_context_obj == new_context_obj)) { return ::mediapipe::OkStatus(); } if (old_context_obj) { // 1. Even if we cannot restore the new context, we want to get out of the // old one (we may be deliberately trying to exit it). // 2. We need to unset the old context before we unlock the old mutex, // Therefore, we first unset the old one before setting the new one. MP_RETURN_IF_ERROR(SetCurrentContextBinding({})); old_context_obj->context_use_mutex_.Unlock(); CurrentContext().reset(); } if (new_context_obj) { new_context_obj->context_use_mutex_.Lock(); auto status = SetCurrentContextBinding(new_context); if (status.ok()) { CurrentContext() = new_context_obj; } else { new_context_obj->context_use_mutex_.Unlock(); } return status; } else { return SetCurrentContextBinding(new_context); } } ::mediapipe::Status GlContext::EnterContext(ContextBinding* saved_context) { DCHECK(HasContext()); return SwitchContext(saved_context, ThisContextBinding()); } ::mediapipe::Status GlContext::ExitContext( const ContextBinding* saved_context) { ContextBinding no_context; if (!saved_context) { saved_context = &no_context; } return SwitchContext(nullptr, *saved_context); } std::shared_ptr<GlContext> GlContext::GetCurrent() { return CurrentContext().lock(); } void GlContext::GlFinishCalled() { absl::MutexLock lock(&mutex_); ++gl_finish_count_; wait_for_gl_finish_cv_.SignalAll(); } class GlFinishSyncPoint : public GlSyncPoint { public: explicit GlFinishSyncPoint(const std::shared_ptr<GlContext>& gl_context) : GlSyncPoint(gl_context), gl_finish_count_(gl_context_->gl_finish_count()) {} void Wait() override { gl_context_->WaitForGlFinishCountPast(gl_finish_count_); } bool IsReady() override { return gl_context_->gl_finish_count() > gl_finish_count_; } private: // Number of glFinish calls done before the creation of this token. int64_t gl_finish_count_ = -1; }; class GlFenceSyncPoint : public GlSyncPoint { public: explicit GlFenceSyncPoint(const std::shared_ptr<GlContext>& gl_context) : GlSyncPoint(gl_context) { gl_context_->Run([this] { sync_ = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); glFlush(); }); } ~GlFenceSyncPoint() { if (sync_) { GLsync sync = sync_; gl_context_->RunWithoutWaiting([sync] { glDeleteSync(sync); }); } } GlFenceSyncPoint(const GlFenceSyncPoint&) = delete; GlFenceSyncPoint& operator=(const GlFenceSyncPoint&) = delete; void Wait() override { if (!sync_) return; gl_context_->Run([this] { GLenum result = glClientWaitSync(sync_, 0, std::numeric_limits<uint64_t>::max()); if (result == GL_ALREADY_SIGNALED || result == GL_CONDITION_SATISFIED) { glDeleteSync(sync_); sync_ = nullptr; } // TODO: do something if the wait fails? }); } void WaitOnGpu() override { if (!sync_) return; // TODO: do not wait if we are already on the same context? glWaitSync(sync_, 0, GL_TIMEOUT_IGNORED); } bool IsReady() override { if (!sync_) return true; bool ready = false; // TODO: we should not block on the original context if possible. gl_context_->Run([this, &ready] { GLenum result = glClientWaitSync(sync_, 0, 0); if (result == GL_ALREADY_SIGNALED || result == GL_CONDITION_SATISFIED) { glDeleteSync(sync_); sync_ = nullptr; ready = true; } }); return ready; } private: GLsync sync_; }; void GlMultiSyncPoint::Add(std::shared_ptr<GlSyncPoint> new_sync) { for (auto& sync : syncs_) { if (sync->GetContext() == new_sync->GetContext()) { sync = std::move(new_sync); return; } } syncs_.emplace_back(std::move(new_sync)); } void GlMultiSyncPoint::Wait() { for (auto& sync : syncs_) { sync->Wait(); } // At this point all the syncs have been reached, so clear them out. syncs_.clear(); } void GlMultiSyncPoint::WaitOnGpu() { for (auto& sync : syncs_) { sync->WaitOnGpu(); } // TODO: when do we clear out these syncs? } bool GlMultiSyncPoint::IsReady() { syncs_.erase( std::remove_if(syncs_.begin(), syncs_.end(), std::bind(&GlSyncPoint::IsReady, std::placeholders::_1)), syncs_.end()); return syncs_.empty(); } // Set this to 1 to disable syncing. This can be used to verify that a test // correctly detects sync issues. #define MEDIAPIPE_DISABLE_GL_SYNC_FOR_DEBUG 0 #if MEDIAPIPE_DISABLE_GL_SYNC_FOR_DEBUG class GlNopSyncPoint : public GlSyncPoint { public: explicit GlNopSyncPoint(const std::shared_ptr<GlContext>& gl_context) : GlSyncPoint(gl_context) {} void Wait() override {} bool IsReady() override { return true; } }; #endif std::shared_ptr<GlSyncPoint> GlContext::CreateSyncToken() { std::shared_ptr<GlSyncPoint> token; #if MEDIAPIPE_DISABLE_GL_SYNC_FOR_DEBUG token.reset(new GlNopSyncPoint(shared_from_this())); #else #ifdef __EMSCRIPTEN__ // In Emscripten the glWaitSync function is non-null depending on linkopts, // but only works in a WebGL2 context, so fall back to use Finish if it is a // WebGL1/ES2 context. // TODO: apply this more generally once b/152794517 is fixed. bool useFenceSync = gl_major_version() > 2; #else bool useFenceSync = SymbolAvailable(&glWaitSync); #endif // __EMSCRIPTEN__ if (useFenceSync) { token.reset(new GlFenceSyncPoint(shared_from_this())); } else { token.reset(new GlFinishSyncPoint(shared_from_this())); } #endif return token; } std::shared_ptr<GlSyncPoint> GlContext::TestOnly_CreateSpecificSyncToken( SyncTokenTypeForTest type) { std::shared_ptr<GlSyncPoint> token; switch (type) { case SyncTokenTypeForTest::kGlFinish: token.reset(new GlFinishSyncPoint(shared_from_this())); return token; } return nullptr; } // Atomically set var to the greater of its current value or target. template <typename T> static void assign_larger_value(std::atomic<T>* var, T target) { T current = var->load(); while (current < target && !var->compare_exchange_weak(current, target)) { } } // Note: this can get called from an arbitrary thread which is dealing with a // GlFinishSyncPoint originating from this context. void GlContext::WaitForGlFinishCountPast(int64_t count_to_pass) { if (gl_finish_count_ > count_to_pass) return; // If we've been asked to do a glFinish, note the count we need to reach and // signal the context our thread may currently be blocked on. { absl::MutexLock lock(&mutex_); assign_larger_value(&gl_finish_count_target_, count_to_pass + 1); wait_for_gl_finish_cv_.SignalAll(); if (context_waiting_on_) { context_waiting_on_->wait_for_gl_finish_cv_.SignalAll(); } } auto finish_task = [this, count_to_pass]() { // When a GlFinishSyncToken is created it takes the current finish count // from the GlContext, and we must wait for gl_finish_count_ to pass it. // Therefore, we need to do at most one more glFinish call. This DCHECK // is used for documentation and sanity-checking purposes. DCHECK(gl_finish_count_ >= count_to_pass); if (gl_finish_count_ == count_to_pass) { glFinish(); GlFinishCalled(); } }; if (IsCurrent()) { // If we are already on the current context, we cannot call // RunWithoutWaiting, since that task will not run until this function // returns. Instead, call it directly. finish_task(); return; } std::shared_ptr<GlContext> other = GetCurrent(); if (other) { // If another context is current, make a note that it is blocked on us, so // it can signal the right condition variable if it is asked to do a // glFinish. absl::MutexLock other_lock(&other->mutex_); DCHECK(!other->context_waiting_on_); other->context_waiting_on_ = this; } // We do not schedule this action using Run because we don't necessarily // want to wait for it to complete. If another job calls GlFinishCalled // sooner, we are done. RunWithoutWaiting(std::move(finish_task)); { absl::MutexLock lock(&mutex_); while (gl_finish_count_ <= count_to_pass) { if (other && other->gl_finish_count_ < other->gl_finish_count_target_) { // If another context's dedicated thread is current, it is blocked // waiting for this context to issue a glFinish call. But this context // may also block waiting for the other context to do the same: this can // happen when two contexts are handling each other's GlFinishSyncPoints // (e.g. a producer and a consumer). To avoid a deadlock a context that // is waiting on another context must still service Wait calls it may // receive from its own GlFinishSyncPoints. // // We unlock this context's mutex to avoid holding both at the same // time. mutex_.Unlock(); { glFinish(); other->GlFinishCalled(); } mutex_.Lock(); // Because we temporarily unlocked mutex_, we cannot wait on the // condition variable wait away; we need to go back to re-checking the // condition. Otherwise we might miss a signal. continue; } wait_for_gl_finish_cv_.Wait(&mutex_); } } if (other) { // The other context is no longer waiting on us. absl::MutexLock other_lock(&other->mutex_); other->context_waiting_on_ = nullptr; } } void GlContext::WaitSyncToken(const std::shared_ptr<GlSyncPoint>& token) { CHECK(token); token->Wait(); } bool GlContext::SyncTokenIsReady(const std::shared_ptr<GlSyncPoint>& token) { CHECK(token); return token->IsReady(); } void GlContext::ForceClearExistingGlErrors() { LogUncheckedGlErrors(CheckForGlErrors(/*force=*/true)); } bool GlContext::CheckForGlErrors() { return CheckForGlErrors(false); } bool GlContext::CheckForGlErrors(bool force) { #if UNSAFE_EMSCRIPTEN_SKIP_GL_ERROR_HANDLING if (!force) { LOG_FIRST_N(WARNING, 1) << "MediaPipe OpenGL error checking is disabled"; return false; } #endif if (!HasContext()) return false; GLenum error; bool had_error = false; while ((error = glGetError()) != GL_NO_ERROR) { had_error = true; switch (error) { case GL_INVALID_ENUM: LOG(INFO) << "Found unchecked GL error: GL_INVALID_ENUM"; break; case GL_INVALID_VALUE: LOG(INFO) << "Found unchecked GL error: GL_INVALID_VALUE"; break; case GL_INVALID_OPERATION: LOG(INFO) << "Found unchecked GL error: GL_INVALID_OPERATION"; break; case GL_INVALID_FRAMEBUFFER_OPERATION: LOG(INFO) << "Found unchecked GL error: GL_INVALID_FRAMEBUFFER_OPERATION"; break; case GL_OUT_OF_MEMORY: LOG(INFO) << "Found unchecked GL error: GL_OUT_OF_MEMORY"; break; default: LOG(INFO) << "Found unchecked GL error: UNKNOWN ERROR"; break; } } return had_error; } void GlContext::LogUncheckedGlErrors(bool had_gl_errors) { if (had_gl_errors) { // TODO: ideally we would print a backtrace here, or at least // the name of the current calculator, to make it easier to find the // culprit. In practice, getting a backtrace from Android without crashing // is nearly impossible, so screw it. Just change this to LOG(FATAL) when // you want to debug. LOG(WARNING) << "Ignoring unchecked GL error."; } } } // namespace mediapipe
{ "pile_set_name": "Github" }
# class ClassPropertyDescriptor: """ ClassPropertyDescriptor """ def __init__(self, fget, fset=None): self.fget = fget self.fset = fset def __get__(self, obj, klass=None): """ __get__ """ if klass is None: klass = type(obj) return self.fget.__get__(obj, klass)() def __set__(self, obj, value): """ __set__ """ if not self.fset: raise AttributeError("can't set attribute") type_ = type(obj) return self.fset.__get__(obj, type_)(value) def setter(self, func): """ setter """ if not isinstance(func, (classmethod, staticmethod)): func = classmethod(func) self.fset = func return self def classproperty(func): """ classproperty """ if not isinstance(func, (classmethod, staticmethod)): func = classmethod(func) return ClassPropertyDescriptor(func)
{ "pile_set_name": "Github" }
#ifndef DEMO_MODEL_H #define DEMO_MODEL_H #include <Aabb.h> #include <Timer.h> #include <DX12_ResourceDescTable.h> #include <SkinnedDecals.h> #define CURRENT_DEMO_MODEL_VERSION 1 #define SKINNING_THREAD_GROUP_SIZE 64 class DX12_PipelineState; class DX12_Buffer; class DX12_TimerQuery; class Material; class Shading; struct WeightIndex { UINT firstIndex; UINT numIndices; }; struct Weight { UINT jointIndex; float weight; Vector3 position; Vector3 normal; Vector3 tangent; }; struct Joint { Vector3 translation; Quat rotation; }; struct AnimFrame { Joint *joints; Aabb bounds; }; struct DemoSubModel { DemoSubModel(): baseNoDecalsPS(nullptr), baseWithDecalsPS(nullptr), material(nullptr), firstIndex(0), numIndices(0) { } DX12_PipelineState *baseNoDecalsPS; DX12_PipelineState *baseWithDecalsPS; DX12_ResourceDescTable materialDT; Material *material; UINT firstIndex; UINT numIndices; }; // DemoModel // // Simple model format (".model") for storing animated models (only one animation set is supported). // Data generated by loading a MD5 model, precalculating all information that is required for culling, // skinning and rendering the model, and storing these information into a binary file format. class DemoModel { public: friend class SkinnedDecals; struct ModelConstData { Matrix4 transformMatrix; UINT numVertices; UINT debugDecalMask; }; DemoModel(): subModels(nullptr), animFrames(nullptr), numSubModels(0), numJoints(0), numAnimFrames(0), currentAnimFrameIndex(0), nextAnimFrameIndex(0), pauseAnim(false), visible(false), useDecals(true), debugDecalMask(false), indexBuffer(nullptr), weightIndexSB(nullptr), weightSB(nullptr), jointSB(nullptr), vertexPositionSB(nullptr), vertexNormalSB(nullptr), vertexTangentSB(nullptr), vertexUvHandednessSB(nullptr), modelCB(nullptr), skinningPS(nullptr), skinningTQ(nullptr), basePassTQ(nullptr), skinnedDecals(nullptr), shadingPP(nullptr) { interpAnimFrame.joints = nullptr; } ~DemoModel() { Release(); } void Release(); bool Load(const char *filename); bool InitSkinnedDecals(const char** materialNames, UINT numMaterials); void Render(); const DemoSubModel* GetSubModel(UINT index) const { assert(index < numSubModels); return &subModels[index]; } UINT GetNumSubModels() const { return numSubModels; } void SetPosition(const Vector3 &position) { this->position = position; } Vector3 GetPosition() const { return position; } void SetRotation(const Vector3 &rotation) { this->rotation = rotation; } Vector3 GetRotation() const { return rotation; } const Aabb& GetBounds() const { return interpAnimFrame.bounds; } void PauseAnim(bool pauseAnim) { this->pauseAnim = pauseAnim; } bool IsAnimPaused() const { return pauseAnim; } void UseDecals(bool useDecals) { this->useDecals = useDecals; } bool AreDecalsUsed() const { return useDecals; } void EnableDebugDecalMask(bool enable) { debugDecalMask = enable; } bool IsDebugDecalMaskEnabled() const { return debugDecalMask; } float GetSkinningGpuTime() const { return skinningTQ->GetGpuElapsedTime(); } float GetBasePassGpuTime() const { return basePassTQ->GetGpuElapsedTime(); } SkinnedDecals *GetSkinnedDecals() { return skinnedDecals; } private: void UpdateSkeleton(); void UpdateBuffers(); void PerformSkinning(); void RenderBasePass(); DemoSubModel *subModels; AnimFrame *animFrames; AnimFrame interpAnimFrame; Timer animTimer; UINT numSubModels; UINT numJoints; UINT numAnimFrames; UINT currentAnimFrameIndex, nextAnimFrameIndex; ModelConstData modelConstData; Vector3 position; Vector3 rotation; bool pauseAnim; bool visible; bool useDecals; bool debugDecalMask; DX12_Buffer *indexBuffer; DX12_Buffer *weightIndexSB; DX12_Buffer *weightSB; DX12_Buffer *jointSB; DX12_Buffer *vertexPositionSB; DX12_Buffer *vertexNormalSB; DX12_Buffer *vertexTangentSB; DX12_Buffer *vertexUvHandednessSB; DX12_Buffer *modelCB; DX12_PipelineState *skinningPS; DX12_ResourceDescTable skinningDT; DX12_ResourceDescTable basePassVertexDT; DX12_TimerQuery *skinningTQ; DX12_TimerQuery *basePassTQ; SkinnedDecals *skinnedDecals; Shading *shadingPP; }; #endif
{ "pile_set_name": "Github" }
"""runpy.py - locating and running Python code using the module namespace Provides support for locating and running Python scripts using the Python module namespace instead of the native filesystem. This allows Python code to play nicely with non-filesystem based PEP 302 importers when locating support scripts as well as when importing modules. """ # Written by Nick Coghlan <ncoghlan at gmail.com> # to implement PEP 338 (Executing Modules as Scripts) import sys import imp from pkgutil import read_code try: from imp import get_loader except ImportError: from pkgutil import get_loader __all__ = [ "run_module", "run_path", ] class _TempModule(object): """Temporarily replace a module in sys.modules with an empty namespace""" def __init__(self, mod_name): self.mod_name = mod_name self.module = imp.new_module(mod_name) self._saved_module = [] def __enter__(self): mod_name = self.mod_name try: self._saved_module.append(sys.modules[mod_name]) except KeyError: pass sys.modules[mod_name] = self.module return self def __exit__(self, *args): if self._saved_module: sys.modules[self.mod_name] = self._saved_module[0] else: del sys.modules[self.mod_name] self._saved_module = [] class _ModifiedArgv0(object): def __init__(self, value): self.value = value self._saved_value = self._sentinel = object() def __enter__(self): if self._saved_value is not self._sentinel: raise RuntimeError("Already preserving saved value") self._saved_value = sys.argv[0] sys.argv[0] = self.value def __exit__(self, *args): self.value = self._sentinel sys.argv[0] = self._saved_value def _run_code(code, run_globals, init_globals=None, mod_name=None, mod_fname=None, mod_loader=None, pkg_name=None): """Helper to run code in nominated namespace""" if init_globals is not None: run_globals.update(init_globals) run_globals.update(__name__ = mod_name, __file__ = mod_fname, __loader__ = mod_loader, __package__ = pkg_name) exec code in run_globals return run_globals def _run_module_code(code, init_globals=None, mod_name=None, mod_fname=None, mod_loader=None, pkg_name=None): """Helper to run code in new namespace with sys modified""" with _TempModule(mod_name) as temp_module, _ModifiedArgv0(mod_fname): mod_globals = temp_module.module.__dict__ _run_code(code, mod_globals, init_globals, mod_name, mod_fname, mod_loader, pkg_name) # Copy the globals of the temporary module, as they # may be cleared when the temporary module goes away return mod_globals.copy() # This helper is needed due to a missing component in the PEP 302 # loader protocol (specifically, "get_filename" is non-standard) # Since we can't introduce new features in maintenance releases, # support was added to zipimporter under the name '_get_filename' def _get_filename(loader, mod_name): for attr in ("get_filename", "_get_filename"): meth = getattr(loader, attr, None) if meth is not None: return meth(mod_name) return None # Helper to get the loader, code and filename for a module def _get_module_details(mod_name): loader = get_loader(mod_name) if loader is None: raise ImportError("No module named %s" % mod_name) if loader.is_package(mod_name): if mod_name == "__main__" or mod_name.endswith(".__main__"): raise ImportError("Cannot use package as __main__ module") try: pkg_main_name = mod_name + ".__main__" return _get_module_details(pkg_main_name) except ImportError, e: raise ImportError(("%s; %r is a package and cannot " + "be directly executed") %(e, mod_name)) code = loader.get_code(mod_name) if code is None: raise ImportError("No code object available for %s" % mod_name) filename = _get_filename(loader, mod_name) return mod_name, loader, code, filename def _get_main_module_details(): # Helper that gives a nicer error message when attempting to # execute a zipfile or directory by invoking __main__.py main_name = "__main__" try: return _get_module_details(main_name) except ImportError as exc: if main_name in str(exc): raise ImportError("can't find %r module in %r" % (main_name, sys.path[0])) raise # This function is the actual implementation of the -m switch and direct # execution of zipfiles and directories and is deliberately kept private. # This avoids a repeat of the situation where run_module() no longer met the # needs of mainmodule.c, but couldn't be changed because it was public def _run_module_as_main(mod_name, alter_argv=True): """Runs the designated module in the __main__ namespace Note that the executed module will have full access to the __main__ namespace. If this is not desirable, the run_module() function should be used to run the module code in a fresh namespace. At the very least, these variables in __main__ will be overwritten: __name__ __file__ __loader__ __package__ """ try: if alter_argv or mod_name != "__main__": # i.e. -m switch mod_name, loader, code, fname = _get_module_details(mod_name) else: # i.e. directory or zipfile execution mod_name, loader, code, fname = _get_main_module_details() except ImportError as exc: msg = "%s: %s" % (sys.executable, str(exc)) sys.exit(msg) pkg_name = mod_name.rpartition('.')[0] main_globals = sys.modules["__main__"].__dict__ if alter_argv: sys.argv[0] = fname return _run_code(code, main_globals, None, "__main__", fname, loader, pkg_name) def run_module(mod_name, init_globals=None, run_name=None, alter_sys=False): """Execute a module's code without importing it Returns the resulting top level namespace dictionary """ mod_name, loader, code, fname = _get_module_details(mod_name) if run_name is None: run_name = mod_name pkg_name = mod_name.rpartition('.')[0] if alter_sys: return _run_module_code(code, init_globals, run_name, fname, loader, pkg_name) else: # Leave the sys module alone return _run_code(code, {}, init_globals, run_name, fname, loader, pkg_name) # XXX (ncoghlan): Perhaps expose the C API function # as imp.get_importer instead of reimplementing it in Python? def _get_importer(path_name): """Python version of PyImport_GetImporter C API function""" cache = sys.path_importer_cache try: importer = cache[path_name] except KeyError: # Not yet cached. Flag as using the # standard machinery until we finish # checking the hooks cache[path_name] = None for hook in sys.path_hooks: try: importer = hook(path_name) break except ImportError: pass else: # The following check looks a bit odd. The trick is that # NullImporter raises ImportError if the supplied path is a # *valid* directory entry (and hence able to be handled # by the standard import machinery) try: importer = imp.NullImporter(path_name) except ImportError: return None cache[path_name] = importer return importer def _get_code_from_file(fname): # Check for a compiled file first with open(fname, "rb") as f: code = read_code(f) if code is None: # That didn't work, so try it as normal source code with open(fname, "rU") as f: code = compile(f.read(), fname, 'exec') return code def run_path(path_name, init_globals=None, run_name=None): """Execute code located at the specified filesystem location Returns the resulting top level namespace dictionary The file path may refer directly to a Python script (i.e. one that could be directly executed with execfile) or else it may refer to a zipfile or directory containing a top level __main__.py script. """ if run_name is None: run_name = "<run_path>" importer = _get_importer(path_name) if isinstance(importer, imp.NullImporter): # Not a valid sys.path entry, so run the code directly # execfile() doesn't help as we want to allow compiled files code = _get_code_from_file(path_name) return _run_module_code(code, init_globals, run_name, path_name) else: # Importer is defined for path, so add it to # the start of sys.path sys.path.insert(0, path_name) try: # Here's where things are a little different from the run_module # case. There, we only had to replace the module in sys while the # code was running and doing so was somewhat optional. Here, we # have no choice and we have to remove it even while we read the # code. If we don't do this, a __loader__ attribute in the # existing __main__ module may prevent location of the new module. main_name = "__main__" saved_main = sys.modules[main_name] del sys.modules[main_name] try: mod_name, loader, code, fname = _get_main_module_details() finally: sys.modules[main_name] = saved_main pkg_name = "" with _TempModule(run_name) as temp_module, \ _ModifiedArgv0(path_name): mod_globals = temp_module.module.__dict__ return _run_code(code, mod_globals, init_globals, run_name, fname, loader, pkg_name).copy() finally: try: sys.path.remove(path_name) except ValueError: pass if __name__ == "__main__": # Run the module specified as the next command line argument if len(sys.argv) < 2: print >> sys.stderr, "No module specified for execution" else: del sys.argv[0] # Make the requested module sys.argv[0] _run_module_as_main(sys.argv[0])
{ "pile_set_name": "Github" }
ο»Ώusing System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using Newtonsoft.Json; using Duplicati.Library.Interface; namespace Duplicati.Library.Main.Volumes { public class IndexVolumeWriter : VolumeWriterBase { private StreamWriter m_streamwriter = null; private JsonWriter m_writer = null; private long m_volumes = 0; private long m_blocks = 0; private long m_blocklists = 0; public long VolumeCount { get { return m_volumes; } } public long BlockCount { get { return m_blocks; } } public long Blocklists { get { return m_blocklists; } } public IndexVolumeWriter(Options options) : base(options) { } public override RemoteVolumeType FileType { get { return RemoteVolumeType.Index; } } public void StartVolume(string filename) { if (m_writer != null || m_streamwriter != null) throw new InvalidOperationException("Previous volume not finished, call FinishVolume before starting a new volume"); m_volumes++; m_streamwriter = new StreamWriter(m_compression.CreateFile(INDEX_VOLUME_FOLDER + filename, CompressionHint.Compressible, DateTime.UtcNow)); m_writer = new JsonTextWriter(m_streamwriter); m_writer.WriteStartObject(); m_writer.WritePropertyName("blocks"); m_writer.WriteStartArray(); } public void AddBlock(string hash, long size) { m_writer.WriteStartObject(); m_writer.WritePropertyName("hash"); m_writer.WriteValue(hash); m_writer.WritePropertyName("size"); m_writer.WriteValue(size); m_writer.WriteEndObject(); m_blocks++; } public void FinishVolume(string volumehash, long volumesize) { m_writer.WriteEndArray(); m_writer.WritePropertyName("volumehash"); m_writer.WriteValue(volumehash); m_writer.WritePropertyName("volumesize"); m_writer.WriteValue(volumesize); m_writer.WriteEndObject(); try { m_writer.Close(); } finally { m_writer = null; } try { m_streamwriter.Dispose(); } finally { m_streamwriter = null; } } public void WriteBlocklist(string hash, byte[] data, int offset, int size) { if (size % m_blockhashsize != 0) throw new InvalidDataException($"Attempted to write a blocklist with {size} bytes which is not evenly divisible with {m_blockhashsize}"); m_blocklists++; //Filenames are encoded with "modified Base64 for URL" https://en.wikipedia.org/wiki/Base64#URL_applications, using (var s = m_compression.CreateFile(INDEX_BLOCKLIST_FOLDER + Library.Utility.Utility.Base64PlainToBase64Url(hash), CompressionHint.Noncompressible, DateTime.UtcNow)) s.Write(data, offset, size); } public void WriteBlocklist(string hash, Stream source) { m_blocklists++; //Filenames are encoded with "modified Base64 for URL" https://en.wikipedia.org/wiki/Base64#URL_applications, using (var s = m_compression.CreateFile(INDEX_BLOCKLIST_FOLDER + Library.Utility.Utility.Base64PlainToBase64Url(hash), CompressionHint.Noncompressible, DateTime.UtcNow)) { var size = Library.Utility.Utility.CopyStream(source, s); if (size % m_blockhashsize != 0) throw new InvalidDataException($"Wrote a blocklist with {size} bytes which is not evenly divisible with {m_blockhashsize}"); } } public void CopyFrom(IndexVolumeReader rd, Func<string, string> filename_mapping) { foreach(var n in rd.Volumes) { this.StartVolume(filename_mapping(n.Filename)); foreach(var x in n.Blocks) this.AddBlock(x.Key, x.Value); this.FinishVolume(n.Hash, n.Length); } foreach(var b in rd.BlockLists) using(var s = b.Data) this.WriteBlocklist(b.Hash, s); } public override void Dispose() { if (m_writer != null || m_streamwriter != null) throw new InvalidOperationException("Attempted to dispose an index volume that was being written"); base.Dispose(); } } }
{ "pile_set_name": "Github" }
package controllers; import java.math.BigDecimal; import apimodels.Client; import java.time.LocalDate; import java.time.OffsetDateTime; import apimodels.OuterComposite; import apimodels.User; import play.mvc.Controller; import play.mvc.Result; import play.mvc.Http; import java.util.List; import java.util.Map; import java.util.ArrayList; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.JsonNode; import com.google.inject.Inject; import java.io.File; import swagger.SwaggerUtils; import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; import play.Configuration; import swagger.SwaggerUtils.ApiAction; public class FakeApiController extends Controller { private final FakeApiControllerImpInterface imp; private final ObjectMapper mapper; private final Configuration configuration; @Inject private FakeApiController(Configuration configuration, FakeApiControllerImpInterface imp) { this.imp = imp; mapper = new ObjectMapper(); this.configuration = configuration; } @ApiAction public Result fakeOuterBooleanSerialize() throws Exception { JsonNode nodebody = request().body().asJson(); Boolean body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), Boolean.class); if (configuration.getBoolean("useInputBeanValidation")) { SwaggerUtils.validate(body); } } else { body = null; } Boolean obj = imp.fakeOuterBooleanSerialize(body); JsonNode result = mapper.valueToTree(obj); return ok(result); } @ApiAction public Result fakeOuterCompositeSerialize() throws Exception { JsonNode nodebody = request().body().asJson(); OuterComposite body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), OuterComposite.class); if (configuration.getBoolean("useInputBeanValidation")) { SwaggerUtils.validate(body); } } else { body = null; } OuterComposite obj = imp.fakeOuterCompositeSerialize(body); if (configuration.getBoolean("useOutputBeanValidation")) { SwaggerUtils.validate(obj); } JsonNode result = mapper.valueToTree(obj); return ok(result); } @ApiAction public Result fakeOuterNumberSerialize() throws Exception { JsonNode nodebody = request().body().asJson(); BigDecimal body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), BigDecimal.class); if (configuration.getBoolean("useInputBeanValidation")) { SwaggerUtils.validate(body); } } else { body = null; } BigDecimal obj = imp.fakeOuterNumberSerialize(body); if (configuration.getBoolean("useOutputBeanValidation")) { SwaggerUtils.validate(obj); } JsonNode result = mapper.valueToTree(obj); return ok(result); } @ApiAction public Result fakeOuterStringSerialize() throws Exception { JsonNode nodebody = request().body().asJson(); String body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), String.class); if (configuration.getBoolean("useInputBeanValidation")) { SwaggerUtils.validate(body); } } else { body = null; } String obj = imp.fakeOuterStringSerialize(body); JsonNode result = mapper.valueToTree(obj); return ok(result); } @ApiAction public Result testBodyWithQueryParams() throws Exception { JsonNode nodebody = request().body().asJson(); User body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), User.class); if (configuration.getBoolean("useInputBeanValidation")) { SwaggerUtils.validate(body); } } else { throw new IllegalArgumentException("'body' parameter is required"); } String valuequery = request().getQueryString("query"); String query; if (valuequery != null) { query = valuequery; } else { throw new IllegalArgumentException("'query' parameter is required"); } imp.testBodyWithQueryParams(body, query); return ok(); } @ApiAction public Result testClientModel() throws Exception { JsonNode nodebody = request().body().asJson(); Client body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), Client.class); if (configuration.getBoolean("useInputBeanValidation")) { SwaggerUtils.validate(body); } } else { throw new IllegalArgumentException("'body' parameter is required"); } Client obj = imp.testClientModel(body); if (configuration.getBoolean("useOutputBeanValidation")) { SwaggerUtils.validate(obj); } JsonNode result = mapper.valueToTree(obj); return ok(result); } @ApiAction public Result testEndpointParameters() throws Exception { String valueinteger = (request().body().asMultipartFormData().asFormUrlEncoded().get("integer"))[0]; Integer integer; if (valueinteger != null) { integer = Integer.parseInt(valueinteger); } else { integer = null; } String valueint32 = (request().body().asMultipartFormData().asFormUrlEncoded().get("int32"))[0]; Integer int32; if (valueint32 != null) { int32 = Integer.parseInt(valueint32); } else { int32 = null; } String valueint64 = (request().body().asMultipartFormData().asFormUrlEncoded().get("int64"))[0]; Long int64; if (valueint64 != null) { int64 = Long.parseLong(valueint64); } else { int64 = null; } String valuenumber = (request().body().asMultipartFormData().asFormUrlEncoded().get("number"))[0]; BigDecimal number; if (valuenumber != null) { number = new BigDecimal(valuenumber); } else { throw new IllegalArgumentException("'number' parameter is required"); } String value_float = (request().body().asMultipartFormData().asFormUrlEncoded().get("float"))[0]; Float _float; if (value_float != null) { _float = Float.parseFloat(value_float); } else { _float = null; } String value_double = (request().body().asMultipartFormData().asFormUrlEncoded().get("double"))[0]; Double _double; if (value_double != null) { _double = Double.parseDouble(value_double); } else { throw new IllegalArgumentException("'double' parameter is required"); } String valuestring = (request().body().asMultipartFormData().asFormUrlEncoded().get("string"))[0]; String string; if (valuestring != null) { string = valuestring; } else { string = null; } String valuepatternWithoutDelimiter = (request().body().asMultipartFormData().asFormUrlEncoded().get("pattern_without_delimiter"))[0]; String patternWithoutDelimiter; if (valuepatternWithoutDelimiter != null) { patternWithoutDelimiter = valuepatternWithoutDelimiter; } else { throw new IllegalArgumentException("'pattern_without_delimiter' parameter is required"); } String value_byte = (request().body().asMultipartFormData().asFormUrlEncoded().get("byte"))[0]; byte[] _byte; if (value_byte != null) { _byte = value_byte.getBytes(); } else { throw new IllegalArgumentException("'byte' parameter is required"); } String valuebinary = (request().body().asMultipartFormData().asFormUrlEncoded().get("binary"))[0]; byte[] binary; if (valuebinary != null) { binary = valuebinary.getBytes(); } else { binary = null; } String valuedate = (request().body().asMultipartFormData().asFormUrlEncoded().get("date"))[0]; LocalDate date; if (valuedate != null) { date = LocalDate.parse(valuedate); } else { date = null; } String valuedateTime = (request().body().asMultipartFormData().asFormUrlEncoded().get("dateTime"))[0]; OffsetDateTime dateTime; if (valuedateTime != null) { dateTime = OffsetDateTime.parse(valuedateTime); } else { dateTime = null; } String valuepassword = (request().body().asMultipartFormData().asFormUrlEncoded().get("password"))[0]; String password; if (valuepassword != null) { password = valuepassword; } else { password = null; } String valueparamCallback = (request().body().asMultipartFormData().asFormUrlEncoded().get("callback"))[0]; String paramCallback; if (valueparamCallback != null) { paramCallback = valueparamCallback; } else { paramCallback = null; } imp.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); return ok(); } @ApiAction public Result testEnumParameters() throws Exception { String[] enumQueryStringArrayArray = request().queryString().get("enum_query_string_array"); List<String> enumQueryStringArrayList = SwaggerUtils.parametersToList("csv", enumQueryStringArrayArray); List<String> enumQueryStringArray = new ArrayList<String>(); for (String curParam : enumQueryStringArrayList) { if (!curParam.isEmpty()) { //noinspection UseBulkOperation enumQueryStringArray.add(curParam); } } String valueenumQueryString = request().getQueryString("enum_query_string"); String enumQueryString; if (valueenumQueryString != null) { enumQueryString = valueenumQueryString; } else { enumQueryString = "-efg"; } String valueenumQueryInteger = request().getQueryString("enum_query_integer"); Integer enumQueryInteger; if (valueenumQueryInteger != null) { enumQueryInteger = Integer.parseInt(valueenumQueryInteger); } else { enumQueryInteger = null; } String[] enumFormStringArrayArray = request().body().asMultipartFormData().asFormUrlEncoded().get("enum_form_string_array"); List<String> enumFormStringArrayList = SwaggerUtils.parametersToList("csv", enumFormStringArrayArray); List<String> enumFormStringArray = new ArrayList<String>(); for (String curParam : enumFormStringArrayList) { if (!curParam.isEmpty()) { //noinspection UseBulkOperation enumFormStringArray.add(curParam); } } String valueenumFormString = (request().body().asMultipartFormData().asFormUrlEncoded().get("enum_form_string"))[0]; String enumFormString; if (valueenumFormString != null) { enumFormString = valueenumFormString; } else { enumFormString = "-efg"; } String valueenumQueryDouble = (request().body().asMultipartFormData().asFormUrlEncoded().get("enum_query_double"))[0]; Double enumQueryDouble; if (valueenumQueryDouble != null) { enumQueryDouble = Double.parseDouble(valueenumQueryDouble); } else { enumQueryDouble = null; } String[] enumHeaderStringArrayArray = request().headers().get("enum_header_string_array"); List<String> enumHeaderStringArrayList = SwaggerUtils.parametersToList("csv", enumHeaderStringArrayArray); List<String> enumHeaderStringArray = new ArrayList<String>(); for (String curParam : enumHeaderStringArrayList) { if (!curParam.isEmpty()) { //noinspection UseBulkOperation enumHeaderStringArray.add(curParam); } } String valueenumHeaderString = request().getHeader("enum_header_string"); String enumHeaderString; if (valueenumHeaderString != null) { enumHeaderString = valueenumHeaderString; } else { enumHeaderString = "-efg"; } imp.testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); return ok(); } @ApiAction public Result testInlineAdditionalProperties() throws Exception { JsonNode nodeparam = request().body().asJson(); Object param; if (nodeparam != null) { param = mapper.readValue(nodeparam.toString(), Object.class); if (configuration.getBoolean("useInputBeanValidation")) { SwaggerUtils.validate(param); } } else { throw new IllegalArgumentException("'param' parameter is required"); } imp.testInlineAdditionalProperties(param); return ok(); } @ApiAction public Result testJsonFormData() throws Exception { String valueparam = (request().body().asMultipartFormData().asFormUrlEncoded().get("param"))[0]; String param; if (valueparam != null) { param = valueparam; } else { throw new IllegalArgumentException("'param' parameter is required"); } String valueparam2 = (request().body().asMultipartFormData().asFormUrlEncoded().get("param2"))[0]; String param2; if (valueparam2 != null) { param2 = valueparam2; } else { throw new IllegalArgumentException("'param2' parameter is required"); } imp.testJsonFormData(param, param2); return ok(); } }
{ "pile_set_name": "Github" }
/* * JBoss, Home of Professional Open Source * Copyright 2015, Red Hat, Inc. and/or its affiliates, and individual * contributors by the @authors tag. See the copyright.txt in the * distribution for a full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.quickstarts.loggingToolsQS.loggers; import org.jboss.logging.BasicLogger; import org.jboss.logging.Logger; import org.jboss.logging.Logger.Level; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; @MessageLogger(projectCode = "GTRDATES") public interface DateLogger extends BasicLogger { DateLogger LOGGER = Logger.getMessageLogger(DateLogger.class, DateLogger.class.getPackage().getName()); @LogMessage(level = Level.ERROR) @Message(id = 3, value = "Invalid date passed as string: %s") void logStringCouldntParseAsDate(String dateString, @Cause Throwable exception); @LogMessage @Message(id = 4, value = "Requested number of days until '%s'") void logDaysUntilRequest(String dateString); }
{ "pile_set_name": "Github" }
{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Using TensorFlow backend.\n" ] } ], "source": [ "import numpy as np\n", "import json\n", "from keras.models import Model\n", "from keras.layers import Input\n", "from keras.layers.convolutional import Conv2D\n", "from keras import backend as K\n", "from collections import OrderedDict" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def format_decimal(arr, places=6):\n", " return [round(x * 10**places) / 10**places for x in arr]" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": true }, "outputs": [], "source": [ "DATA = OrderedDict()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### pipeline 1" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": true }, "outputs": [], "source": [ "random_seed = 1000\n", "data_in_shape = (17, 17, 2)\n", "\n", "layers = [\n", " Conv2D(5, (3,3), activation='relu', padding='same', strides=(2, 2), data_format='channels_last', use_bias=True),\n", " Conv2D(4, (3,3), activation='linear', padding='same', strides=(1, 1), data_format='channels_last', use_bias=True),\n", " Conv2D(2, (3,3), activation='relu', padding='valid', strides=(1, 1), data_format='channels_last', use_bias=True),\n", " Conv2D(3, (5,5), activation='relu', padding='valid', strides=(1, 1), data_format='channels_last', use_bias=True),\n", " Conv2D(2, (3,3), activation='linear', padding='valid', strides=(1, 1), data_format='channels_last', use_bias=True)\n", "]\n", "\n", "input_layer = Input(shape=data_in_shape)\n", "x = layers[0](input_layer)\n", "for layer in layers[1:-1]:\n", " x = layer(x)\n", "output_layer = layers[-1](x)\n", "model = Model(inputs=input_layer, outputs=output_layer)\n", "\n", "np.random.seed(random_seed)\n", "data_in = 2 * np.random.random(data_in_shape) - 1\n", "\n", "# set weights to random (use seed for reproducibility)\n", "weights = []\n", "for i, w in enumerate(model.get_weights()):\n", " np.random.seed(random_seed + i)\n", " weights.append(2 * np.random.random(w.shape) - 1)\n", "model.set_weights(weights)\n", "\n", "result = model.predict(np.array([data_in]))\n", "data_out_shape = result[0].shape\n", "data_in_formatted = format_decimal(data_in.ravel().tolist())\n", "data_out_formatted = format_decimal(result[0].ravel().tolist())\n", "\n", "DATA['pipeline_01'] = {\n", " 'input': {'data': data_in_formatted, 'shape': data_in_shape},\n", " 'weights': [{'data': format_decimal(w.ravel().tolist()), 'shape': w.shape} for w in weights],\n", " 'expected': {'data': data_out_formatted, 'shape': data_out_shape}\n", "}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### export for Keras.js tests" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import os\n", "\n", "filename = '../../test/data/pipeline/01.json'\n", "if not os.path.exists(os.path.dirname(filename)):\n", " os.makedirs(os.path.dirname(filename))\n", "with open(filename, 'w') as f:\n", " json.dump(DATA, f)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{\"pipeline_01\": {\"input\": {\"data\": [0.307179, -0.769986, 0.900566, -0.035617, 0.744949, -0.575335, -0.918581, -0.205611, -0.533736, 0.683481, -0.585835, 0.484939, -0.215692, -0.635487, 0.487079, -0.860836, 0.770674, 0.905289, 0.862287, -0.169138, -0.942037, 0.964055, -0.320725, 0.413374, -0.276246, -0.929788, 0.710117, 0.314507, 0.531366, 0.108174, 0.770186, 0.808395, -0.979157, -0.850887, -0.510742, -0.73339, 0.39585, -0.20359, 0.766244, -0.637985, -0.135002, -0.963714, 0.382876, -0.060619, -0.743556, 0.782674, 0.836407, -0.853758, -0.909104, -0.122854, 0.203442, -0.379546, 0.363816, -0.581974, 0.039209, 0.131978, -0.117665, -0.724888, -0.572914, -0.733256, -0.355407, -0.532226, 0.054996, 0.131942, -0.123549, -0.356255, 0.119282, 0.730691, 0.694566, -0.784366, -0.367361, -0.181043, 0.374178, 0.404471, -0.107604, -0.159356, 0.605261, 0.077235, 0.847001, -0.876185, -0.264833, 0.940798, 0.398208, 0.781951, -0.492895, 0.451054, -0.593011, 0.075024, -0.526114, -0.127016, 0.596049, -0.383182, 0.243033, -0.120704, 0.826647, 0.317372, 0.307263, -0.283084, 0.045883, -0.909825, -0.811381, 0.843224, -0.853911, 0.858835, 0.43403, 0.244621, 0.509979, -0.71666, 0.587644, 0.450806, 0.082879, -0.034831, -0.047045, -0.107934, 0.63214, -0.451297, -0.876076, 0.920593, -0.083764, 0.515784, 0.362317, 0.083556, -0.734335, -0.493589, -0.112289, 0.1175, 0.627729, -0.364343, -0.20591, 0.780336, 0.650832, -0.786626, -0.680448, 0.302439, 0.138128, 0.968167, 0.498318, 0.604799, -0.54338, 0.037427, 0.260217, -0.995629, 0.02643, -0.10162, -0.301287, -0.452637, 0.804166, -0.938051, -0.351662, -0.426815, 0.914272, -0.966934, -0.085353, -0.350128, 0.392927, 0.3855, 0.365292, 0.784261, 0.891156, -0.836385, -0.766222, -0.926262, 0.84758, 0.963802, -0.246749, -0.873048, -0.744287, 0.759778, -0.091904, -0.601018, 0.252064, 0.552859, -0.070904, -0.919266, -0.252198, 0.733837, -0.793589, -0.774978, 0.560268, -0.729902, -0.742883, -0.518994, -0.416378, -0.333527, 0.584328, -0.511306, -0.78923, -0.765839, -0.281298, -0.532119, 0.65626, 0.221575, -0.420019, 0.994877, -0.161517, 0.789445, -0.423508, -0.37311, 0.961123, -0.821726, 0.760378, 0.920009, -0.318366, 0.831071, 0.797277, 0.998735, -0.764629, 0.190218, 0.571854, 0.451473, 0.659159, -0.961103, 0.893633, -0.673254, -0.945135, 0.958047, -0.630267, 0.668912, -0.97545, -0.932668, -0.855912, 0.273892, -0.508473, -0.147774, 0.92673, -0.589615, -0.529108, -0.026501, -0.442497, 0.043248, -0.097879, -0.32872, -0.976222, 0.516042, 0.77989, -0.275965, -0.066363, -0.878685, 0.477652, -0.531969, -0.738158, -0.719768, -0.598863, 0.459657, -0.136082, 0.397067, -0.716891, -0.552125, 0.645655, -0.992376, -0.547147, 0.675121, 0.359423, -0.452114, 0.642834, -0.65893, 0.084555, 0.198223, 0.947512, 0.347592, -0.30919, 0.017157, -0.504988, 0.975185, -0.18213, -0.827767, 0.962281, 0.793245, 0.066392, -0.929715, 0.675438, 0.807816, 0.260682, -0.437998, 0.865408, -0.964172, -0.358725, -0.297628, 0.698402, -0.991327, 0.296135, 0.111031, -0.325199, -0.829535, -0.706708, 0.315692, -0.908343, -0.876177, -0.084321, 0.042117, -0.96889, 0.065587, -0.761545, -0.771358, 0.370507, -0.371447, 0.567487, 0.906827, 0.306348, 0.991507, -0.251738, -0.179506, -0.13481, 0.009328, 0.50426, -0.478935, -0.23036, 0.482967, 0.108361, 0.323875, -0.107073, 0.484604, 0.976787, -0.757528, 0.55991, -0.087214, -0.45433, 0.964335, -0.710762, -0.223378, 0.338984, -0.566817, -0.423957, -0.133355, 0.771202, -0.348399, 0.698459, -0.553718, 0.362846, 0.765188, -0.810349, 0.415447, -0.261726, 0.141378, 0.394877, -0.236814, -0.136671, -0.605446, -0.816587, -0.834155, -0.867417, -0.005713, 0.832653, -0.74534, 0.015888, -0.859369, 0.263748, -0.514297, -0.724415, -0.519365, -0.26064, 0.562583, 0.556172, -0.894421, 0.485605, 0.068895, -0.574381, 0.952707, 0.854282, -0.816716, 0.566863, -0.851922, -0.304581, 0.940295, -0.092955, -0.252095, -0.366209, 0.8118, 0.609144, 0.66955, 0.296141, -0.522011, -0.547367, -0.046487, -0.141129, -0.683622, -0.608246, -0.942115, 0.200807, -0.171167, 0.913158, -0.576902, -0.177556, -0.085063, 0.942418, -0.803642, -0.231319, 0.110499, 0.216448, 0.554095, -0.775795, -0.858061, -0.894796, -0.177721, 0.812784, 0.032743, 0.14351, 0.759765, -0.70414, -0.310653, -0.70489, -0.174463, -0.927175, -0.788743, -0.979671, 0.48012, 0.132285, -0.671046, -0.958749, 0.945391, 0.040751, -0.738711, 0.822168, 0.910797, 0.662187, 0.325641, -0.134855, 0.310373, -0.499573, 0.135194, 0.376075, 0.742203, -0.185185, 0.681693, -0.614504, 0.345224, 0.663712, 0.014513, 0.42408, 0.833134, -0.260953, -0.078377, -0.933143, -0.000877, -0.478206, 0.430175, -0.840631, 0.428118, 0.846154, -0.40912, 0.509388, 0.669512, 0.756252, -0.375561, -0.551532, 0.88488, 0.436005, -0.751576, -0.563339, 0.004887, 0.137054, 0.19583, -0.215128, -0.232628, -0.257705, 0.010894, -0.638739, 0.98891, 0.761058, 0.692921, 0.183508, 0.590217, -0.769043, 0.707619, -0.393498, 0.806385, -0.468566, -0.96876, 0.760738, 0.436183, -0.535061, -0.5628, 0.886738, 0.816212, 0.004339, -0.891716, 0.782022, 0.107881, 0.594794, 0.171877, -0.817309, 0.675026, 0.824638, -0.890092, -0.45473, -0.371234, 0.087631, -0.569719, -0.864876, 0.215788, 0.716897, 0.727561, -0.569618, -0.850193, 0.307958, -0.477611, 0.660603, 0.779336, 0.535998, -0.280336, -0.701544, -0.055577, 0.706065, 0.288925, -0.635776, -0.431255, 0.831398, 0.454381, 0.062509, 0.856797, -0.675694, -0.783077, 0.829229, 0.012088, 0.298661, -0.092186, 0.103526, 0.322325, -0.303668, 0.574324, -0.879712, 0.924606, -0.743586, -0.737669, -0.977774, -0.04452, 0.338219, -0.214654, -0.549583, 0.314906, -0.659444, -0.128102, 0.719527, 0.643744, 0.405795, 0.500263, -0.968486, -0.103665, 0.381867, -0.002469, -0.078127, 0.806476, -0.87487, -0.409392, 0.632035, -0.159183, -0.01837, -0.464667, 0.171106, 0.491622, -0.939924, 0.929357, 0.889669, 0.693238, -0.425875, -0.792446, 0.992246, -0.714005, 0.477842, 0.014597, 0.088993, 0.478136, -0.63804, -0.777092, -0.704203, 0.141475, -0.285228, 0.287741, 0.136988, 0.121701, 0.481481, 0.098355, -0.759691, 0.258656, 0.925657, 0.56495, 0.004887, 0.934166], \"shape\": [17, 17, 2]}, \"weights\": [{\"data\": [0.307179, -0.769986, 0.900566, -0.035617, 0.744949, -0.575335, -0.918581, -0.205611, -0.533736, 0.683481, -0.585835, 0.484939, -0.215692, -0.635487, 0.487079, -0.860836, 0.770674, 0.905289, 0.862287, -0.169138, -0.942037, 0.964055, -0.320725, 0.413374, -0.276246, -0.929788, 0.710117, 0.314507, 0.531366, 0.108174, 0.770186, 0.808395, -0.979157, -0.850887, -0.510742, -0.73339, 0.39585, -0.20359, 0.766244, -0.637985, -0.135002, -0.963714, 0.382876, -0.060619, -0.743556, 0.782674, 0.836407, -0.853758, -0.909104, -0.122854, 0.203442, -0.379546, 0.363816, -0.581974, 0.039209, 0.131978, -0.117665, -0.724888, -0.572914, -0.733256, -0.355407, -0.532226, 0.054996, 0.131942, -0.123549, -0.356255, 0.119282, 0.730691, 0.694566, -0.784366, -0.367361, -0.181043, 0.374178, 0.404471, -0.107604, -0.159356, 0.605261, 0.077235, 0.847001, -0.876185, -0.264833, 0.940798, 0.398208, 0.781951, -0.492895, 0.451054, -0.593011, 0.075024, -0.526114, -0.127016], \"shape\": [3, 3, 2, 5]}, {\"data\": [-0.387536, -0.469873, -0.60788, -0.138957, -0.953773], \"shape\": [5]}, {\"data\": [-0.742023, -0.077688, -0.167692, 0.205448, -0.633864, -0.164175, -0.731823, 0.313236, 0.613465, -0.723716, -0.299231, 0.229032, 0.102561, 0.384949, -0.90948, -0.294898, -0.916217, -0.699031, -0.323329, -0.673445, 0.521949, -0.306796, -0.476018, -0.628623, 0.808028, -0.585043, -0.307429, -0.234868, -0.897584, 0.741743, 0.320785, 0.709132, -0.978084, 0.601894, -0.228816, -0.069558, -0.522066, -0.399597, -0.916222, 0.161549, -0.211915, 0.823372, -0.6549, -0.30403, 0.677588, -0.431259, 0.219659, -0.091937, -0.101636, -0.595218, -0.815428, 0.502932, 0.775249, 0.624226, 0.622601, -0.091075, 0.763603, 0.472659, 0.621131, -0.504549, -0.270214, 0.492749, 0.643055, -0.290058, -0.752162, 0.758918, 0.011832, -0.183967, 0.768298, 0.764241, 0.906398, 0.872853, -0.292238, 0.16788, -0.447741, 0.679196, 0.566614, 0.867549, -0.011606, -0.252108, 0.165669, -0.509362, 0.620632, -0.32465, -0.071143, -0.823613, 0.331067, -0.016903, -0.76138, -0.491146, 0.106088, -0.641492, 0.234893, 0.658853, -0.475623, 0.269103, 0.935505, -0.577134, 0.985015, -0.405957, -0.325882, 0.849518, -0.589155, 0.378331, -0.753075, 0.711411, 0.04547, 0.398327, -0.665657, 0.531142, -0.410293, -0.526649, 0.860648, 0.32795, -0.197082, -0.095526, -0.391361, 0.785465, -0.267269, -0.020154, -0.95189, -0.580742, 0.788104, -0.092433, 0.320354, 0.070651, 0.045416, 0.99799, 0.583116, -0.708131, -0.104784, -0.838947, -0.598224, 0.209105, 0.824956, 0.10438, 0.692046, -0.091308, 0.884896, 0.730617, 0.244486, -0.415624, -0.397714, -0.647236, -0.816162, 0.001325, 0.593873, -0.243723, 0.168275, 0.192345, -0.522916, 0.458154, -0.333828, -0.014549, -0.744552, -0.203297, 0.771256, -0.703928, 0.998892, -0.947633, 0.566086, -0.274437, -0.218108, -0.800599, 0.504541, 0.233776, -0.111802, -0.03089, 0.761595, 0.537963, 0.217941, -0.910822, 0.531235, -0.018533, -0.161811, -0.200401, -0.742618, -0.35126, -0.954474, -0.071092], \"shape\": [3, 3, 5, 4]}, {\"data\": [0.195612, -0.128132, -0.96626, 0.193375], \"shape\": [4]}, {\"data\": [-0.922097, 0.712992, 0.493001, 0.727856, 0.119969, -0.839034, -0.536727, -0.515472, 0.231, 0.214218, -0.791636, -0.148304, 0.309846, 0.742779, -0.123022, 0.427583, -0.882276, 0.818571, 0.043634, 0.454859, -0.007311, -0.744895, -0.368229, 0.324805, -0.388758, -0.556215, -0.542859, 0.685655, 0.350785, -0.312753, 0.591401, 0.95999, 0.136369, -0.58844, -0.506667, -0.208736, 0.548969, 0.653173, 0.128943, 0.180094, -0.16098, 0.208798, 0.666245, 0.347307, -0.384733, -0.88354, -0.328468, -0.515324, 0.479247, -0.360647, 0.09069, -0.221424, 0.091284, 0.202631, 0.208087, 0.582248, -0.164064, -0.925036, -0.678806, -0.212846, 0.960861, 0.536089, -0.038634, -0.473456, -0.409408, 0.620315, -0.873085, -0.695405, -0.024465, 0.762843, -0.928228, 0.557106], \"shape\": [3, 3, 4, 2]}, {\"data\": [0.318429, -0.858397], \"shape\": [2]}, {\"data\": [0.486255, -0.547151, 0.285068, 0.764711, 0.481398, 0.442527, -0.409304, 0.051033, -0.652471, 0.623918, 0.698811, -0.48696, -0.525531, -0.083229, -0.54216, -0.595979, 0.965361, 0.961457, 0.469608, -0.18139, 0.237622, -0.841546, -0.201479, 0.210842, -0.099026, -0.017468, -0.270985, -0.421947, 0.990418, 0.633556, -0.46994, -0.283905, 0.339371, 0.851372, -0.963439, 0.672347, -0.592494, 0.115008, 0.77155, -0.629049, -0.284972, 0.08256, -0.526964, -0.579017, 0.048964, 0.296374, -0.503246, -0.95555, -0.759658, -0.148746, 0.527992, 0.419541, -0.601167, -0.246472, 0.611566, -0.47989, -0.796678, 0.845136, -0.929013, 0.081316, -0.965527, 0.064677, 0.687209, -0.781686, 0.556524, -0.294628, 0.343468, -0.693394, -0.864068, 0.522942, -0.854592, 0.954066, 0.352462, 0.404271, 0.935993, 0.006064, -0.614327, -0.951249, -0.974544, -0.981322, -0.524456, -0.353175, -0.283883, 0.270072, 0.336334, -0.529043, 0.880513, -0.663035, -0.709319, -0.69236, 0.233949, 0.90419, -0.721928, 0.580281, -0.149192, -0.246252, 0.099723, 0.986128, -0.979644, 0.242715, 0.433547, 0.199869, -0.572331, -0.152181, 0.329916, -0.071652, -0.580827, 0.88984, -0.857622, -0.926973, -0.444937, -0.183938, 0.72548, -0.238406, -0.651195, -0.770945, -0.97797, -0.666038, 0.253825, 0.001102, -0.769608, -0.364219, 0.653122, -0.845224, -0.900383, 0.916435, 0.562575, 0.577639, -0.655935, 0.683806, -0.955929, 0.271965, 0.670582, -0.874893, -0.671992, -0.124948, 0.354001, -0.289044, -0.880824, -0.505697, 0.975131, -0.404046, 0.345771, -0.013626, -0.077943, 0.837888, -0.371654, 0.453362, 0.331138, -0.360725], \"shape\": [5, 5, 2, 3]}, {\"data\": [0.0965, 0.594443, -0.987782], \"shape\": [3]}, {\"data\": [0.228005, 0.859479, -0.49018, 0.232871, -0.303968, -0.799141, 0.621228, 0.850429, 0.029476, -0.583346, 0.889636, -0.128896, 0.067108, -0.1059, -0.788773, -0.559347, 0.674802, 0.513275, -0.95495, -0.230976, -0.430566, 0.607782, -0.292593, -0.362274, -0.825576, 0.904458, 0.531651, 0.139053, -0.797761, 0.905804, -0.875903, 0.04377, -0.704592, 0.203555, -0.083031, 0.321316, 0.334565, 0.965166, 0.31912, 0.987618, 0.11275, 0.755438, 0.133156, -0.271605, -0.739053, 0.930942, 0.723852, -0.399546, 0.365907, 0.680404, 0.302211, 0.481088, -0.254831, -0.719056], \"shape\": [3, 3, 3, 2]}, {\"data\": [0.229761, -0.670851], \"shape\": [2]}], \"expected\": {\"data\": [1.396554, 4.630284], \"shape\": [1, 1, 2]}}}\n" ] } ], "source": [ "print(json.dumps(DATA))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "metadata": { "anaconda-cloud": {}, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.3" } }, "nbformat": 4, "nbformat_minor": 2 }
{ "pile_set_name": "Github" }
<?php namespace phpbu\App\Backup\Cleaner; use phpbu\App\Backup\Cleaner; use phpbu\App\Backup\Collector; use phpbu\App\Result; use phpbu\App\Backup\Target; /** * Simulator interface. * * @package phpbu * @subpackage Backup * @author Sebastian Feldmann <sebastian@phpbu.de> * @copyright Sebastian Feldmann <sebastian@phpbu.de> * @license https://opensource.org/licenses/MIT The MIT License (MIT) * @link http://phpbu.de/ * @since Class available since Release 3.0.0 */ interface Simulator extends Cleaner { /** * Simulate the cleanup execution. * * @param \phpbu\App\Backup\Target $target * @param \phpbu\App\Backup\Collector $collector * @param \phpbu\App\Result $result */ public function simulate(Target $target, Collector $collector, Result $result); }
{ "pile_set_name": "Github" }
framework module Pods_DemoApp { umbrella header "Pods-DemoApp-umbrella.h" export * module * { export * } }
{ "pile_set_name": "Github" }
@file:Suppress("NOTHING_TO_INLINE") package io.ktor.utils.io.bits import io.ktor.utils.io.core.internal.* import java.nio.* @Suppress("ACTUAL_WITHOUT_EXPECT", "EXPERIMENTAL_FEATURE_WARNING") public actual inline class Memory @DangerousInternalIoApi constructor(public val buffer: ByteBuffer) { /** * Size of memory range in bytes. */ public actual inline val size: Long get() = buffer.limit().toLong() /** * Size of memory range in bytes represented as signed 32bit integer * @throws IllegalStateException when size doesn't fit into a signed 32bit integer */ public actual inline val size32: Int get() = buffer.limit() /** * Returns byte at [index] position. */ public actual inline fun loadAt(index: Int): Byte = buffer.get(index) /** * Returns byte at [index] position. */ public actual inline fun loadAt(index: Long): Byte = buffer.get(index.toIntOrFail("index")) /** * Write [value] at the specified [index]. */ public actual inline fun storeAt(index: Int, value: Byte) { buffer.put(index, value) } /** * Write [value] at the specified [index] */ public actual inline fun storeAt(index: Long, value: Byte) { buffer.put(index.toIntOrFail("index"), value) } public actual fun slice(offset: Int, length: Int): Memory = Memory(buffer.sliceSafe(offset, length)) public actual fun slice(offset: Long, length: Long): Memory { return slice(offset.toIntOrFail("offset"), length.toIntOrFail("length")) } /** * Copies bytes from this memory range from the specified [offset] and [length] * to the [destination] at [destinationOffset]. * Copying bytes from a memory to itself is allowed. */ public actual fun copyTo(destination: Memory, offset: Int, length: Int, destinationOffset: Int) { if (buffer.hasArray() && destination.buffer.hasArray() && !buffer.isReadOnly && !destination.buffer.isReadOnly ) { System.arraycopy( buffer.array(), buffer.arrayOffset() + offset, destination.buffer.array(), destination.buffer.arrayOffset() + destinationOffset, length ) return } // NOTE: it is ok here to make copy since it will be escaped by JVM // while temporary moving position/offset makes memory concurrent unsafe that is unacceptable val srcCopy = buffer.duplicate().apply { position(offset) limit(offset + length) } val dstCopy = destination.buffer.duplicate().apply { position(destinationOffset) } dstCopy.put(srcCopy) } /** * Copies bytes from this memory range from the specified [offset] and [length] * to the [destination] at [destinationOffset]. * Copying bytes from a memory to itself is allowed. */ public actual fun copyTo(destination: Memory, offset: Long, length: Long, destinationOffset: Long) { copyTo( destination, offset.toIntOrFail("offset"), length.toIntOrFail("length"), destinationOffset.toIntOrFail("destinationOffset") ) } public actual companion object { public actual val Empty: Memory = Memory(ByteBuffer.allocate(0).order(ByteOrder.BIG_ENDIAN)) } } /** * Copies bytes from this memory range from the specified [offset] and [length] * to the [destination] at [destinationOffset]. */ public actual fun Memory.copyTo( destination: ByteArray, offset: Int, length: Int, destinationOffset: Int ) { if (buffer.hasArray() && !buffer.isReadOnly) { System.arraycopy( buffer.array(), buffer.arrayOffset() + offset, destination, destinationOffset, length ) return } // we need to make a copy to prevent moving position buffer.duplicate().get(destination, destinationOffset, length) } /** * Copies bytes from this memory range from the specified [offset] and [length] * to the [destination] at [destinationOffset]. */ public actual fun Memory.copyTo( destination: ByteArray, offset: Long, length: Int, destinationOffset: Int ) { copyTo(destination, offset.toIntOrFail("offset"), length, destinationOffset) } /** * Copies bytes from this memory range from the specified [offset] * to the [destination] buffer. */ public fun Memory.copyTo( destination: ByteBuffer, offset: Int ) { val size = destination.remaining() if (buffer.hasArray() && !buffer.isReadOnly && destination.hasArray() && !destination.isReadOnly) { val dstPosition = destination.position() System.arraycopy( buffer.array(), buffer.arrayOffset() + offset, destination.array(), destination.arrayOffset() + dstPosition, size ) destination.position(dstPosition + size) return } // we need to make a copy to prevent moving position val source = buffer.duplicate().apply { limit(offset + size) position(offset) } destination.put(source) } /** * Copies bytes from this memory range from the specified [offset] * to the [destination] buffer. */ public fun Memory.copyTo(destination: ByteBuffer, offset: Long) { copyTo(destination, offset.toIntOrFail("offset")) } /** * Copy byte from this buffer moving it's position to the [destination] at [offset]. */ public fun ByteBuffer.copyTo(destination: Memory, offset: Int) { if (hasArray() && !isReadOnly) { destination.storeByteArray(offset, array(), arrayOffset() + position(), remaining()) position(limit()) return } destination.buffer.sliceSafe(offset, remaining()).put(this) } private inline fun ByteBuffer.myDuplicate(): ByteBuffer { duplicate().apply { return suppressNullCheck() } } private inline fun ByteBuffer.mySlice(): ByteBuffer { slice().apply { return suppressNullCheck() } } private inline fun ByteBuffer.suppressNullCheck(): ByteBuffer { return this } internal fun ByteBuffer.sliceSafe(offset: Int, length: Int): ByteBuffer { return myDuplicate().apply { position(offset); limit(offset + length) }.mySlice() } /** * Fill memory range starting at the specified [offset] with [value] repeated [count] times. */ public actual fun Memory.fill(offset: Long, count: Long, value: Byte) { fill(offset.toIntOrFail("offset"), count.toIntOrFail("count"), value) } /** * Fill memory range starting at the specified [offset] with [value] repeated [count] times. */ public actual fun Memory.fill(offset: Int, count: Int, value: Byte) { for (index in offset until offset + count) { buffer.put(index, value) } }
{ "pile_set_name": "Github" }
"use strict"; module.exports = exports = build; exports.usage = 'Attempts to compile the module by dispatching to node-gyp or nw-gyp'; var compile = require('./util/compile.js'); var handle_gyp_opts = require('./util/handle_gyp_opts.js'); var configure = require('./configure.js'); function do_build(gyp,argv,callback) { handle_gyp_opts(gyp,argv,function(err,result) { var final_args = ['build'].concat(result.gyp).concat(result.pre); if (result.unparsed.length > 0) { final_args = final_args. concat(['--']). concat(result.unparsed); } compile.run_gyp(final_args,result.opts,function(err) { return callback(err); }); }); } function build(gyp, argv, callback) { // Form up commands to pass to node-gyp: // We map `node-pre-gyp build` to `node-gyp configure build` so that we do not // trigger a clean and therefore do not pay the penalty of a full recompile if (argv.length && (argv.indexOf('rebuild') > -1)) { // here we map `node-pre-gyp rebuild` to `node-gyp rebuild` which internally means // "clean + configure + build" and triggers a full recompile compile.run_gyp(['clean'],{},function(err) { if (err) return callback(err); configure(gyp,argv,function(err) { if (err) return callback(err); return do_build(gyp,argv,callback); }); }); } else { return do_build(gyp,argv,callback); } }
{ "pile_set_name": "Github" }
""" Base class with plot generating commands. Does not define any special non-GMT methods (savefig, show, etc). """ import contextlib import numpy as np import pandas as pd from .clib import Session from .exceptions import GMTError, GMTInvalidInput from .helpers import ( build_arg_string, dummy_context, data_kind, fmt_docstring, use_alias, kwargs_to_strings, ) class BasePlotting: """ Base class for Figure and Subplot. Defines the plot generating methods and a hook for subclasses to insert special arguments (the _preprocess method). """ def _preprocess(self, **kwargs): # pylint: disable=no-self-use """ Make any changes to kwargs or required actions before plotting. This method is run before all plotting commands and can be used to insert special arguments into the kwargs or make any actions that are required before ``call_module``. For example, the :class:`pygmt.Figure` needs this to tell the GMT modules to plot to a specific figure. This is a dummy method that does nothing. Returns ------- kwargs : dict The same input kwargs dictionary. Examples -------- >>> base = BasePlotting() >>> base._preprocess(resolution='low') {'resolution': 'low'} """ return kwargs @fmt_docstring @use_alias( R="region", J="projection", A="area_thresh", B="frame", D="resolution", I="rivers", L="map_scale", N="borders", W="shorelines", G="land", S="water", U="timestamp", X="xshift", Y="yshift", p="perspective", t="transparency", ) @kwargs_to_strings(R="sequence", p="sequence") def coast(self, **kwargs): """ Plot continents, shorelines, rivers, and borders on maps Plots grayshaded, colored, or textured land-masses [or water-masses] on maps and [optionally] draws coastlines, rivers, and political boundaries. Alternatively, it can (1) issue clip paths that will contain all land or all water areas, or (2) dump the data to an ASCII table. The data files come in 5 different resolutions: (**f**)ull, (**h**)igh, (**i**)ntermediate, (**l**)ow, and (**c**)rude. The full resolution files amount to more than 55 Mb of data and provide great detail; for maps of larger geographical extent it is more economical to use one of the other resolutions. If the user selects to paint the land-areas and does not specify fill of water-areas then the latter will be transparent (i.e., earlier graphics drawn in those areas will not be overwritten). Likewise, if the water-areas are painted and no land fill is set then the land-areas will be transparent. A map projection must be supplied. Full option list at :gmt-docs:`coast.html` {aliases} Parameters ---------- {J} {R} area_thresh : int, float, or str ``'min_area[/min_level/max_level][+ag|i|s|S][+r|l][+ppercent]'`` Features with an area smaller than min_area in km^2 or of hierarchical level that is lower than min_level or higher than max_level will not be plotted. {B} C : str Set the shade, color, or pattern for lakes and river-lakes. resolution : str Selects the resolution of the data set to use ((f)ull, (h)igh, (i)ntermediate, (l)ow, and (c)rude). land : str Select filling or clipping of β€œdry” areas. rivers : str ``'river[/pen]'`` Draw rivers. Specify the type of rivers and [optionally] append pen attributes. map_scale : str ``'[g|j|J|n|x]refpoint'`` Draws a simple map scale centered on the reference point specified. borders : str ``'border[/pen]'`` Draw political boundaries. Specify the type of boundary and [optionally] append pen attributes water : str Select filling or clipping of β€œwet” areas. {U} shorelines : str ``'[level/]pen'`` Draw shorelines [Default is no shorelines]. Append pen attributes. {XY} {p} {t} """ kwargs = self._preprocess(**kwargs) with Session() as lib: lib.call_module("coast", build_arg_string(kwargs)) @fmt_docstring @use_alias( R="region", J="projection", B="frame", C="cmap", D="position", F="box", G="truncate", W="scale", X="xshift", Y="yshift", p="perspective", t="transparency", ) @kwargs_to_strings(R="sequence", G="sequence", p="sequence") def colorbar(self, **kwargs): """ Plot a gray or color scale-bar on maps. Both horizontal and vertical scales are supported. For CPTs with gradational colors (i.e., the lower and upper boundary of an interval have different colors) we will interpolate to give a continuous scale. Variations in intensity due to shading/illumination may be displayed by setting the option -I. Colors may be spaced according to a linear scale, all be equal size, or by providing a file with individual tile widths. Full option list at :gmt-docs:`colorbar.html` {aliases} Parameters ---------- position : str ``[g|j|J|n|x]refpoint[+wlength[/width]][+e[b|f][length]][+h|v] [+jjustify][+m[a|c|l|u]][+n[txt]][+odx[/dy]]``. Defines the reference point on the map for the color scale using one of four coordinate systems: (1) Use *g* for map (user) coordinates, (2) use *j* or *J* for setting refpoint via a 2-char justification code that refers to the (invisible) map domain rectangle, (3) use *n* for normalized (0-1) coordinates, or (4) use *x* for plot coordinates (inches, cm, etc.). All but *x* requires both *region* and *projection* to be specified. Append +w followed by the length and width of the color bar. If width is not specified then it is set to 4% of the given length. Give a negative length to reverse the scale bar. Append +h to get a horizontal scale [Default is vertical (+v)]. By default, the anchor point on the scale is assumed to be the bottom left corner (BL), but this can be changed by appending +j followed by a 2-char justification code *justify*. box : bool or str ``[+cclearances][+gfill][+i[[gap/]pen]][+p[pen]][+r[radius]] [+s[[dx/dy/][shade]]]``. If set to True, draws a rectangular border around the color scale. Alternatively, specify a different pen with +ppen. Add +gfill to fill the scale panel [no fill]. Append +cclearance where clearance is either gap, xgap/ygap, or lgap/rgap/bgap/tgap where these items are uniform, separate in x- and y-direction, or individual side spacings between scale and border. Append +i to draw a secondary, inner border as well. We use a uniform gap between borders of 2p and the MAP_DEFAULTS_PEN unless other values are specified. Append +r to draw rounded rectangular borders instead, with a 6p corner radius. You can override this radius by appending another value. Finally, append +s to draw an offset background shaded region. Here, dx/dy indicates the shift relative to the foreground frame [4p/-4p] and shade sets the fill style to use for shading [gray50]. truncate : list or str ``zlo/zhi`` Truncate the incoming CPT so that the lowest and highest z-levels are to zlo and zhi. If one of these equal NaN then we leave that end of the CPT alone. The truncation takes place before the plotting. scale : float Multiply all z-values in the CPT by the provided scale. By default the CPT is used as is. {XY} {p} {t} """ kwargs = self._preprocess(**kwargs) with Session() as lib: lib.call_module("colorbar", build_arg_string(kwargs)) @fmt_docstring @use_alias( A="annotation", B="frame", C="interval", G="label_placement", J="projection", L="limit", Q="cut", R="region", S="resample", U="timestamp", W="pen", l="label", X="xshift", Y="yshift", p="perspective", t="transparency", ) @kwargs_to_strings(R="sequence", L="sequence", A="sequence_plus", p="sequence") def grdcontour(self, grid, **kwargs): """ Convert grids or images to contours and plot them on maps Takes a grid file name or an xarray.DataArray object as input. Full option list at :gmt-docs:`grdcontour.html` {aliases} Parameters ---------- grid : str or xarray.DataArray The file name of the input grid or the grid loaded as a DataArray. interval : str or int Specify the contour lines to generate. - The filename of a `CPT` file where the color boundaries will be used as contour levels. - The filename of a 2 (or 3) column file containing the contour levels (col 1), (C)ontour or (A)nnotate (col 2), and optional angle (col 3) - A fixed contour interval ``cont_int`` or a single contour with ``+[cont_int]`` annotation : str, int, or list Specify or disable annotated contour levels, modifies annotated contours specified in ``-C``. - Specify a fixed annotation interval ``annot_int`` or a single annotation level ``+[annot_int]`` - Disable all annotation with ``'-'`` - Optional label modifiers can be specified as a single string ``'[annot_int]+e'`` or with a list of options ``([annot_int], 'e', 'f10p', 'gred')``. limit : str or list of 2 ints Do no draw contours below `low` or above `high`, specify as string ``'[low]/[high]'`` or list ``[low,high]``. cut : str or int Do not draw contours with less than `cut` number of points. resample : str or int Resample smoothing factor. {J} {R} {B} {G} {U} {W} {XY} label : str Add a legend entry for the contour being plotted. Normally, the annotated contour is selected for the legend. You can select the regular contour instead, or both of them, by considering the label to be of the format [*annotcontlabel*][/*contlabel*]. If either label contains a slash (/) character then use ``|`` as the separator for the two labels instead. {p} {t} """ kwargs = self._preprocess(**kwargs) kind = data_kind(grid, None, None) with Session() as lib: if kind == "file": file_context = dummy_context(grid) elif kind == "grid": file_context = lib.virtualfile_from_grid(grid) else: raise GMTInvalidInput("Unrecognized data type: {}".format(type(grid))) with file_context as fname: arg_str = " ".join([fname, build_arg_string(kwargs)]) lib.call_module("grdcontour", arg_str) @fmt_docstring @use_alias( A="img_out", B="frame", C="cmap", D="img_in", E="dpi", G="bit_color", I="shading", J="projection", M="monochrome", N="no_clip", Q="nan_transparent", R="region", U="timestamp", V="verbose", X="xshift", Y="yshift", n="interpolation", p="perspective", t="transparency", x="cores", ) @kwargs_to_strings(R="sequence", p="sequence") def grdimage(self, grid, **kwargs): """ Project and plot grids or images. Reads a 2-D grid file and produces a gray-shaded (or colored) map by building a rectangular image and assigning pixels a gray-shade (or color) based on the z-value and the CPT file. Optionally, illumination may be added by providing a file with intensities in the (-1,+1) range or instructions to derive intensities from the input data grid. Values outside this range will be clipped. Such intensity files can be created from the grid using `grdgradient` and, optionally, modified by `grdmath` or `grdhisteq`. If GMT is built with GDAL support, *grid* can be an image file (geo-referenced or not). In this case the image can optionally be illuminated with the file provided via the *shading* option. Here, if image has no coordinates then those of the intensity file will be used. When using map projections, the grid is first resampled on a new rectangular grid with the same dimensions. Higher resolution images can be obtained by using the *dpi* option. To obtain the resampled value (and hence shade or color) of each map pixel, its location is inversely projected back onto the input grid after which a value is interpolated between the surrounding input grid values. By default bi-cubic interpolation is used. Aliasing is avoided by also forward projecting the input grid nodes. If two or more nodes are projected onto the same pixel, their average will dominate in the calculation of the pixel value. Interpolation and aliasing is controlled with the *interpolation* option. The *region* option can be used to select a map region larger or smaller than that implied by the extent of the grid. Full option list at :gmt-docs:`grdimage.html` {aliases} Parameters ---------- grid : str or xarray.DataArray The file name or a DataArray containing the input 2-D gridded data set or image to be plotted (See GRID FILE FORMATS at :gmt-docs:`grdimage.html#grid-file-formats`). img_out : str ``out_img[=driver]``. Save an image in a raster format instead of PostScript. Use extension .ppm for a Portable Pixel Map format which is the only raster format GMT can natively write. For GMT installations configured with GDAL support there are more choices: Append *out_img* to select the image file name and extension. If the extension is one of .bmp, .gif, .jpg, .png, or .tif then no driver information is required. For other output formats you must append the required GDAL driver. The *driver* is the driver code name used by GDAL; see your GDAL installation's documentation for available drivers. Append a **+c**\\ *options* string where options is a list of one or more concatenated number of GDAL **-co** options. For example, to write a GeoPDF with the TerraGo format use ``=PDF+cGEO_ENCODING=OGC_BP``. Notes: (1) If a tiff file (.tif) is selected then we will write a GeoTiff image if the GMT projection syntax translates into a PROJ syntax, otherwise a plain tiff file is produced. (2) Any vector elements will be lost. {B} {CPT} img_in : str ``[r]`` GMT will automatically detect standard image files (Geotiff, TIFF, JPG, PNG, GIF, etc.) and will read those via GDAL. For very obscure image formats you may need to explicitly set *img_in*, which specifies that the grid is in fact an image file to be read via GDAL. Append **r** to assign the region specified by *region* to the image. For example, if you have used ``region='d'`` then the image will be assigned a global domain. This mode allows you to project a raw image (an image without referencing coordinates). dpi : int ``[i|dpi]``. Sets the resolution of the projected grid that will be created if a map projection other than Linear or Mercator was selected [100]. By default, the projected grid will be of the same size (rows and columns) as the input file. Specify **i** to use the PostScript image operator to interpolate the image at the device resolution. bit_color : str ``color[+b|f]``. This option only applies when a resulting 1-bit image otherwise would consist of only two colors: black (0) and white (255). If so, this option will instead use the image as a transparent mask and paint the mask with the given color. Append **+b** to paint the background pixels (1) or **+f** for the foreground pixels [Default]. shading : str ``[intensfile|intensity|modifiers]``. Give the name of a grid file with intensities in the (-1,+1) range, or a constant intensity to apply everywhere (affects the ambient light). Alternatively, derive an intensity grid from the input data grid via a call to `grdgradient`; append **+a**\\ *azimuth*, **+n**\\ *args*, and **+m**\\ *ambient* to specify azimuth, intensity, and ambient arguments for that module, or just give **+d** to select the default arguments (``+a-45+nt1+m0``). If you want a more specific intensity scenario then run `grdgradient` separately first. If we should derive intensities from another file than grid, specify the file with suitable modifiers [Default is no illumination]. {J} monochrome : bool Force conversion to monochrome image using the (television) YIQ transformation. Cannot be used with *nan_transparent*. no_clip : bool Do not clip the image at the map boundary (only relevant for non-rectangular maps). nan_transparent : bool Make grid nodes with z = NaN transparent, using the color-masking feature in PostScript Level 3 (the PS device must support PS Level 3). {R} {V} {XY} {n} {p} {t} {x} """ kwargs = self._preprocess(**kwargs) kind = data_kind(grid, None, None) with Session() as lib: if kind == "file": file_context = dummy_context(grid) elif kind == "grid": file_context = lib.virtualfile_from_grid(grid) else: raise GMTInvalidInput("Unrecognized data type: {}".format(type(grid))) with file_context as fname: arg_str = " ".join([fname, build_arg_string(kwargs)]) lib.call_module("grdimage", arg_str) @fmt_docstring @use_alias( R="region", J="projection", Jz="zscale", JZ="zsize", B="frame", C="cmap", G="drapegrid", N="plane", Q="surftype", Wc="contourpen", Wm="meshpen", Wf="facadepen", I="shading", X="xshift", Y="yshift", p="perspective", t="transparency", ) @kwargs_to_strings(R="sequence", p="sequence") def grdview(self, grid, **kwargs): """ Create 3-D perspective image or surface mesh from a grid. Reads a 2-D grid file and produces a 3-D perspective plot by drawing a mesh, painting a colored/gray-shaded surface made up of polygons, or by scanline conversion of these polygons to a raster image. Options include draping a data set on top of a surface, plotting of contours on top of the surface, and apply artificial illumination based on intensities provided in a separate grid file. Full option list at :gmt-docs:`grdview.html` {aliases} Parameters ---------- grid : str or xarray.DataArray The file name of the input relief grid or the grid loaded as a DataArray. zscale/zsize : float or str Set z-axis scaling or z-axis size. cmap : str The name of the color palette table to use. drapegrid : str or xarray.DataArray The file name or a DataArray of the image grid to be draped on top of the relief provided by grid. [Default determines colors from grid]. Note that -Jz and -N always refers to the grid. The drapegrid only provides the information pertaining to colors, which (if drapegrid is a grid) will be looked-up via the CPT (see -C). plane : float or str ``level[+gfill]``. Draws a plane at this z-level. If the optional color is provided via the +g modifier, and the projection is not oblique, the frontal facade between the plane and the data perimeter is colored. surftype : str Specifies cover type of the grid. Select one of following settings: 1. 'm' for mesh plot [Default]. 2. 'mx' or 'my' for waterfall plots (row or column profiles). 3. 's' for surface plot. 4. 'i' for image plot. 5. 'c'. Same as 'i' but will make nodes with z = NaN transparent. For any of these choices, you may force a monochrome image by appending the modifier +m. contourpen : str Draw contour lines on top of surface or mesh (not image). Append pen attributes used for the contours. meshpen : str Sets the pen attributes used for the mesh. You must also select -Qm or -Qsm for meshlines to be drawn. facadepen :str Sets the pen attributes used for the facade. You must also select -N for the facade outline to be drawn. shading : str Provide the name of a grid file with intensities in the (-1,+1) range, or a constant intensity to apply everywhere (affects the ambient light). Alternatively, derive an intensity grid from the input data grid reliefgrid via a call to ``grdgradient``; append ``+aazimuth``, ``+nargs``, and ``+mambient`` to specify azimuth, intensity, and ambient arguments for that module, or just give ``+d`` to select the default arguments (``+a-45+nt1+m0``). {XY} {p} {t} """ kwargs = self._preprocess(**kwargs) kind = data_kind(grid, None, None) with Session() as lib: if kind == "file": file_context = dummy_context(grid) elif kind == "grid": file_context = lib.virtualfile_from_grid(grid) else: raise GMTInvalidInput(f"Unrecognized data type for grid: {type(grid)}") with contextlib.ExitStack() as stack: fname = stack.enter_context(file_context) if "G" in kwargs: drapegrid = kwargs["G"] if data_kind(drapegrid) in ("file", "grid"): if data_kind(drapegrid) == "grid": drape_context = lib.virtualfile_from_grid(drapegrid) drapefile = stack.enter_context(drape_context) kwargs["G"] = drapefile else: raise GMTInvalidInput( f"Unrecognized data type for drapegrid: {type(drapegrid)}" ) arg_str = " ".join([fname, build_arg_string(kwargs)]) lib.call_module("grdview", arg_str) @fmt_docstring @use_alias( R="region", J="projection", B="frame", S="style", G="color", W="pen", i="columns", l="label", C="cmap", U="timestamp", X="xshift", Y="yshift", p="perspective", t="transparency", ) @kwargs_to_strings(R="sequence", i="sequence_comma", p="sequence") def plot(self, x=None, y=None, data=None, sizes=None, direction=None, **kwargs): """ Plot lines, polygons, and symbols on maps. Used to be psxy. Takes a matrix, (x,y) pairs, or a file name as input and plots lines, polygons, or symbols at those locations on a map. Must provide either *data* or *x* and *y*. If providing data through *x* and *y*, *color* (G) can be a 1d array that will be mapped to a colormap. If a symbol is selected and no symbol size given, then psxy will interpret the third column of the input data as symbol size. Symbols whose size is <= 0 are skipped. If no symbols are specified then the symbol code (see *S* below) must be present as last column in the input. If *S* is not used, a line connecting the data points will be drawn instead. To explicitly close polygons, use *L*. Select a fill with *G*. If *G* is set, *W* will control whether the polygon outline is drawn or not. If a symbol is selected, *G* and *W* determines the fill and outline/no outline, respectively. Full option list at :gmt-docs:`plot.html` {aliases} Parameters ---------- x/y : float or 1d arrays The x and y coordinates, or arrays of x and y coordinates of the data points data : str or 2d array Either a data file name or a 2d numpy array with the tabular data. Use option *columns* (i) to choose which columns are x, y, color, and size, respectively. sizes : 1d array The sizes of the data points in units specified in *style* (S). Only valid if using *x* and *y*. direction : list of two 1d arrays If plotting vectors (using ``style='V'`` or ``style='v'``), then should be a list of two 1d arrays with the vector directions. These can be angle and length, azimuth and length, or x and y components, depending on the style options chosen. {J} {R} A : bool or str ``'[m|p|x|y]'`` By default, geographic line segments are drawn as great circle arcs. To draw them as straight lines, use *A*. {B} {CPT} D : str ``'dx/dy'``: Offset the plot symbol or line locations by the given amounts dx/dy. E : bool or str ``'[x|y|X|Y][+a][+cl|f][+n][+wcap][+ppen]'``. Draw symmetrical error bars. {G} style : str Plot symbols (including vectors, pie slices, fronts, decorated or quoted lines). {W} {U} {XY} label : str Add a legend entry for the symbol or line being plotted. {p} {t} """ kwargs = self._preprocess(**kwargs) kind = data_kind(data, x, y) extra_arrays = [] if "S" in kwargs and kwargs["S"][0] in "vV" and direction is not None: extra_arrays.extend(direction) if "G" in kwargs and not isinstance(kwargs["G"], str): if kind != "vectors": raise GMTInvalidInput( "Can't use arrays for color if data is matrix or file." ) extra_arrays.append(kwargs["G"]) del kwargs["G"] if sizes is not None: if kind != "vectors": raise GMTInvalidInput( "Can't use arrays for sizes if data is matrix or file." ) extra_arrays.append(sizes) with Session() as lib: # Choose how data will be passed in to the module if kind == "file": file_context = dummy_context(data) elif kind == "matrix": file_context = lib.virtualfile_from_matrix(data) elif kind == "vectors": file_context = lib.virtualfile_from_vectors( np.atleast_1d(x), np.atleast_1d(y), *extra_arrays ) with file_context as fname: arg_str = " ".join([fname, build_arg_string(kwargs)]) lib.call_module("plot", arg_str) @fmt_docstring @use_alias( R="region", J="projection", B="frame", S="skip", G="label_placement", W="pen", L="triangular_mesh_pen", i="columns", l="label", C="levels", X="xshift", Y="yshift", p="perspective", t="transparency", ) @kwargs_to_strings(R="sequence", i="sequence_comma", p="sequence") def contour(self, x=None, y=None, z=None, data=None, **kwargs): """ Contour table data by direct triangulation. Takes a matrix, (x,y,z) pairs, or a file name as input and plots lines, polygons, or symbols at those locations on a map. Must provide either *data* or *x*, *y*, and *z*. [TODO: Insert more documentation] Full option list at :gmt-docs:`contour.html` {aliases} Parameters ---------- x/y/z : 1d arrays Arrays of x and y coordinates and values z of the data points. data : str or 2d array Either a data file name or a 2d numpy array with the tabular data. {J} {R} A : bool or str ``'[m|p|x|y]'`` By default, geographic line segments are drawn as great circle arcs. To draw them as straight lines, use *A*. {B} levels : str Contour file or level(s) D : str Dump contour coordinates E : str Network information label_placement : str Placement of labels I : bool Color the triangles using CPT triangular_mesh_pen : str Pen to draw the underlying triangulation (default none) N : bool Do not clip contours Q : float or str Do not draw contours with less than cut number of points. ``'[cut[unit]][+z]'`` skip : bool or str Skip input points outside region ``'[p|t]'`` {W} label : str Add a legend entry for the contour being plotted. Normally, the annotated contour is selected for the legend. You can select the regular contour instead, or both of them, by considering the label to be of the format [*annotcontlabel*][/*contlabel*]. If either label contains a slash (/) character then use ``|`` as the separator for the two labels instead. {XY} {p} {t} """ kwargs = self._preprocess(**kwargs) kind = data_kind(data, x, y, z) if kind == "vectors" and z is None: raise GMTInvalidInput("Must provided both x, y, and z.") with Session() as lib: # Choose how data will be passed in to the module if kind == "file": file_context = dummy_context(data) elif kind == "matrix": file_context = lib.virtualfile_from_matrix(data) elif kind == "vectors": file_context = lib.virtualfile_from_vectors(x, y, z) with file_context as fname: arg_str = " ".join([fname, build_arg_string(kwargs)]) lib.call_module("contour", arg_str) @fmt_docstring @use_alias( R="region", J="projection", B="frame", L="map_scale", Td="rose", Tm="compass", U="timestamp", X="xshift", Y="yshift", p="perspective", t="transparency", ) @kwargs_to_strings(R="sequence", p="sequence") def basemap(self, **kwargs): """ Produce a basemap for the figure. Several map projections are available, and the user may specify separate tick-mark intervals for boundary annotation, ticking, and [optionally] gridlines. A simple map scale or directional rose may also be plotted. At least one of the options *frame*, *map_scale*, *rose* or *compass* must be specified. Full option list at :gmt-docs:`basemap.html` {aliases} Parameters ---------- {J} {R} {B} map_scale : str ``'[g|j|J|n|x]refpoint'`` Draws a simple map scale centered on the reference point specified. rose : str Draws a map directional rose on the map at the location defined by the reference and anchor points. compass : str Draws a map magnetic rose on the map at the location defined by the reference and anchor points {U} {XY} {p} {t} """ kwargs = self._preprocess(**kwargs) if not ("B" in kwargs or "L" in kwargs or "T" in kwargs): raise GMTInvalidInput("At least one of B, L, or T must be specified.") with Session() as lib: lib.call_module("basemap", build_arg_string(kwargs)) @fmt_docstring @use_alias( R="region", J="projection", U="timestamp", D="position", F="box", X="xshift", Y="yshift", p="perspective", t="transparency", ) @kwargs_to_strings(R="sequence", p="sequence") def logo(self, **kwargs): """ Place the GMT graphics logo on a map. By default, the GMT logo is 2 inches wide and 1 inch high and will be positioned relative to the current plot origin. Use various options to change this and to place a transparent or opaque rectangular map panel behind the GMT logo. Full option list at :gmt-docs:`logo.html` {aliases} Parameters ---------- {J} {R} position : str ``'[g|j|J|n|x]refpoint+wwidth[+jjustify][+odx[/dy]]'``. Sets reference point on the map for the image. box : bool or str Without further options, draws a rectangular border around the GMT logo. {U} {XY} {p} {t} """ kwargs = self._preprocess(**kwargs) if "D" not in kwargs: raise GMTInvalidInput("Option D must be specified.") with Session() as lib: lib.call_module("logo", build_arg_string(kwargs)) @fmt_docstring @use_alias( R="region", J="projection", D="position", F="box", M="monochrome", X="xshift", Y="yshift", p="perspective", t="transparency", ) @kwargs_to_strings(R="sequence", p="sequence") def image(self, imagefile, **kwargs): """ Place images or EPS files on maps. Reads an Encapsulated PostScript file or a raster image file and plots it on a map. Full option list at :gmt-docs:`image.html` {aliases} Parameters ---------- imagefile : str This must be an Encapsulated PostScript (EPS) file or a raster image. An EPS file must contain an appropriate BoundingBox. A raster file can have a depth of 1, 8, 24, or 32 bits and is read via GDAL. Note: If GDAL was not configured during GMT installation then only EPS files are supported. {J} {R} position : str ``'[g|j|J|n|x]refpoint+rdpi+w[-]width[/height][+jjustify] [+nnx[/ny]][+odx[/dy]]'`` Sets reference point on the map for the image. box : bool or str ``'[+cclearances][+gfill][+i[[gap/]pen]][+p[pen]][+r[radius]] [+s[[dx/dy/][shade]]]'`` Without further options, draws a rectangular border around the image using **MAP_FRAME_PEN**. monochrome : bool Convert color image to monochrome grayshades using the (television) YIQ-transformation. {XY} {p} {t} """ kwargs = self._preprocess(**kwargs) with Session() as lib: arg_str = " ".join([imagefile, build_arg_string(kwargs)]) lib.call_module("image", arg_str) @fmt_docstring @use_alias( R="region", J="projection", D="position", F="box", X="xshift", Y="yshift", p="perspective", t="transparency", ) @kwargs_to_strings(R="sequence", p="sequence") def legend(self, spec=None, position="JTR+jTR+o0.2c", box="+gwhite+p1p", **kwargs): """ Plot legends on maps. Makes legends that can be overlaid on maps. Reads specific legend-related information from an input file, or automatically creates legend entries from plotted symbols that have labels. Unless otherwise noted, annotations will be made using the primary annotation font and size in effect (i.e., FONT_ANNOT_PRIMARY). Full option list at :gmt-docs:`legend.html` {aliases} Parameters ---------- spec : None or str Either None (default) for using the automatically generated legend specification file, or a filename pointing to the legend specification file. {J} {R} position : str ``'[g|j|J|n|x]refpoint+wwidth[/height][+jjustify][+lspacing] [+odx[/dy]]'`` Defines the reference point on the map for the legend. By default, uses 'JTR+jTR+o0.2c' which places the legend at the top-right corner inside the map frame, with a 0.2 cm offset. box : bool or str ``'[+cclearances][+gfill][+i[[gap/]pen]][+p[pen]][+r[radius]] [+s[[dx/dy/][shade]]]'`` Without further options, draws a rectangular border around the legend using **MAP_FRAME_PEN**. By default, uses '+gwhite+p1p' which draws a box around the legend using a 1 point black pen and adds a white background. {XY} {p} {t} """ kwargs = self._preprocess(**kwargs) if "D" not in kwargs: kwargs["D"] = position if "F" not in kwargs: kwargs["F"] = box with Session() as lib: if spec is None: specfile = "" elif data_kind(spec) == "file": specfile = spec else: raise GMTInvalidInput("Unrecognized data type: {}".format(type(spec))) arg_str = " ".join([specfile, build_arg_string(kwargs)]) lib.call_module("legend", arg_str) @fmt_docstring @use_alias( R="region", J="projection", B="frame", C="clearance", D="offset", G="fill", W="pen", X="xshift", Y="yshift", p="perspective", t="transparency", ) @kwargs_to_strings( R="sequence", textfiles="sequence_space", angle="sequence_comma", font="sequence_comma", justify="sequence_comma", p="sequence", ) def text( self, textfiles=None, x=None, y=None, position=None, text=None, angle=None, font=None, justify=None, **kwargs, ): """ Plot or typeset text strings of variable size, font type, and orientation. Must provide at least one of the following combinations as input: - *textfiles* - *x*, *y*, and *text* - *position* and *text* Full option list at :gmt-docs:`text.html` {aliases} Parameters ---------- textfiles : str or list A text data file name, or a list of filenames containing 1 or more records with (x, y[, angle, font, justify], text). x/y : float or 1d arrays The x and y coordinates, or an array of x and y coordinates to plot the text position : str Sets reference point on the map for the text by using x,y coordinates extracted from *region* instead of providing them through *x* and *y*. Specify with a two letter (order independent) code, chosen from: * Horizontal: L(eft), C(entre), R(ight) * Vertical: T(op), M(iddle), B(ottom) For example, position="TL" plots the text at the Upper Left corner of the map. text : str or 1d array The text string, or an array of strings to plot on the figure angle: int, float, str or bool Set the angle measured in degrees counter-clockwise from horizontal. E.g. 30 sets the text at 30 degrees. If no angle is explicitly given (i.e. angle=True) then the input textfile(s) must have this as a column. font : str or bool Set the font specification with format "size,font,color" where size is text size in points, font is the font to use, and color sets the font color. E.g. "12p,Helvetica-Bold,red" selects a 12p red Helvetica-Bold font. If no font info is explicitly given (i.e. font=True), then the input textfile(s) must have this information in one of its columns. justify : str or bool Set the alignment which refers to the part of the text string that will be mapped onto the (x,y) point. Choose a 2 character combination of L, C, R (for left, center, or right) and T, M, B for top, middle, or bottom. E.g., BL for lower left. If no justification is explicitly given (i.e. justify=True), then the input textfile(s) must have this as a column. {J} {R} clearance : str ``[dx/dy][+to|O|c|C]`` Adjust the clearance between the text and the surrounding box [15%]. Only used if *pen* or *fill* are specified. Append the unit you want ('c' for cm, 'i' for inch, or 'p' for point; if not given we consult 'PROJ_LENGTH_UNIT') or '%' for a percentage of the font size. Optionally, use modifier '+t' to set the shape of the textbox when using *fill* and/or *pen*. Append lower case 'o' to get a straight rectangle [Default]. Append upper case 'O' to get a rounded rectangle. In paragraph mode (*paragraph*) you can also append lower case 'c' to get a concave rectangle or append upper case 'C' to get a convex rectangle. fill : str Sets the shade or color used for filling the text box [Default is no fill]. offset : str ``[j|J]dx[/dy][+v[pen]]`` Offsets the text from the projected (x,y) point by dx,dy [0/0]. If dy is not specified then it is set equal to dx. Use offset='j' to offset the text away from the point instead (i.e., the text justification will determine the direction of the shift). Using offset='J' will shorten diagonal offsets at corners by sqrt(2). Optionally, append '+v' which will draw a line from the original point to the shifted point; append a pen to change the attributes for this line. pen : str Sets the pen used to draw a rectangle around the text string (see *clearance*) [Default is width = default, color = black, style = solid]. {XY} {p} {t} """ kwargs = self._preprocess(**kwargs) # Ensure inputs are either textfiles, x/y/text, or position/text if position is None: kind = data_kind(textfiles, x, y, text) else: if x is not None or y is not None: raise GMTInvalidInput( "Provide either position only, or x/y pairs, not both" ) kind = "vectors" if kind == "vectors" and text is None: raise GMTInvalidInput("Must provide text with x/y pairs or position") # Build the `-F` argument in gmt text. if "F" not in kwargs.keys() and ( ( position is not None or angle is not None or font is not None or justify is not None ) ): kwargs.update({"F": ""}) if angle is not None and isinstance(angle, (int, float, str)): kwargs["F"] += f"+a{str(angle)}" if font is not None and isinstance(font, str): kwargs["F"] += f"+f{font}" if justify is not None and isinstance(justify, str): kwargs["F"] += f"+j{justify}" if position is not None and isinstance(position, str): kwargs["F"] += f'+c{position}+t"{text}"' with Session() as lib: file_context = dummy_context(textfiles) if kind == "file" else "" if kind == "vectors": if position is not None: file_context = dummy_context("") else: file_context = lib.virtualfile_from_vectors( np.atleast_1d(x), np.atleast_1d(y), np.atleast_1d(text) ) with file_context as fname: arg_str = " ".join([fname, build_arg_string(kwargs)]) lib.call_module("text", arg_str) @fmt_docstring @use_alias( R="region", J="projection", B="frame", C="offset", X="xshift", Y="yshift", p="perspective", t="transparency", ) @kwargs_to_strings(R="sequence", p="sequence") def meca( self, spec, scale, longitude=None, latitude=None, depth=None, convention=None, component="full", plot_longitude=None, plot_latitude=None, **kwargs, ): """ Plot focal mechanisms. Full option list at :gmt-docs:`supplements/seis/meca.html` Note ---- Currently, labeling of beachballs with text strings is only supported via providing a file to `spec` as input. {aliases} Parameters ---------- spec: dict, 1D array, 2D array, pd.DataFrame, or str Either a filename containing focal mechanism parameters as columns, a 1- or 2-D array with the same, or a dictionary. If a filename or array, `convention` is required so we know how to interpret the columns/entries. If a dictionary, the following combinations of keys are supported; these determine the convention. Dictionary may contain values for a single focal mechanism or lists of values for many focal mechanisms. A Pandas DataFrame may optionally contain columns latitude, longitude, depth, plot_longitude, and/or plot_latitude instead of passing them to the meca method. - ``"aki"`` β€” *strike, dip, rake, magnitude* - ``"gcmt"`` β€” *strike1, dip1, rake1, strike2, dip2, rake2, mantissa, exponent* - ``"mt"`` β€” *mrr, mtt, mff, mrt, mrf, mtf, exponent* - ``"partial"`` β€” *strike1, dip1, strike2, fault_type, magnitude* - ``"principal_axis"`` β€” *t_exponent, t_azimuth, t_plunge, n_exponent, n_azimuth, n_plunge, p_exponent, p_azimuth, p_plunge, exponent* scale: str Adjusts the scaling of the radius of the beachball, which is proportional to the magnitude. Scale defines the size for magnitude = 5 (i.e. scalar seismic moment M0 = 4.0E23 dynes-cm) longitude: int, float, list, or 1d numpy array Longitude(s) of event location. Ignored if `spec` is not a dictionary. List must be the length of the number of events. Ignored if `spec` is a DataFrame and contains a 'longitude' column. latitude: int, float, list, or 1d numpy array Latitude(s) of event location. Ignored if `spec` is not a dictionary. List must be the length of the number of events. Ignored if `spec` is a DataFrame and contains a 'latitude' column. depth: int, float, list, or 1d numpy array Depth(s) of event location in kilometers. Ignored if `spec` is not a dictionary. List must be the length of the number of events. Ignored if `spec` is a DataFrame and contains a 'depth' column. convention: str ``"aki"`` (Aki & Richards), ``"gcmt"`` (global CMT), ``"mt"`` (seismic moment tensor), ``"partial"`` (partial focal mechanism), or ``"principal_axis"`` (principal axis). Ignored if `spec` is a dictionary or dataframe. component: str The component of the seismic moment tensor to plot. ``"full"`` (the full seismic moment tensor), ``"dc"`` (the closest double couple with zero trace and zero determinant), ``"deviatoric"`` (zero trace) plot_longitude: int, float, list, or 1d numpy array Longitude(s) at which to place beachball, only used if `spec` is a dictionary. List must be the length of the number of events. Ignored if `spec` is a DataFrame and contains a 'plot_longitude' column. plot_latitude: int, float, list, or 1d numpy array Latitude(s) at which to place beachball, only used if `spec` is a dictionary. List must be the length of the number of events. Ignored if `spec` is a DataFrame and contains a 'plot_latitude' column. offset: bool or str Offsets beachballs to the longitude, latitude specified in the last two columns of the input file or array, or by `plot_longitude` and `plot_latitude` if provided. A small circle is plotted at the initial location and a line connects the beachball to the circle. Specify pen and optionally append ``+ssize`` to change the line style and/or size of the circle. {J} {R} {B} {XY} {p} {t} """ # pylint warnings that need to be fixed # pylint: disable=too-many-locals # pylint: disable=too-many-nested-blocks # pylint: disable=too-many-branches # pylint: disable=no-self-use # pylint: disable=too-many-statements def set_pointer(data_pointers, spec): """Set optional parameter pointers based on DataFrame or dict, if those parameters are present in the DataFrame or dict.""" for param in list(data_pointers.keys()): if param in spec: # set pointer based on param name data_pointers[param] = spec[param] def update_pointers(data_pointers): """Updates variables based on the location of data, as the following data can be passed as parameters or it can be contained in `spec`.""" # update all pointers longitude = data_pointers["longitude"] latitude = data_pointers["latitude"] depth = data_pointers["depth"] plot_longitude = data_pointers["plot_longitude"] plot_latitude = data_pointers["plot_latitude"] return (longitude, latitude, depth, plot_longitude, plot_latitude) # Check the spec and parse the data according to the specified # convention if isinstance(spec, (dict, pd.DataFrame)): # dicts and DataFrames are handed similarly but not identically if ( longitude is None or latitude is None or depth is None ) and not isinstance(spec, (dict, pd.DataFrame)): raise GMTError("Location not fully specified.") param_conventions = { "AKI": ["strike", "dip", "rake", "magnitude"], "GCMT": ["strike1", "dip1", "dip2", "rake2", "mantissa", "exponent"], "MT": ["mrr", "mtt", "mff", "mrt", "mrf", "mtf", "exponent"], "PARTIAL": ["strike1", "dip1", "strike2", "fault_type", "magnitude"], "PRINCIPAL_AXIS": [ "t_exponent", "t_azimuth", "t_plunge", "n_exponent", "n_azimuth", "n_plunge", "p_exponent", "p_azimuth", "p_plunge", "exponent", ], } # to keep track of where optional parameters exist data_pointers = { "longitude": longitude, "latitude": latitude, "depth": depth, "plot_longitude": plot_longitude, "plot_latitude": plot_latitude, } # make a DataFrame copy to check convention if it contains # other parameters if isinstance(spec, (dict, pd.DataFrame)): # check if a copy is necessary copy = False drop_list = [] for pointer in data_pointers: if pointer in spec: copy = True drop_list.append(pointer) if copy: spec_conv = spec.copy() # delete optional parameters from copy for convention check for item in drop_list: del spec_conv[item] else: spec_conv = spec # set convention and focal parameters based on spec convention convention_assigned = False for conv in param_conventions: if set(spec_conv.keys()) == set(param_conventions[conv]): convention = conv.lower() foc_params = param_conventions[conv] convention_assigned = True break if not convention_assigned: raise GMTError( "Parameters in spec dictionary do not match known " "conventions." ) # create a dict type pointer for easier to read code if isinstance(spec, dict): dict_type_pointer = list(spec.values())[0] elif isinstance(spec, pd.DataFrame): # use df.values as pointer for DataFrame behavior dict_type_pointer = spec.values # assemble the 1D array for the case of floats and ints as values if isinstance(dict_type_pointer, (int, float)): # update pointers set_pointer(data_pointers, spec) # look for optional parameters in the right place ( longitude, latitude, depth, plot_longitude, plot_latitude, ) = update_pointers(data_pointers) # Construct the array (order matters) spec = [longitude, latitude, depth] + [spec[key] for key in foc_params] # Add in plotting options, if given, otherwise add 0s for arg in plot_longitude, plot_latitude: if arg is None: spec.append(0) else: if "C" not in kwargs: kwargs["C"] = True spec.append(arg) # or assemble the 2D array for the case of lists as values elif isinstance(dict_type_pointer, list): # update pointers set_pointer(data_pointers, spec) # look for optional parameters in the right place ( longitude, latitude, depth, plot_longitude, plot_latitude, ) = update_pointers(data_pointers) # before constructing the 2D array lets check that each key # of the dict has the same quantity of values to avoid bugs list_length = len(list(spec.values())[0]) for value in list(spec.values()): if len(value) != list_length: raise GMTError( "Unequal number of focal mechanism " "parameters supplied in 'spec'." ) # lets also check the inputs for longitude, latitude, # and depth if it is a list or array if ( isinstance(longitude, (list, np.ndarray)) or isinstance(latitude, (list, np.ndarray)) or isinstance(depth, (list, np.ndarray)) ): if (len(longitude) != len(latitude)) or ( len(longitude) != len(depth) ): raise GMTError( "Unequal number of focal mechanism " "locations supplied." ) # values are ok, so build the 2D array spec_array = [] for index in range(list_length): # Construct the array one row at a time (note that order # matters here, hence the list comprehension!) row = [longitude[index], latitude[index], depth[index]] + [ spec[key][index] for key in foc_params ] # Add in plotting options, if given, otherwise add 0s as # required by GMT for arg in plot_longitude, plot_latitude: if arg is None: row.append(0) else: if "C" not in kwargs: kwargs["C"] = True row.append(arg[index]) spec_array.append(row) spec = spec_array # or assemble the array for the case of pd.DataFrames elif isinstance(dict_type_pointer, np.ndarray): # update pointers set_pointer(data_pointers, spec) # look for optional parameters in the right place ( longitude, latitude, depth, plot_longitude, plot_latitude, ) = update_pointers(data_pointers) # lets also check the inputs for longitude, latitude, and depth # just in case the user entered different length lists if ( isinstance(longitude, (list, np.ndarray)) or isinstance(latitude, (list, np.ndarray)) or isinstance(depth, (list, np.ndarray)) ): if (len(longitude) != len(latitude)) or ( len(longitude) != len(depth) ): raise GMTError( "Unequal number of focal mechanism locations supplied." ) # values are ok, so build the 2D array in the correct order spec_array = [] for index in range(len(spec)): # Construct the array one row at a time (note that order # matters here, hence the list comprehension!) row = [longitude[index], latitude[index], depth[index]] + [ spec[key][index] for key in foc_params ] # Add in plotting options, if given, otherwise add 0s as # required by GMT for arg in plot_longitude, plot_latitude: if arg is None: row.append(0) else: if "C" not in kwargs: kwargs["C"] = True row.append(arg[index]) spec_array.append(row) spec = spec_array else: raise GMTError( "Parameter 'spec' contains values of an unsupported type." ) # Add condition and scale to kwargs if convention == "aki": data_format = "a" elif convention == "gcmt": data_format = "c" elif convention == "mt": # Check which component of mechanism the user wants plotted if component == "deviatoric": data_format = "z" elif component == "dc": data_format = "d" else: # component == 'full' data_format = "m" elif convention == "partial": data_format = "p" elif convention == "principal_axis": # Check which component of mechanism the user wants plotted if component == "deviatoric": data_format = "t" elif component == "dc": data_format = "y" else: # component == 'full' data_format = "x" # Support old-school GMT format options elif convention in ["a", "c", "m", "d", "z", "p", "x", "y", "t"]: data_format = convention else: raise GMTError("Convention not recognized.") # Assemble -S flag kwargs["S"] = data_format + scale kind = data_kind(spec) with Session() as lib: if kind == "matrix": file_context = lib.virtualfile_from_matrix(np.atleast_2d(spec)) elif kind == "file": file_context = dummy_context(spec) else: raise GMTInvalidInput("Unrecognized data type: {}".format(type(spec))) with file_context as fname: arg_str = " ".join([fname, build_arg_string(kwargs)]) lib.call_module("meca", arg_str)
{ "pile_set_name": "Github" }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.models.generated; /** * The Enum Signin Frequency Type. */ public enum SigninFrequencyType { /** * days */ DAYS, /** * hours */ HOURS, /** * For SigninFrequencyType values that were not expected from the service */ UNEXPECTED_VALUE }
{ "pile_set_name": "Github" }
protocol NSLocking { func lock() func unlock() } class NSLock : NSObject, NSLocking { func tryLock() -> Bool func lock(before limit: NSDate) -> Bool @available(iOS 2.0, *) var name: String? func lock() func unlock() } class NSConditionLock : NSObject, NSLocking { init(condition condition: Int) var condition: Int { get } func lock(whenCondition condition: Int) func tryLock() -> Bool func tryWhenCondition(_ condition: Int) -> Bool func unlock(withCondition condition: Int) func lock(before limit: NSDate) -> Bool func lock(whenCondition condition: Int, before limit: NSDate) -> Bool @available(iOS 2.0, *) var name: String? func lock() func unlock() } class NSRecursiveLock : NSObject, NSLocking { func tryLock() -> Bool func lock(before limit: NSDate) -> Bool @available(iOS 2.0, *) var name: String? func lock() func unlock() } @available(iOS 2.0, *) class NSCondition : NSObject, NSLocking { func wait() func wait(until limit: NSDate) -> Bool func signal() func broadcast() @available(iOS 2.0, *) var name: String? @available(iOS 2.0, *) func lock() @available(iOS 2.0, *) func unlock() }
{ "pile_set_name": "Github" }
/* gzlib.c -- zlib functions common to reading and writing gzip files * Copyright (C) 2004-2017 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ #include "gzguts.h" #if defined(_WIN32) && !defined(__BORLANDC__) && !defined(__MINGW32__) # define LSEEK _lseeki64 #else #if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0 # define LSEEK lseek64 #else # define LSEEK lseek #endif #endif /* Local functions */ local void gz_reset OF((gz_statep)); local gzFile gz_open OF((const void *, int, const char *)); #if defined UNDER_CE /* Map the Windows error number in ERROR to a locale-dependent error message string and return a pointer to it. Typically, the values for ERROR come from GetLastError. The string pointed to shall not be modified by the application, but may be overwritten by a subsequent call to gz_strwinerror The gz_strwinerror function does not change the current setting of GetLastError. */ char ZLIB_INTERNAL *gz_strwinerror (error) DWORD error; { static char buf[1024]; wchar_t *msgbuf; DWORD lasterr = GetLastError(); DWORD chars = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, error, 0, /* Default language */ (LPVOID)&msgbuf, 0, NULL); if (chars != 0) { /* If there is an \r\n appended, zap it. */ if (chars >= 2 && msgbuf[chars - 2] == '\r' && msgbuf[chars - 1] == '\n') { chars -= 2; msgbuf[chars] = 0; } if (chars > sizeof (buf) - 1) { chars = sizeof (buf) - 1; msgbuf[chars] = 0; } wcstombs(buf, msgbuf, chars + 1); LocalFree(msgbuf); } else { sprintf(buf, "unknown win32 error (%ld)", error); } SetLastError(lasterr); return buf; } #endif /* UNDER_CE */ /* Reset gzip file state */ local void gz_reset(state) gz_statep state; { state->x.have = 0; /* no output data available */ if (state->mode == GZ_READ) { /* for reading ... */ state->eof = 0; /* not at end of file */ state->past = 0; /* have not read past end yet */ state->how = LOOK; /* look for gzip header */ } state->seek = 0; /* no seek request pending */ gz_error(state, Z_OK, NULL); /* clear error */ state->x.pos = 0; /* no uncompressed data yet */ state->strm.avail_in = 0; /* no input data yet */ } /* Open a gzip file either by name or file descriptor. */ local gzFile gz_open(path, fd, mode) const void *path; int fd; const char *mode; { gz_statep state; z_size_t len; int oflag; #ifdef O_CLOEXEC int cloexec = 0; #endif #ifdef O_EXCL int exclusive = 0; #endif /* check input */ if (path == NULL) return NULL; /* allocate gzFile structure to return */ state = (gz_statep)malloc(sizeof(gz_state)); if (state == NULL) return NULL; state->size = 0; /* no buffers allocated yet */ state->want = GZBUFSIZE; /* requested buffer size */ state->msg = NULL; /* no error message yet */ /* interpret mode */ state->mode = GZ_NONE; state->level = Z_DEFAULT_COMPRESSION; state->strategy = Z_DEFAULT_STRATEGY; state->direct = 0; while (*mode) { if (*mode >= '0' && *mode <= '9') state->level = *mode - '0'; else switch (*mode) { case 'r': state->mode = GZ_READ; break; #ifndef NO_GZCOMPRESS case 'w': state->mode = GZ_WRITE; break; case 'a': state->mode = GZ_APPEND; break; #endif case '+': /* can't read and write at the same time */ free(state); return NULL; case 'b': /* ignore -- will request binary anyway */ break; #ifdef O_CLOEXEC case 'e': cloexec = 1; break; #endif #ifdef O_EXCL case 'x': exclusive = 1; break; #endif case 'f': state->strategy = Z_FILTERED; break; case 'h': state->strategy = Z_HUFFMAN_ONLY; break; case 'R': state->strategy = Z_RLE; break; case 'F': state->strategy = Z_FIXED; break; case 'T': state->direct = 1; break; default: /* could consider as an error, but just ignore */ ; } mode++; } /* must provide an "r", "w", or "a" */ if (state->mode == GZ_NONE) { free(state); return NULL; } /* can't force transparent read */ if (state->mode == GZ_READ) { if (state->direct) { free(state); return NULL; } state->direct = 1; /* for empty file */ } /* save the path name for error messages */ #ifdef WIDECHAR if (fd == -2) { len = wcstombs(NULL, path, 0); if (len == (z_size_t)-1) len = 0; } else #endif len = strlen((const char *)path); state->path = (char *)malloc(len + 1); if (state->path == NULL) { free(state); return NULL; } #ifdef WIDECHAR if (fd == -2) if (len) wcstombs(state->path, path, len + 1); else *(state->path) = 0; else #endif #if !defined(NO_snprintf) && !defined(NO_vsnprintf) (void)snprintf(state->path, len + 1, "%s", (const char *)path); #else strcpy(state->path, path); #endif /* compute the flags for open() */ oflag = #ifdef O_LARGEFILE O_LARGEFILE | #endif #ifdef O_BINARY O_BINARY | #endif #ifdef O_CLOEXEC (cloexec ? O_CLOEXEC : 0) | #endif (state->mode == GZ_READ ? O_RDONLY : (O_WRONLY | O_CREAT | #ifdef O_EXCL (exclusive ? O_EXCL : 0) | #endif (state->mode == GZ_WRITE ? O_TRUNC : O_APPEND))); /* open the file with the appropriate flags (or just use fd) */ state->fd = fd > -1 ? fd : ( #ifdef WIDECHAR fd == -2 ? _wopen(path, oflag, 0666) : #endif open((const char *)path, oflag, 0666)); if (state->fd == -1) { free(state->path); free(state); return NULL; } if (state->mode == GZ_APPEND) { LSEEK(state->fd, 0, SEEK_END); /* so gzoffset() is correct */ state->mode = GZ_WRITE; /* simplify later checks */ } /* save the current position for rewinding (only if reading) */ if (state->mode == GZ_READ) { state->start = LSEEK(state->fd, 0, SEEK_CUR); if (state->start == -1) state->start = 0; } /* initialize stream */ gz_reset(state); /* return stream */ return (gzFile)state; } /* -- see zlib.h -- */ gzFile ZEXPORT gzopen(path, mode) const char *path; const char *mode; { return gz_open(path, -1, mode); } /* -- see zlib.h -- */ gzFile ZEXPORT gzopen64(path, mode) const char *path; const char *mode; { return gz_open(path, -1, mode); } /* -- see zlib.h -- */ gzFile ZEXPORT gzdopen(fd, mode) int fd; const char *mode; { char *path; /* identifier for error messages */ gzFile gz; if (fd == -1 || (path = (char *)malloc(7 + 3 * sizeof(int))) == NULL) return NULL; #if !defined(NO_snprintf) && !defined(NO_vsnprintf) (void)snprintf(path, 7 + 3 * sizeof(int), "<fd:%d>", fd); #else sprintf(path, "<fd:%d>", fd); /* for debugging */ #endif gz = gz_open(path, fd, mode); free(path); return gz; } /* -- see zlib.h -- */ #ifdef WIDECHAR gzFile ZEXPORT gzopen_w(path, mode) const wchar_t *path; const char *mode; { return gz_open(path, -2, mode); } #endif /* -- see zlib.h -- */ int ZEXPORT gzbuffer(file, size) gzFile file; unsigned size; { gz_statep state; /* get internal structure and check integrity */ if (file == NULL) return -1; state = (gz_statep)file; if (state->mode != GZ_READ && state->mode != GZ_WRITE) return -1; /* make sure we haven't already allocated memory */ if (state->size != 0) return -1; /* check and set requested size */ if ((size << 1) < size) return -1; /* need to be able to double it */ if (size < 2) size = 2; /* need two bytes to check magic header */ state->want = size; return 0; } /* -- see zlib.h -- */ int ZEXPORT gzrewind(file) gzFile file; { gz_statep state; /* get internal structure */ if (file == NULL) return -1; state = (gz_statep)file; /* check that we're reading and that there's no error */ if (state->mode != GZ_READ || (state->err != Z_OK && state->err != Z_BUF_ERROR)) return -1; /* back up and start over */ if (LSEEK(state->fd, state->start, SEEK_SET) == -1) return -1; gz_reset(state); return 0; } /* -- see zlib.h -- */ z_off64_t ZEXPORT gzseek64(file, offset, whence) gzFile file; z_off64_t offset; int whence; { unsigned n; z_off64_t ret; gz_statep state; /* get internal structure and check integrity */ if (file == NULL) return -1; state = (gz_statep)file; if (state->mode != GZ_READ && state->mode != GZ_WRITE) return -1; /* check that there's no error */ if (state->err != Z_OK && state->err != Z_BUF_ERROR) return -1; /* can only seek from start or relative to current position */ if (whence != SEEK_SET && whence != SEEK_CUR) return -1; /* normalize offset to a SEEK_CUR specification */ if (whence == SEEK_SET) offset -= state->x.pos; else if (state->seek) offset += state->skip; state->seek = 0; /* if within raw area while reading, just go there */ if (state->mode == GZ_READ && state->how == COPY && state->x.pos + offset >= 0) { ret = LSEEK(state->fd, offset - state->x.have, SEEK_CUR); if (ret == -1) return -1; state->x.have = 0; state->eof = 0; state->past = 0; state->seek = 0; gz_error(state, Z_OK, NULL); state->strm.avail_in = 0; state->x.pos += offset; return state->x.pos; } /* calculate skip amount, rewinding if needed for back seek when reading */ if (offset < 0) { if (state->mode != GZ_READ) /* writing -- can't go backwards */ return -1; offset += state->x.pos; if (offset < 0) /* before start of file! */ return -1; if (gzrewind(file) == -1) /* rewind, then skip to offset */ return -1; } /* if reading, skip what's in output buffer (one less gzgetc() check) */ if (state->mode == GZ_READ) { n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > offset ? (unsigned)offset : state->x.have; state->x.have -= n; state->x.next += n; state->x.pos += n; offset -= n; } /* request skip (if not zero) */ if (offset) { state->seek = 1; state->skip = offset; } return state->x.pos + offset; } /* -- see zlib.h -- */ z_off_t ZEXPORT gzseek(file, offset, whence) gzFile file; z_off_t offset; int whence; { z_off64_t ret; ret = gzseek64(file, (z_off64_t)offset, whence); return ret == (z_off_t)ret ? (z_off_t)ret : -1; } /* -- see zlib.h -- */ z_off64_t ZEXPORT gztell64(file) gzFile file; { gz_statep state; /* get internal structure and check integrity */ if (file == NULL) return -1; state = (gz_statep)file; if (state->mode != GZ_READ && state->mode != GZ_WRITE) return -1; /* return position */ return state->x.pos + (state->seek ? state->skip : 0); } /* -- see zlib.h -- */ z_off_t ZEXPORT gztell(file) gzFile file; { z_off64_t ret; ret = gztell64(file); return ret == (z_off_t)ret ? (z_off_t)ret : -1; } /* -- see zlib.h -- */ z_off64_t ZEXPORT gzoffset64(file) gzFile file; { z_off64_t offset; gz_statep state; /* get internal structure and check integrity */ if (file == NULL) return -1; state = (gz_statep)file; if (state->mode != GZ_READ && state->mode != GZ_WRITE) return -1; /* compute and return effective offset in file */ offset = LSEEK(state->fd, 0, SEEK_CUR); if (offset == -1) return -1; if (state->mode == GZ_READ) /* reading */ offset -= state->strm.avail_in; /* don't count buffered input */ return offset; } /* -- see zlib.h -- */ z_off_t ZEXPORT gzoffset(file) gzFile file; { z_off64_t ret; ret = gzoffset64(file); return ret == (z_off_t)ret ? (z_off_t)ret : -1; } /* -- see zlib.h -- */ int ZEXPORT gzeof(file) gzFile file; { gz_statep state; /* get internal structure and check integrity */ if (file == NULL) return 0; state = (gz_statep)file; if (state->mode != GZ_READ && state->mode != GZ_WRITE) return 0; /* return end-of-file state */ return state->mode == GZ_READ ? state->past : 0; } /* -- see zlib.h -- */ const char * ZEXPORT gzerror(file, errnum) gzFile file; int *errnum; { gz_statep state; /* get internal structure and check integrity */ if (file == NULL) return NULL; state = (gz_statep)file; if (state->mode != GZ_READ && state->mode != GZ_WRITE) return NULL; /* return error information */ if (errnum != NULL) *errnum = state->err; return state->err == Z_MEM_ERROR ? "out of memory" : (state->msg == NULL ? "" : state->msg); } /* -- see zlib.h -- */ void ZEXPORT gzclearerr(file) gzFile file; { gz_statep state; /* get internal structure and check integrity */ if (file == NULL) return; state = (gz_statep)file; if (state->mode != GZ_READ && state->mode != GZ_WRITE) return; /* clear error and end-of-file */ if (state->mode == GZ_READ) { state->eof = 0; state->past = 0; } gz_error(state, Z_OK, NULL); } /* Create an error message in allocated memory and set state->err and state->msg accordingly. Free any previous error message already there. Do not try to free or allocate space if the error is Z_MEM_ERROR (out of memory). Simply save the error message as a static string. If there is an allocation failure constructing the error message, then convert the error to out of memory. */ void ZLIB_INTERNAL gz_error(state, err, msg) gz_statep state; int err; const char *msg; { /* free previously allocated message and clear */ if (state->msg != NULL) { if (state->err != Z_MEM_ERROR) free(state->msg); state->msg = NULL; } /* if fatal, set state->x.have to 0 so that the gzgetc() macro fails */ if (err != Z_OK && err != Z_BUF_ERROR) state->x.have = 0; /* set error code, and if no message, then done */ state->err = err; if (msg == NULL) return; /* for an out of memory error, return literal string when requested */ if (err == Z_MEM_ERROR) return; /* construct error message with path */ if ((state->msg = (char *)malloc(strlen(state->path) + strlen(msg) + 3)) == NULL) { state->err = Z_MEM_ERROR; return; } #if !defined(NO_snprintf) && !defined(NO_vsnprintf) (void)snprintf(state->msg, strlen(state->path) + strlen(msg) + 3, "%s%s%s", state->path, ": ", msg); #else strcpy(state->msg, state->path); strcat(state->msg, ": "); strcat(state->msg, msg); #endif } #ifndef INT_MAX /* portably return maximum value for an int (when limits.h presumed not available) -- we need to do this to cover cases where 2's complement not used, since C standard permits 1's complement and sign-bit representations, otherwise we could just use ((unsigned)-1) >> 1 */ unsigned ZLIB_INTERNAL gz_intmax() { unsigned p, q; p = 1; do { q = p; p <<= 1; p++; } while (p > q); return q >> 1; } #endif
{ "pile_set_name": "Github" }
module network { export class PlayCardsResolver extends IResolver{ public constructor() { super(); } /** * ε‘ι€ζΆˆζ―ε°εŒ… */ protected Package(data:any):any{ let event = { action:131, data:data }; event = data; return event; } /** * ζŽ₯ζ”ΆζΆˆζ―θ§£εŒ… */ protected Parse(data:any){ return data; } } }
{ "pile_set_name": "Github" }
/* * Copyright (C) 2016 Cavium, Inc. * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License * as published by the Free Software Foundation. */ #ifndef __REQUEST_MANAGER_H #define __REQUEST_MANAGER_H #include "cpt_common.h" #define TIME_IN_RESET_COUNT 5 #define COMPLETION_CODE_SIZE 8 #define COMPLETION_CODE_INIT 0 #define PENDING_THOLD 100 #define MAX_SG_IN_CNT 12 #define MAX_SG_OUT_CNT 13 #define SG_LIST_HDR_SIZE 8 #define MAX_BUF_CNT 16 union ctrl_info { u32 flags; struct { #if defined(__BIG_ENDIAN_BITFIELD) u32 reserved0:26; u32 grp:3; /* Group bits */ u32 dma_mode:2; /* DMA mode */ u32 se_req:1;/* To SE core */ #else u32 se_req:1; /* To SE core */ u32 dma_mode:2; /* DMA mode */ u32 grp:3; /* Group bits */ u32 reserved0:26; #endif } s; }; union opcode_info { u16 flags; struct { u8 major; u8 minor; } s; }; struct cptvf_request { union opcode_info opcode; u16 param1; u16 param2; u16 dlen; }; struct buf_ptr { u8 *vptr; dma_addr_t dma_addr; u16 size; }; struct cpt_request_info { u8 incnt; /* Number of input buffers */ u8 outcnt; /* Number of output buffers */ u16 rlen; /* Output length */ union ctrl_info ctrl; /* User control information */ struct cptvf_request req; /* Request Information (Core specific) */ struct buf_ptr in[MAX_BUF_CNT]; struct buf_ptr out[MAX_BUF_CNT]; void (*callback)(int, void *); /* Kernel ASYNC request callabck */ void *callback_arg; /* Kernel ASYNC request callabck arg */ }; struct sglist_component { union { u64 len; struct { u16 len0; u16 len1; u16 len2; u16 len3; } s; } u; u64 ptr0; u64 ptr1; u64 ptr2; u64 ptr3; }; struct cpt_info_buffer { struct cpt_vf *cptvf; unsigned long time_in; u8 extra_time; struct cpt_request_info *req; dma_addr_t dptr_baddr; u32 dlen; dma_addr_t rptr_baddr; dma_addr_t comp_baddr; u8 *in_buffer; u8 *out_buffer; u8 *gather_components; u8 *scatter_components; struct pending_entry *pentry; volatile u64 *completion_addr; volatile u64 *alternate_caddr; }; /* * CPT_INST_S software command definitions * Words EI (0-3) */ union vq_cmd_word0 { u64 u64; struct { u16 opcode; u16 param1; u16 param2; u16 dlen; } s; }; union vq_cmd_word3 { u64 u64; struct { #if defined(__BIG_ENDIAN_BITFIELD) u64 grp:3; u64 cptr:61; #else u64 cptr:61; u64 grp:3; #endif } s; }; struct cpt_vq_command { union vq_cmd_word0 cmd; u64 dptr; u64 rptr; union vq_cmd_word3 cptr; }; void vq_post_process(struct cpt_vf *cptvf, u32 qno); int process_request(struct cpt_vf *cptvf, struct cpt_request_info *req); #endif /* __REQUEST_MANAGER_H */
{ "pile_set_name": "Github" }
<?php namespace GuzzleHttp\Exception; use GuzzleHttp\Promise\PromiseInterface; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\UriInterface; /** * HTTP Request exception */ class RequestException extends TransferException { /** @var RequestInterface */ private $request; /** @var ResponseInterface|null */ private $response; /** @var array */ private $handlerContext; public function __construct( $message, RequestInterface $request, ResponseInterface $response = null, \Exception $previous = null, array $handlerContext = [] ) { // Set the code of the exception if the response is set and not future. $code = $response && !($response instanceof PromiseInterface) ? $response->getStatusCode() : 0; parent::__construct($message, $code, $previous); $this->request = $request; $this->response = $response; $this->handlerContext = $handlerContext; } /** * Wrap non-RequestExceptions with a RequestException * * @param RequestInterface $request * @param \Exception $e * * @return RequestException */ public static function wrapException(RequestInterface $request, \Exception $e) { return $e instanceof RequestException ? $e : new RequestException($e->getMessage(), $request, null, $e); } /** * Factory method to create a new exception with a normalized error message * * @param RequestInterface $request Request * @param ResponseInterface $response Response received * @param \Exception $previous Previous exception * @param array $ctx Optional handler context. * * @return self */ public static function create( RequestInterface $request, ResponseInterface $response = null, \Exception $previous = null, array $ctx = [] ) { if (!$response) { return new self( 'Error completing request', $request, null, $previous, $ctx ); } $level = (int) floor($response->getStatusCode() / 100); if ($level === 4) { $label = 'Client error'; $className = ClientException::class; } elseif ($level === 5) { $label = 'Server error'; $className = ServerException::class; } else { $label = 'Unsuccessful request'; $className = __CLASS__; } $uri = $request->getUri(); $uri = static::obfuscateUri($uri); // Client Error: `GET /` resulted in a `404 Not Found` response: // <html> ... (truncated) $message = sprintf( '%s: `%s %s` resulted in a `%s %s` response', $label, $request->getMethod(), $uri, $response->getStatusCode(), $response->getReasonPhrase() ); $summary = static::getResponseBodySummary($response); if ($summary !== null) { $message .= ":\n{$summary}\n"; } return new $className($message, $request, $response, $previous, $ctx); } /** * Get a short summary of the response * * Will return `null` if the response is not printable. * * @param ResponseInterface $response * * @return string|null */ public static function getResponseBodySummary(ResponseInterface $response) { return \GuzzleHttp\Psr7\get_message_body_summary($response); } /** * Obfuscates URI if there is a username and a password present * * @param UriInterface $uri * * @return UriInterface */ private static function obfuscateUri(UriInterface $uri) { $userInfo = $uri->getUserInfo(); if (false !== ($pos = strpos($userInfo, ':'))) { return $uri->withUserInfo(substr($userInfo, 0, $pos), '***'); } return $uri; } /** * Get the request that caused the exception * * @return RequestInterface */ public function getRequest() { return $this->request; } /** * Get the associated response * * @return ResponseInterface|null */ public function getResponse() { return $this->response; } /** * Check if a response was received * * @return bool */ public function hasResponse() { return $this->response !== null; } /** * Get contextual information about the error from the underlying handler. * * The contents of this array will vary depending on which handler you are * using. It may also be just an empty array. Relying on this data will * couple you to a specific handler, but can give more debug information * when needed. * * @return array */ public function getHandlerContext() { return $this->handlerContext; } }
{ "pile_set_name": "Github" }
ο»Ώusing System; using System.Collections.Generic; using System.ComponentModel; using AudioBand.AudioSource; namespace AudioBand.TextFormatting { /// <summary> /// A placeholder text that has values based on the current song. /// </summary> public abstract class TextPlaceholder { private readonly HashSet<string> _propertyFilter = new HashSet<string>(); /// <summary> /// Initializes a new instance of the <see cref="TextPlaceholder"/> class. /// </summary> /// <param name="parameters">The parameters passed to the text format.</param> /// <param name="audioSession">The audio session to use for the placeholder value.</param> protected TextPlaceholder(IEnumerable<TextPlaceholderParameter> parameters, IAudioSession audioSession) { Session = audioSession; Session.PropertyChanged += AudioSessionOnPropertyChanged; // TODO parameters } /// <summary> /// Occurs when the placeholders text has changed. /// </summary> public event EventHandler TextChanged; /// <summary> /// Gets the audio session. /// </summary> protected IAudioSession Session { get; private set; } /// <summary> /// Gets the current text value for the placeholder. /// </summary> /// <returns>The value.</returns> public abstract string GetText(); /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected void RaiseTextChanged() { TextChanged?.Invoke(this, EventArgs.Empty); } /// <summary> /// Gets the parameter from the name. /// </summary> /// <param name="parameterName">The parameter name.</param> /// <returns>The value of the parameter or null if not passed in.</returns> protected string GetParameter(string parameterName) { return null; } /// <summary> /// Adds a filter for <see cref="OnAudioSessionPropertyChanged"/>. /// </summary> /// <param name="audioSessionPropertyName">The property name to filter.</param> protected void AddSessionPropertyFilter(string audioSessionPropertyName) { _propertyFilter.Add(audioSessionPropertyName); } /// <summary> /// Called when the audio session property value changes. /// </summary> /// <param name="propertyName">The name of the property that changed.</param> protected virtual void OnAudioSessionPropertyChanged(string propertyName) { } private void AudioSessionOnPropertyChanged(object sender, PropertyChangedEventArgs e) { if (_propertyFilter.Contains(e.PropertyName) || _propertyFilter.Count == 0) { OnAudioSessionPropertyChanged(e.PropertyName); } } } }
{ "pile_set_name": "Github" }
import decimalAdjust from "discourse/lib/decimal-adjust"; export default function (value, exp) { return decimalAdjust("round", value, exp); }
{ "pile_set_name": "Github" }
/* * Copyright (C) 2016 Red Hat, 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. */ package io.syndesis.server.api.generator; import io.syndesis.common.model.api.APISummary; import io.syndesis.common.model.connection.ConfigurationProperty; import io.syndesis.common.model.connection.Connector; import io.syndesis.common.model.connection.ConnectorGroup; import io.syndesis.common.model.connection.ConnectorSettings; import io.syndesis.common.model.connection.ConnectorTemplate; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class ConnectorGeneratorTest { private final ConnectorGenerator generator = new ConnectorGenerator(new Connector.Builder() .addTags("from-connector") .build()) { @Override public Connector generate(final ConnectorTemplate connectorTemplate, final ConnectorSettings connectorSettings) { return null; } @Override public APISummary info(final ConnectorTemplate connectorTemplate, final ConnectorSettings connectorSettings) { return null; } @Override protected String determineConnectorDescription(final ConnectorTemplate connectorTemplate, final ConnectorSettings connectorSettings) { return "test-description"; } @Override protected String determineConnectorName(final ConnectorTemplate connectorTemplate, final ConnectorSettings connectorSettings) { return "test-name"; } }; private final ConnectorTemplate template = new ConnectorTemplate.Builder() .id("template-id") .connectorGroup(new ConnectorGroup.Builder().id("template-group").build()) .putProperty("property1", new ConfigurationProperty.Builder().build()) .putProperty("property2", new ConfigurationProperty.Builder().build()) .build(); @Test public void shouldCreateBaseConnectors() { final ConnectorSettings settings = new ConnectorSettings.Builder().putConfiguredProperty("property2", "value2").build(); final Connector connector = generator.baseConnectorFrom(template, settings); assertThat(connector).isEqualToIgnoringGivenFields( new Connector.Builder() .name("test-name") .description("test-description") .addTags("from-connector") .connectorGroup(template.getConnectorGroup()) .connectorGroupId("template-group") .properties(template.getConnectorProperties()) .putConfiguredProperty("property2", "value2") .build(), "id", "icon"); assertThat(connector.getIcon()).isEqualTo("data:image/svg+xml,dummy"); } @Test public void shouldCreateBaseConnectorsWithGivenNameAndDescription() { final ConnectorSettings settings = new ConnectorSettings.Builder().name("given-name").description("given-description") .putConfiguredProperty("property2", "value2").build(); final Connector connector = generator.baseConnectorFrom(template, settings); assertThat(connector).isEqualToIgnoringGivenFields( new Connector.Builder() .name("given-name") .description("given-description") .addTags("from-connector") .connectorGroup(template.getConnectorGroup()) .connectorGroupId("template-group") .properties(template.getConnectorProperties()) .putConfiguredProperty("property2", "value2").build(), "id", "icon"); assertThat(connector.getIcon()).isEqualTo("data:image/svg+xml,dummy"); } }
{ "pile_set_name": "Github" }
// Copyright 2012 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 windows package main import ( "fmt" "time" "golang.org/x/sys/windows/svc" "golang.org/x/sys/windows/svc/mgr" ) func startService(name string) error { m, err := mgr.Connect() if err != nil { return err } defer m.Disconnect() s, err := m.OpenService(name) if err != nil { return fmt.Errorf("could not access service: %v", err) } defer s.Close() err = s.Start("is", "manual-started") if err != nil { return fmt.Errorf("could not start service: %v", err) } return nil } func controlService(name string, c svc.Cmd, to svc.State) error { m, err := mgr.Connect() if err != nil { return err } defer m.Disconnect() s, err := m.OpenService(name) if err != nil { return fmt.Errorf("could not access service: %v", err) } defer s.Close() status, err := s.Control(c) if err != nil { return fmt.Errorf("could not send control=%d: %v", c, err) } timeout := time.Now().Add(10 * time.Second) for status.State != to { if timeout.Before(time.Now()) { return fmt.Errorf("timeout waiting for service to go to state=%d", to) } time.Sleep(300 * time.Millisecond) status, err = s.Query() if err != nil { return fmt.Errorf("could not retrieve service status: %v", err) } } return nil }
{ "pile_set_name": "Github" }
/******************************************************************************* * Copyright 2012-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file 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. * ***************************************************************************** * * AWS Tools for Windows (TM) PowerShell (TM) * */ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using Amazon.PowerShell.Common; using Amazon.Runtime; using Amazon.GroundStation; using Amazon.GroundStation.Model; namespace Amazon.PowerShell.Cmdlets.GS { /// <summary> /// Returns a mission profile. /// </summary> [Cmdlet("Get", "GSMissionProfile")] [OutputType("Amazon.GroundStation.Model.GetMissionProfileResponse")] [AWSCmdlet("Calls the AWS Ground Station GetMissionProfile API operation.", Operation = new[] {"GetMissionProfile"}, SelectReturnType = typeof(Amazon.GroundStation.Model.GetMissionProfileResponse))] [AWSCmdletOutput("Amazon.GroundStation.Model.GetMissionProfileResponse", "This cmdlet returns an Amazon.GroundStation.Model.GetMissionProfileResponse object containing multiple properties. The object can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class GetGSMissionProfileCmdlet : AmazonGroundStationClientCmdlet, IExecutor { #region Parameter MissionProfileId /// <summary> /// <para> /// <para>UUID of a mission profile.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] #else [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String MissionProfileId { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The default value is '*'. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.GroundStation.Model.GetMissionProfileResponse). /// Specifying the name of a property of type Amazon.GroundStation.Model.GetMissionProfileResponse will result in that property being returned. /// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public string Select { get; set; } = "*"; #endregion #region Parameter PassThru /// <summary> /// Changes the cmdlet behavior to return the value passed to the MissionProfileId parameter. /// The -PassThru parameter is deprecated, use -Select '^MissionProfileId' instead. This parameter will be removed in a future version. /// </summary> [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^MissionProfileId' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion protected override void ProcessRecord() { base.ProcessRecord(); var context = new CmdletContext(); // allow for manipulation of parameters prior to loading into context PreExecutionContextLoad(context); #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute if (ParameterWasBound(nameof(this.Select))) { context.Select = CreateSelectDelegate<Amazon.GroundStation.Model.GetMissionProfileResponse, GetGSMissionProfileCmdlet>(Select) ?? throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select)); if (this.PassThru.IsPresent) { throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select)); } } else if (this.PassThru.IsPresent) { context.Select = (response, cmdlet) => this.MissionProfileId; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute context.MissionProfileId = this.MissionProfileId; #if MODULAR if (this.MissionProfileId == null && ParameterWasBound(nameof(this.MissionProfileId))) { WriteWarning("You are passing $null as a value for parameter MissionProfileId which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; // create request var request = new Amazon.GroundStation.Model.GetMissionProfileRequest(); if (cmdletContext.MissionProfileId != null) { request.MissionProfileId = cmdletContext.MissionProfileId; } CmdletOutput output; // issue call var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; pipelineOutput = cmdletContext.Select(response, this); output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } return output; } public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.GroundStation.Model.GetMissionProfileResponse CallAWSServiceOperation(IAmazonGroundStation client, Amazon.GroundStation.Model.GetMissionProfileRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS Ground Station", "GetMissionProfile"); try { #if DESKTOP return client.GetMissionProfile(request); #elif CORECLR return client.GetMissionProfileAsync(request).GetAwaiter().GetResult(); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } } #endregion internal partial class CmdletContext : ExecutorContext { public System.String MissionProfileId { get; set; } public System.Func<Amazon.GroundStation.Model.GetMissionProfileResponse, GetGSMissionProfileCmdlet, object> Select { get; set; } = (response, cmdlet) => response; } } }
{ "pile_set_name": "Github" }
/// Copyright (c) 2012 Ecma International. All rights reserved. /// Ecma International makes this code available under the terms and conditions set /// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the /// "Use Terms"). Any redistribution of this code must retain the above /// copyright and this notice and otherwise comply with the Use Terms. /** * @path ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-4-267.js * @description Object.defineProperty - 'O' is an Array, 'name' is an array index named property, name is accessor property and 'desc' is accessor descriptor, test updating the [[Get]] attribute value of 'name' from undefined to function object (15.4.5.1 step 4.c) */ function testcase() { var arrObj = []; function getFunc() { return 12; } Object.defineProperty(arrObj, "0", { get: undefined, configurable: true }); Object.defineProperty(arrObj, "0", { get: getFunc }); return accessorPropertyAttributesAreCorrect(arrObj, "0", getFunc, undefined, undefined, false, true); } runTestCase(testcase);
{ "pile_set_name": "Github" }
// Configure enzyme adapter const enzyme = require('enzyme'); const Adapter = require('enzyme-adapter-react-16'); enzyme.configure({ adapter: new Adapter() }); // require all modules ending in ".spec" from the // current directory and all subdirectories const testsContext = require.context('./src', true, /.spec$/); testsContext.keys().forEach(testsContext); const componentsContext = require.context('./src', true, /.ts$/); componentsContext.keys().forEach(componentsContext);
{ "pile_set_name": "Github" }
export * from './styles' export * from './accessibility' export * from './common' export * from './strings' export * from './window' export * from './isFixed'
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleName</key> <string>EtoApp.1</string> <key>CFBundleIdentifier</key> <string>com.example.EtoApp.1</string> <key>CFBundleShortVersionString</key> <string>1.0</string> <key>LSMinimumSystemVersion</key> <string>10.12</string> <key>CFBundleDevelopmentRegion</key> <string>en</string> <key>NSHumanReadableCopyright</key> <string></string> <key>CFBundleIconFile</key> <string>Icon.icns</string> </dict> </plist>
{ "pile_set_name": "Github" }
// Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #include "leveldb/options.h" #include "leveldb/comparator.h" #include "leveldb/env.h" namespace leveldb { Options::Options() : comparator(BytewiseComparator()), create_if_missing(false), error_if_exists(false), paranoid_checks(false), env(Env::Default()), info_log(NULL), write_buffer_size(4<<20), max_open_files(1000), block_cache(NULL), block_size(4096), block_restart_interval(16), max_file_size(2<<20), compression(kSnappyCompression), reuse_logs(false), filter_policy(NULL) { } } // namespace leveldb
{ "pile_set_name": "Github" }
// RUN: llvm-mc -triple i686-elf -filetype asm -o - %s | FileCheck %s .type TYPE STT_FUNC // CHECK: .type TYPE,@function .type comma_TYPE, STT_FUNC // CHECK: .type comma_TYPE,@function .type at_TYPE, @STT_FUNC // CHECK: .type at_TYPE,@function .type percent_TYPE, %STT_FUNC // CHECK: .type percent_TYPE,@function .type string_TYPE, "STT_FUNC" // CHECK: .type string_TYPE,@function .type type function // CHECK: .type type,@function .type comma_type, function // CHECK: .type comma_type,@function .type at_type, @function // CHECK: .type at_type,@function .type percent_type, %function // CHECK: .type percent_type,@function .type string_type, "function" // CHECK: .type string_type,@function .type special gnu_unique_object // CHECK: .type special,@gnu_unique_object .type comma_special, gnu_unique_object // CHECK: .type comma_special,@gnu_unique_object
{ "pile_set_name": "Github" }
<b:style src="./Node.css"/> <b:style src="./Node_Expander.css"/> <b:style src="./Folder.css"/> <b:define name="selected" type="bool"/> <b:define name="collapsed" type="bool"/> <b:define name="disabled" type="bool"/> <li class="Basis-TreeNode"> <div{content} class="Basis-TreeNode-Title"> <div class="Basis-TreeNode_Expander Basis-TreeNode_Expander__{collapsed}" event-click="toggle" /> <span class="Basis-TreeNode-Caption Basis-TreeNode-FolderCaption Basis-TreeNode-FolderCaption_{collapsed} Basis-TreeNode-Caption__{disabled} Basis-TreeNode-Caption__{selected}" event-click="select"> {title} </span> </div> <ul{childNodesElement} class="Basis-TreeNode-Content Basis-TreeNode-Content__{collapsed}"/> </li>
{ "pile_set_name": "Github" }
// Copyright Oliver Kowalke 2009. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <boost/config.hpp> #if defined(BOOST_USE_SEGMENTED_STACKS) # if defined(BOOST_WINDOWS) # error "segmented stacks are not supported by Windows" # else # include <boost/coroutine/posix/segmented_stack_allocator.hpp> # endif #endif
{ "pile_set_name": "Github" }
#ifdef __OBJC__ #import <UIKit/UIKit.h> #else #ifndef FOUNDATION_EXPORT #if defined(__cplusplus) #define FOUNDATION_EXPORT extern "C" #else #define FOUNDATION_EXPORT extern #endif #endif #endif #import "MotionOrientation.h" FOUNDATION_EXPORT double MotionOrientation_PTEzVersionNumber; FOUNDATION_EXPORT const unsigned char MotionOrientation_PTEzVersionString[];
{ "pile_set_name": "Github" }
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import <Foundation/Foundation.h> #import "SDWebImageCompat.h" #import "SDImageCoder.h" /// A player to control the playback of animated image, which can be used to drive Animated ImageView or any rendering usage, like CALayer/WatchKit/SwiftUI rendering. @interface SDAnimatedImagePlayer : NSObject /// Current playing frame image. This value is KVO Compliance. @property (nonatomic, readonly, nullable) UIImage *currentFrame; /// Current frame index, zero based. This value is KVO Compliance. @property (nonatomic, readonly) NSUInteger currentFrameIndex; /// Current loop count since its latest animating. This value is KVO Compliance. @property (nonatomic, readonly) NSUInteger currentLoopCount; /// Total frame count for niamted image rendering. Defaults is animated image's frame count. /// @note For progressive animation, you can update this value when your provider receive more frames. @property (nonatomic, assign) NSUInteger totalFrameCount; /// Total loop count for animated image rendering. Default is animated image's loop count. @property (nonatomic, assign) NSUInteger totalLoopCount; /// The animation playback rate. Default is 1.0 /// `1.0` means the normal speed. /// `0.0` means stopping the animation. /// `0.0-1.0` means the slow speed. /// `> 1.0` means the fast speed. /// `< 0.0` is not supported currently and stop animation. (may support reverse playback in the future) @property (nonatomic, assign) double playbackRate; /// Provide a max buffer size by bytes. This is used to adjust frame buffer count and can be useful when the decoding cost is expensive (such as Animated WebP software decoding). Default is 0. /// `0` means automatically adjust by calculating current memory usage. /// `1` means without any buffer cache, each of frames will be decoded and then be freed after rendering. (Lowest Memory and Highest CPU) /// `NSUIntegerMax` means cache all the buffer. (Lowest CPU and Highest Memory) @property (nonatomic, assign) NSUInteger maxBufferSize; /// You can specify a runloop mode to let it rendering. /// Default is NSRunLoopCommonModes on multi-core device, NSDefaultRunLoopMode on single-core device @property (nonatomic, copy, nonnull) NSRunLoopMode runLoopMode; /// Create a player with animated image provider. If the provider's `animatedImageFrameCount` is less than 1, returns nil. /// The provider can be any protocol implementation, like `SDAnimatedImage`, `SDImageGIFCoder`, etc. /// @note This provider can represent mutable content, like prorgessive animated loading. But you need to update the frame count by yourself /// @param provider The animated provider - (nullable instancetype)initWithProvider:(nonnull id<SDAnimatedImageProvider>)provider; /// Create a player with animated image provider. If the provider's `animatedImageFrameCount` is less than 1, returns nil. /// The provider can be any protocol implementation, like `SDAnimatedImage` or `SDImageGIFCoder`, etc. /// @note This provider can represent mutable content, like prorgessive animated loading. But you need to update the frame count by yourself /// @param provider The animated provider + (nullable instancetype)playerWithProvider:(nonnull id<SDAnimatedImageProvider>)provider; /// The handler block when current frame and index changed. @property (nonatomic, copy, nullable) void (^animationFrameHandler)(NSUInteger index, UIImage * _Nonnull frame); /// The handler block when one loop count finished. @property (nonatomic, copy, nullable) void (^animationLoopHandler)(NSUInteger loopCount); /// Return the status whehther animation is playing. @property (nonatomic, readonly) BOOL isPlaying; /// Start the animation. Or resume the previously paused animation. - (void)startPlaying; /// Pause the aniamtion. Keep the current frame index and loop count. - (void)pausePlaying; /// Stop the animation. Reset the current frame index and loop count. - (void)stopPlaying; /// Seek to the desired frame index and loop count. /// @note This can be used for advanced control like progressive loading, or skipping specify frames. /// @param index The frame index /// @param loopCount The loop count - (void)seekToFrameAtIndex:(NSUInteger)index loopCount:(NSUInteger)loopCount; /// Clear the frame cache buffer. The frame cache buffer size can be controled by `maxBufferSize`. /// By default, when stop or pause the animation, the frame buffer is still kept to ready for the next restart - (void)clearFrameBuffer; @end
{ "pile_set_name": "Github" }
from __future__ import absolute_import from builtins import str from .base_monitor import BaseMonitor from kafka import KafkaProducer from kafka.common import KafkaUnavailableError from scutils.method_timer import MethodTimer from retrying import retry import json import sys import traceback class KafkaBaseMonitor(BaseMonitor): ''' Base monitor for handling outbound Kafka results ''' def setup(self, settings): ''' Setup the handler @param settings: The loaded settings file ''' self.producer = self._create_producer(settings) self.topic_prefix = settings['KAFKA_TOPIC_PREFIX'] self.use_appid_topics = settings['KAFKA_APPID_TOPICS'] self.logger.debug("Successfully connected to Kafka in {name}" .format(name=self.__class__.__name__)) @retry(wait_exponential_multiplier=500, wait_exponential_max=10000) def _create_producer(self, settings): """Tries to establish a Kafka consumer connection""" try: brokers = settings['KAFKA_HOSTS'] self.logger.debug("Creating new kafka producer using brokers: " + str(brokers)) return KafkaProducer(bootstrap_servers=brokers, value_serializer=lambda m: json.dumps(m), retries=3, linger_ms=settings['KAFKA_PRODUCER_BATCH_LINGER_MS'], buffer_memory=settings['KAFKA_PRODUCER_BUFFER_BYTES']) except KeyError as e: self.logger.error('Missing setting named ' + str(e), {'ex': traceback.format_exc()}) except: self.logger.error("Couldn't initialize kafka producer in plugin.", {'ex': traceback.format_exc()}) raise def _kafka_success(self, response): ''' Callback for successful send ''' self.logger.debug("Sent message to Kafka") def _kafka_failure(self, response): ''' Callback for failed send ''' self.logger.error("Failed to send message to Kafka") def _send_to_kafka(self, master): ''' Sends the message back to Kafka @param master: the final dict to send @returns: True if successfully sent to kafka ''' appid_topic = "{prefix}.outbound_{appid}".format( prefix=self.topic_prefix, appid=master['appid']) firehose_topic = "{prefix}.outbound_firehose".format( prefix=self.topic_prefix) try: # dont want logger in outbound kafka message if self.use_appid_topics: f1 = self.producer.send(appid_topic, master) f1.add_callback(self._kafka_success) f1.add_errback(self._kafka_failure) f2 = self.producer.send(firehose_topic, master) f2.add_callback(self._kafka_success) f2.add_errback(self._kafka_failure) return True except Exception as ex: message = "An exception '{0}' occured while sending a message " \ "to kafka. Arguments:\n{1!r}" \ .format(type(ex).__name__, ex.args) self.logger.error(message) return False def close(self): self.producer.flush() self.producer.close(timeout=10)
{ "pile_set_name": "Github" }
/* YUI 3.7.3 (build 5687) Copyright 2012 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ if (typeof _yuitest_coverage == "undefined"){ _yuitest_coverage = {}; _yuitest_coverline = function(src, line){ var coverage = _yuitest_coverage[src]; if (!coverage.lines[line]){ coverage.calledLines++; } coverage.lines[line]++; }; _yuitest_coverfunc = function(src, name, line){ var coverage = _yuitest_coverage[src], funcId = name + ":" + line; if (!coverage.functions[funcId]){ coverage.calledFunctions++; } coverage.functions[funcId]++; }; } _yuitest_coverage["build/yui-later/yui-later.js"] = { lines: {}, functions: {}, coveredLines: 0, calledLines: 0, coveredFunctions: 0, calledFunctions: 0, path: "build/yui-later/yui-later.js", code: [] }; _yuitest_coverage["build/yui-later/yui-later.js"].code=["YUI.add('yui-later', function (Y, NAME) {","","/**"," * Provides a setTimeout/setInterval wrapper. This module is a `core` YUI module, <a href=\"../classes/YUI.html#method_later\">it's documentation is located under the YUI class</a>."," *"," * @module yui"," * @submodule yui-later"," */","","var NO_ARGS = [];","","/**"," * Executes the supplied function in the context of the supplied"," * object 'when' milliseconds later. Executes the function a"," * single time unless periodic is set to true."," * @for YUI"," * @method later"," * @param when {int} the number of milliseconds to wait until the fn"," * is executed."," * @param o the context object."," * @param fn {Function|String} the function to execute or the name of"," * the method in the 'o' object to execute."," * @param data [Array] data that is provided to the function. This"," * accepts either a single item or an array. If an array is provided,"," * the function is executed with one parameter for each array item."," * If you need to pass a single array parameter, it needs to be wrapped"," * in an array [myarray]."," *"," * Note: native methods in IE may not have the call and apply methods."," * In this case, it will work, but you are limited to four arguments."," *"," * @param periodic {boolean} if true, executes continuously at supplied"," * interval until canceled."," * @return {object} a timer object. Call the cancel() method on this"," * object to stop the timer."," */","Y.later = function(when, o, fn, data, periodic) {"," when = when || 0;"," data = (!Y.Lang.isUndefined(data)) ? Y.Array(data) : NO_ARGS;"," o = o || Y.config.win || Y;",""," var cancelled = false,"," method = (o && Y.Lang.isString(fn)) ? o[fn] : fn,"," wrapper = function() {"," // IE 8- may execute a setInterval callback one last time"," // after clearInterval was called, so in order to preserve"," // the cancel() === no more runny-run, we have to jump through"," // an extra hoop."," if (!cancelled) {"," if (!method.apply) {"," method(data[0], data[1], data[2], data[3]);"," } else {"," method.apply(o, data || NO_ARGS);"," }"," }"," },"," id = (periodic) ? setInterval(wrapper, when) : setTimeout(wrapper, when);",""," return {"," id: id,"," interval: periodic,"," cancel: function() {"," cancelled = true;"," if (this.interval) {"," clearInterval(id);"," } else {"," clearTimeout(id);"," }"," }"," };","};","","Y.Lang.later = Y.later;","","","","}, '3.7.3', {\"requires\": [\"yui-base\"]});"]; _yuitest_coverage["build/yui-later/yui-later.js"].lines = {"1":0,"10":0,"37":0,"38":0,"39":0,"40":0,"42":0,"49":0,"50":0,"51":0,"53":0,"59":0,"63":0,"64":0,"65":0,"67":0,"73":0}; _yuitest_coverage["build/yui-later/yui-later.js"].functions = {"wrapper:44":0,"cancel:62":0,"later:37":0,"(anonymous 1):1":0}; _yuitest_coverage["build/yui-later/yui-later.js"].coveredLines = 17; _yuitest_coverage["build/yui-later/yui-later.js"].coveredFunctions = 4; _yuitest_coverline("build/yui-later/yui-later.js", 1); YUI.add('yui-later', function (Y, NAME) { /** * Provides a setTimeout/setInterval wrapper. This module is a `core` YUI module, <a href="../classes/YUI.html#method_later">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-later */ _yuitest_coverfunc("build/yui-later/yui-later.js", "(anonymous 1)", 1); _yuitest_coverline("build/yui-later/yui-later.js", 10); var NO_ARGS = []; /** * Executes the supplied function in the context of the supplied * object 'when' milliseconds later. Executes the function a * single time unless periodic is set to true. * @for YUI * @method later * @param when {int} the number of milliseconds to wait until the fn * is executed. * @param o the context object. * @param fn {Function|String} the function to execute or the name of * the method in the 'o' object to execute. * @param data [Array] data that is provided to the function. This * accepts either a single item or an array. If an array is provided, * the function is executed with one parameter for each array item. * If you need to pass a single array parameter, it needs to be wrapped * in an array [myarray]. * * Note: native methods in IE may not have the call and apply methods. * In this case, it will work, but you are limited to four arguments. * * @param periodic {boolean} if true, executes continuously at supplied * interval until canceled. * @return {object} a timer object. Call the cancel() method on this * object to stop the timer. */ _yuitest_coverline("build/yui-later/yui-later.js", 37); Y.later = function(when, o, fn, data, periodic) { _yuitest_coverfunc("build/yui-later/yui-later.js", "later", 37); _yuitest_coverline("build/yui-later/yui-later.js", 38); when = when || 0; _yuitest_coverline("build/yui-later/yui-later.js", 39); data = (!Y.Lang.isUndefined(data)) ? Y.Array(data) : NO_ARGS; _yuitest_coverline("build/yui-later/yui-later.js", 40); o = o || Y.config.win || Y; _yuitest_coverline("build/yui-later/yui-later.js", 42); var cancelled = false, method = (o && Y.Lang.isString(fn)) ? o[fn] : fn, wrapper = function() { // IE 8- may execute a setInterval callback one last time // after clearInterval was called, so in order to preserve // the cancel() === no more runny-run, we have to jump through // an extra hoop. _yuitest_coverfunc("build/yui-later/yui-later.js", "wrapper", 44); _yuitest_coverline("build/yui-later/yui-later.js", 49); if (!cancelled) { _yuitest_coverline("build/yui-later/yui-later.js", 50); if (!method.apply) { _yuitest_coverline("build/yui-later/yui-later.js", 51); method(data[0], data[1], data[2], data[3]); } else { _yuitest_coverline("build/yui-later/yui-later.js", 53); method.apply(o, data || NO_ARGS); } } }, id = (periodic) ? setInterval(wrapper, when) : setTimeout(wrapper, when); _yuitest_coverline("build/yui-later/yui-later.js", 59); return { id: id, interval: periodic, cancel: function() { _yuitest_coverfunc("build/yui-later/yui-later.js", "cancel", 62); _yuitest_coverline("build/yui-later/yui-later.js", 63); cancelled = true; _yuitest_coverline("build/yui-later/yui-later.js", 64); if (this.interval) { _yuitest_coverline("build/yui-later/yui-later.js", 65); clearInterval(id); } else { _yuitest_coverline("build/yui-later/yui-later.js", 67); clearTimeout(id); } } }; }; _yuitest_coverline("build/yui-later/yui-later.js", 73); Y.Lang.later = Y.later; }, '3.7.3', {"requires": ["yui-base"]});
{ "pile_set_name": "Github" }
package br.com.swconsultoria.nfe.schema_4.retConsReciNFe; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Classe Java de KeyInfoType complex type. * * <p>O seguinte fragmento do esquema especifica o contedo esperado contido dentro desta classe. * * <pre> * &lt;complexType name="KeyInfoType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="X509Data" type="{http://www.w3.org/2000/09/xmldsig#}X509DataType"/> * &lt;/sequence> * &lt;attribute name="Id" type="{http://www.w3.org/2001/XMLSchema}ID" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "KeyInfoType", namespace = "http://www.w3.org/2000/09/xmldsig#", propOrder = { "x509Data" }) public class KeyInfoType { @XmlElement(name = "X509Data", namespace = "http://www.w3.org/2000/09/xmldsig#", required = true) protected X509DataType x509Data; @XmlAttribute(name = "Id") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected String id; /** * Obtm o valor da propriedade x509Data. * * @return * possible object is * {@link X509DataType } * */ public X509DataType getX509Data() { return x509Data; } /** * Define o valor da propriedade x509Data. * * @param value * allowed object is * {@link X509DataType } * */ public void setX509Data(X509DataType value) { this.x509Data = value; } /** * Obtm o valor da propriedade id. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Define o valor da propriedade id. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } }
{ "pile_set_name": "Github" }
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "AM", "PM" ], "DAY": [ "\u0432\u043e\u0441\u043a\u0440\u0435\u0441\u0435\u043d\u044c\u0435", "\u043f\u043e\u043d\u0435\u0434\u0435\u043b\u044c\u043d\u0438\u043a", "\u0432\u0442\u043e\u0440\u043d\u0438\u043a", "\u0441\u0440\u0435\u0434\u0430", "\u0447\u0435\u0442\u0432\u0435\u0440\u0433", "\u043f\u044f\u0442\u043d\u0438\u0446\u0430", "\u0441\u0443\u0431\u0431\u043e\u0442\u0430" ], "ERANAMES": [ "\u0434\u043e \u043d. \u044d.", "\u043d. \u044d." ], "ERAS": [ "\u0434\u043e \u043d. \u044d.", "\u043d. \u044d." ], "FIRSTDAYOFWEEK": 0, "MONTH": [ "\u044f\u043d\u0432\u0430\u0440\u044f", "\u0444\u0435\u0432\u0440\u0430\u043b\u044f", "\u043c\u0430\u0440\u0442\u0430", "\u0430\u043f\u0440\u0435\u043b\u044f", "\u043c\u0430\u044f", "\u0438\u044e\u043d\u044f", "\u0438\u044e\u043b\u044f", "\u0430\u0432\u0433\u0443\u0441\u0442\u0430", "\u0441\u0435\u043d\u0442\u044f\u0431\u0440\u044f", "\u043e\u043a\u0442\u044f\u0431\u0440\u044f", "\u043d\u043e\u044f\u0431\u0440\u044f", "\u0434\u0435\u043a\u0430\u0431\u0440\u044f" ], "SHORTDAY": [ "\u0432\u0441", "\u043f\u043d", "\u0432\u0442", "\u0441\u0440", "\u0447\u0442", "\u043f\u0442", "\u0441\u0431" ], "SHORTMONTH": [ "\u044f\u043d\u0432.", "\u0444\u0435\u0432\u0440.", "\u043c\u0430\u0440\u0442\u0430", "\u0430\u043f\u0440.", "\u043c\u0430\u044f", "\u0438\u044e\u043d\u044f", "\u0438\u044e\u043b\u044f", "\u0430\u0432\u0433.", "\u0441\u0435\u043d\u0442.", "\u043e\u043a\u0442.", "\u043d\u043e\u044f\u0431.", "\u0434\u0435\u043a." ], "STANDALONEMONTH": [ "\u044f\u043d\u0432\u0430\u0440\u044c", "\u0444\u0435\u0432\u0440\u0430\u043b\u044c", "\u043c\u0430\u0440\u0442", "\u0430\u043f\u0440\u0435\u043b\u044c", "\u043c\u0430\u0439", "\u0438\u044e\u043d\u044c", "\u0438\u044e\u043b\u044c", "\u0430\u0432\u0433\u0443\u0441\u0442", "\u0441\u0435\u043d\u0442\u044f\u0431\u0440\u044c", "\u043e\u043a\u0442\u044f\u0431\u0440\u044c", "\u043d\u043e\u044f\u0431\u0440\u044c", "\u0434\u0435\u043a\u0430\u0431\u0440\u044c" ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE, d MMMM y '\u0433'.", "longDate": "d MMMM y '\u0433'.", "medium": "d MMM y '\u0433'. H:mm:ss", "mediumDate": "d MMM y '\u0433'.", "mediumTime": "H:mm:ss", "short": "dd.MM.yy H:mm", "shortDate": "dd.MM.yy", "shortTime": "H:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "\u0440\u0443\u0431.", "DECIMAL_SEP": ",", "GROUP_SEP": "\u00a0", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-", "negSuf": "\u00a0\u00a4", "posPre": "", "posSuf": "\u00a0\u00a4" } ] }, "id": "ru", "localeID": "ru", "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (vf.v == 0 && i % 10 == 1 && i % 100 != 11) { return PLURAL_CATEGORY.ONE; } if (vf.v == 0 && i % 10 >= 2 && i % 10 <= 4 && (i % 100 < 12 || i % 100 > 14)) { return PLURAL_CATEGORY.FEW; } if (vf.v == 0 && i % 10 == 0 || vf.v == 0 && i % 10 >= 5 && i % 10 <= 9 || vf.v == 0 && i % 100 >= 11 && i % 100 <= 14) { return PLURAL_CATEGORY.MANY; } return PLURAL_CATEGORY.OTHER;} }); }]);
{ "pile_set_name": "Github" }
#include <rosePublicConfig.h> #ifdef ROSE_BUILD_BINARY_ANALYSIS_SUPPORT #include <sage3basic.h> #include <BinarySmtCommandLine.h> #include <BinarySmtSolver.h> namespace Rose { namespace BinaryAnalysis { bool listSmtSolverNames(std::ostream &out) { BinaryAnalysis::SmtSolver::Availability solvers = BinaryAnalysis::SmtSolver::availability(); bool foundSolver = false; out <<"solver \"none\" is available\n"; BOOST_FOREACH (BinaryAnalysis::SmtSolver::Availability::value_type &node, solvers) { out <<"solver \"" <<node.first <<"\" is " <<(node.second?"":"not ") <<"available\n"; if (node.second) foundSolver = true; } return foundSolver; } std::string validateSmtSolverName(const std::string &name) { BinaryAnalysis::SmtSolver::Availability solvers = BinaryAnalysis::SmtSolver::availability(); if (solvers.find(name) != solvers.end()) return ""; return "SMT solver \"" + StringUtility::cEscape(name) + "\" is not recognized"; } std::string bestSmtSolverName() { std::string name; if (const BinaryAnalysis::SmtSolverPtr &solver = BinaryAnalysis::SmtSolver::bestAvailable()) name = solver->name(); return name; } void checkSmtCommandLineArg(const std::string &arg, const std::string &listSwitch, std::ostream &out) { if ("list" == arg) { listSmtSolverNames(std::cout); std::cout <<"solver \"best\" is an alias for \"" <<bestSmtSolverName() <<"\"\n"; exit(0); } else if ("" == arg || "none" == arg || "best" == arg) { // no solver } else { std::string err = validateSmtSolverName(arg); if (!err.empty()) { out <<err <<"\n"; if (!listSwitch.empty()) out <<"use \"" <<listSwitch <<"\" to get a list of supported solvers.\n"; exit(1); } } } std::string smtSolverDocumentationString(const std::string &dfltValue) { using namespace StringUtility; std::string docstr = "Specifies which connection is used to interface to an SMT solver for analyses that don't " "otherwise specify a solver. The choices are names of solver interfaces, \"none\" " "(or the empty string), \"best\", or \"list\"."; SmtSolver::Availability solvers = SmtSolver::availability(); std::vector<std::string> enabled, disabled; BOOST_FOREACH (const SmtSolver::Availability::value_type &node, solvers) { if (node.second) { enabled.push_back("\"" + cEscape(node.first) + "\""); } else { disabled.push_back("\"" + cEscape(node.first) + "\""); } } if (enabled.empty()) { docstr += " ROSE was not configured with any SMT solvers."; } else { docstr += " The following solvers are available in this configuration: " + joinEnglish(enabled) + "."; } if (!disabled.empty()) { docstr += " These solvers would be available, but were not configured: " + joinEnglish(disabled) + "."; } docstr += " In general, solvers ending with \"-exe\" translate the ROSE internal representation to text, send the " "text to a solver executable program which then parses it to another internal representation, solves, " "converts its internal representation to text, which ROSE then reads and parses. These \"-exe\" parsers " "are therefore quite slow, but work well for debugging. On the other hand, the \"-lib\" parsers use " "a solver library and can avoid two of the four translation steps, but don't produce much debugging " "output. To debug solvers, enable the " + SmtSolver::mlog.name() + " diagnostic facility (see @s{log})."; docstr += " The default is \"" + dfltValue + "\""; if ("best" == dfltValue) { if (SmtSolverPtr solver = SmtSolver::bestAvailable()) { docstr += ", which currently means \"" + solver->name() + "\"."; } else { docstr += ", which currently mean \"none\"."; } } else { docstr += "."; } return docstr; } void SmtSolverValidator::operator()(const Sawyer::CommandLine::ParserResult &cmdline) { ASSERT_require(cmdline.have("smt-solver")); std::string arg = cmdline.parsed("smt-solver", 0).as<std::string>(); if (cmdline.parser().errorStream().get()) { checkSmtCommandLineArg(arg, "--smt-solver=list", *cmdline.parser().errorStream().get()); } else { checkSmtCommandLineArg(arg, "--smt-solver=list", std::cerr); } } } // namespace } // namespace #endif
{ "pile_set_name": "Github" }
//===--- ParallelUtilities.cpp -------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // //===----------------------------------------------------------------------===// #include "ParallelUtilities.h" #include "llvm/Support/Timer.h" #include <mutex> #include <shared_mutex> #define DEBUG_TYPE "par-utils" namespace opts { extern cl::OptionCategory BoltCategory; cl::opt<unsigned> ThreadCount("thread-count", cl::desc("number of threads"), cl::init(hardware_concurrency()), cl::cat(BoltCategory)); cl::opt<bool> NoThreads("no-threads", cl::desc("disable multithreading"), cl::init(false), cl::cat(BoltCategory)); cl::opt<unsigned> TaskCount("tasks-per-thread", cl::desc("number of tasks to be created per thread"), cl::init(20), cl::cat(BoltCategory)); } // namespace opts namespace llvm { namespace bolt { namespace ParallelUtilities { namespace { /// A single thread pool that is used to run parallel tasks std::unique_ptr<ThreadPool> ThreadPoolPtr; unsigned computeCostFor(const BinaryFunction &BF, const PredicateTy &SkipPredicate, const SchedulingPolicy &SchedPolicy) { if (SchedPolicy == SchedulingPolicy::SP_TRIVIAL) return 1; if (SkipPredicate && SkipPredicate(BF)) return 0; switch (SchedPolicy) { case SchedulingPolicy::SP_CONSTANT: return 1; case SchedulingPolicy::SP_INST_LINEAR: return BF.getSize(); case SchedulingPolicy::SP_INST_QUADRATIC: return BF.getSize() * BF.getSize(); case SchedulingPolicy::SP_BB_LINEAR: return BF.size(); case SchedulingPolicy::SP_BB_QUADRATIC: return BF.size() * BF.size(); default: llvm_unreachable("unsupported scheduling policy"); } } inline unsigned estimateTotalCost(const BinaryContext &BC, const PredicateTy &SkipPredicate, SchedulingPolicy &SchedPolicy) { if (SchedPolicy == SchedulingPolicy::SP_TRIVIAL) return BC.getBinaryFunctions().size(); unsigned TotalCost = 0; for (auto &BFI : BC.getBinaryFunctions()) { auto &BF = BFI.second; TotalCost += computeCostFor(BF, SkipPredicate, SchedPolicy); } // Switch to trivial scheduling if total estimated work is zero if (TotalCost == 0) { outs() << "BOLT-WARNING: Running parallel work of 0 estimated cost, will " "switch to trivial scheduling.\n"; SchedPolicy = SP_TRIVIAL; TotalCost = BC.getBinaryFunctions().size(); } return TotalCost; } } // namespace ThreadPool &getThreadPool() { if (ThreadPoolPtr.get()) return *ThreadPoolPtr; ThreadPoolPtr = std::make_unique<ThreadPool>(opts::ThreadCount); return *ThreadPoolPtr; } void runOnEachFunction(BinaryContext &BC, SchedulingPolicy SchedPolicy, WorkFuncTy WorkFunction, PredicateTy SkipPredicate, std::string LogName, bool ForceSequential, unsigned TasksPerThread) { if (BC.getBinaryFunctions().size() == 0) return; auto runBlock = [&](std::map<uint64_t, BinaryFunction>::iterator BlockBegin, std::map<uint64_t, BinaryFunction>::iterator BlockEnd) { Timer T(LogName, LogName); DEBUG(T.startTimer()); for (auto It = BlockBegin; It != BlockEnd; ++It) { auto &BF = It->second; if (SkipPredicate && SkipPredicate(BF)) continue; WorkFunction(BF); } DEBUG(T.stopTimer()); }; if (opts::NoThreads || ForceSequential) { runBlock(BC.getBinaryFunctions().begin(), BC.getBinaryFunctions().end()); return; } // Estimate the overall runtime cost using the scheduling policy const unsigned TotalCost = estimateTotalCost(BC, SkipPredicate, SchedPolicy); const unsigned BlocksCount = TasksPerThread * opts::ThreadCount; const unsigned BlockCost = TotalCost > BlocksCount ? TotalCost / BlocksCount : 1; // Divide work into blocks of equal cost ThreadPool &Pool = getThreadPool(); auto BlockBegin = BC.getBinaryFunctions().begin(); unsigned CurrentCost = 0; for (auto It = BC.getBinaryFunctions().begin(); It != BC.getBinaryFunctions().end(); ++It) { auto &BF = It->second; CurrentCost += computeCostFor(BF, SkipPredicate, SchedPolicy); if (CurrentCost >= BlockCost) { Pool.async(runBlock, BlockBegin, std::next(It)); BlockBegin = std::next(It); CurrentCost = 0; } } Pool.async(runBlock, BlockBegin, BC.getBinaryFunctions().end()); Pool.wait(); } void runOnEachFunctionWithUniqueAllocId( BinaryContext &BC, SchedulingPolicy SchedPolicy, WorkFuncWithAllocTy WorkFunction, PredicateTy SkipPredicate, std::string LogName, bool ForceSequential, unsigned TasksPerThread) { if (BC.getBinaryFunctions().size() == 0) return; std::shared_timed_mutex MainLock; auto runBlock = [&](std::map<uint64_t, BinaryFunction>::iterator BlockBegin, std::map<uint64_t, BinaryFunction>::iterator BlockEnd, MCPlusBuilder::AllocatorIdTy AllocId) { Timer T(LogName, LogName); DEBUG(T.startTimer()); std::shared_lock<std::shared_timed_mutex> Lock(MainLock); for (auto It = BlockBegin; It != BlockEnd; ++It) { auto &BF = It->second; if (SkipPredicate && SkipPredicate(BF)) continue; WorkFunction(BF, AllocId); } DEBUG(T.stopTimer()); }; if (opts::NoThreads || ForceSequential) { runBlock(BC.getBinaryFunctions().begin(), BC.getBinaryFunctions().end(), 0); return; } // This lock is used to postpone task execution std::unique_lock<std::shared_timed_mutex> Lock(MainLock); // Estimate the overall runtime cost using the scheduling policy const unsigned TotalCost = estimateTotalCost(BC, SkipPredicate, SchedPolicy); const unsigned BlocksCount = TasksPerThread * opts::ThreadCount; const unsigned BlockCost = TotalCost > BlocksCount ? TotalCost / BlocksCount : 1; // Divide work into blocks of equal cost ThreadPool &Pool = getThreadPool(); auto BlockBegin = BC.getBinaryFunctions().begin(); unsigned CurrentCost = 0; unsigned AllocId = 1; for (auto It = BC.getBinaryFunctions().begin(); It != BC.getBinaryFunctions().end(); ++It) { auto &BF = It->second; CurrentCost += computeCostFor(BF, SkipPredicate, SchedPolicy); if (CurrentCost >= BlockCost) { if (!BC.MIB->checkAllocatorExists(AllocId)) { auto Id = BC.MIB->initializeNewAnnotationAllocator(); assert(AllocId == Id && "unexpected allocator id created"); } Pool.async(runBlock, BlockBegin, std::next(It), AllocId); AllocId++; BlockBegin = std::next(It); CurrentCost = 0; } } if (!BC.MIB->checkAllocatorExists(AllocId)) { auto Id = BC.MIB->initializeNewAnnotationAllocator(); assert(AllocId == Id && "unexpected allocator id created"); } Pool.async(runBlock, BlockBegin, BC.getBinaryFunctions().end(), AllocId); Lock.unlock(); Pool.wait(); } } // namespace ParallelUtilities } // namespace bolt } // namespace llvm
{ "pile_set_name": "Github" }
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("commonlisp", function (config) { var assumeBody = /^with|^def|^do|^prog|case$|^cond$|bind$|when$|unless$/; var numLiteral = /^(?:[+\-]?(?:\d+|\d*\.\d+)(?:[efd][+\-]?\d+)?|[+\-]?\d+(?:\/[+\-]?\d+)?|#b[+\-]?[01]+|#o[+\-]?[0-7]+|#x[+\-]?[\da-f]+)/; var symbol = /[^\s'`,@()\[\]";]/; var type; function readSym(stream) { var ch; while (ch = stream.next()) { if (ch == "\\") stream.next(); else if (!symbol.test(ch)) { stream.backUp(1); break; } } return stream.current(); } function base(stream, state) { if (stream.eatSpace()) {type = "ws"; return null;} if (stream.match(numLiteral)) return "number"; var ch = stream.next(); if (ch == "\\") ch = stream.next(); if (ch == '"') return (state.tokenize = inString)(stream, state); else if (ch == "(") { type = "open"; return "bracket"; } else if (ch == ")" || ch == "]") { type = "close"; return "bracket"; } else if (ch == ";") { stream.skipToEnd(); type = "ws"; return "comment"; } else if (/['`,@]/.test(ch)) return null; else if (ch == "|") { if (stream.skipTo("|")) { stream.next(); return "symbol"; } else { stream.skipToEnd(); return "error"; } } else if (ch == "#") { var ch = stream.next(); if (ch == "[") { type = "open"; return "bracket"; } else if (/[+\-=\.']/.test(ch)) return null; else if (/\d/.test(ch) && stream.match(/^\d*#/)) return null; else if (ch == "|") return (state.tokenize = inComment)(stream, state); else if (ch == ":") { readSym(stream); return "meta"; } else return "error"; } else { var name = readSym(stream); if (name == ".") return null; type = "symbol"; if (name == "nil" || name == "t") return "atom"; if (name.charAt(0) == ":") return "keyword"; if (name.charAt(0) == "&") return "variable-2"; return "variable"; } } function inString(stream, state) { var escaped = false, next; while (next = stream.next()) { if (next == '"' && !escaped) { state.tokenize = base; break; } escaped = !escaped && next == "\\"; } return "string"; } function inComment(stream, state) { var next, last; while (next = stream.next()) { if (next == "#" && last == "|") { state.tokenize = base; break; } last = next; } type = "ws"; return "comment"; } return { startState: function () { return {ctx: {prev: null, start: 0, indentTo: 0}, tokenize: base}; }, token: function (stream, state) { if (stream.sol() && typeof state.ctx.indentTo != "number") state.ctx.indentTo = state.ctx.start + 1; type = null; var style = state.tokenize(stream, state); if (type != "ws") { if (state.ctx.indentTo == null) { if (type == "symbol" && assumeBody.test(stream.current())) state.ctx.indentTo = state.ctx.start + config.indentUnit; else state.ctx.indentTo = "next"; } else if (state.ctx.indentTo == "next") { state.ctx.indentTo = stream.column(); } } if (type == "open") state.ctx = {prev: state.ctx, start: stream.column(), indentTo: null}; else if (type == "close") state.ctx = state.ctx.prev || state.ctx; return style; }, indent: function (state, _textAfter) { var i = state.ctx.indentTo; return typeof i == "number" ? i : state.ctx.start + 1; }, lineComment: ";;", blockCommentStart: "#|", blockCommentEnd: "|#" }; }); CodeMirror.defineMIME("text/x-common-lisp", "commonlisp"); });
{ "pile_set_name": "Github" }
ο»Ώ// Β© 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html // Generated using tools/cldr/cldr-to-icu/build-icu-data.xml en_NZ{ %%Parent{"en_001"} calendar{ generic{ DateTimePatterns{ "h:mm:ss a zzzz", "h:mm:ss a z", "h:mm:ss a", "h:mm a", "EEEE, d MMMM y G", "d MMMM y G", "d/MM/y G", "d/MM/y GGGGG", "{1}, {0}", "{1} 'at' {0}", "{1} 'at' {0}", "{1}, {0}", "{1}, {0}", } availableFormats{ Md{"d/M"} yyyyMd{"d/MM/y G"} } intervalFormats{ MEd{ M{"E, d/MM – E, d/MM"} d{"E, d/MM – E, d/MM"} } MMMEd{ M{"E, d MMM – E, d MMM"} d{"E, d – E, d MMM"} } Md{ M{"d/MM – d/MM"} d{"d/MM – d/MM"} } yM{ M{"MM/y – MM/y G"} y{"MM/y – MM/y G"} } yMEd{ M{"E, d/MM/y – E, d/MM/y G"} d{"E, d/MM/y – E, d/MM/y G"} y{"E, d/MM/y – E, d/MM/y G"} } yMd{ M{"d/MM/y – d/MM/y G"} d{"d/MM/y – d/MM/y G"} y{"d/MM/y – d/MM/y G"} } } } gregorian{ DateTimePatterns{ "h:mm:ss a zzzz", "h:mm:ss a z", "h:mm:ss a", "h:mm a", "EEEE, d MMMM y", "d MMMM y", "d/MM/y", "d/MM/yy", "{1}, {0}", "{1} 'at' {0}", "{1} 'at' {0}", "{1}, {0}", "{1}, {0}", } availableFormats{ Md{"d/M"} yMd{"d/MM/y"} } intervalFormats{ MEd{ M{"E, d/MM – E, d/MM"} d{"E, d/MM – E, d/MM"} } MMMEd{ M{"E, d MMM – E, d MMM"} d{"E, d – E, d MMM"} } Md{ M{"d/MM – d/MM"} d{"d/MM – d/MM"} } yMEd{ M{"E, d/MM/y – E, d/MM/y"} d{"E, d/MM/y – E, d/MM/y"} y{"E, d/MM/y – E, d/MM/y"} } yMd{ M{"d/MM/y – d/MM/y"} d{"d/MM/y – d/MM/y"} y{"d/MM/y – d/MM/y"} } } } } }
{ "pile_set_name": "Github" }