repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
fino-digital/finapi-java-client
src/test/java/org/proshin/finapi/webform/FpWebFormTest.java
/* * Copyright 2018 <NAME> * * 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.proshin.finapi.webform; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; import org.json.JSONObject; import org.junit.jupiter.api.Test; public final class FpWebFormTest { @Test public void testSuccess() { final WebForm webForm = new FpWebForm( new JSONObject( '{' + " \"id\": 12," + " \"token\": \"random token\"," + " \"status\": \"NOT_YET_OPENED\"," + " \"serviceResponseCode\": 422," + " \"serviceResponseBody\": \"some JSON here\"" + '}' ) ); assertThat(webForm.id()).isEqualTo(12L); assertThat(webForm.token()).isEqualTo("random token"); assertThat(webForm.status()).isEqualTo(WebForm.Status.NOT_YET_OPENED); assertThat(webForm.serviceResponseCode()).isEqualTo(Optional.of(422)); assertThat(webForm.serviceResponseBody()).isEqualTo(Optional.of("some JSON here")); } }
VladT-Tempest/MisionTIC2022-Ciclo2
CodigosClase/src/semana3/Polimorfismo/PrincipalAnimalSinPolimorfismoArray.java
<gh_stars>10-100 package semana3.Polimorfismo; import java.util.ArrayList; public class PrincipalAnimalSinPolimorfismoArray { public static void main(String[] args) { Gato g1 = new Gato("Ozzy"); Gato g2 = new Gato("Jackie"); Gato g3 = new Gato("Michi"); Perro p1 = new Perro("Trosqui"); Perro p2 = new Perro("Firulais"); Perro p3 = new Perro("Galaxia"); ArrayList<Gato> gatitos = new ArrayList<Gato>(); gatitos.add(g1); gatitos.add(g2); gatitos.add(g3); ArrayList<Perro> perritos = new ArrayList<Perro>(); perritos.add(p1); perritos.add(p2); perritos.add(p3); sonidosGatos(gatitos); } public static void sonidosGatos(ArrayList<Gato> gatitos){ for(Gato i: gatitos){ System.out.println(i.getNombre()+ " sonido "); i.sonido(); } } public static void sonidosPerros(ArrayList<Perro> perritos){ for(Perro i: perritos){ System.out.println(i.getNombre()+ " sonido "); i.sonido(); } } }
GeniusVentures/SuperGenius
src/runtime/binaryen/runtime_api/production_api_impl.cpp
<reponame>GeniusVentures/SuperGenius #include "runtime/binaryen/runtime_api/production_api_impl.hpp" namespace sgns::runtime::binaryen { ProductionApiImpl::ProductionApiImpl( const std::shared_ptr<WasmProvider> &wasm_provider, const std::shared_ptr<RuntimeManager> &runtime_manager) : RuntimeApi(wasm_provider, runtime_manager), logger_{ base::createLogger("ProductionApiImpl")} {} outcome::result<primitives::ProductionConfiguration> ProductionApiImpl::configuration() { logger_->debug("ProductionApi_configuration"); primitives::ProductionConfiguration result; primitives::ProductionDuration duration{30000000}; //0x0000000001c9c380 result.slot_duration = duration; result.epoch_length = 0x00000000000000c8; //200 result.leadership_rate = { 0x0000000000000001,0x0000000000000004 }; result.genesis_authorities = { primitives::Authority{{}, 1} , primitives::Authority{{}, 0x00000137ddc9a180} , primitives::Authority{{}, 0x00000137ddc9a180} }; //return result; // return execute<primitives::ProductionConfiguration>("ProductionApi_configuration", // CallPersistency::EPHEMERAL); return execute<primitives::ProductionConfiguration>("BabeApi_configuration", CallPersistency::EPHEMERAL); } } // namespace sgns::runtime::binaryen
AugustYuan/MSRNet
models/repair_net.py
import torch import torch.nn as nn from src import IRU, RCU, BF, Conv_2D base_block={ 'RCU':RCU, 'IRU':IRU } def RepairNets(cfg): repairNet = [] for channel in cfg['channels'][::-1]: repairNet.append( Repairnet( in_channels=channel, num_class=cfg['num_class'], blocks=cfg['base_block'], is_dsc=cfg['is_dsc'] ) ) return repairNet class Repairnet(nn.Module): def __init__(self, in_channels, num_class, blocks, is_dsc=True): super(Repairnet, self).__init__() self.in_channels = in_channels self.num_class = num_class self.blocks = blocks self.is_dsc = is_dsc self.bf = self._bf_block() self.conv = self._conv_block() def forward(self, feats, res): feats = self.bf(feats, res) feats = self.conv(feats) return feats def _bf_block(self): return BF( channels=self.in_channels, num_class=self.num_class, scale_factor=2.0, is_dsc=self.is_dsc ) def _conv_block(self): conv = nn.Sequential() for block in self.blocks: conv.add_module( block, base_block[block]( channels=self.in_channels, is_dsc=self.is_dsc) ) conv.add_module( 'out_conv', Conv_2D( in_channels=self.in_channels, out_channels=self.in_channels, kernel_size=3, padding=1, bias=False, is_dsc=False, with_bn=True, activation='relu', stride=1 ) ) conv.add_module( 'out_conv', Conv_2D( in_channels=self.in_channels, out_channels=self.num_class, kernel_size=3, padding=1, bias=False, is_dsc=False, with_bn=False, activation=None, stride=1 ) ) return conv
michaelawyu/nanopie
src/nanopie/tracing/base.py
"""This module includes the base classes for tracing handlers and related objects. A tracing handler enables easy OpenTelemetry based tracing when processing requests arriving at an endpoint. Once configured, the tracing handler will start a trace (span) automatically when a service begins processing a request and it will conclude the trace (span) when the service finishes the work; the result trace (span) will then be sent to a source (standard streams, Jaeger, Zipkin, etc.). Fuurthermore, tracing handlers support trace context propagation, so that traces (spans) across services can be resumed without additional setup. """ from abc import abstractmethod import json import os from typing import Dict, Optional try: from opentelemetry import trace from opentelemetry.sdk import util from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import ( BatchExportSpanProcessor, ConsoleSpanExporter, SimpleExportSpanProcessor, ) from opentelemetry.trace.sampling import ProbabilitySampler OPENTELEMETRY_INSTALLED = True except ImportError: OPENTELEMETRY_INSTALLED = False from ..globals import endpoint, request as request_proxy from ..handler import Handler from ..logger import logger from ..misc import get_flattenable_dikt from ..model import Model from ..services.base import Extractor class TraceContext(Model): """The base class for all trace contexts. A trace context is a `Model` (see `model.py`) that specifies a number of attributes which tracing handlers require for trace propagation. """ @property @abstractmethod def trace_id(self) -> int: """Returns the trace ID.""" @property @abstractmethod def span_id(self) -> int: """Returns the span ID.""" @property @abstractmethod def trace_flags(self) -> "TraceOptions": """Returns the trace flags.""" return trace.TraceFlags.get_default() @property @abstractmethod def trace_state(self) -> "TraceState": """Returns the trace states.""" return trace.TraceState.get_default() def process(self): """Processes the trace context. Different services propagate their traces (spans) differently. In many cases, the format of trace contexts in requests are not the same from the one OpenTelemetry uses. If required, one may override this method, call it in the trace context extractor, and do some additional parsing to translate custom trace contexts into OpenTelemetry recommended ones. """ class TraceContextExtractor(Extractor): """The base class for all trace context extractors. A trace context extractor extracts a trace context from a request. For example, a trace context extractor for an HTTP microservice/API service may check the W3C Trace Context headers from an HTTP request and parse them into a trace context which tracing handlers can use. """ @abstractmethod def extract(self, request: "RPCRequest") -> "TraceContext": """Extracts a trace context from a request. Args: request (RPCRequest): A request. Returns: TraceContext: The extracted trace context. """ class OpenTelemetryTracingHandler(Handler): """The base class for all tracing handlers. This tracing handler can also be used directly if the microservice/API service requires only trace outputs to standard streams (stdout/stderr). """ def __init__( self, with_span_name: Optional[str] = None, with_span_attributes: Optional[Dict] = None, with_span_kind: "SpanKind" = None, with_endpoint_config: bool = False, with_endpoint_extras: bool = False, propagated: bool = False, trace_ctx_extractor: Optional["TraceContextExtractor"] = None, quiet: bool = False, batched: bool = False, with_sampler: Optional["Sampler"] = None, probability: Optional[float] = None, write_to_console: bool = True, jsonprint: bool = True, ): """Initializes a tracing handler. Args: with_span_name (str, Optional): The name of the trace span. with_span_attributes (Dict, Optional): The attributes of the trace span. with_span_kind (str): The kind of the trace span. with_endpoint_config (bool): If set to True, the tracing handler will add the basic information about the current endpoint to the span attributes. with_endpoint_extras (bool): If set to True, the tracing handler will add the user provided extra information about the current endpoint to the span attributes. propagated (bool): If set to True, trace propagation will be enabled. trace_ctx_extractor (TraceContextExtractor, Optional): A trace context extractor. quiet (bool): If set to True, the tracing handlers will run quietly when extracting trace contexts, i.e. it will not report any error should a trace context cannot be extracted or processed. batched (bool): If set to True, trace spans will be sent to sources in batch for better performance. with_sampler (Sampler, Optional): An OpenTelemetry trace sampler. probability (float, Optional): The rate for probability sampling. write_to_console (bool): If set to True, the traces (spans) will be written to standard streams (stdout/stderr) in addition to source transmission. jsonprint (bool): If set to True, the traces (spans) will be output in the format of JSON strings when written to standard streams. """ if not OPENTELEMETRY_INSTALLED: raise ImportError( "Packages opentelemetry-api " "(https://pypi.org/project/opentelemetry-api/) " "and opentelemtry-sdk " "(https://pypi.org/project/opentelemetry-sdk/) " "are required to enable tracing. To install " "these packages, run " "`pip install opentelemetry-api " "opentelemetry-sdk`" ) self._with_span_name = with_span_name self._with_span_attributes = with_span_attributes self._with_span_kind = with_span_kind if not with_span_kind: self._with_span_kind = trace.SpanKind.SERVER self._with_endpoint_config = with_endpoint_config self._with_endpoint_extras = with_endpoint_extras self._propagated = propagated self._trace_ctx_extractor = trace_ctx_extractor self._quiet = quiet self._processor = ( BatchExportSpanProcessor if batched else SimpleExportSpanProcessor ) self._span_processers = [] if write_to_console: if jsonprint: def dump_span_as_dict(span): if isinstance(span, trace.Span): return { "name": "{}".format(span.name), "context": { "trace_id": "{}".format(span.context.trace_id), "span_id": "{}".format(span.context.span_id), "trace_state": "{}".format(span.context.trace_state), "is_remote": "{}".format(span.context.is_remote), }, "kind": "{}".format(span.kind), "parent": dump_span_as_dict(span.parent), "start_time": "{}".format( util.ns_to_iso_str(span.start_time) ) if span.start_time else None, "end_time": "{}".format(util.ns_to_iso_str(span.end_time)) if span.end_time else None, "attributes": "{}".format(dict(span.attributes)), } elif isinstance(span, trace.SpanContext): return { "trace_id": "{}".format(span.trace_id), "span_id": "{}".format(span.span_id), "trace_state": "{}".format(span.trace_state), "is_remote": "{}".format(span.is_remote), } else: return None console_exporter = ConsoleSpanExporter( formatter=lambda span: json.dumps(dump_span_as_dict(span)) + os.linesep ) else: console_exporter = ConsoleSpanExporter() self._span_processers.insert(0, self._processor(console_exporter)) if with_sampler and probability: raise RuntimeError("with_sampler and probability are mutually exclusive.") elif not with_sampler and probability == None: self._sampler = trace.sampling.ALWAYS_ON else: self._sampler = ( with_sampler if with_sampler else ProbabilitySampler(rate=probability) ) self._tracer_provider = None super().__init__() def _setup_tracer_provider(self): """Sets up a tracer provider.""" tracer_provider = TracerProvider(sampler=self._sampler) for processor in self._span_processers: tracer_provider.add_span_processor(processor) self._tracer_provider = tracer_provider def get_trace_ctx(self): """Gets the trace context.""" if self._trace_ctx_extractor: return self._trace_ctx_extractor.extract(request=request_proxy) else: raise RuntimeError("trace_ctx_extractor is not present.") def get_tracer(self): """Gets a tracer.""" if not self._tracer_provider: self._setup_tracer_provider() return self._tracer_provider.get_tracer(__name__) def __call__(self, *args, **kwargs): """Runs the handler. It performs the following tasks: 1. Set up a tracer providers (if one has not been set up yet) and get a tracer. 2. Set up trace propagation (if a trace context is available). 3. Perform additional setup. 4. Start a new span. 5. Pass the baton to the chained handler. 6. End the span. Args: *args: Arbitrary positional arguments. **kwargs: Arbitrary named arguments. Returns: Any: Any object. """ tracer = self.get_tracer() current_span = trace.get_current_span() if self._propagated: if not current_span or not current_span.get_context().is_valid(): trace_ctx = self.get_trace_ctx() try: trace_id = trace_ctx.trace_id span_id = trace_ctx.span_id trace_flags = trace_ctx.trace_flags trace_state = trace_ctx.trace_state current_span = trace.SpanContext( trace_id=trace_id, span_id=span_id, trace_flags=trace_flags, trace_state=trace_state, is_remote=True, ) assert current_span.is_valid() except Exception as ex: # pylint: disable=broad-except if not self._quiet: raise ex current_span = None else: current_span = None span_name = self._with_span_name if not span_name: span_name = "unspecified" span_attributes = {} if self._with_span_attributes: span_attributes.update(get_flattenable_dikt(self._with_span_attributes)) if self._with_endpoint_config: span_attributes.update( get_flattenable_dikt( {"endpoint.name": endpoint.name, "endpoint.rule": endpoint.rule} ) ) if self._with_endpoint_extras: flattened_extras = get_flattenable_dikt(endpoint.extras) prefixed_flattened_extras = {} for k in flattened_extras: prefixed_flattened_extras[ "endpoint.extras.{}".format(k) ] = flattened_extras[k] span_attributes.update(prefixed_flattened_extras) span = tracer.start_span( span_name, parent=current_span, kind=self._with_span_kind, attributes=span_attributes, ) try: with tracer.use_span(span, end_on_exit=True): res = super().__call__(*args, **kwargs) return res except: span.end() raise
icyleaf/app_info
spec/app_info/ipa/framework_spec.rb
describe AppInfo::Framework do subject { AppInfo::Framework.parse(fixture_path('payload'), 'frameworks') } it { expect(subject).to be_a Array} it { expect(subject.size).to eq(2) } it { expect(subject[0]).to be_a AppInfo::Framework } it { expect(subject[0].lib?).to be_falsey } it { expect(subject[0].name).to eq('FMDB.framework') } it { expect(subject[0].release_version).to eq '2.7.5' } it { expect(subject[0].build_version).to eq '1' } it { expect(subject[0].bundle_id).to eq 'org.cocoapods.FMDB' } it { expect(subject[0].macho).to be_nil } it { expect(subject[1]).to be_a AppInfo::Framework } it { expect(subject[1].name).to eq('libswiftPhotos.dylib') } it { expect(subject[1].lib?).to be_truthy } it { expect(subject[1].release_version).to be_nil } it { expect(subject[1].build_version).to be_nil } it { expect(subject[1].info).to be_a AppInfo::InfoPlist } it { expect(subject[1].bundle_id).to be_nil } it { expect(subject[1].macho).to be_a MachO::FatFile } end
gingerkirsch/record-and-replay
symber-transformer/src/edu/ist/symber/tloax/XStartJoinAnalysis.java
<gh_stars>0 package edu.ist.symber.tloax; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import soot.*; import soot.jimple.*; import soot.jimple.spark.pag.AllocNode; import soot.jimple.spark.pag.Node; import soot.jimple.spark.pag.PAG; import soot.jimple.spark.sets.P2SetVisitor; import soot.jimple.spark.sets.PointsToSetInternal; import soot.jimple.toolkits.callgraph.CallGraph; import soot.jimple.toolkits.callgraph.Filter; import soot.jimple.toolkits.callgraph.TransitiveTargets; import soot.jimple.toolkits.scalar.EqualUsesAnalysis; import soot.jimple.toolkits.thread.mhp.RunMethodsPred; import soot.toolkits.graph.BriefUnitGraph; import soot.toolkits.graph.MHGPostDominatorsFinder; import soot.toolkits.graph.UnitGraph; public class XStartJoinAnalysis { private UnitGraph graph; private SootMethod method; private CallGraph cg; private PAG pag; Set<Stmt> startStatements; Set<Stmt> joinStatements; Hierarchy hierarchy; Map<Stmt, List<SootMethod>> startToRunMethods; Map<Stmt, List<AllocNode>> startToAllocNodes; Map<Stmt, Stmt> startToJoin; public XStartJoinAnalysis(UnitGraph g, SootMethod sm) { this.graph = g; this.method = sm; this.pag = XG.v().getPAG(); this.cg = Scene.v().getCallGraph(); this.startStatements = new HashSet<Stmt>(); this.joinStatements = new HashSet<Stmt>(); this.hierarchy = Scene.v().getActiveHierarchy(); this.startToRunMethods = new HashMap<Stmt, List<SootMethod>>(); this.startToAllocNodes = new HashMap<Stmt, List<AllocNode>>(); this.startToJoin = new HashMap<Stmt, Stmt>(); // Get lists of start and join statements doFlowInsensitiveSingleIterationAnalysis();//right run(); } private void run() { if(!startStatements.isEmpty()) { TransitiveTargets runMethodTargets = new TransitiveTargets( cg, new Filter(new RunMethodsPred()) ); // Build a map from start stmt to possible run methods, // and a map from start stmt to possible allocation nodes, // and a map from start stmt to guaranteed join stmt Iterator<Stmt> startIt = startStatements.iterator(); while (startIt.hasNext()) { Stmt start = startIt.next(); List<SootMethod> runMethodsList = new ArrayList<SootMethod>(); // will be a list of possible run methods called by this start stmt List<AllocNode> allocNodesList = new ArrayList<AllocNode>(); // will be a list of possible allocation nodes for the thread object that's getting started // Get possible thread objects (may alias) Value startObject = ((InstanceInvokeExpr) (start).getInvokeExpr()).getBase(); PointsToSetInternal pts = (PointsToSetInternal) pag.reachingObjects((Local) startObject);//that's good!! List<AllocNode> mayAlias = getMayAliasList(pts); if( mayAlias.size() < 1 ) continue; // If the may alias is empty, this must be dead code // For each possible thread object, get run method Iterator<MethodOrMethodContext> mayRunIt = runMethodTargets.iterator( start ); // fails for some call graphs while( mayRunIt.hasNext() ) { SootMethod runMethod = (SootMethod) mayRunIt.next(); if( runMethod.getSubSignature().equals("void run()") ) { runMethodsList.add(runMethod); } } // If haven't found any run methods, then use the type of the startObject, // and add run from it and all subclasses if(runMethodsList.isEmpty() && ((RefType) startObject.getType()).getSootClass().isApplicationClass()) { List<SootClass> threadClasses = hierarchy.getSubclassesOfIncluding( ((RefType) startObject.getType()).getSootClass() ); Iterator<SootClass> threadClassesIt = threadClasses.iterator(); while(threadClassesIt.hasNext()) { SootClass currentClass = threadClassesIt.next(); if( currentClass.declaresMethod("void run()") ) { runMethodsList.add(currentClass.getMethod("void run()")); } } } // For each possible thread object, get alloc node Iterator<AllocNode> mayAliasIt = mayAlias.iterator(); while( mayAliasIt.hasNext() ) { AllocNode allocNode = mayAliasIt.next(); allocNodesList.add(allocNode); if(runMethodsList.isEmpty()) { throw new RuntimeException("Can't find run method for: " + startObject); } } // Add this start stmt to both maps startToRunMethods.put(start, runMethodsList); startToAllocNodes.put(start, allocNodesList); /* // does this start stmt match any join stmt??? // Get supporting info and analyses MHGPostDominatorsFinder pd = new MHGPostDominatorsFinder(new BriefUnitGraph(method.getActiveBody())); EqualUsesAnalysis lif = new EqualUsesAnalysis(graph); Iterator<Stmt> joinIt = joinStatements.iterator(); while (joinIt.hasNext()) { Stmt join = joinIt.next(); Value joinObject = ((InstanceInvokeExpr) (join).getInvokeExpr()).getBase(); // If startObject and joinObject MUST be the same, and if join post-dominates start if( lif.areEqualUses( start, (Local) startObject, join, (Local) joinObject ) ) { if((pd.getDominators(start)).contains(join)) // does join post-dominate start? { // G.v().out.println("START-JOIN PAIR: " + start + ", " + join); startToJoin.put(start, join); // then this join always joins this start's thread } } }*/ } } } private List<AllocNode> getMayAliasList(PointsToSetInternal pts) { List<AllocNode> list = new ArrayList<AllocNode>(); final HashSet<AllocNode> ret = new HashSet<AllocNode>(); pts.forall( new P2SetVisitor() { public void visit( Node n ) { ret.add( (AllocNode)n ); } } ); Iterator<AllocNode> it = ret.iterator(); while (it.hasNext()){ list.add( it.next() ); } return list; } private void doFlowInsensitiveSingleIterationAnalysis() { Iterator stmtIt = graph.iterator(); while(stmtIt.hasNext()) { Stmt s = (Stmt) stmtIt.next(); flowThrough(s); } } protected void flowThrough(Stmt stmt) { // Search for start/join invoke expressions if(stmt.containsInvokeExpr()) { // If this is a start stmt, add it to startStatements InvokeExpr ie = stmt.getInvokeExpr(); if(ie instanceof InstanceInvokeExpr) { InstanceInvokeExpr iie = (InstanceInvokeExpr) ie; SootMethod invokeMethod = ie.getMethod(); if(invokeMethod.getName().equals("start")) { RefType baseType = (RefType) iie.getBase().getType(); if(!baseType.getSootClass().isInterface()) // the start method we're looking for is NOT an interface method { List<SootClass> superClasses = hierarchy.getSuperclassesOfIncluding(baseType.getSootClass()); Iterator<SootClass> it = superClasses.iterator(); while (it.hasNext()) { if( it.next().getName().equals("java.lang.Thread") ) { // This is a Thread.start() if(!startStatements.contains(stmt)) startStatements.add(stmt); } } } } // If this is a join stmt, add it to joinStatements /*if(invokeMethod.getName().equals("join")) // the join method we're looking for is NOT an interface method { RefType baseType = (RefType) iie.getBase().getType(); if(!baseType.getSootClass().isInterface()) { List<SootClass> superClasses = hierarchy.getSuperclassesOfIncluding(baseType.getSootClass()); Iterator<SootClass> it = superClasses.iterator(); while (it.hasNext()) { if( it.next().getName().equals("java.lang.Thread") ) { // This is a Thread.join() if(!joinStatements.contains(stmt)) joinStatements.add(stmt); } } } }*/ } } } public Set<Stmt> getStartStatements() { return startStatements; } public Set<Stmt> getJoinStatements() { return joinStatements; } public Map<Stmt, List<SootMethod>> getStartToRunMethods() { return startToRunMethods; } public Map<Stmt, List<AllocNode>> getStartToAllocNodes() { return startToAllocNodes; } public Map<Stmt, Stmt> getStartToJoin() { return startToJoin; } }
joseluis-max/holbertonschool-low_level_programming
0x0D-preprocessor/4-sum.h
#ifndef SUMHEADER #define SUMHEADER #define SUM(x, y) ((x) + (y)) #endif
concord-consortium/rigse
rails/db/migrate/20170202190333_add_class_hash.rb
class AddClassHash < ActiveRecord::Migration[5.1] def up add_column :portal_clazzes, :class_hash, :string, :limit => 48 Portal::Clazz.where(class_hash: nil).find_each(batch_size: 100) do |portal_clazz| portal_clazz.generate_class_hash portal_clazz.save! end end def down remove_column :portal_clazzes, :class_hash end end
MoozaInspire/base-components-recipes
force-app/test/@salesforce/label/c.lightning_LightningPill_delete.js
<reponame>MoozaInspire/base-components-recipes export default 'Press delete or backspace to remove';
wanglei339/wms-test
wms-core/src/main/java/com/lsh/wms/core/dao/baseinfo/BaseinfoDepartmentDao.java
package com.lsh.wms.core.dao.baseinfo; import com.lsh.wms.core.dao.MyBatisRepository; import com.lsh.wms.model.baseinfo.BaseinfoDepartment; import java.util.List; import java.util.Map; @MyBatisRepository public interface BaseinfoDepartmentDao { void insert(BaseinfoDepartment baseinfoDepartment); void update(BaseinfoDepartment baseinfoDepartment); BaseinfoDepartment getBaseinfoDepartmentById(Long id); Integer countBaseinfoDepartment(Map<String, Object> params); List<BaseinfoDepartment> getBaseinfoDepartmentList(Map<String, Object> params); }
liuhaozzu/linux
kernels/linux-2.6.24/drivers/scsi/st.h
<filename>kernels/linux-2.6.24/drivers/scsi/st.h #ifndef _ST_H #define _ST_H #include <linux/completion.h> #include <linux/mutex.h> #include <linux/kref.h> #include <scsi/scsi_cmnd.h> /* Descriptor for analyzed sense data */ struct st_cmdstatus { int midlevel_result; struct scsi_sense_hdr sense_hdr; int have_sense; u64 uremainder64; u8 flags; u8 remainder_valid; u8 fixed_format; u8 deferred; }; struct scsi_tape; /* scsi tape command */ struct st_request { unsigned char cmd[MAX_COMMAND_SIZE]; unsigned char sense[SCSI_SENSE_BUFFERSIZE]; int result; struct scsi_tape *stp; struct completion *waiting; }; /* The tape buffer descriptor. */ struct st_buffer { unsigned char dma; /* DMA-able buffer */ unsigned char do_dio; /* direct i/o set up? */ int buffer_size; int buffer_blocks; int buffer_bytes; int read_pointer; int writing; int syscall_result; struct st_request *last_SRpnt; struct st_cmdstatus cmdstat; unsigned char *b_data; unsigned short use_sg; /* zero or max number of s/g segments for this adapter */ unsigned short sg_segs; /* number of segments in s/g list */ unsigned short orig_frp_segs; /* number of segments allocated at first try */ unsigned short frp_segs; /* number of buffer segments */ unsigned int frp_sg_current; /* driver buffer length currently in s/g list */ struct st_buf_fragment *frp; /* the allocated buffer fragment list */ struct scatterlist sg[1]; /* MUST BE last item */ }; /* The tape buffer fragment descriptor */ struct st_buf_fragment { struct page *page; unsigned int length; }; /* The tape mode definition */ struct st_modedef { unsigned char defined; unsigned char sysv; /* SYS V semantics? */ unsigned char do_async_writes; unsigned char do_buffer_writes; unsigned char do_read_ahead; unsigned char defaults_for_writes; unsigned char default_compression; /* 0 = don't touch, etc */ short default_density; /* Forced density, -1 = no value */ int default_blksize; /* Forced blocksize, -1 = no value */ struct cdev *cdevs[2]; /* Auto-rewind and non-rewind devices */ }; /* Number of modes can be changed by changing ST_NBR_MODE_BITS. The maximum number of modes is 16 (ST_NBR_MODE_BITS 4) */ #define ST_NBR_MODE_BITS 2 #define ST_NBR_MODES (1 << ST_NBR_MODE_BITS) #define ST_MODE_SHIFT (7 - ST_NBR_MODE_BITS) #define ST_MODE_MASK ((ST_NBR_MODES - 1) << ST_MODE_SHIFT) #define ST_MAX_TAPES 128 #define ST_MAX_TAPE_ENTRIES (ST_MAX_TAPES << (ST_NBR_MODE_BITS + 1)) /* The status related to each partition */ struct st_partstat { unsigned char rw; unsigned char eof; unsigned char at_sm; unsigned char last_block_valid; u32 last_block_visited; int drv_block; /* The block where the drive head is */ int drv_file; }; #define ST_NBR_PARTITIONS 4 /* The tape drive descriptor */ struct scsi_tape { struct scsi_driver *driver; struct scsi_device *device; struct mutex lock; /* For serialization */ struct completion wait; /* For SCSI commands */ struct st_buffer *buffer; /* Drive characteristics */ unsigned char omit_blklims; unsigned char do_auto_lock; unsigned char can_bsr; unsigned char can_partitions; unsigned char two_fm; unsigned char fast_mteom; unsigned char immediate; unsigned char restr_dma; unsigned char scsi2_logical; unsigned char default_drvbuffer; /* 0xff = don't touch, value 3 bits */ unsigned char cln_mode; /* 0 = none, otherwise sense byte nbr */ unsigned char cln_sense_value; unsigned char cln_sense_mask; unsigned char use_pf; /* Set Page Format bit in all mode selects? */ unsigned char try_dio; /* try direct i/o in general? */ unsigned char try_dio_now; /* try direct i/o before next close? */ unsigned char c_algo; /* compression algorithm */ unsigned char pos_unknown; /* after reset position unknown */ int tape_type; int long_timeout; /* timeout for commands known to take long time */ unsigned long max_pfn; /* the maximum page number reachable by the HBA */ /* Mode characteristics */ struct st_modedef modes[ST_NBR_MODES]; int current_mode; /* Status variables */ int partition; int new_partition; int nbr_partitions; /* zero until partition support enabled */ struct st_partstat ps[ST_NBR_PARTITIONS]; unsigned char dirty; unsigned char ready; unsigned char write_prot; unsigned char drv_write_prot; unsigned char in_use; unsigned char blksize_changed; unsigned char density_changed; unsigned char compression_changed; unsigned char drv_buffer; unsigned char density; unsigned char door_locked; unsigned char autorew_dev; /* auto-rewind device */ unsigned char rew_at_close; /* rewind necessary at close */ unsigned char inited; unsigned char cleaning_req; /* cleaning requested? */ int block_size; int min_block; int max_block; int recover_count; /* From tape opening */ int recover_reg; /* From last status call */ #if DEBUG unsigned char write_pending; int nbr_finished; int nbr_waits; int nbr_requests; int nbr_dio; int nbr_pages; int nbr_combinable; unsigned char last_cmnd[6]; unsigned char last_sense[16]; #endif struct gendisk *disk; struct kref kref; }; /* Bit masks for use_pf */ #define USE_PF 1 #define PF_TESTED 2 /* Values of eof */ #define ST_NOEOF 0 #define ST_FM_HIT 1 #define ST_FM 2 #define ST_EOM_OK 3 #define ST_EOM_ERROR 4 #define ST_EOD_1 5 #define ST_EOD_2 6 #define ST_EOD 7 /* EOD hit while reading => ST_EOD_1 => return zero => ST_EOD_2 => return zero => ST_EOD, return ENOSPC */ /* When writing: ST_EOM_OK == early warning found, write OK ST_EOD_1 == allow trying new write after early warning ST_EOM_ERROR == early warning found, not able to write all */ /* Values of rw */ #define ST_IDLE 0 #define ST_READING 1 #define ST_WRITING 2 /* Values of ready state */ #define ST_READY 0 #define ST_NOT_READY 1 #define ST_NO_TAPE 2 /* Values for door lock state */ #define ST_UNLOCKED 0 #define ST_LOCKED_EXPLICIT 1 #define ST_LOCKED_AUTO 2 #define ST_LOCK_FAILS 3 /* Positioning SCSI-commands for Tandberg, etc. drives */ #define QFA_REQUEST_BLOCK 0x02 #define QFA_SEEK_BLOCK 0x0c /* Setting the binary options */ #define ST_DONT_TOUCH 0 #define ST_NO 1 #define ST_YES 2 #define EXTENDED_SENSE_START 18 /* Masks for some conditions in the sense data */ #define SENSE_FMK 0x80 #define SENSE_EOM 0x40 #define SENSE_ILI 0x20 #endif
dougbrion/ModernGL
tests/experimental/conftest.py
<reponame>dougbrion/ModernGL import pytest from context import ctx
freundlich/fcppt
libs/core/include/fcppt/algorithm/loop_break_tuple.hpp
<filename>libs/core/include/fcppt/algorithm/loop_break_tuple.hpp<gh_stars>10-100 // Copyright <NAME> 2009 - 2021. // 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) #ifndef FCPPT_ALGORITHM_LOOP_BREAK_TUPLE_HPP_INCLUDED #define FCPPT_ALGORITHM_LOOP_BREAK_TUPLE_HPP_INCLUDED #include <fcppt/algorithm/loop_break_impl_fwd.hpp> #include <fcppt/algorithm/detail/tuple_loop_break.hpp> #include <fcppt/tuple/is_object.hpp> #include <fcppt/config/external_begin.hpp> #include <type_traits> #include <utility> #include <fcppt/config/external_end.hpp> namespace fcppt::algorithm { template <typename Range> struct loop_break_impl<Range, std::enable_if_t<fcppt::tuple::is_object<Range>::value>> { template <typename Tuple, typename Body> inline static void execute(Tuple &&_range, Body const &_body) { fcppt::algorithm::detail::tuple_loop_break<0U>(std::forward<Tuple>(_range), _body); } }; } #endif
owebboy/canvas-editor
app/components/placeholder-editor/component.js
export { default } from 'canvas-editor/components/placeholder-editor/component';
wangsxx/yiniko_edu_system
edu-springcloud/service/service_oss/src/main/java/com/wangs/oss/util/ReadProperties.java
package com.wangs.oss.util; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; /** * @File : ReadProperties.java * @Time : 2021/2/3 14:12 * @Author: Wangs * @Decs : */ @Component public class ReadProperties implements InitializingBean { // 读取配置文件内容 @Value("${aliyun.oss.file.endpoint}") private String endPoint; @Value("${aliyun.oss.file.keyid}") private String keyId; @Value("${aliyun.oss.file.keysecret}") private String keySecret; @Value("${aliyun.oss.file.bucketname}") private String bucketName; // 定义公开常量 public static String END_POINT; public static String KEY_ID; public static String KEY_SECRET; public static String BUCKET_NAME; public void afterPropertiesSet() throws Exception { END_POINT = endPoint; KEY_ID = keyId; KEY_SECRET = keySecret; BUCKET_NAME = bucketName; } }
davidtangGT/mol2vector
molml/base.py
""" A collection of all the base transformer constructions. This module is a collection of all the base classes and mixins for use with the other transformers. """ import inspect import multiprocessing from functools import reduce import json import numpy from pathos.multiprocessing import ProcessingPool as Pool from .utils import get_smoothing_function, get_spacing_function from .utils import LazyValues, IndexMap from .io import read_file_data def _func_star(args): """ A function and argument expanding helper function. The first item in args is callable, and the remainder of the items are used as expanded arguments. This is to make the function header for reduce the same for the normal and parallel versions. Otherwise, the functions would have to do their own unpacking of arguments. """ f = args[0] args = args[1:] return f(*args) class BaseFeature(object): """ A base class for all the features. Parameters ---------- input_type : str, list of str, or callable, default='list' Specifies the format the input values will be (must be one of 'list', 'filename', a list of strings, or a callable). If it is a list of strings, the strings tell the order of (and if they are included) the different molecule attributes (coords, elements, numbers, connections). If a callable is given, then it is assumed to return a LazyValues object. n_jobs : int, default=1 Specifies the number of processes to create when generating the features. Positive numbers specify a specifc amount, and numbers less than 1 will use the number of cores the computer has. """ def __init__(self, input_type='list', n_jobs=1): self.input_type = input_type self.n_jobs = n_jobs def _get_param_strings(self): argspec = inspect.getargspec(type(self).__init__) # Delete the only non-keyword argument args = [x for x in argspec.args if x != "self"] values = [getattr(self, x) for x in args] return ["%s=%r" % (x, y) for x, y in zip(args, values)] def __repr__(self): name = type(self).__name__ params = self._get_param_strings() return "%s(%s)" % (name, ', '.join(params)) def set_params(self, **kwargs): """ Set the feature parameter values. Parameters ---------- kwargs : kwargs Key value pairs to set for the feature parameters. Keys that are not valid parameters will be ignored. """ for key, value in kwargs.items(): try: getattr(self, key) setattr(self, key, value) except AttributeError: continue def get_params(self): """ Get a dictonary of all the feature parameters. Returns ------- params : dict A dictonary of all the feature parameters. """ argspec = inspect.getargspec(type(self).__init__) # Delete the only non-keyword argument args = [x for x in argspec.args if x != "self"] values = [getattr(self, x) for x in args] return {key: value for key, value in zip(args, values)} def slugify(self): """ Convert an instance to a simple string. Returns ------- string : str The slug string """ name = type(self).__name__ # Skip the first two parameters params = self._get_param_strings()[2:] string = '__'.join([name] + params).replace("'", '') return string def convert_input(self, X): """ Convert the input (as specified in self.input_type) to a usable form. Parameters ---------- X : list or string (depends on the instance value of input_type) An object that stores the data for a single molecule. See the Notes for more details. Returns ------- values : Object An object that allows the lazy evaluation of different properties Raises ------ ValueError If the input_type given is not allowed. Notes ----- If input_type is 'list', then it must be an iterable of (elements, coodinates pairs) for each molecule. Where the elements are an iterable of the form (ele1, ele2, ..., elen) and coordinates are an iterable of the form [(x1, y1, z1), (x2, y2, z2), ..., (xn, yn, zn)]. This allows allows for connections to be included. This is a dictionary where the keys are the indices of the atoms and the values are dictonaries with the key being another index and the value is the bond order (one of '1', 'Ar', '2', or '3'). Example for methane:: { 0: {1: "1", 2: "1", 3: "1", 4: "1"}, 1: {0: "1"}, 2: {0: "1"}, 3: {0: "1"}, 4: {0: "1"}, } If input_type is 'filename', then it must be an iterable of paths/filenames for each molecule. Currently, the supported formats are: xyz, mol2, and a simple xyz format (.out). If input_type is a list, then they will be treated as labels to each of the arguments passed in via a tuple. For example, input_type="list" can be reproduced with ["elements", "coords"] or ["elements", "coords", "connections"]. If input_type is a callable, then it is assumed that the callable returns a LazyValues object. """ connections = None if self.input_type == "list": try: first, coords = X except ValueError: first, coords, connections = X if len(first) and isinstance(first[0], str): values = LazyValues(elements=first, coords=coords, connections=connections) else: values = LazyValues(numbers=first, coords=coords, connections=connections) elif self.input_type == "filename": values = read_file_data(X) elif type(self.input_type) in (list, tuple): d = {x: y for x, y in zip(self.input_type, X)} values = LazyValues(**d) elif callable(self.input_type): values = self.input_type(X) else: raise ValueError("The input_type '%s' is not allowed." % self.input_type) return values def get_labels(self): """ Get the labels for the features in the transformer Returns ------- values : tuple All of the labels of the resulting features. """ if self.LABELS is None: return tuple() values = [] for x in self.LABELS: try: func_name, data_name = x func = getattr(self, func_name) if data_name is None: temp = func() else: data = getattr(self, data_name) temp = func(data) except (TypeError, ValueError) as e: if len(x) == 2: # Error in calling the function raise e temp = getattr(self, x) values.append(tuple(temp)) return sum(values, tuple()) def check_fit(self): """ Check if the transformer has been fit Raises ------ ValueError The transformer has not been fit. """ if self.ATTRIBUTES is None: return msg = "This %s instance is not fitted yet. Call 'fit' first." for key in self.ATTRIBUTES: if getattr(self, key) is None: raise ValueError(msg % type(self).__name__) @classmethod def get_citation(self): try: docs = self.__doc__ idx = docs.index("References") values = [x.strip() for x in docs[idx:].split('\n')[2:]] new_values = [[]] for value in values: if "----" in value: new_values.pop() break elif not value: new_values.append([]) else: new_values[-1].append(value) strings = [' '.join(x) for x in new_values if x] return '\n'.join(strings) except ValueError: return "MolML https://github.com/crcollins/molml" def map(self, f, seq): """ Parallel implementation of map. Parameters ---------- f : callable A function to map to all the values in 'seq' seq : iterable An iterable of values to process with 'f' Returns ------- results : list, shape=[len(seq)] The evaluated values """ if self.n_jobs < 1: n_jobs = multiprocessing.cpu_count() elif self.n_jobs == 1: return list(map(f, seq)) else: n_jobs = self.n_jobs pool = Pool(n_jobs) results = list(pool.map(f, seq)) # Closing/joining is not really allowed because pathos sees pools as # lasting for the duration of the program. return results def reduce(self, f, seq): """ Parallel implementation of reduce. This changes the problem from being O(n) steps to O(lg n) Parameters ---------- f : callable A function to use to reduce the values of 'seq' seq : iterable An iterable of values to process Returns ------- results : object A single reduced object based on 'seq' and 'f' """ if self.n_jobs == 1: return reduce(f, seq) while len(seq) > 1: pairs = [(f, x, y) for x, y in zip(seq[::2], seq[1::2])] temp_seq = self.map(_func_star, pairs) # If the sequence length is odd add the last element on # This is because it will not get included with the zip if len(seq) % 2: temp_seq.append(seq[-1]) seq = temp_seq return seq[0] def fit(self, X, y=None): """ Fit the model. Parameters ---------- X : list, shape=(n_samples, ) A list of objects to use to fit. Returns ------- self : object Returns the instance itself. """ raise NotImplementedError def _para_transform(self, X): """ A single instance of the transform procedure. This is formulated in a way that the transformations can be done completely parallel with map. Parameters ---------- X : object An object to use for the transform Returns ------- value : array-like The features extracted from the molecule """ raise NotImplementedError def transform(self, X, y=None): """ Framework for a potentially parallel transform. Parameters ---------- X : list, shape=(n_samples, ) A list of objects to use to transform Returns ------- array : array, shape=(n_samples, n_features) The transformed features """ self.check_fit() results = self.map(self._para_transform, X) return numpy.array(results) def fit_transform(self, X, y=None): """ A naive default implementation of fitting and transforming. Parameters ---------- X : list, shape=(n_samples, ) A list of objects to use to fit and then transform Returns ------- array : array, shape=(n_samples, n_features) The transformed features """ self.fit(X, y) return self.transform(X, y) def to_json(self): """ Return model data as a json compatible dict This will recursively convert other transformer objects as well. Returns ------- data : dict The json data """ attributes = {} if self.ATTRIBUTES is not None: attributes = {key: getattr(self, key) for key in self.ATTRIBUTES} full_name = self.__module__ + '.' + self.__class__.__name__ params = {} for key, value in self.get_params().items(): try: params[key] = value.to_json() except AttributeError: params[key] = value data = { "transformer": full_name, "parameters": params, "attributes": attributes, } return data def save_json(self, f): """ Save the model data in a json file Parameters ---------- f : str or file descriptor The path to save the data or a file descriptor to save it to. """ data = self.to_json() try: json.dump(data, f) except AttributeError: with open(f, 'w') as out_file: json.dump(data, out_file) class SetMergeMixin(object): """ A simple mixin that will merge sets. This mixin replaces all the duplicate code that just merges sets when doing the parallel fits. For this to work, it requires that the subclasses define `ATTRIBUTES`. """ def fit(self, X, y=None): """ Fit the model. Parameters ---------- X : list, shape=(n_samples, ) A list of objects to use to fit. Returns ------- self : object Returns the instance itself. """ res = self.map(self._para_fit, X) if len(self.ATTRIBUTES) > 1: temp = self.reduce(lambda x, y: tuple(set(xx) | set(yy) for xx, yy in zip(x, y)), res) for attr, vals in zip(self.ATTRIBUTES, temp): setattr(self, attr, tuple(sorted(set(vals)))) else: vals = self.reduce(lambda x, y: set(x) | set(y), res) setattr(self, self.ATTRIBUTES[0], tuple(sorted(set(vals)))) return self class FormMixin(object): """ A simple mixin for handling form transformations This mixin handles all how index mapping is done when going from higher dimensional attributes to lower dimensional ones. By default, this mixin uses the first value in ATTRIBUTES as the basis for the index mapping. use_comb_idxs : bool, default=False Whether or not to use all combinations of indices when doing the subselection. If this is false, a middle out scheme will be used. """ def __init__(self, form=1, add_unknown=False, use_comb_idxs=False, *args, **kwargs): super(FormMixin, self).__init__(*args, **kwargs) self.form = form self.add_unknown = add_unknown self.use_comb_idxs = use_comb_idxs self._idx_map = None def get_idx_map(self): """ Lazily load the idx_map. Returns ------- idx_map : IndexMap The IndexMap object for this form and add_unknown setting. """ values = getattr(self, self.ATTRIBUTES[0]) if self._idx_map is None or not self._idx_map.is_valid(values): self._idx_map = IndexMap(values, self.form, self.add_unknown, self.use_comb_idxs) return self._idx_map def get_group_order(self, groups): """ Parameters ---------- groups : list A list of all the groups. This is ignored. Returns ------- value_order : list A list of all groups in order. """ return self.get_idx_map().get_value_order() def transform(self, X, y=None): """ Framework for a potentially parallel transform. Parameters ---------- X : list, shape=(n_samples, ) A list of objects to use to transform Returns ------- array : array, shape=(n_samples, n_features) The transformed features """ self.check_fit() # This is to ensure that the idx_map exists before potentially # duplicating the process for parallelization. self.get_idx_map() results = self.map(self._para_transform, X) return numpy.array(results) class InputTypeMixin(object): """ A simple mixin to to check input_types if there are multiples. This mixin adds a method to check if a transformer parameter does not have the same input_type as the parent object. """ def check_transformer(self, transformer): """ Check a transformer. Parameters ---------- transformer : BaseFeature A transformer object. Raises ------ ValueError If the input_type pairing given is not allowed. """ if self.input_type is None: if transformer is not None: self.input_type = transformer.input_type else: # Standard default self.input_type = 'list' elif transformer is not None: if self.input_type != transformer.input_type: string = "The input_type for transformer (%r) does not " string += "match the input_type of this %s (%r)" raise ValueError(string % (transformer.input_type, self.__class__.__name__, self.input_type)) class EncodedFeature(BaseFeature): """ This is a generalized class to handle all kinds of encoding feature representations. These approaches seem to be a fairly general way of making lists of scalar values more effective to use in machine learning models. Essentially, it can be viewed as kernel smoothed histograms over the values of interest. Parameters ---------- input_type : string, default='list' Specifies the format the input values will be (must be one of 'list' or 'filename'). n_jobs : int, default=1 Specifies the number of processes to create when generating the features. Positive numbers specify a specifc amount, and numbers less than 1 will use the number of cores the computer has. segments : int, default=100 The number of bins/segments to use when generating the histogram. Empirically, it has been found that values beyond 50-100 have little benefit. smoothing : string or callable, default='norm' A string or callable to use to smooth the histogram values. If a callable is given, it must take just a single argument that is a float (or vector of floats). For a list of supported default functions look at SMOOTHING_FUNCTIONS. start : float, default=0.2 The starting point for the histgram sampling in angstroms. end : float, default=6.0 The ending point for the histogram sampling in angstroms. slope : float, default=20. A parameter to tune the smoothing values. This is applied as a multiplication before calling the smoothing function. spacing : string or callable, default='linear' The histogram interval spacing type. Must be one of ("linear", "inverse", or "log"). Linear spacing is normal spacing. Inverse takes and evaluates the distances as 1/r and the start and end points are 1/x. For log spacing, the distances are evaluated as numpy.log(r) and the start and end points are numpy.log(x). If the value is callable, then it should take a float or vector of floats and return a similar mapping like the other methods. References ---------- <NAME>.; <NAME>.; <NAME>.; <NAME>. Constant Size Molecular Descriptors For Use With Machine Learning. arXiv:1701.06649 """ def __init__(self, input_type='list', n_jobs=1, segments=100, smoothing='norm', slope=20., start=0.2, end=6., spacing='linear'): super(EncodedFeature, self).__init__(input_type=input_type, n_jobs=n_jobs) self.segments = segments self.smoothing = smoothing self.slope = slope self.start = start self.end = end self.spacing = spacing def _get_theta_info(self): theta_func = get_spacing_function(self.spacing) theta = numpy.linspace(theta_func(self.start), theta_func(self.end), self.segments) return theta, theta_func def encode_values(self, iterator, lengths, saved_lengths=0): ''' Encodes an iterable of values into a uniform length array. These values can then be indexed to allow binning them in different sections of the array. After the values are processed, the array can by flattened down to a desired number of axes. Parameters ---------- iterator : iterable The collection of values to encode. Each item in the iterable must contain values for (idx, value, scaling). Where idx is a tuple of integer values indicating which encoding bucket the values go in, value is the value to encode, and scaling is a factor that gets multiplied by the final encoded subvector before getting added to the total (This is mostly used to mask values and scale their influence with distance. If idx is None, then the value will be skipped. lengths : tuple of ints The number of encoding axes to create. In terms of EncodedBonds, this would be the number of element pairs. saved_lengths : ints The number of axis components to retain. The order that they get saved is the same order that is given in lengths. For example, when doing atom encodings, this should be 1 to retain the atom axis. Returns ------- vector : array The final concatenated vector of all the subvectors. This will have a shape of lengths[:saved_lengths] + product(lengths[saved_lengths:]) * segments). ''' smoothing_func = get_smoothing_function(self.smoothing) vector = numpy.zeros(tuple(lengths) + (self.segments, )) theta, theta_func = self._get_theta_info() for idxs, value, scaling in iterator: if idxs is None: continue diff = theta - theta_func(value) value = smoothing_func(diff, self.slope) vector[tuple(idxs)] += value * scaling reshape = tuple(lengths)[:saved_lengths] + (-1, ) return vector.reshape(*reshape) def get_group_order(self, groups): """ Parameters ---------- groups : list A list of all the groups. Returns ------- value_order : list A list of all groups in order. """ return groups def get_encoded_labels(self, groups): """ Parameters ---------- groups : list A list of all the groups. Returns ------- labels : list A list of all the feature labels. """ theta, theta_func = self._get_theta_info() labels = [] for group in self.get_group_order(groups): name = '-'.join(group) for x in theta: labels.append('%s_%s' % (name, round(x, 5))) return labels
lparth/spiffe-spire
test/mock/agent/manager/cache/cache_mock.go
// Code generated by MockGen. DO NOT EDIT. // Source: github.com/spiffe/spire/pkg/agent/manager/cache (interfaces: Cache) package mock_cache import ( gomock "github.com/golang/mock/gomock" cache "github.com/spiffe/spire/pkg/agent/manager/cache" common "github.com/spiffe/spire/proto/common" reflect "reflect" ) // MockCache is a mock of Cache interface type MockCache struct { ctrl *gomock.Controller recorder *MockCacheMockRecorder } // MockCacheMockRecorder is the mock recorder for MockCache type MockCacheMockRecorder struct { mock *MockCache } // NewMockCache creates a new mock instance func NewMockCache(ctrl *gomock.Controller) *MockCache { mock := &MockCache{ctrl: ctrl} mock.recorder = &MockCacheMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use func (_m *MockCache) EXPECT() *MockCacheMockRecorder { return _m.recorder } // DeleteEntries mocks base method func (_m *MockCache) DeleteEntries(_param0 *common.RegistrationEntry) int { ret := _m.ctrl.Call(_m, "DeleteEntries", _param0) ret0, _ := ret[0].(int) return ret0 } // DeleteEntries indicates an expected call of DeleteEntries func (_mr *MockCacheMockRecorder) DeleteEntries(arg0 interface{}) *gomock.Call { return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "DeleteEntries", reflect.TypeOf((*MockCache)(nil).DeleteEntries), arg0) } // DeleteEntry mocks base method func (_m *MockCache) DeleteEntry(_param0 *common.RegistrationEntry) bool { ret := _m.ctrl.Call(_m, "DeleteEntry", _param0) ret0, _ := ret[0].(bool) return ret0 } // DeleteEntry indicates an expected call of DeleteEntry func (_mr *MockCacheMockRecorder) DeleteEntry(arg0 interface{}) *gomock.Call { return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "DeleteEntry", reflect.TypeOf((*MockCache)(nil).DeleteEntry), arg0) } // Entries mocks base method func (_m *MockCache) Entries() chan cache.Entry { ret := _m.ctrl.Call(_m, "Entries") ret0, _ := ret[0].(chan cache.Entry) return ret0 } // Entries indicates an expected call of Entries func (_mr *MockCacheMockRecorder) Entries() *gomock.Call { return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "Entries", reflect.TypeOf((*MockCache)(nil).Entries)) } // Entry mocks base method func (_m *MockCache) Entry(_param0 *common.RegistrationEntry) *cache.Entry { ret := _m.ctrl.Call(_m, "Entry", _param0) ret0, _ := ret[0].(*cache.Entry) return ret0 } // Entry indicates an expected call of Entry func (_mr *MockCacheMockRecorder) Entry(arg0 interface{}) *gomock.Call { return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "Entry", reflect.TypeOf((*MockCache)(nil).Entry), arg0) } // IsEmpty mocks base method func (_m *MockCache) IsEmpty() bool { ret := _m.ctrl.Call(_m, "IsEmpty") ret0, _ := ret[0].(bool) return ret0 } // IsEmpty indicates an expected call of IsEmpty func (_mr *MockCacheMockRecorder) IsEmpty() *gomock.Call { return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "IsEmpty", reflect.TypeOf((*MockCache)(nil).IsEmpty)) } // SetEntry mocks base method func (_m *MockCache) SetEntry(_param0 *cache.Entry) { _m.ctrl.Call(_m, "SetEntry", _param0) } // SetEntry indicates an expected call of SetEntry func (_mr *MockCacheMockRecorder) SetEntry(arg0 interface{}) *gomock.Call { return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "SetEntry", reflect.TypeOf((*MockCache)(nil).SetEntry), arg0) }
gsanchezgavier/nri-kubernetes
src/ksm/client/client.go
<gh_stars>0 package client import ( "fmt" "time" "github.com/sethgrid/pester" log "github.com/sirupsen/logrus" "github.com/newrelic/nri-kubernetes/v2/internal/logutil" "github.com/newrelic/nri-kubernetes/v2/src/client" "github.com/newrelic/nri-kubernetes/v2/src/prometheus" ) // Client implements a client for KSM, capable of retrieving prometheus metrics from a given endpoint. type Client struct { // http is an HttpDoer that the KSM client will use to make requests. http client.HTTPDoer logger *log.Logger } type OptionFunc func(kc *Client) error // WithLogger returns an OptionFunc to change the logger from the default noop logger. func WithLogger(logger *log.Logger) OptionFunc { return func(kc *Client) error { kc.logger = logger return nil } } // New builds a Client using the given options. By default, it will use pester as an HTTP Doer and a noop logger. func New(opts ...OptionFunc) (*Client, error) { k := &Client{ logger: logutil.Discard, } httpPester := pester.New() httpPester.Backoff = pester.LinearBackoff httpPester.MaxRetries = 3 httpPester.Timeout = 10 * time.Second httpPester.LogHook = func(e pester.ErrEntry) { k.logger.Debugf("getting data from ksm: %v", e) } k.http = httpPester for i, opt := range opts { if err := opt(k); err != nil { return nil, fmt.Errorf("applying option #%d: %w", i, err) } } return k, nil } // MetricFamiliesGetFunc returns a function that obtains metric families from a list of prometheus queries. func (c *Client) MetricFamiliesGetFunc(url string) prometheus.FetchAndFilterMetricsFamilies { return func(queries []prometheus.Query) ([]prometheus.MetricFamily, error) { mFamily, err := prometheus.GetFilteredMetricFamilies(c.http, url, queries, c.logger) if err != nil { return nil, fmt.Errorf("getting filtered metric families: %w", err) } return mFamily, nil } }
ayush-kr-gupta/beginners-C-program-examples
BasicArithmatic.c
<gh_stars>100-1000 // A simple arithmetic operation on two integers #include<stdio.h> int main() { int number1, number2, addition, subtraction, multiplication, division, modulo; printf("Enter two numbers :\n"); scanf("%d%d", & number1, & number2); addition = number1 + number2; subtraction = number1 - number2; multiplication = number1 * number2; division = number1 / number2; modulo = number1 % number2; printf("Addition of number 1 and number 2 : %d\n", addition); printf("Subtraction of number 1 and number 2 : %d\n", subtraction); printf("Multiplication of number 1 and number 2 : %d\n", multiplication); printf("Division of number 1 and number 2 : %d\n", division); printf("Modulo of number 1 and number 2 : %d\n", modulo); return 0; }
jhaapako/tcf
ttbd/conf_00_lib_capture.py
#! /usr/bin/python3 # # Copyright (c) 2019 Intel Corporation # # SPDX-License-Identifier: Apache-2.0 # # """.. _conf_00_lib_capture: Configuration API for capturing audio and video ----------------------------------------------- These capture objects are meant to be fed to the capture interface declaration of a target in the server, for example, in any server configuration file you could have added a target and then a capture interface can be added with: .. code-block:: python ttbl.test_target.get('TARGETNAME').interface_add( "capture", ttbl.capture.interface( screen = "hdmi0_screenshot", screen_stream = "hdmi0_vstream", audio_stream = "front_astream", front_astream = capture_front_astream_vtop_0c76_161e, hdmi0_screenshot = capture_screenshot_ffmpeg_v4l, hdmi0_vstream = capture_vstream_ffmpeg_v4l, hdmi0_astream = capture_astream_ffmpeg_v4l, ) ) This assumes we have connected and configured: - an HDMI grabber to the target's HDMI0 output (see :data:`setup instructions <capture_screenshot_ffmpeg_v4l>`) - an audio grabber to the front audio output (see :data:`setup instructions <capture_front_astream_vtop_0c76_161e>`). to create multiple capture capabilityies (video and sound streams, and screenshots) with specific names for the ouputs and aliases) Note the audio capturers are many times HW specific because they expose different audio controls that have to be set or queried. """ import signal import ttbl.capture #: A capturer to take screenshots from a v4l device using ffmpeg #: #: Note the fields are target's tags and others specified in #: :class:`ttbl.capture.generic_snapshot` and #: :class:`ttbl.capture.generic_stream`. #: #: To use: #: #: - define a target #: #: - physically connect the capture interface to it and to the #: server #: #: - Create a *udev* configuration so the capture device exposes #: itself as */dev/video-TARGETNAME-INDEX*. #: #: This requires creating a *udev* configuration so that the v4l #: device gets recognized and an alias created, which can be #: accomplished by dropping a udev rule in */etc/udev/rules.d* such #: as:: #: #: SUBSYSTEM == "video4linux", ACTION == "add", \ #: KERNEL=="video*", \ #: ENV{ID_SERIAL_SHORT} == "SOMESERIALNUMBER", \ #: SYMLINK += "video-nuc-01A-$attr{index}" #: #: note some USB devices don't offer a serial number, then you #: can use a device path, such as:: #: #: ENV{ID_PATH} == "pci-0000:00:14.0-usb-0:2.1:1.0", \ #: #: this is shall be a last resort, as then moving cables to #: different USB ports will change the paths and you will have to #: reconfigure. #: #: See :ref:`methods to find device information <find_usb_info>` #: #: - add the configuration snippet:: #: #: ttbl.test_target.get(TARGETNAME).interface_add( #: "capture", #: ttbl.capture.interface( #: screen = "hdmi0_screenshot", #: screen_stream = "hdmi0_vstream", #: hdmi0_screenshot = capture_screenshot_ffmpeg_v4l, #: hdmi0_vstream = capture_vstream_ffmpeg_v4l, #: )) #: #: Note in this case we have used an #: #: This has tested with with: #: #: - https://www.agptek.com/AGPTEK-USB-3-0-HDMI-HD-Video-Capture-1089-212-1.html #: #: Which shows in USB as:: #: #: 3-2.2.4 1bcf:2c99 ef 3.10 5000MBit/s 512mA 4IFs (VXIS Inc ezcap U3 capture) #: 3-2.2.4:1.2 (IF) 01:01:00 0EPs (Audio:Control Device) snd-usb-audio sound/card5 #: 3-2.2.4:1.0 (IF) 0e:01:00 1EP (Video:Video Control) uvcvideo video4linux/video5 video4linux/video4 input/input15 #: 3-2.2.4:1.3 (IF) 01:02:00 0EPs (Audio:Streaming) snd-usb-audio #: 3-2.2.4:1.1 (IF) 0e:02:00 1EP (Video:Video Streaming) uvcvideo #: #: Note this also can be used to capture video of the HDMI stream #: using capture_vstream_ffmpeg_v4l and audio played over HDMI via #: an exposed ALSA interface (see capture_astream_ffmpeg_v4l below). capture_screenshot_ffmpeg_v4l = ttbl.capture.generic_snapshot( "screenshot:/dev/video-%(id)s-0", "ffmpeg -i /dev/video-%(id)s-0" # -ss .50 to let the capturer warm up; 0 will come a # black frame always " -ss 0.5 -frames 1 -c:v png -f image2pipe " "-y %(output_file_name)s", mimetype = "image/png", extension = ".png" ) #: A capturer to take screenshots from VNC #: #: Note the fields are target's tags and others specified in #: :class:`ttbl.capture.generic_snapshot` and #: :class:`ttbl.capture.generic_stream`. #: #: Deprecated in favour of :func:`mk_capture_screenshot_vnc` capture_screenshot_vnc = ttbl.capture.generic_snapshot( # dont set the port for the name, otherwise the UPID keeps # changing "VNC %(id)s@%(vnc-host)s", # need to make sure vnc-host/port are defined in the target's tags # needs the .png, otherwise it balks at guessing extensions # don't do -q, otherwise when it fails, it fails silently; for # QEMU, it is *localhost*. "gvnccapture %(vnc-host)s:%(vnc-port)s %(output_file_name)s", mimetype = "image/png", extension = ".png" ) def mk_capture_screenshot_vnc(name): """ Create a VNC screenshot capturer that captures off a VNC source declared in inventory entry *vnc.NAME* Note the fields are target's tags and others specified in :class:`ttbl.capture.generic_snapshot` and :class:`ttbl.capture.generic_stream`. to use, add in a :ref:`server configuration file <ttbd_configuration>` to any target that offers a VNC source: >>> target.interface_add("capture", ttbl.capture.interface( >>> vnc0_screenshot = mk_capture_screenshot_vnc("vnc0"), >>> screen = "vnc0_screenshot", >>> )) """ assert isinstance(name, str) # note the %(FIELD)s will be mapped to entries in the target's # inventory when the capture is going to be done, so if name is # ABC, it will capture off vnc.ABC,host return ttbl.capture.generic_snapshot( # dont set the port for the name, otherwise the UPID keeps # changing f"VNC %(id)s@%(vnc.{name}.host)s", # need to make sure vnc-host/port are defined in the target's tags # needs the .png, otherwise it balks at guessing extensions # don't do -q, otherwise when it fails, it fails silently; for # QEMU, it is *localhost*. f"gvnccapture %(vnc.{name}.host)s:%(vnc.{name}.port)s %(output_file_name)s", mimetype = "image/png", extension = ".png" ) #: Capture a screenshot off VNC port declared in inventory *vnc.vnc0* capture_screenshot_vnc0 = mk_capture_screenshot_vnc("vnc0") #: Capture video off a v4l device using ffmpeg #: #: See capture_screenshot_ffmpeg_v4l for setup instructions, as they #: are common. capture_vstream_ffmpeg_v4l = ttbl.capture.generic_stream( "video:/dev/video-%(id)s-0", "ffmpeg -y -nostdin -i /dev/video-%(id)s-0" " -flush_packets" # disable some buffering " -f avi -qscale:v 10 -y %(stream_filename)s", mimetype = "video/avi", extension = ".avi", wait_to_kill = 4, use_signal = signal.SIGINT # flushes ffmpeg ) #: Capture audio off an Alsa device using ffmpeg #: #: See capture_screenshot_ffmpeg_v4l for setup instructions, as they #: are similar. #: #: Note the udev setup instructions for Alsa devices are slightly #: different; instead of *SYMLINKS* we have to set *ATTR{id}*:: #: #: SUBSYSTEM == "sound", ACTION == "add", \ #: ENV{ID_PATH} == "pci-0000:00:14.0-usb-0:2.1:1.2", \ #: ATTR{id} = "TARGETNAME" #: #: Once this configuration is completed, udev is reloaded (*sudo #: udevadm control --reload-rules*) and the #: device is triggered (with *udevadm trigger /dev/snd/controlCX* or #: the machine restarted), */proc/asound* should contain a symlink to #: the actual card:: #: #: $ ls /proc/asound/ -l #: total 0 #: dr-xr-xr-x. 3 root root 0 Jun 21 21:52 card0 #: dr-xr-xr-x. 7 root root 0 Jun 21 21:52 card4 #: .. #: lrwxrwxrwx. 1 root root 5 Jun 21 21:52 TARGETNAME -> card4 #: ... #: #: Device information for Alsa devices (Card 0, Card 1, etc...) can be #: found with:: #: #: $ udevadm info /dev/snd/controlC0 #: P: /devices/pci0000:00/0000:00:1f.3/sound/card0/controlC0 #: N: snd/controlC0 #: S: snd/by-path/pci-0000:00:1f.3 #: E: DEVLINKS=/dev/snd/by-path/pci-0000:00:1f.3 #: E: DEVNAME=/dev/snd/controlC0 #: E: DEVPATH=/devices/pci0000:00/0000:00:1f.3/sound/card0/controlC0 #: E: ID_PATH=pci-0000:00:1f.3 #: E: ID_PATH_TAG=pci-0000_00_1f_3 #: E: MAJOR=116 #: E: MINOR=11 #: E: SUBSYSTEM=sound #: E: TAGS=:uaccess: #: E: USEC_INITIALIZED=30391111 #: #: As indicated in capture_screenshot_ffmpeg_v4l, using #: *ENV{ID_SERIAL_SHORT}* is preferred if available. capture_astream_ffmpeg_v4l = ttbl.capture.generic_stream( "audio:%(id)s", "ffmpeg -f alsa -i sysdefault:%(id)s" " -f avi -qscale:v 10 -y %(output_file_name)s", mimetype = "audio/wav" ) #: #: Capture HDMI Audio from an AGPTEK USB 3.0 HDMI HD Video Capture #: #: - https://www.agptek.com/AGPTEK-USB-3-0-HDMI-HD-Video-Capture-1089-212-1.html #: #: We can't use a generic ALSA capturer because there seem to be #: glitches in the device #: capture_agptek_hdmi_astream = ttbl.capture.generic_stream( "hdmi0-audio:%(id)s", "ffmpeg -f alsa -i sysdefault:%(id)s-hdmi" " -f avi -qscale:v 10 -y %(output_file_name)s", mimetype = "audio/wav", pre_commands = [ # somehow the adapter doesn't work right unless "reset" it # with the USB kernel interface. # # This gets the path in the # /sys sysfs filesystem of /dev/video-%(id)s-0 (wih 'udevadm # info') that yiedls something like: # # $ udevadm info /dev/video-%(id)s-0 -q path # /devices/pci0000:00/0000:00:14.0/usb1/1-4/1-4.2/1-4.2:1.0/video4linux/video0 # # three levels up (removing 1-4.2:1.0/video4linux/video0) gets # us to the top level USB device information node: # # /devices/pci0000:00/0000:00:14.0/usb1/1-4/1-4.2 # # so in /sys/devices/pci0000:00/0000:00:14.0/usb1/1-4/1-4.2 # there is a file called 'authorized' that will force the USB # device to be disconnected or connected to the # system. Writing 0 we soft-disconnect it, writing 1 we ask # for it to be connected. "echo 0 > /sys/$(udevadm info video-%(id)s-0 -q path)/../../../authorized", "sleep 0.5s", "echo 1 > /sys/$(udevadm info video-%(id)s-0 -q path)/../../../authorized", "sleep 1s", # vtop HW has "Digital In" for an input name # FIXME: we have issues with the spaces, somewhere it is being # split? "amixer -c %(id)s-hdmi sset 'Digital In' 75%%" ] ) #: Capture audio with the USB capturer VTOP/JMTEK 0c76:161e #: #: https://www.amazon.com/Digital-Audio-Capture-Windows-10-11/dp/B019T9KS04 #: #: This is for capturing audio on the audio grabber connected to the #: main builtin sound output of the target (usually identified as #: *front* by the Linux driver subsystem), which UDEV has configured #: to be called TARGETNAME-front:: #: #: SUBSYSTEM == "sound", ACTION == "add", \ #: ENV{ID_PATH} == "pci-0000:00:14.0-usb-0:2.3.1:1.0", \ #: ATTR{id} = "TARGETNAME-front" #: capture_front_astream_vtop_0c76_161e = ttbl.capture.generic_stream( "audio:%(id)s-front", "ffmpeg -f alsa -i sysdefault:%(id)s-front" " -f wav -qscale:v 10 -y %(output_file_name)s", mimetype = "audio/wav", # vtop HW has Mic for an input name pre_commands = [ "amixer -c %(id)s-front sset Mic 75%%" ] )
1960176680/LiquorAndroidProject
app/src/main/java/com/hz/tt/util/ThreadPoolManager.java
<gh_stars>0 package com.hz.tt.util; import android.os.Handler; import android.os.Looper; import android.os.Message; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * Created by Administrator on 2018-04-08. */ public class ThreadPoolManager { private static ThreadPoolManager mThreadPoolManager; private final BlockingQueue<Runnable> mDecodeWorkQueue; public ThreadPoolExecutor mThreadPoolExecutor; private static final int KEEP_ALIVE_TIME = 1; private static final TimeUnit KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS; private static int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors(); private static int CORE_OF_SIZE =3; public Handler mHandler=new Handler(Looper.getMainLooper()){ @Override public void handleMessage(Message msg) { } }; private ThreadPoolManager() { mDecodeWorkQueue = new LinkedBlockingQueue<Runnable>(); mThreadPoolExecutor = new ThreadPoolExecutor( CORE_OF_SIZE, NUMBER_OF_CORES, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, mDecodeWorkQueue); } static { mThreadPoolManager = new ThreadPoolManager(); } public static ThreadPoolManager getInstance(){ return mThreadPoolManager; } public void handleState(int state) { switch (state) { case 1: mThreadPoolExecutor.execute(new Runnable() { @Override public void run() { } }); } } }
horfee/alarmpi
devices/Device.h
/* * Sensor.h * * Created on: 21 juil. 2015 * Author: horfee */ #ifndef ALARMDEVICE_H_ #define ALARMDEVICE_H_ #include <string> #include "../json/json.h" namespace alarmpi { class Device { public: Device(int id, std::string description); virtual ~Device(); int getId() const; std::string getDescription() const; void setDescription(std::string description); virtual std::string getType() const = 0; virtual Json::Value toJSON() const; virtual bool operator==(const int& deviceId); virtual bool operator==(const Device& device); virtual bool operator!=(const int& deviceId); virtual bool operator!=(const Device& device); private: int id; std::string description; // AlarmSystem* system; }; } /* namespace alarmpi */ #endif /* ALARMDEVICE_H_ */
Unchained112/WebCardGames
public/js/views/game24startViews.js
function StartView(props){ return( <div className="game24start"> <div className="w3-container w3-center"> <div className="w3-container w3-margin-top"> <img src={"./assets/24gamelogowhite.png"} style="width:200px"></img> </div> <div class=" w3-content w3-text-white w3-animate-opacity" style="max-width:500px"> <p>The 24 game is a simple math game played with poker cards. It has been played in Shanghai since the 1960s. The player draws four cards from a shuffled deck of cards and finds a way to manipulate the four values with elementary arithmetic operations (,+,-,*,/,) to come up with 24. </p> <button className="w3-button w3-green" onClick={e => { window.location.hash = "#24gameContent" }}>Start! </button> <p>A simple example:</p> <p><img src={"./assets/24gameJD.png"} style="width:100px"></img> <img src={"./assets/24game7S.png"} style="width:100px"></img> <img src={"./assets/24gameAC.png"} style="width:100px"></img> <img src={"./assets/24game6H.png"} style="width:100px"></img> </p> <p> {"The quadruple is {11,7,1,6}. There are several different solutions:"} </p> <p> (11 - 7) * (1 * 6)</p> <p> (11 - 7) / (1 / 6)</p> <p> (11 + 7) + (1 * 6)</p> <p>...</p> </div> </div> </div> ) }
maierfelix/emerald-engine
src/engine/map/autotile.js
import * as CFG from "../../cfg"; import { assert, getTilesetTileIndexBy, getTilesetTilePositionByIndex } from "../../utils"; export function drawAutotile(x, y, tileset, layer, sx, sy) { // don't allow drawing into preview layer if (layer === CFG.ENGINE_TS_LAYERS.PREVIEW) return; if (!this.coordsInBounds(x, y)) return this.clearPreviewTable(); let texture = this.textures[layer - 1]; for (let ii = 0; ii < 9; ++ii) { let xx = ((ii % 3) | 0) - 1; let yy = ((ii / 3) | 0) - 1; this.drawTileAt( tileset, sx + 1, sy + 1, x + xx, y + yy, layer ); }; for (let ii = 0; ii < 9; ++ii) { let xx = ((ii % 3) | 0) - 1; let yy = ((ii / 3) | 0) - 1; let autoTile = this.getAutoTileAt(x + xx, y + yy, layer, sx, sy); this.drawTileAt( tileset, sx + autoTile.x, sy + autoTile.y, x + xx, y + yy, layer ); }; }; export function getTileAutoAt(x, y, layer) { let tile = this.getTileAt(x, y, layer); let tsPos = getTilesetTilePositionByIndex(tile); return { x: tsPos.x, y: tsPos.y } }; export function inTileRange(newTile, srcTile, srcTileX, srcTileY) { let newTilePos = getTilesetTilePositionByIndex(newTile + 1); return ( (newTilePos.x >= srcTileX) && (newTilePos.y >= srcTileY) && (newTilePos.x < (srcTileX + CFG.ENGINE_AUTOTILE_WIDTH)) && (newTilePos.y < (srcTileY + CFG.ENGINE_AUTOTILE_HEIGHT)) ); }; export function getAutoTileAt(x, y, layer, sx, sy) { let edges = ""; let edgeType; let tile = this.getTileAt(x, y, layer); let n = this.getTileAt(x, y - 1, layer); let s = this.getTileAt(x, y + 1, layer); let e = this.getTileAt(x + 1, y, layer); let w = this.getTileAt(x - 1, y, layer); let nw = this.getTileAt(x - 1, y - 1, layer); let ne = this.getTileAt(x + 1, y - 1, layer); let se = this.getTileAt(x + 1, y + 1, layer); let sw = this.getTileAt(x - 1, y + 1, layer); if (!this.inTileRange(n, tile, sx, sy)) edges += "N"; if (!this.inTileRange(s, tile, sx, sy)) edges += "S"; if (!this.inTileRange(e, tile, sx, sy)) edges += "E"; if (!this.inTileRange(w, tile, sx, sy)) edges += "W"; if (edges === "") { if (!this.inTileRange(nw, tile, sx, sy)) edges = "N+W"; else if (!this.inTileRange(ne, tile, sx, sy)) edges = "N+E"; if (!this.inTileRange(se, tile, sx, sy)) edges = "S+E"; else if (!this.inTileRange(sw, tile, sx, sy)) edges = "S+W"; } return CFG.TERRAIN_SHEET_EDGES[edges] || CFG.TERRAIN_SHEET_EDGES.MID; };
specter01wj/LAB-Lynda
Front-End/React/Learning Redux/Ex_Files_Learning_Redux/Exercise Files/Ch03/03_05/finished/src/index.js
<filename>Front-End/React/Learning Redux/Ex_Files_Learning_Redux/Exercise Files/Ch03/03_05/finished/src/index.js<gh_stars>0 import C from './constants' import storeFactory from './store' const initialState = (localStorage['redux-store']) ? JSON.parse(localStorage['redux-store']) : {} const saveState = () => { const state = JSON.stringify(store.getState()) localStorage['redux-store'] = state } const store = storeFactory(initialState) store.subscribe(saveState) store.dispatch({ type: C.ADD_DAY, payload: { "resort": "Mt Shasta", "date": "2016-10-28", "powder": true, "backcountry": true } }) store.dispatch({ type: C.ADD_DAY, payload: { "resort": "Squaw Valley", "date": "2016-3-28", "powder": true, "backcountry": false } }) store.dispatch({ type: C.ADD_DAY, payload: { "resort": "The Canyons", "date": "2016-1-2", "powder": false, "backcountry": true } })
Gerhut/DLWorkspace
src/ClusterManager/endpoint_manager.py
#!/usr/bin/env python3 import json import os import time import sys import datetime import random import re import logging import yaml import logging.config import argparse from kubernetes import client, config as k8s_config from kubernetes.client.rest import ApiException from cluster_manager import setup_exporter_thread, manager_iteration_histogram, register_stack_trace_dump, update_file_modification_time from job_launcher import JobDeployer sys.path.append(os.path.join(os.path.dirname( os.path.abspath(__file__)), "../utils")) from DataHandler import DataHandler from config import config import k8sUtils logger = logging.getLogger(__name__) deployer = JobDeployer() k8s_config.load_kube_config() k8s_core_api = client.CoreV1Api() def is_ssh_server_ready(pod_name): bash_script = "service ssh status" output = k8sUtils.kubectl_exec( "exec %s %s" % (pod_name, " -- " + bash_script)) if output == "": return False return True def query_ssh_port(pod_name): bash_script = "grep ^Port /usr/etc/sshd_config | cut -d' ' -f2" status_code, output = deployer.pod_exec( pod_name, ["/bin/bash", "-c", bash_script]) if status_code != 0: raise RuntimeError("Query ssh port failed: {}".format(pod_name)) if not output: return 22 return int(output) def start_ssh_server(pod_name): '''Setup the ssh server in container, and return the listening port.''' bash_script = "service ssh start" # assume ssh server already setup # TODO setup reasonable timeout # output = k8sUtils.kubectl_exec("exec %s %s" % (jobId, " -- " + bash_script), 1) output = k8sUtils.kubectl_exec( "exec %s %s" % (pod_name, " -- " + bash_script)) if output == "": raise Exception( "Failed to setup ssh server in container. JobId: %s " % pod_name) def get_k8s_endpoint(endpoint_id): try: resp = k8s_core_api.read_namespaced_service(endpoint_id, "default") return resp except ApiException as e: if e.status == 404: return None logger.exception("could not get k8s service") return None def delete_k8s_endpoint(service_name): try: return k8s_core_api.delete_namespaced_service(service_name, "default") except ApiException as e: logger.exception("delete k8s service %s failed") def generate_node_port_service(job_id, pod_name, endpoint_id, name, target_port): endpoint = { "kind": "Service", "apiVersion": "v1", "metadata": { "name": endpoint_id, "labels": { "run": job_id, "jobId": job_id, "pod_name": pod_name, } }, "spec": { "type": "NodePort", "selector": {"podName": pod_name}, "ports": [{ "name": name, "protocol": "TCP", "targetPort": target_port, "port": target_port, }] } } logger.debug("endpoint description: %s", json.dumps(endpoint)) return endpoint def create_node_port(endpoint): endpoint_description = generate_node_port_service( endpoint["jobId"], endpoint["podName"], endpoint["id"], endpoint["name"], endpoint["podPort"]) try: resp = k8s_core_api.create_namespaced_service("default", endpoint_description) logger.info("submitted endpoint %s to k8s, returned with status %s", endpoint["jobId"], resp) except ApiException as e: logger.exception("could not create k8s service") raise Exception( "Failed to create NodePort for ssh. JobId: %s " % endpoint["jobId"]) def setup_ssh_server(user_name, pod_name, host_network=False): '''Setup ssh server on pod and return the port''' # setup ssh server only is the ssh server is not up if not is_ssh_server_ready(pod_name): logger.info("Ssh server is not ready for pod: %s. Setup ...", pod_name) start_ssh_server(pod_name) ssh_port = query_ssh_port(pod_name) logger.info("Ssh server is ready for pod: %s. Ssh listen on %s", pod_name, ssh_port) return ssh_port def setup_jupyter_server(user_name, pod_name): jupyter_port = random.randint(40000, 49999) bash_script = "bash -c 'export DEBIAN_FRONTEND=noninteractive; apt-get update && apt-get install -y python3-pip && python3 -m pip install --upgrade pip && python3 -m pip install jupyter && cd /home/" + \ user_name + " && runuser -l " + user_name + \ " -c \"jupyter notebook --no-browser --ip=0.0.0.0 --NotebookApp.token= --port=" + \ str(jupyter_port) + " &>/dev/null &\"'" output = k8sUtils.kubectl_exec( "exec %s %s" % (pod_name, " -- " + bash_script)) if output == "": raise Exception( "Failed to start jupyter server in container. JobId: %s " % pod_name) else: logger.info("install jupyter output is %s", output) return jupyter_port def setup_tensorboard(user_name, pod_name): tensorboard_port = random.randint(40000, 49999) bash_script = "bash -c 'export DEBIAN_FRONTEND=noninteractive; pip install tensorboard; runuser -l " + user_name + \ " -c \"mkdir -p ~/tensorboard/\${DLWS_JOB_ID}/logs; nohup tensorboard --logdir=~/tensorboard/\${DLWS_JOB_ID}/logs --port=" + str( tensorboard_port) + " &>/dev/null &\"'" output = k8sUtils.kubectl_exec( "exec %s %s" % (pod_name, " -- " + bash_script)) if output == "": raise Exception( "Failed to start tensorboard in container. JobId: %s " % pod_name) else: logger.info("install tensorboard output is %s", output) return tensorboard_port def start_endpoint(endpoint): # pending, running, stopped logger.info("Starting endpoint: %s", endpoint) # podName pod_name = endpoint["podName"] user_name = endpoint["username"] host_network = endpoint["hostNetwork"] port_name = endpoint["name"] if port_name == "ssh": endpoint["podPort"] = setup_ssh_server( user_name, pod_name, host_network) elif port_name == "ipython": endpoint["podPort"] = setup_jupyter_server(user_name, pod_name) elif port_name == "tensorboard": endpoint["podPort"] = setup_tensorboard(user_name, pod_name) else: endpoint["podPort"] = int(endpoint["podPort"]) # create NodePort create_node_port(endpoint) def start_endpoints(): try: data_handler = DataHandler() try: pending_endpoints = data_handler.GetPendingEndpoints() for endpoint_id, endpoint in list(pending_endpoints.items()): try: job = data_handler.GetJob(jobId=endpoint["jobId"])[0] logger.info("checking endpoint %s, status is %s", endpoint["jobId"], job["jobStatus"]) if job["jobStatus"] != "running": continue point = get_k8s_endpoint(endpoint["id"]) logger.info("endpoint of %s has %s", endpoint["jobId"], point) if point is not None: endpoint["status"] = "running" # only retain spec here, some other fields have datetime, # can not be serialized to json endpoint["endpointDescription"] = {"spec": point.spec.to_dict()} pod = k8sUtils.GetPod("podName=" + endpoint["podName"]) if "items" in pod and len(pod["items"]) > 0: logger.info("update endpoint's nodeName %s", endpoint["jobId"]) endpoint["nodeName"] = pod["items"][0]["spec"]["nodeName"] else: start_endpoint(endpoint) endpoint["lastUpdated"] = datetime.datetime.now().isoformat() data_handler.UpdateEndpoint(endpoint) except Exception as e: logger.warning("Process endpoint failed {}".format( endpoint), exc_info=True) except Exception as e: logger.exception("start endpoint failed") finally: data_handler.Close() except Exception as e: logger.exception("close data handler failed") def cleanup_endpoints(): try: data_handler = DataHandler() try: dead_endpoints = data_handler.GetDeadEndpoints() for endpoint_id, dead_endpoint in list(dead_endpoints.items()): try: logger.info("Begin to cleanup endpoint %s", endpoint_id) point = get_k8s_endpoint(dead_endpoint["id"]) if point is None: logger.info("Endpoint already gone %s", endpoint_id) status = "stopped" else: delete_resp = delete_k8s_endpoint(endpoint.metadata.name) logger.info("delete_resp for endpoint is %s", delete_resp) # we are not changing status from "pending", "pending" endpoints are planed to setup later if dead_endpoint["status"] != "pending": dead_endpoint["status"] = status dead_endpoint["lastUpdated"] = datetime.datetime.now( ).isoformat() data_handler.UpdateEndpoint(dead_endpoint) except Exception as e: logger.warning("Clanup endpoint failed {}".format( dead_endpoint), exc_info=True) except Exception as e: logger.exception("cleanup endpoint failed") finally: data_handler.Close() except Exception as e: logger.exception("close data handler failed") def create_log(logdir='/var/log/dlworkspace'): if not os.path.exists(logdir): os.system("mkdir -p " + logdir) with open('logging.yaml') as f: logging_config = yaml.full_load(f) f.close() logging_config["handlers"]["file"]["filename"] = logdir + \ "/endpoint_manager.log" logging.config.dictConfig(logging_config) def Run(): register_stack_trace_dump() create_log() while True: update_file_modification_time("endpoint_manager") with manager_iteration_histogram.labels("endpoint_manager").time(): # start endpoints start_endpoints() time.sleep(1) # clean up endpoints for jobs which is NOT running cleanup_endpoints() time.sleep(1) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( "--port", "-p", help="port of exporter", type=int, default=9205) args = parser.parse_args() setup_exporter_thread(args.port) Run()
soungsid/algoliasearch-client-java-2
algoliasearch-common/src/main/java/com/algolia/search/responses/CreateUpdateKey.java
<reponame>soungsid/algoliasearch-client-java-2 package com.algolia.search.responses; public class CreateUpdateKey { private String key; private String createdAt; /** * Name of this key */ public String getKey() { return key; } public CreateUpdateKey setKey(String key) { this.key = key; return this; } @SuppressWarnings("unused") public String getCreatedAt() { return createdAt; } @SuppressWarnings("unused") public CreateUpdateKey setCreatedAt(String createdAt) { this.createdAt = createdAt; return this; } @Override public String toString() { return "CreateUpdateKey{" + "key='" + key + '\'' + ", createdAt='" + createdAt + '\'' + '}'; } }
mrragava/mystikos-security
src/dynamic/fuzzing/syscallfuzzer/fds/fds.c
<filename>src/dynamic/fuzzing/syscallfuzzer/fds/fds.c #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "fd.h" #include "list.h" #include "net.h" #include "params.h" #include "pids.h" #include "random.h" #include "sanitise.h" #include "shm.h" #include "trinity.h" #include "utils.h" static unsigned int num_fd_providers; // num in list. static unsigned int num_fd_providers_to_enable = 0; // num of --fd-enable= params static unsigned int num_fd_providers_enabled = 0; // final num we enabled. static unsigned int num_fd_providers_initialized = 0; // num we called ->init on static bool enable_fd_initialized = FALSE; // initialized (disabled all) fd providers static struct fd_provider *fd_providers = NULL; /* * This is called by the REG_FD_PROV constructors on startup. * Because of this, this function shouldn't rely on anything * already existing/being initialized. */ void register_fd_provider(const struct fd_provider *prov) { struct fd_provider *newnode; if (fd_providers == NULL) { fd_providers = zmalloc(sizeof(struct fd_provider)); INIT_LIST_HEAD(&fd_providers->list); } newnode = zmalloc(sizeof(struct fd_provider)); newnode->name = strdup(prov->name); newnode->enabled = prov->enabled; newnode->open = prov->open; newnode->get = prov->get; num_fd_providers++; list_add_tail(&newnode->list, &fd_providers->list); } static void __open_fds(bool do_rand) { struct list_head *node; list_for_each(node, &fd_providers->list) { struct fd_provider *provider; provider = (struct fd_provider *) node; /* disabled on cmdline */ if (provider->enabled == FALSE) continue; /* already done */ if (provider->initialized == TRUE) continue; if (do_rand == TRUE) { /* to mix up init order */ if (RAND_BOOL()) continue; } provider->enabled = provider->open(); if (provider->enabled == TRUE) { provider->initialized = TRUE; num_fd_providers_initialized++; num_fd_providers_enabled++; } else { outputstd("Error during initialization of %s\n", provider->name); num_fd_providers_to_enable--; } } } unsigned int open_fds(void) { /* Open half the providers randomly */ while (num_fd_providers_initialized < (num_fd_providers_to_enable / 2)) __open_fds(TRUE); /* Now open any leftovers */ __open_fds(FALSE); output(0, "Enabled %d/%d fd providers. initialized:%d.\n", num_fd_providers_enabled, num_fd_providers, num_fd_providers_initialized); return TRUE; } int get_new_random_fd(void) { struct list_head *node; int fd = -1; /* short-cut if we've disabled everything. */ if (num_fd_providers_enabled == 0) return -1; /* if nothing has initialized yet, bail */ if (num_fd_providers_initialized == 0) return -1; while (fd < 0) { unsigned int i, j; retry: i = rnd() % num_fd_providers; // FIXME: after below fixme, this should be num_fd_providers_initialized j = 0; list_for_each(node, &fd_providers->list) { struct fd_provider *provider; if (i == j) { provider = (struct fd_provider *) node; if (provider->enabled == FALSE) // FIXME: Better would be to just remove disabled providers from the list. goto retry; // Hasn't been run yet. if (provider->initialized == FALSE) goto retry; fd = provider->get(); break; } j++; } } return fd; } int get_random_fd(void) { /* return the same fd as last time if we haven't over-used it yet. */ regen: if (shm->fd_lifetime == 0) { shm->current_fd = get_new_random_fd(); if (max_children > 5) shm->fd_lifetime = RAND_RANGE(5, max_children); else shm->fd_lifetime = RAND_RANGE(max_children, 5); } else shm->fd_lifetime--; if (shm->current_fd == 0) { shm->fd_lifetime = 0; goto regen; } return shm->current_fd; } static void toggle_fds_param(char *str, bool enable) { struct list_head *node; list_for_each(node, &fd_providers->list) { struct fd_provider *provider; provider = (struct fd_provider *) node; if (strcmp(provider->name, str) == 0) { if (enable == TRUE) { provider->enabled = TRUE; outputstd("Enabled fd provider %s\n", str); num_fd_providers_to_enable++; } else { provider->enabled = FALSE; outputstd("Disabled fd provider %s\n", str); } return; } } outputstd("Unknown parameter \"%s\"\n", str); enable_disable_fd_usage(); exit(EXIT_FAILURE); } //TODO: prevent --enable and --disable being passed at the same time. void process_fds_param(char *param, bool enable) { unsigned int len, i; char *str_orig = strdup(param); char *str = str_orig; len = strlen(param); if (enable_fd_initialized == FALSE && enable == TRUE) { struct list_head *node; /* First, pass through and mark everything disabled. */ list_for_each(node, &fd_providers->list) { struct fd_provider *provider; provider = (struct fd_provider *) node; provider->enabled = FALSE; } enable_fd_initialized = TRUE; } /* Check if there are any commas. If so, split them into multiple params, * validating them as we go. */ for (i = 0; i < len; i++) { if (str_orig[i] == ',') { str_orig[i] = 0; toggle_fds_param(str, enable); str = str_orig + i + 1; } } if (str < str_orig + len) toggle_fds_param(str, enable); free(str_orig); }
ustegrew/csv-validator
assets/charset-detector/icu/src/icu4j-61_1_src/main/tests/translit/src/com/ibm/icu/dev/test/translit/IncrementalProgressTest.java
<filename>assets/charset-detector/icu/src/icu4j-61_1_src/main/tests/translit/src/com/ibm/icu/dev/test/translit/IncrementalProgressTest.java // © 2017 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html#License package com.ibm.icu.dev.test.translit; import java.util.Enumeration; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import com.ibm.icu.dev.test.TestFmwk; import com.ibm.icu.impl.UtilityExtensions; import com.ibm.icu.text.Replaceable; import com.ibm.icu.text.ReplaceableString; import com.ibm.icu.text.Transliterator; // Check to see that incremental gets at least part way through a reasonable string. @RunWith(Parameterized.class) public class IncrementalProgressTest extends TestFmwk { private String lang; private String text; public IncrementalProgressTest(String lang, String text){ this.lang = lang; this.text = text; } @Parameterized.Parameters public static String[][] testData(){ String latinTest = "The Quick Brown Fox."; String devaTest = Transliterator.getInstance("Latin-Devanagari").transliterate(latinTest); String kataTest = Transliterator.getInstance("Latin-Katakana").transliterate(latinTest); // Labels have to be valid transliterator source names. String[][] tests = { {"Any", latinTest}, {"Latin", latinTest}, {"Halfwidth", latinTest}, {"Devanagari", devaTest}, {"Katakana", kataTest}, }; return tests; } public void CheckIncrementalAux(Transliterator t, String input) { Replaceable test = new ReplaceableString(input); Transliterator.Position pos = new Transliterator.Position(0, test.length(), 0, test.length()); t.transliterate(test, pos); boolean gotError = false; // we have a few special cases. Any-Remove (pos.start = 0, but also = limit) and U+XXXXX?X? if (pos.start == 0 && pos.limit != 0 && !t.getID().equals("Hex-Any/Unicode")) { errln("No Progress, " + t.getID() + ": " + UtilityExtensions.formatInput(test, pos)); gotError = true; } else { logln("PASS Progress, " + t.getID() + ": " + UtilityExtensions.formatInput(test, pos)); } t.finishTransliteration(test, pos); if (pos.start != pos.limit) { errln("Incomplete, " + t.getID() + ": " + UtilityExtensions.formatInput(test, pos)); gotError = true; } if(!gotError){ //errln("FAIL: Did not get expected error"); } } @Test public void TestIncrementalProgress() { Enumeration targets = Transliterator.getAvailableTargets(this.lang); while(targets.hasMoreElements()) { String target = (String) targets.nextElement(); Enumeration variants = Transliterator.getAvailableVariants(this.lang, target); while(variants.hasMoreElements()) { String variant = (String) variants.nextElement(); String id = this.lang + "-" + target + "/" + variant; logln("id: " + id); Transliterator t = Transliterator.getInstance(id); CheckIncrementalAux(t, text); String rev = t.transliterate(text); // Special treatment: This transliterator has no registered inverse, skip for now. if (id.equals("Devanagari-Arabic/")) continue; Transliterator inv = t.getInverse(); CheckIncrementalAux(inv, rev); } } } }
gkorland/cytoscaperedisgraph
src/test/java/com/redislabs/cytoscape/redisgraph/internal/graph/GraphTest.java
<gh_stars>1-10 package com.redislabs.cytoscape.redisgraph.internal.graph; import org.junit.Test; public class GraphTest { @Test public void addNode() { Graph graph = new Graph(); graph.add(new GraphNode(1)); graph.add(new GraphNode(2)); assert (graph.size() == 2); GraphNode node1 = new GraphNode(1); node1.getProperties().put("test", 123); graph.add(node1); assert (graph.size() == 2); } @Test public void add1() { } }
glenn-edgar/esp32_gateway
components/modbus_relay_control/modbus_relay_configuration.c
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <esp_types.h> #include "msgpack_rx_handler.h" #include "modbus_relay_configuration.h" static bool modbus_relay_find_baud_rate( cmp_ctx_t *ctx, uint32_t *baud_rate); static bool modbus_relay_find_modbus_address( cmp_ctx_t *ctx, uint32_t *modbus_address); static bool modbus_relay_find_baud_rtu_flag( cmp_ctx_t *ctx,bool *rtu_flag); static bool modbus_relay_find_baud_parity( cmp_ctx_t *ctx, uint32_t *parity); bool modbus_relay_read_file_configuration( uint32_t *baud_rate, uint32_t *modbus_address, bool *rtu_flag, uint32_t *parity) { cmp_ctx_t ctx; char *buffer; uint32_t buffer_size = 1000; if( msgpack_rx_handler_file(&ctx,"/spiffs/MD_RELAY.MPK", &buffer,&buffer_size ) != true) { return false; } msgpack_rx_handler_init(&ctx, buffer, buffer_size); if( modbus_relay_find_baud_rate(&ctx,baud_rate) == false) {goto error;} if( modbus_relay_find_modbus_address(&ctx,modbus_address) == false) {goto error;} if( modbus_relay_find_baud_rtu_flag(&ctx,rtu_flag) == false) {goto error;} if( modbus_relay_find_baud_parity(&ctx,parity) == false) {goto error;} free(buffer); return true; error: free(buffer); return false; } static bool modbus_relay_find_baud_rate( cmp_ctx_t *ctx, uint32_t *baud_rate) { return msgpack_rx_handler_find_unsigned( ctx,"BAUD_RATE", baud_rate ); } static bool modbus_relay_find_modbus_address( cmp_ctx_t *ctx, uint32_t *modbus_address) { return msgpack_rx_handler_find_unsigned( ctx,"ADDRESS", modbus_address ); } static bool modbus_relay_find_baud_rtu_flag( cmp_ctx_t *ctx, bool *rtu_flag) { return msgpack_rx_handler_find_boolean( ctx,"RTU_FLAG", rtu_flag ); } /* parity values esp32 expects UART_PARITY_DISABLE = 0x0, UART_PARITY_EVEN = 0x2, UART_PARITY_ODD = 0x3 */ static bool modbus_relay_find_baud_parity( cmp_ctx_t *ctx, uint32_t *parity) { return msgpack_rx_handler_find_unsigned( ctx,"PARITY", parity ); }
pyronia-sys/libpyronia
libapparmor/parser/parser_main.c
<reponame>pyronia-sys/libpyronia /* * Copyright (c) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007 * NOVELL (All rights reserved) * * Copyright (c) 2010 - 2013 * Canonical Ltd. (All rights reserved) * * 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 published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, contact Novell, Inc. or Canonical, * Ltd. */ #include <ctype.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdarg.h> #include <stddef.h> #include <getopt.h> #include <errno.h> #include <fcntl.h> /* enable the following line to get voluminous debug info */ /* #define DEBUG */ #include <unistd.h> #include <limits.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/wait.h> #include <sys/apparmor.h> #include "lib.h" #include "features.h" #include "parser.h" #include "parser_version.h" #include "parser_include.h" #include "common_optarg.h" #include "policy_cache.h" #include "libapparmor_re/apparmor_re.h" #define OLD_MODULE_NAME "subdomain" #define PROC_MODULES "/proc/modules" #define MATCH_FILE "/sys/kernel/security/" MODULE_NAME "/matching" #define MOUNTED_FS "/proc/mounts" #define AADFA "pattern=pyrdfa" #define PRIVILEGED_OPS (kernel_load) #define UNPRIVILEGED_OPS (!(PRIVILEGED_OPS)) const char *parser_title = "AppArmor parser"; const char *parser_copyright = "Copyright (C) 1999-2008 Novell Inc.\nCopyright 2009-2012 Canonical Ltd."; int opt_force_complain = 0; int binary_input = 0; int dump_vars = 0; int dump_expanded_vars = 0; int show_cache = 0; int skip_cache = 0; int skip_read_cache = 0; int write_cache = 0; int cond_clear_cache = 1; /* only applies if write is set */ int force_clear_cache = 0; /* force clearing regargless of state */ int create_cache_dir = 0; /* DEPRECATED in favor of write_cache */ int preprocess_only = 0; int skip_mode_force = 0; int abort_on_error = 0; /* stop processing profiles if error */ int skip_bad_cache_rebuild = 0; int mru_skip_cache = 1; int debug_cache = 0; /* for jobs_max and jobs * LONG_MAX : no limit * 0 : auto = detect system processing cores * n : use that number of processes/threads to compile policy */ #define JOBS_AUTO 0 long jobs_max = -8; /* 8 * cpus */ long jobs = JOBS_AUTO; /* default: number of processor cores */ long njobs = 0; long jobs_scale = 0; /* number of chance to resample online * cpus. This allows jobs spawning to * scale when scheduling policy is * taking cpus off line, and brings * them back with load */ bool debug_jobs = false; struct timespec cache_tstamp, mru_policy_tstamp; static char *apparmorfs = NULL; static char *cacheloc = NULL; static aa_features *features = NULL; /* Make sure to update BOTH the short and long_options */ static const char *short_options = "ad::f:h::rRVvI:b:BCD:NSm:M:qQn:XKTWkL:O:po:j:"; struct option long_options[] = { {"add", 0, 0, 'a'}, {"binary", 0, 0, 'B'}, {"base", 1, 0, 'b'}, {"subdomainfs", 1, 0, 'f'}, {"help", 2, 0, 'h'}, {"replace", 0, 0, 'r'}, {"reload", 0, 0, 'r'}, /* undocumented reload option == replace */ {"version", 0, 0, 'V'}, {"complain", 0, 0, 'C'}, {"Complain", 0, 0, 'C'}, /* Erk, apparently documented as --Complain */ {"Include", 1, 0, 'I'}, {"remove", 0, 0, 'R'}, {"names", 0, 0, 'N'}, {"stdout", 0, 0, 'S'}, {"ofile", 1, 0, 'o'}, {"match-string", 1, 0, 'm'}, {"features-file", 1, 0, 'M'}, {"quiet", 0, 0, 'q'}, {"skip-kernel-load", 0, 0, 'Q'}, {"verbose", 0, 0, 'v'}, {"namespace", 1, 0, 'n'}, {"readimpliesX", 0, 0, 'X'}, {"skip-cache", 0, 0, 'K'}, {"skip-read-cache", 0, 0, 'T'}, {"write-cache", 0, 0, 'W'}, {"show-cache", 0, 0, 'k'}, {"skip-bad-cache", 0, 0, 129}, /* no short option */ {"purge-cache", 0, 0, 130}, /* no short option */ {"create-cache-dir", 0, 0, 131}, /* no short option */ {"cache-loc", 1, 0, 'L'}, {"debug", 2, 0, 'd'}, {"dump", 1, 0, 'D'}, {"Dump", 1, 0, 'D'}, {"optimize", 1, 0, 'O'}, {"Optimize", 1, 0, 'O'}, {"preprocess", 0, 0, 'p'}, {"abort-on-error", 0, 0, 132}, /* no short option */ {"skip-bad-cache-rebuild", 0, 0, 133}, /* no short option */ {"warn", 1, 0, 134}, /* no short option */ {"debug-cache", 0, 0, 135}, /* no short option */ {"jobs", 1, 0, 'j'}, {"max-jobs", 1, 0, 136}, /* no short option */ {NULL, 0, 0, 0}, }; static int debug = 0; void display_version(void) { printf("%s version " PARSER_VERSION "\n%s\n", parser_title, parser_copyright); } static void display_usage(const char *command) { display_version(); printf("\nUsage: %s [options] [profile]\n\n" "Options:\n" "--------\n" "-a, --add Add apparmor definitions [default]\n" "-r, --replace Replace apparmor definitions\n" "-R, --remove Remove apparmor definitions\n" "-C, --Complain Force the profile into complain mode\n" "-B, --binary Input is precompiled profile\n" "-N, --names Dump names of profiles in input.\n" "-S, --stdout Dump compiled profile to stdout\n" "-o n, --ofile n Write output to file n\n" "-b n, --base n Set base dir and cwd\n" "-I n, --Include n Add n to the search path\n" "-f n, --subdomainfs n Set location of apparmor filesystem\n" "-m n, --match-string n Use only features n\n" "-M n, --features-file n Use only features in file n\n" "-n n, --namespace n Set Namespace for the profile\n" "-X, --readimpliesX Map profile read permissions to mr\n" "-k, --show-cache Report cache hit/miss details\n" "-K, --skip-cache Do not attempt to load or save cached profiles\n" "-T, --skip-read-cache Do not attempt to load cached profiles\n" "-W, --write-cache Save cached profile (force with -T)\n" " --skip-bad-cache Don't clear cache if out of sync\n" " --purge-cache Clear cache regardless of its state\n" " --debug-cache Debug cache file checks\n" "-L, --cache-loc n Set the location of the profile cache\n" "-q, --quiet Don't emit warnings\n" "-v, --verbose Show profile names as they load\n" "-Q, --skip-kernel-load Do everything except loading into kernel\n" "-V, --version Display version info and exit\n" "-d [n], --debug Debug apparmor definitions OR [n]\n" "-p, --preprocess Dump preprocessed profile\n" "-D [n], --dump Dump internal info for debugging\n" "-O [n], --Optimize Control dfa optimizations\n" "-h [cmd], --help[=cmd] Display this text or info about cmd\n" "-j n, --jobs n Set the number of compile threads\n" "--max-jobs n Hard cap on --jobs. Default 8*cpus\n" "--abort-on-error Abort processing of profiles on first error\n" "--skip-bad-cache-rebuild Do not try rebuilding the cache if it is rejected by the kernel\n" "--warn n Enable warnings (see --help=warn)\n" ,command); } optflag_table_t warnflag_table[] = { { 0, "rule-not-enforced", "warn if a rule is not enforced", WARN_RULE_NOT_ENFORCED }, { 0, "rule-downgraded", "warn if a rule is downgraded to a lesser but still enforcing rule", WARN_RULE_DOWNGRADED }, { 0, NULL, NULL, 0 }, }; void display_warn(const char *command) { display_version(); printf("\n%s: --warn [Option]\n\n" "Options:\n" "--------\n" ,command); print_flag_table(warnflag_table); } /* Treat conf file like options passed on command line */ static int getopt_long_file(FILE *f, const struct option *longopts, char **optarg, int *longindex) { static char line[256]; char *pos, *opt, *save; int i; for (;;) { if (!fgets(line, 256, f)) return -1; pos = line; while (isblank(*pos)) pos++; if (*pos == '#') continue; opt = strtok_r(pos, " \t\r\n=", &save); /* blank line */ if (!opt) continue; for (i = 0; longopts[i].name && strcmp(longopts[i].name, opt) != 0; i++) ; if (!longopts[i].name) { PERROR("%s: unknown option (%s) in config file.\n", progname, opt); /* skip it */ continue; } break; } if (longindex) *longindex = i; if (*save) { int len; while(isblank(*save)) save++; len = strlen(save) - 1; if (save[len] == '\n') save[len] = 0; } switch (longopts[i].has_arg) { case 0: *optarg = NULL; break; case 1: if (!strlen(save)) { *optarg = NULL; return '?'; } *optarg = save; break; case 2: *optarg = save; break; default: PERROR("%s: internal error bad longopt value\n", progname); exit(1); } if (longopts[i].flag == NULL) return longopts[i].val; else *longopts[i].flag = longopts[i].val; return 0; } static long process_jobs_arg(const char *arg, const char *val) { char *end; long n; if (!val || strcmp(val, "auto") == 0) n = JOBS_AUTO; else if (strcmp(val, "max") == 0) n = LONG_MAX; else { bool multiple = false; if (*val == 'x') { multiple = true; val++; } n = strtol(val, &end, 0); if (!(*val && val != end && *end == '\0')) { PERROR("%s: Invalid option %s=%s%s\n", progname, arg, multiple ? "x" : "", val); exit(1); } if (multiple) n = -n; } return n; } /* process a single argment from getopt_long * Returns: 1 if an action arg, else 0 */ static int process_arg(int c, char *optarg) { int count = 0; switch (c) { case 0: PERROR("Assert, in getopt_long handling\n"); display_usage(progname); exit(0); break; case 'a': count++; option = OPTION_ADD; break; case 'd': if (!optarg) { debug++; skip_read_cache = 1; } else if (strcmp(optarg, "jobs") == 0 || strcmp(optarg, "j") == 0) { debug_jobs = true; } else { PERROR("%s: Invalid --debug option '%s'\n", progname, optarg); exit(1); } break; case 'h': if (!optarg) { display_usage(progname); } else if (strcmp(optarg, "Dump") == 0 || strcmp(optarg, "dump") == 0 || strcmp(optarg, "D") == 0) { display_dump(progname); } else if (strcmp(optarg, "Optimize") == 0 || strcmp(optarg, "optimize") == 0 || strcmp(optarg, "O") == 0) { display_optimize(progname); } else if (strcmp(optarg, "warn") == 0) { display_warn(progname); } else { PERROR("%s: Invalid --help option %s\n", progname, optarg); exit(1); } exit(0); break; case 'r': count++; option = OPTION_REPLACE; break; case 'R': count++; option = OPTION_REMOVE; skip_cache = 1; break; case 'V': display_version(); exit(0); break; case 'I': add_search_dir(optarg); break; case 'b': set_base_dir(optarg); break; case 'B': binary_input = 1; skip_cache = 1; break; case 'C': opt_force_complain = 1; skip_cache = 1; break; case 'N': count++; names_only = 1; skip_cache = 1; kernel_load = 0; break; case 'S': count++; option = OPTION_STDOUT; skip_read_cache = 1; kernel_load = 0; break; case 'o': count++; option = OPTION_OFILE; skip_read_cache = 1; kernel_load = 0; ofile = fopen(optarg, "w"); if (!ofile) { PERROR("%s: Could not open file %s\n", progname, optarg); exit(1); } break; case 'f': apparmorfs = strndup(optarg, PATH_MAX); break; case 'D': skip_read_cache = 1; if (!optarg) { dump_vars = 1; } else if (strcmp(optarg, "variables") == 0) { dump_vars = 1; } else if (strcmp(optarg, "expanded-variables") == 0) { dump_expanded_vars = 1; } else if (!handle_flag_table(dumpflag_table, optarg, &dfaflags)) { PERROR("%s: Invalid --Dump option %s\n", progname, optarg); exit(1); } break; case 'O': skip_read_cache = 1; if (!handle_flag_table(optflag_table, optarg, &dfaflags)) { PERROR("%s: Invalid --Optimize option %s\n", progname, optarg); exit(1); } break; case 'm': if (aa_features_new_from_string(&features, optarg, strlen(optarg))) { fprintf(stderr, "Failed to parse features string: %m\n"); exit(1); } break; case 'M': if (aa_features_new(&features, AT_FDCWD, optarg)) { fprintf(stderr, "Failed to load features from '%s': %m\n", optarg); exit(1); } break; case 'q': conf_verbose = 0; conf_quiet = 1; warnflags = 0; break; case 'v': conf_verbose = 1; conf_quiet = 0; break; case 'n': profile_ns = strdup(optarg); break; case 'X': read_implies_exec = 1; break; case 'K': skip_cache = 1; break; case 'k': show_cache = 1; break; case 'W': write_cache = 1; break; case 'T': skip_read_cache = 1; break; case 129: cond_clear_cache = 0; break; case 130: force_clear_cache = 1; break; case 131: create_cache_dir = 1; break; case 132: abort_on_error = 1; break; case 133: skip_bad_cache_rebuild = 1; break; case 'L': cacheloc = strdup(optarg); break; case 'Q': kernel_load = 0; break; case 'p': count++; kernel_load = 0; skip_cache = 1; preprocess_only = 1; skip_mode_force = 1; break; case 134: if (!handle_flag_table(warnflag_table, optarg, &warnflags)) { PERROR("%s: Invalid --warn option %s\n", progname, optarg); exit(1); } break; case 135: debug_cache = 1; break; case 'j': jobs = process_jobs_arg("-j", optarg); break; case 136: jobs_max = process_jobs_arg("max-jobs", optarg); break; default: display_usage(progname); exit(1); break; } return count; } static int process_args(int argc, char *argv[]) { int c, o; int count = 0; option = OPTION_ADD; while ((c = getopt_long(argc, argv, short_options, long_options, &o)) != -1) { count += process_arg(c, optarg); } if (count > 1) { PERROR("%s: Too many actions given on the command line.\n", progname); display_usage(progname); exit(1); } PDEBUG("optind = %d argc = %d\n", optind, argc); return optind; } static int process_config_file(const char *name) { char *optarg; autofclose FILE *f = NULL; int c, o; f = fopen(name, "r"); if (!f) return 0; while ((c = getopt_long_file(f, long_options, &optarg, &o)) != -1) process_arg(c, optarg); return 1; } int have_enough_privilege(void) { uid_t uid, euid; uid = getuid(); euid = geteuid(); if (uid != 0 && euid != 0) { PERROR(_("%s: Sorry. You need root privileges to run this program.\n\n"), progname); display_usage(progname); return EPERM; } if (uid != 0 && euid == 0) { PERROR(_("%s: Warning! You've set this program setuid root.\n" "Anybody who can run this program can update " "your AppArmor profiles.\n\n"), progname); } return 0; } static void set_features_by_match_file(void) { autofclose FILE *ms = fopen(MATCH_FILE, "r"); if (ms) { autofree char *match_string = (char *) malloc(1000); if (!match_string) goto no_match; if (!fgets(match_string, 1000, ms)) goto no_match; if (strstr(match_string, " perms=c")) perms_create = 1; kernel_supports_network = 1; return; } no_match: perms_create = 1; } static void set_supported_features(void) { /* has process_args() already assigned a match string? */ if (!features && aa_features_new_from_kernel(&features) == -1) { set_features_by_match_file(); return; } perms_create = 1; kernel_supports_policydb = aa_features_supports(features, "file"); kernel_supports_network = aa_features_supports(features, "network"); kernel_supports_unix = aa_features_supports(features, "network/af_unix"); kernel_supports_mount = aa_features_supports(features, "mount"); kernel_supports_dbus = aa_features_supports(features, "dbus"); kernel_supports_signal = aa_features_supports(features, "signal"); kernel_supports_ptrace = aa_features_supports(features, "ptrace"); kernel_supports_setload = aa_features_supports(features, "policy/set_load"); kernel_supports_diff_encode = aa_features_supports(features, "policy/diff_encode"); kernel_supports_stacking = aa_features_supports(features, "domain/stack"); if (aa_features_supports(features, "policy/versions/v7")) kernel_abi_version = 7; else if (aa_features_supports(features, "policy/versions/v6")) kernel_abi_version = 6; if (!kernel_supports_diff_encode) /* clear diff_encode because it is not supported */ dfaflags &= ~DFA_CONTROL_DIFF_ENCODE; } int process_binary(int option, aa_kernel_interface *kernel_interface, const char *profilename) { const char *printed_name; int retval; printed_name = profilename ? profilename : "stdin"; if (kernel_load) { if (option == OPTION_ADD) { retval = profilename ? aa_kernel_interface_load_policy_from_file(kernel_interface, AT_FDCWD, profilename) : aa_kernel_interface_load_policy_from_fd(kernel_interface, 0); if (retval == -1) { retval = errno; PERROR(_("Error: Could not load profile %s: %s\n"), printed_name, strerror(retval)); return retval; } } else if (option == OPTION_REPLACE) { retval = profilename ? aa_kernel_interface_replace_policy_from_file(kernel_interface, AT_FDCWD, profilename) : aa_kernel_interface_replace_policy_from_fd(kernel_interface, 0); if (retval == -1) { retval = errno; PERROR(_("Error: Could not replace profile %s: %s\n"), printed_name, strerror(retval)); return retval; } } else { PERROR(_("Error: Invalid load option specified: %d\n"), option); return EINVAL; } } if (conf_verbose) { switch (option) { case OPTION_ADD: printf(_("Cached load succeeded for \"%s\".\n"), printed_name); break; case OPTION_REPLACE: printf(_("Cached reload succeeded for \"%s\".\n"), printed_name); break; default: break; } } return 0; } void reset_parser(const char *filename) { memset(&mru_policy_tstamp, 0, sizeof(mru_policy_tstamp)); memset(&cache_tstamp, 0, sizeof(cache_tstamp)); mru_skip_cache = 1; free_aliases(); free_symtabs(); free_policies(); reset_include_stack(filename); } int test_for_dir_mode(const char *basename, const char *linkdir) { int rc = 0; if (!skip_mode_force) { autofree char *target = NULL; if (asprintf(&target, "%s/%s/%s", basedir, linkdir, basename) < 0) { perror("asprintf"); exit(1); } if (access(target, R_OK) == 0) rc = 1; } return rc; } int process_profile(int option, aa_kernel_interface *kernel_interface, const char *profilename, const char *cachedir) { int retval = 0; autofree const char *cachename = NULL; autofree const char *cachetmpname = NULL; autoclose int cachetmp = -1; const char *basename = NULL; /* per-profile states */ force_complain = opt_force_complain; if (profilename) { if ( !(yyin = fopen(profilename, "r")) ) { PERROR(_("Error: Could not read profile %s: %s.\n"), profilename, strerror(errno)); return errno; } } else { pwarn("%s: cannot use or update cache, disable, or force-complain via stdin\n", progname); } reset_parser(profilename); if (profilename && option != OPTION_REMOVE) { /* make decisions about disabled or complain-mode profiles */ basename = strrchr(profilename, '/'); if (basename) basename++; else basename = profilename; if (test_for_dir_mode(basename, "disable")) { if (!conf_quiet) PERROR("Skipping profile in %s/disable: %s\n", basedir, basename); goto out; } if (test_for_dir_mode(basename, "force-complain")) { PERROR("Warning: found %s in %s/force-complain, forcing complain mode\n", basename, basedir); force_complain = 1; } /* setup cachename and tstamp */ if (!force_complain && !skip_cache) { cachename = cache_filename(cachedir, basename); valid_read_cache(cachename); } } if (yyin) { yyrestart(yyin); update_mru_tstamp(yyin, profilename ? profilename : "stdin"); } retval = yyparse(); if (retval != 0) goto out; /* Test to see if profile is for another namespace, if so disable * caching for now * TODO: Add support for caching profiles in an alternate namespace * TODO: Add support for embedded namespace defines if they aren't * removed from the language. * TODO: test profile->ns NOT profile_ns (must be after parse) */ if (profile_ns) skip_cache = 1; if (cachename) { /* Load a binary cache if it exists and is newest */ if (cache_hit(cachename)) { retval = process_binary(option, kernel_interface, cachename); if (!retval || skip_bad_cache_rebuild) return retval; } cachetmp = setup_cache_tmp(&cachetmpname, cachename); } if (show_cache) PERROR("Cache miss: %s\n", profilename ? profilename : "stdin"); if (preprocess_only) goto out; if (names_only) { dump_policy_names(); goto out; } if (dump_vars) { dump_symtab(); goto out; } retval = post_process_policy(debug); if (retval != 0) { PERROR(_("%s: Errors found in file. Aborting.\n"), progname); goto out; } if (dump_expanded_vars) { dump_expanded_symtab(); goto out; } if (debug > 0) { printf("----- Debugging built structures -----\n"); dump_policy(); goto out; } /* cache file generated by load_policy */ retval = load_policy(option, kernel_interface, cachetmp); if (retval == 0 && write_cache) { if (cachetmp == -1) { unlink(cachetmpname); PERROR("Warning failed to create cache: %s\n", basename); } else { install_cache(cachetmpname, cachename); } } out: return retval; } /* Do not call directly, this is a helper for work_sync, which can handle * single worker cases and cases were the work queue is optimized away * * call only if there are work children to wait on */ #define work_sync_one(RESULT) \ do { \ int status; \ wait(&status); \ if (WIFEXITED(status)) \ RESULT(WEXITSTATUS(status)); \ else \ RESULT(ECHILD); \ /* TODO: do we need to handle traced */ \ njobs--; \ if (debug_jobs) \ fprintf(stderr, " JOBS SYNC ONE: result %d, jobs left %ld\n", status, njobs); \ } while (0) #define work_sync(RESULT) \ do { \ if (debug_jobs) \ fprintf(stderr, "JOBS SYNC: jobs left %ld\n", njobs); \ while (njobs) \ work_sync_one(RESULT); \ } while (0) #define work_spawn(WORK, RESULT) \ do { \ /* what to do to avoid fork() overhead when single threaded \ if (jobs == 1) { \ // no parallel work so avoid fork() overhead \ RESULT(WORK); \ break; \ }*/ \ if (jobs_scale) { \ long n = sysconf(_SC_NPROCESSORS_ONLN); \ if (n > jobs_max) \ n = jobs_max; \ if (n > jobs) { \ /* reset sample chances - potentially reduce to 0 */ \ jobs_scale = jobs_max - n; \ jobs = n; \ } else \ /* reduce scaling chance by 1 */ \ jobs_scale--; \ } \ if (njobs == jobs) { \ /* wait for a child */ \ if (debug_jobs) \ fprintf(stderr, " JOBS SPAWN: waiting (jobs %ld == max %ld) ...\n", njobs, jobs); \ work_sync_one(RESULT); \ } \ \ pid_t child = fork(); \ if (child == 0) { \ /* child - exit work unit with returned value */ \ exit(WORK); \ } else if (child > 0) { \ /* parent */ \ njobs++; \ if (debug_jobs) \ fprintf(stderr, " JOBS SPAWN: created %ld ...\n", njobs); \ } else { \ /* error */ \ if (debug_jobs) \ fprintf(stderr, " JOBS SPAWN: failed error: %d) ...\n", errno); \ RESULT(errno); \ } \ } while (0) /* sadly C forces us to do this with exit, long_jump or returning error * from work_spawn and work_sync. We could throw a C++ exception, is it * worth doing it to avoid the exit here. * * atm not all resources maybe cleanedup at exit */ int last_error = 0; void handle_work_result(int retval) { if (retval) { last_error = retval; if (abort_on_error) { /* already in abort mode we don't need subsequent * syncs to do this too */ abort_on_error = 0; work_sync(handle_work_result); exit(last_error); } } } static long compute_jobs(long n, long j) { if (j == JOBS_AUTO) j = n; else if (j < 0) j = n * j * -1; return j; } static void setup_parallel_compile(void) { /* jobs and paralell_max set by default, config or args */ long n = sysconf(_SC_NPROCESSORS_ONLN); long maxn = sysconf(_SC_NPROCESSORS_CONF); if (n == -1) /* unable to determine number of processors, default to 1 */ n = 1; if (maxn == -1) /* unable to determine number of processors, default to 1 */ maxn = 1; jobs = compute_jobs(n, jobs); jobs_max = compute_jobs(maxn, jobs_max); if (jobs > jobs_max) { pwarn("%s: Warning capping number of jobs to %ld * # of cpus == '%ld'", progname, jobs_max, jobs); jobs = jobs_max; } else if (jobs < jobs_max) /* the bigger the difference the more sample chances given */ jobs_scale = jobs_max + 1 - n; njobs = 0; if (debug_jobs) fprintf(stderr, "jobs: %ld\n", jobs); } struct dir_cb_data { aa_kernel_interface *kernel_interface; const char *dirname; /* name of the parent dir */ const char *cachedir; /* path to the cache sub directory */ }; /* data - pointer to a dir_cb_data */ static int profile_dir_cb(int dirfd unused, const char *name, struct stat *st, void *data) { int rc = 0; if (!S_ISDIR(st->st_mode) && !is_blacklisted(name, NULL)) { struct dir_cb_data *cb_data = (struct dir_cb_data *)data; autofree char *path = NULL; if (asprintf(&path, "%s/%s", cb_data->dirname, name) < 0) PERROR(_("Out of memory")); work_spawn(process_profile(option, cb_data->kernel_interface, path, cb_data->cachedir), handle_work_result); } return rc; } /* data - pointer to a dir_cb_data */ static int binary_dir_cb(int dirfd unused, const char *name, struct stat *st, void *data) { int rc = 0; if (!S_ISDIR(st->st_mode) && !is_blacklisted(name, NULL)) { struct dir_cb_data *cb_data = (struct dir_cb_data *)data; autofree char *path = NULL; if (asprintf(&path, "%s/%s", cb_data->dirname, name) < 0) PERROR(_("Out of memory")); work_spawn(process_binary(option, cb_data->kernel_interface, path), handle_work_result); } return rc; } static void setup_flags(void) { /* Get the match string to determine type of regex support needed */ set_supported_features(); /* Gracefully handle AppArmor kernel without compatibility patch */ if (!features) { PERROR("Cache read/write disabled: interface file missing. " "(Kernel needs AppArmor 2.4 compatibility patch.)\n"); write_cache = 0; skip_read_cache = 1; return; } } int main(int argc, char *argv[]) { aa_kernel_interface *kernel_interface = NULL; aa_policy_cache *policy_cache = NULL; int retval; int i; int optind; /* name of executable, for error reporting and usage display */ progname = argv[0]; init_base_dir(); process_config_file("/etc/apparmor/parser.conf"); optind = process_args(argc, argv); setup_parallel_compile(); setlocale(LC_MESSAGES, ""); bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); /* Check to see if we have superuser rights, if we're not * debugging */ if (!(UNPRIVILEGED_OPS) && ((retval = have_enough_privilege()))) { return retval; } if (!binary_input) parse_default_paths(); setup_flags(); if (!(UNPRIVILEGED_OPS) && aa_kernel_interface_new(&kernel_interface, features, apparmorfs) == -1) { PERROR(_("Warning: unable to find a suitable fs in %s, is it " "mounted?\nUse --subdomainfs to override.\n"), MOUNTED_FS); return 1; } if ((!skip_cache && (write_cache || !skip_read_cache)) || force_clear_cache) { uint16_t max_caches = write_cache && cond_clear_cache ? 1 : 0; if (!cacheloc && asprintf(&cacheloc, "%s/cache", basedir) == -1) { PERROR(_("Memory allocation error.")); return 1; } if (force_clear_cache) { if (aa_policy_cache_remove(AT_FDCWD, cacheloc)) { PERROR(_("Failed to clear cache files (%s): %s\n"), cacheloc, strerror(errno)); return 1; } return 0; } if (create_cache_dir) pwarn(_("The --create-cache-dir option is deprecated. Please use --write-cache.\n")); retval = aa_policy_cache_new(&policy_cache, features, AT_FDCWD, cacheloc, max_caches); if (retval) { if (errno != ENOENT && errno != EEXIST) { PERROR(_("Failed setting up policy cache (%s): %s\n"), cacheloc, strerror(errno)); return 1; } if (show_cache) { if (max_caches > 0) PERROR("Cache write disabled: Cannot create cache '%s': %m\n", cacheloc); else PERROR("Cache read/write disabled: Policy cache is invalid\n"); } write_cache = 0; skip_read_cache = 1; } } retval = last_error = 0; for (i = optind; i <= argc; i++) { struct stat stat_file; if (i < argc && !(profilename = strdup(argv[i]))) { perror("strdup"); last_error = ENOMEM; if (abort_on_error) break; continue; } /* skip stdin if we've seen other command line arguments */ if (i == argc && optind != argc) continue; if (profilename && stat(profilename, &stat_file) == -1) { PERROR("File %s not found, skipping...\n", profilename); continue; } if (profilename && S_ISDIR(stat_file.st_mode)) { int (*cb)(int dirfd, const char *name, struct stat *st, void *data); struct dir_cb_data cb_data; memset(&cb_data, 0, sizeof(struct dir_cb_data)); cb_data.dirname = profilename; cb_data.cachedir = cacheloc; cb_data.kernel_interface = kernel_interface; cb = binary_input ? binary_dir_cb : profile_dir_cb; if ((retval = dirat_for_each(AT_FDCWD, profilename, &cb_data, cb))) { PDEBUG("Failed loading profiles from %s\n", profilename); } } else if (binary_input) { work_spawn(process_binary(option, kernel_interface, profilename), handle_work_result); } else { work_spawn(process_profile(option, kernel_interface, profilename, cacheloc), handle_work_result); } if (profilename) free(profilename); profilename = NULL; } work_sync(handle_work_result); if (ofile) fclose(ofile); aa_policy_cache_unref(policy_cache); return last_error; }
Taxcut/Fishy
Abilities/src/me/fishy/abilities/listeners/AntiBuildEggListener.java
<filename>Abilities/src/me/fishy/abilities/listeners/AntiBuildEggListener.java package me.fishy.abilities.listeners; import me.fishy.abilities.Main; import me.fishy.abilities.utils.CC; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Egg; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.ProjectileLaunchEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.metadata.FixedMetadataValue; import java.util.List; import java.util.UUID; public class AntiBuildEggListener implements Listener { private final FileConfiguration config = Main.getInstance().getConfig(); private final List<String> buildeggm = Main.getInstance().getConfig().getStringList("Anti-BuildEgg.Messages.Used"); private final List<String> buildegghitm = Main.getInstance().getConfig().getStringList("Anti-BuildEgg.Messages.Hit"); private final List<String> cantbuild = Main.getInstance().getConfig().getStringList("Anti-BuildEgg.Messages.Anti-Build"); private Main plugin = Main.getPlugin(Main.class); @EventHandler public void on(PlayerInteractEvent event) { Player player = event.getPlayer(); if (event.getAction() == Action.LEFT_CLICK_AIR || event.getAction() == Action.LEFT_CLICK_BLOCK) return; if (player.getInventory().getItemInHand().getType() != Material.EGG) return; if (!(player.getInventory().getItemInHand().hasItemMeta())) return; if (!(player.getInventory().getItemInHand().getItemMeta().getLore().contains(CC.translate(Main.getInstance().getConfig().getString("Anti-BuildEgg.Lore"))))) return; if (Main.getInstance().getAntibuildegg().onCooldown(player)) { player.sendMessage(CC.translate(Main.getInstance().getConfig().getString("Main.Cooldown").replace("%time%", Main.getInstance().getAntibuildegg().getRemaining(player)))); event.setCancelled(true); // player.getItemInHand().setAmount(player.getItemInHand().getAmount() + 1); return; } Main.getInstance().getAntibuildegg().CooldownApply(player, config.getInt("Cocaine.Cooldown") * 1000); Egg egg = event.getPlayer().launchProjectile(Egg.class); egg.setMetadata("buildegg", new FixedMetadataValue(plugin, player.getUniqueId())); player.playSound(player.getLocation(), Sound.CHICKEN_EGG_POP, 1f, 1f); event.setCancelled(true); } @EventHandler(priority = EventPriority.HIGH) public void onEntityDamage(EntityDamageByEntityEvent event) { if (!(event.getDamager() instanceof Egg)) return; Egg egg = (Egg) event.getDamager(); if (!(egg.getShooter() instanceof Player) && !(event.getEntity() instanceof Player)) return; if (!egg.hasMetadata("buildegg")) return; Player damaged = (Player) event.getEntity(); Main.getInstance().getAntibuildegghit().CooldownApply(damaged, config.getInt("Anti-BuildEgg.Time") * 1000); Player damager1 = (Player) egg.getShooter(); Player damaged1 = (Player) event.getEntity(); for (String s : buildegghitm) { damaged1.sendMessage(CC.translate(s).replace("%heart%", "").replace("%player%", damager1.getName())); } for (String s : buildeggm) { damager1.sendMessage(CC.translate(s).replace("%heart%", "").replace("%player%", damaged1.getName())); } } @EventHandler(priority = EventPriority.HIGH) public void onPlace(BlockPlaceEvent event) { Player player = event.getPlayer(); UUID uuid = player.getUniqueId(); if (Main.getInstance().getAntibuildegghit().onCooldown(player)) { event.setCancelled(true); for (String s : cantbuild) { player.sendMessage(CC.translate(s).replace("%time%", Main.getInstance().getAntibuildegghit().getRemaining(player))); } } } }
ruleLearn/rulelearn
src/test/java/org/rulelearn/dominance/DominanceConeCalculatorTest.java
<reponame>ruleLearn/rulelearn /** * Copyright (C) <NAME>, <NAME> * * 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.rulelearn.dominance; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.rulelearn.data.AttributePreferenceType; import org.rulelearn.data.EvaluationAttribute; import org.rulelearn.data.InformationTable; import org.rulelearn.data.Table; import org.rulelearn.types.EvaluationField; import org.rulelearn.types.IntegerField; import org.rulelearn.types.IntegerFieldFactory; import org.rulelearn.types.UnknownSimpleFieldMV15; import org.rulelearn.types.UnknownSimpleFieldMV2; import it.unimi.dsi.fastutil.ints.IntSortedSet; /** * Tests for {@link DominanceConeCalculator}. * * @author <NAME> (<a href="mailto:<EMAIL>"><EMAIL></a>) * @author <NAME> (<a href="mailto:<EMAIL>"><EMAIL></a>) */ class DominanceConeCalculatorTest { /** * Supplementary method for creating {@link IntegerField} instances. * * @param value value passed to {@link IntegerFieldFactory#create(int, AttributePreferenceType)} method. * @param preferenceType preference type passed to {@link IntegerFieldFactory#create(int, AttributePreferenceType)} method. * @return created {@link IntegerField} instance. */ private IntegerField intField(int value, AttributePreferenceType preferenceType) { return IntegerFieldFactory.getInstance().create(value, preferenceType); } /** * Creates a mock of an {@link InformationTable}. * * @param evaluationsList list with arrays of evaluations such that each array stores subsequent evaluations of a single object of an information table * @return mock of an {@link InformationTable} corresponding to given evaluations */ private InformationTable createInformationTableMock(List<EvaluationField[]> evaluationsList) { @SuppressWarnings("unchecked") Table<EvaluationAttribute, EvaluationField> evaluations = (Table<EvaluationAttribute, EvaluationField>)Mockito.mock(Table.class); for (int i = 0; i < evaluationsList.size(); i++) { Mockito.when(evaluations.getFields(i)).thenReturn(evaluationsList.get(i)); } InformationTable informationTableMock = Mockito.mock(InformationTable.class); Mockito.when(informationTableMock.getNumberOfObjects()).thenReturn(evaluationsList.size()); Mockito.when(informationTableMock.getActiveConditionAttributeFields()).thenReturn(evaluations); return informationTableMock; } /** * Gets first mock of an information table, injected in tested methods. * * @return first mock of an information table, injected in tested methods */ private InformationTable getInformationTableMock01() { List<EvaluationField[]> evaluationsList = new ArrayList<EvaluationField[]>(); evaluationsList.add(new EvaluationField[] {intField(2, AttributePreferenceType.GAIN), intField(5, AttributePreferenceType.COST)}); //x evaluationsList.add(new EvaluationField[] {intField(3, AttributePreferenceType.GAIN), intField(4, AttributePreferenceType.COST)}); //dominating object evaluationsList.add(new EvaluationField[] {intField(3, AttributePreferenceType.GAIN), intField(6, AttributePreferenceType.COST)}); //incomparable object evaluationsList.add(new EvaluationField[] {intField(1, AttributePreferenceType.GAIN), intField(4, AttributePreferenceType.COST)}); //incomparable object evaluationsList.add(new EvaluationField[] {intField(1, AttributePreferenceType.GAIN), intField(6, AttributePreferenceType.COST)}); //dominated object return createInformationTableMock(evaluationsList); } /** * Gets second mock of an information table, injected in tested methods. Constructed information table contains missing values. * * @return second mock of an information table, injected in tested methods */ private InformationTable getInformationTableMock02() { List<EvaluationField[]> evaluationsList = new ArrayList<EvaluationField[]>(); evaluationsList.add(new EvaluationField[] {intField(2, AttributePreferenceType.GAIN), intField(5, AttributePreferenceType.GAIN)}); //x evaluationsList.add(new EvaluationField[] {intField(3, AttributePreferenceType.GAIN), intField(5, AttributePreferenceType.GAIN)}); //dominating object evaluationsList.add(new EvaluationField[] {intField(2, AttributePreferenceType.GAIN), intField(6, AttributePreferenceType.GAIN)}); //dominating object evaluationsList.add(new EvaluationField[] {intField(3, AttributePreferenceType.GAIN), intField(4, AttributePreferenceType.GAIN)}); //incomparable object evaluationsList.add(new EvaluationField[] {intField(1, AttributePreferenceType.GAIN), intField(6, AttributePreferenceType.GAIN)}); //incomparable object evaluationsList.add(new EvaluationField[] {intField(2, AttributePreferenceType.GAIN), intField(4, AttributePreferenceType.GAIN)}); //dominated object evaluationsList.add(new EvaluationField[] {intField(1, AttributePreferenceType.GAIN), intField(5, AttributePreferenceType.GAIN)}); //dominated object evaluationsList.add(new EvaluationField[] {new UnknownSimpleFieldMV2(), intField(5, AttributePreferenceType.GAIN)}); //object that x can be compared with evaluationsList.add(new EvaluationField[] {intField(2, AttributePreferenceType.GAIN), new UnknownSimpleFieldMV15()}); //object that x can not be compared with return createInformationTableMock(evaluationsList); } /** * Test method for {@link DominanceConeCalculator#calculatePositiveDCone(int, InformationTable)}. */ @Test void testCalculatePositiveDCone01() { InformationTable informationTableMock = getInformationTableMock01(); IntSortedSet dominanceCone = DominanceConeCalculator.INSTANCE.calculatePositiveDCone(0, informationTableMock); assertEquals(dominanceCone.size(), 2); assertTrue(dominanceCone.contains(0)); assertTrue(dominanceCone.contains(1)); } /** * Test method for {@link DominanceConeCalculator#calculatePositiveDCone(int, InformationTable)}. */ @Test void testCalculatePositiveDCone02() { InformationTable informationTableMock = getInformationTableMock02(); IntSortedSet dominanceCone = DominanceConeCalculator.INSTANCE.calculatePositiveDCone(0, informationTableMock); assertEquals(dominanceCone.size(), 5); assertTrue(dominanceCone.contains(0)); assertTrue(dominanceCone.contains(1)); assertTrue(dominanceCone.contains(2)); assertTrue(dominanceCone.contains(7)); assertTrue(dominanceCone.contains(8)); } /** * Test method for {@link DominanceConeCalculator#calculateNegativeDCone(int, InformationTable)}. */ @Test void testCalculateNegativeDCone01() { InformationTable informationTableMock = getInformationTableMock01(); IntSortedSet dominanceCone = DominanceConeCalculator.INSTANCE.calculateNegativeDCone(0, informationTableMock); assertEquals(dominanceCone.size(), 2); assertTrue(dominanceCone.contains(0)); assertTrue(dominanceCone.contains(4)); } /** * Test method for {@link DominanceConeCalculator#calculateNegativeDCone(int, InformationTable)}. */ @Test void testCalculateNegativeDCone02() { InformationTable informationTableMock = getInformationTableMock02(); IntSortedSet dominanceCone = DominanceConeCalculator.INSTANCE.calculateNegativeDCone(0, informationTableMock); assertEquals(dominanceCone.size(), 4); assertTrue(dominanceCone.contains(0)); assertTrue(dominanceCone.contains(5)); assertTrue(dominanceCone.contains(6)); assertTrue(dominanceCone.contains(7)); } /** * Test method for {@link DominanceConeCalculator#calculatePositiveInvDCone(int, InformationTable)}. */ @Test void testCalculatePositiveInvDCone01() { InformationTable informationTableMock = getInformationTableMock01(); IntSortedSet dominanceCone = DominanceConeCalculator.INSTANCE.calculatePositiveInvDCone(0, informationTableMock); assertEquals(dominanceCone.size(), 2); assertTrue(dominanceCone.contains(0)); assertTrue(dominanceCone.contains(1)); } /** * Test method for {@link DominanceConeCalculator#calculatePositiveInvDCone(int, InformationTable)}. */ @Test void testCalculatePositiveInvDCone02() { InformationTable informationTableMock = getInformationTableMock02(); IntSortedSet dominanceCone = DominanceConeCalculator.INSTANCE.calculatePositiveInvDCone(0, informationTableMock); assertEquals(dominanceCone.size(), 4); assertTrue(dominanceCone.contains(0)); assertTrue(dominanceCone.contains(1)); assertTrue(dominanceCone.contains(2)); assertTrue(dominanceCone.contains(7)); //no object no. 8! } /** * Test method for {@link DominanceConeCalculator#calculateNegativeInvDCone(int, InformationTable)}. */ @Test void testCalculateNegativeInvDCone01() { InformationTable informationTableMock = getInformationTableMock01(); IntSortedSet dominanceCone = DominanceConeCalculator.INSTANCE.calculateNegativeInvDCone(0, informationTableMock); assertEquals(dominanceCone.size(), 2); assertTrue(dominanceCone.contains(0)); assertTrue(dominanceCone.contains(4)); } /** * Test method for {@link DominanceConeCalculator#calculateNegativeInvDCone(int, InformationTable)}. */ @Test void testCalculateNegativeInvDCone02() { InformationTable informationTableMock = getInformationTableMock02(); IntSortedSet dominanceCone = DominanceConeCalculator.INSTANCE.calculateNegativeInvDCone(0, informationTableMock); assertEquals(dominanceCone.size(), 5); assertTrue(dominanceCone.contains(0)); assertTrue(dominanceCone.contains(5)); assertTrue(dominanceCone.contains(6)); assertTrue(dominanceCone.contains(7)); assertTrue(dominanceCone.contains(8)); //object no. 8! } }
ruitobias/T2ti-ERP-JAVA
ECD/src/java/com/t2tierp/sped/contabil/blocoj/RegistroJ930.java
<reponame>ruitobias/T2ti-ERP-JAVA /* * The MIT License * * Copyright: Copyright (C) 2014 T2Ti.COM * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * The author may be contacted at: <EMAIL> * * @author <NAME> (T2Ti.com) * @version 2.0 */ package com.t2tierp.sped.contabil.blocoj; import java.io.Serializable; public class RegistroJ930 implements Serializable { private static final long serialVersionUID = 1L; private String identNom; /// Nome do signatário. private String identCpf; /// CPF. private String identQualif; /// Qualificação do assinante, conforme tabela do Departamento Nacional de Registro do Comércio - DNRC. private String codAssin; /// Código de qualificação do assinante, conforme tabela do Departamento Nacional de Registro do Comércio - DNRC. private String indCrc; /// Número de inscrição do contabilista no Conselho Regional de Contabilidade. /** * @return the identNom */ public String getIdentNom() { return identNom; } /** * @param identNom the identNom to set */ public void setIdentNom(String identNom) { this.identNom = identNom; } /** * @return the identCpf */ public String getIdentCpf() { return identCpf; } /** * @param identCpf the identCpf to set */ public void setIdentCpf(String identCpf) { this.identCpf = identCpf; } /** * @return the identQualif */ public String getIdentQualif() { return identQualif; } /** * @param identQualif the identQualif to set */ public void setIdentQualif(String identQualif) { this.identQualif = identQualif; } /** * @return the codAssin */ public String getCodAssin() { return codAssin; } /** * @param codAssin the codAssin to set */ public void setCodAssin(String codAssin) { this.codAssin = codAssin; } /** * @return the indCrc */ public String getIndCrc() { return indCrc; } /** * @param indCrc the indCrc to set */ public void setIndCrc(String indCrc) { this.indCrc = indCrc; } }
ipa-mdl/textX-LS
textX-LS/server/textx_ls_server/utils.py
<filename>textX-LS/server/textx_ls_server/utils.py import functools from typing import Callable def skip_not_supported_langs(func: Callable) -> Callable: """Decorator which checks if document is in the workspace and call decorated function. Args: func: callable that is being decorated Returns: Decorated callable Raises: None """ @functools.wraps(func) def decorator(ls, params, **kwargs): try: doc = ls.workspace.documents[params.textDocument.uri] kwargs["doc"] = doc return func(ls, params, **kwargs) except KeyError: pass return decorator
uruzahe/carla
Co-Simulation/Sumo/sumo-1.7.0/tools/contributed/sumopy/agilepy/lib_base/logger.py
# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo # Copyright (C) 2016-2020 German Aerospace Center (DLR) and others. # SUMOPy module # Copyright (C) 2012-2017 University of Bologna - DICAM # This program and the accompanying materials are made available under the # terms of the Eclipse Public License 2.0 which is available at # https://www.eclipse.org/legal/epl-2.0/ # This Source Code may also be made available under the following Secondary # Licenses when the conditions for such availability set forth in the Eclipse # Public License 2.0 are satisfied: GNU General Public License, version 2 # or later which is available at # https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html # SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later # @file logger.py # @author <NAME> # @date import types from time import gmtime, strftime class Logger: def __init__(self, filepath=None, is_stdout=True, timeformat="%a, %d %b %Y %H:%M:%S"): self._filepath = filepath self._logfile = None self._callbacks = {} self._is_stdout = is_stdout self._timeformat = timeformat def start(self, text="Start logging."): # print 'Logger.start:',self._filepath,self._filepath is not None if self._filepath is not None: ttext = strftime(self._timeformat, gmtime())+' '+text self._logfile = open(self._filepath, 'w') self._logfile.write(ttext+'\n') if self._is_stdout: print text def add_callback(self, function, key='message'): self._callbacks[key] = function def get_clallbackfunc(self, key): return self._callbacks.get(key, None) def del_callback(self, key): del self._callbacks[key] def progress(self, percent): pass def w(self, data, key='message', **kwargs): # print 'Logger.w:',self._logfile is not None,self._is_stdout,data if key == 'progress': text = '%d %% completed.' % data else: text = str(data) if self._logfile is not None: self._logfile.write(strftime(self._timeformat, gmtime())+' '+text+'\n') elif self._callbacks.has_key(key): kwargs['key'] = key self._callbacks[key](data, **kwargs) # elif type(data)==types.StringType: # print data if self._is_stdout: print text def stop(self, text="End logging."): if self._logfile is not None: ttext = strftime(self._timeformat, gmtime())+' '+text self._logfile.write(ttext+'\n') self._logfile.close() self._logfile = None if self._is_stdout: print text
densogiaichned/serenity
Userland/Libraries/LibWeb/HTML/TextMetrics.cpp
/* * Copyright (c) 2021, sin-ack <<EMAIL>> * * SPDX-License-Identifier: BSD-2-Clause */ #include "TextMetrics.h" namespace Web::HTML { RefPtr<TextMetrics> TextMetrics::create() { return adopt_ref(*new TextMetrics()); } }
marpple/FxDOM
src/parents.js
import nextOrPrevAll from "./_internal/_nextOrPrevAll.js"; export default nextOrPrevAll("parentNode", "push");
googleapis/googleapis-gen
google/cloud/retail/v2alpha/google-cloud-retail-v2alpha-java/proto-google-cloud-retail-v2alpha-java/src/main/java/com/google/cloud/retail/v2alpha/ImportCompletionDataRequestOrBuilder.java
<filename>google/cloud/retail/v2alpha/google-cloud-retail-v2alpha-java/proto-google-cloud-retail-v2alpha-java/src/main/java/com/google/cloud/retail/v2alpha/ImportCompletionDataRequestOrBuilder.java<gh_stars>1-10 // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/retail/v2alpha/import_config.proto package com.google.cloud.retail.v2alpha; public interface ImportCompletionDataRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.retail.v2alpha.ImportCompletionDataRequest) com.google.protobuf.MessageOrBuilder { /** * <pre> * Required. The catalog which the suggestions dataset belongs to. * Format: `projects/1234/locations/global/catalogs/default_catalog`. * </pre> * * <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }</code> * @return The parent. */ java.lang.String getParent(); /** * <pre> * Required. The catalog which the suggestions dataset belongs to. * Format: `projects/1234/locations/global/catalogs/default_catalog`. * </pre> * * <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }</code> * @return The bytes for parent. */ com.google.protobuf.ByteString getParentBytes(); /** * <pre> * Required. The desired input location of the data. * </pre> * * <code>.google.cloud.retail.v2alpha.CompletionDataInputConfig input_config = 2 [(.google.api.field_behavior) = REQUIRED];</code> * @return Whether the inputConfig field is set. */ boolean hasInputConfig(); /** * <pre> * Required. The desired input location of the data. * </pre> * * <code>.google.cloud.retail.v2alpha.CompletionDataInputConfig input_config = 2 [(.google.api.field_behavior) = REQUIRED];</code> * @return The inputConfig. */ com.google.cloud.retail.v2alpha.CompletionDataInputConfig getInputConfig(); /** * <pre> * Required. The desired input location of the data. * </pre> * * <code>.google.cloud.retail.v2alpha.CompletionDataInputConfig input_config = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ com.google.cloud.retail.v2alpha.CompletionDataInputConfigOrBuilder getInputConfigOrBuilder(); /** * <pre> * Pub/Sub topic for receiving notification. If this field is set, * when the import is finished, a notification will be sent to * specified Pub/Sub topic. The message data will be JSON string of a * [Operation][google.longrunning.Operation]. * Format of the Pub/Sub topic is `projects/{project}/topics/{topic}`. * </pre> * * <code>string notification_pubsub_topic = 3;</code> * @return The notificationPubsubTopic. */ java.lang.String getNotificationPubsubTopic(); /** * <pre> * Pub/Sub topic for receiving notification. If this field is set, * when the import is finished, a notification will be sent to * specified Pub/Sub topic. The message data will be JSON string of a * [Operation][google.longrunning.Operation]. * Format of the Pub/Sub topic is `projects/{project}/topics/{topic}`. * </pre> * * <code>string notification_pubsub_topic = 3;</code> * @return The bytes for notificationPubsubTopic. */ com.google.protobuf.ByteString getNotificationPubsubTopicBytes(); }
maciejg-git/vue-bootstrap-icons
dist-mdi/mdi/puzzle-heart.js
<filename>dist-mdi/mdi/puzzle-heart.js import { h } from 'vue' export default { name: "PuzzleHeart", vendor: "Mdi", type: "", tags: ["puzzle","heart"], render() { return h( "svg", {"xmlns":"http://www.w3.org/2000/svg","width":"24","height":"24","viewBox":"0 0 24 24","class":"v-icon","fill":"currentColor","data-name":"mdi-puzzle-heart","innerHTML":"<path d='M19 22.3L18.4 21.8C16.4 19.9 15 18.7 15 17.2C15 16 16 15 17.2 15C17.9 15 18.6 15.3 19 15.8C19.4 15.3 20.1 15 20.8 15C22 15 23 15.9 23 17.2C23 18.7 21.6 19.9 19.6 21.8L19 22.3M20.5 11H19V7C19 5.89 18.1 5 17 5H13V3.5C13 2.12 11.88 1 10.5 1S8 2.12 8 3.5V5H4C2.9 5 2 5.9 2 7V10.8H3.5C5 10.8 6.2 12 6.2 13.5S5 16.2 3.5 16.2H2V20C2 21.11 2.9 22 4 22H7.8V20.5C7.8 19 9 17.8 10.5 17.8C11.44 17.8 12.27 18.27 12.75 19H13.09C13.04 18.67 13 18.34 13 18C13 14.69 15.69 12 19 12C20.54 12 21.94 12.58 23 13.53C23 13.5 23 13.5 23 13.5C23 12.12 21.88 11 20.5 11Z' />"}, ) } }
mats9693/study
points/eth/subscrib_log/main.go
package main import ( "context" "fmt" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/ethclient" "github.com/mats9693/study/points/eth/utils" "log" "strings" "sync" ) const ( ethNodeAddr = "ws://192.168.2.57:8546" contractAddr = "0x8a8CcB904ECf84B4ea43AEfCA1e6847640fB7f4c" contractABIStr = `[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"admin","type":"address"},{"indexed":false,"internalType":"uint8","name":"invokeTimes","type":"uint8"}],"name":"TestEventName","type":"event"},{"inputs":[],"name":"testFuncEmitEvent","outputs":[],"stateMutability":"nonpayable","type":"function"}]` ) var ( ethConn *ethclient.Client sub ethereum.Subscription contractABI abi.ABI eventNameMap sync.Map // event hash - event name query = ethereum.FilterQuery{ Addresses: []common.Address{common.HexToAddress(contractAddr)}, } logs = make(chan types.Log, 10000) err error ) func main() { registerEvents() ethConn, err = ethclient.Dial(ethNodeAddr) utils.CheckError(err, "dial eth client failed") sub, err = ethConn.SubscribeFilterLogs(context.Background(), query, logs) utils.CheckError(err, "subscribe logs failed") for { select { case err = <-sub.Err(): log.Fatalln(err) // exit case vLog := <-logs: // core data fmt.Printf("> --- Receive a new event: %s ---\n", matchEventName(vLog.Topics[0].Hex())) fmt.Println("> Log Data:(parsed) ", parseContractEvents(vLog.Topics[0].Hex(), vLog.Data)) fmt.Println("> Block Number: ", vLog.BlockNumber) fmt.Println("> Block Hash: ", vLog.BlockHash.Hex()) fmt.Println("> Transaction Hash: ", vLog.TxHash.Hex()) fmt.Println() // some other data fmt.Println("> Contract Address: ", vLog.Address.Hex()) fmt.Println("> Contract Topics: ", printEventTopics(vLog.Topics)) fmt.Println("> Log Data:(origin) ", hexutil.Encode(vLog.Data)) fmt.Println("> Transaction Index: ", vLog.TxIndex) fmt.Println("> Log Index in Block: ", vLog.Index) fmt.Println("> Is Removed: ", vLog.Removed) fmt.Println() } } } func registerEvents() { eventDeclaration := []byte("TestEventName(address,uint8)") hash := crypto.Keccak256Hash(eventDeclaration) //fmt.Println("> Contract Event Signature(calc): ", hash.Hex() == "0x37bf82b399445377adc74da9876029ab2e1a0de7fedb054ecbf811afb4f6abe5", hash.Hex()) eventNameMap.Store(hash.Hex(), "TestEventName") contractABI, err = abi.JSON(strings.NewReader(contractABIStr)) utils.CheckError(err, "parse contract abi failed") } func matchEventName(hash string) string { eventNameI, ok := eventNameMap.Load(hash) if !ok { return "" } eventName, ok := eventNameI.(string) if !ok { return "" } return eventName } func printEventTopics(topics []common.Hash) []string { res := make([]string, 0, len(topics)) for _, t := range topics { res = append(res, t.Hex()) } return res } func parseContractEvents(hash string, data []byte) (res string) { switch hash { case "0x37bf82b399445377adc74da9876029ab2e1a0de7fedb054ecbf811afb4f6abe5": // TestEventName var payload []interface{} payload, err = contractABI.Unpack("TestEventName", data) utils.CheckError(err, "unpack params on event: TestEventName failed") utils.CheckBool(len(payload) == 2, "unexpected params amount") event := &EventParams_TestEventName{} paramOne, ok := payload[0].(common.Address) utils.CheckBool(ok, "type assert failed on event: TestEventName, param index: 0") event.Admin = paramOne paramTwo, ok := payload[1].(uint8) utils.CheckBool(ok, "type assert failed on event: TestEventName, param index: 1") event.InvokeTimes = paramTwo res = event.String() default: res = "unknown event hash: " + hash log.Println(res) } return }
snippet-bank/snippets
files/file-read-by-lines/snippet.go
package snippets import ( "bufio" "log" "os" ) // readByLines reads a file into memory line by line. func readByLines(path string, callback func(str string)) { file, err := os.Open(path) if err != nil { log.Fatal(err) } defer file.Close() scanner := bufio.NewScanner(file) for scanner.Scan() { line := scanner.Text() callback(line) } if err := scanner.Err(); err != nil { log.Fatal(err) } }
crimsonknave/trakt
lib/trakt/users.rb
<reponame>crimsonknave/trakt module Trakt class Users < Cot::Collection collected_class User end end
cientopolis/collaboratory
spec/workers/classification_data_mailer_worker_spec.rb
require 'spec_helper' RSpec.describe ClassificationDataMailerWorker do let(:project) { create(:project) } let(:s3_url) { "https://fake.s3.url.example.com" } it 'should deliver the mail' do expect{ subject.perform(project.id, s3_url, ["<EMAIL>"]) }.to change{ ActionMailer::Base.deliveries.count }.by(1) end context 'when there are no recipients' do it 'does not call the mailer' do expect(ClassificationDataMailer).to receive(:classification_data).never subject.perform(project.id, s3_url, []) end end end
sizeofvoid/ifconfigd
usr/src/sys/nfs/nfs_node.c
/* $OpenBSD: nfs_node.c,v 1.55 2010/12/21 20:14:43 thib Exp $ */ /* $NetBSD: nfs_node.c,v 1.16 1996/02/18 11:53:42 fvdl Exp $ */ /* * Copyright (c) 1989, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * <NAME> at The University of Guelph. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)nfs_node.c 8.6 (Berkeley) 5/22/95 */ #include <sys/param.h> #include <sys/systm.h> #include <sys/proc.h> #include <sys/mount.h> #include <sys/namei.h> #include <sys/vnode.h> #include <sys/kernel.h> #include <sys/malloc.h> #include <sys/pool.h> #include <sys/rwlock.h> #include <sys/queue.h> #include <nfs/rpcv2.h> #include <nfs/nfsproto.h> #include <nfs/nfs.h> #include <nfs/nfsnode.h> #include <nfs/nfsmount.h> #include <nfs/nfs_var.h> struct pool nfs_node_pool; extern int prtactive; struct rwlock nfs_hashlock = RWLOCK_INITIALIZER("nfshshlk"); /* XXX */ extern struct vops nfs_vops; /* filehandle to node lookup. */ static __inline int nfsnode_cmp(const struct nfsnode *a, const struct nfsnode *b) { if (a->n_fhsize != b->n_fhsize) return (a->n_fhsize - b->n_fhsize); return (memcmp(a->n_fhp, b->n_fhp, a->n_fhsize)); } RB_PROTOTYPE(nfs_nodetree, nfsnode, n_entry, nfsnode_cmp); RB_GENERATE(nfs_nodetree, nfsnode, n_entry, nfsnode_cmp); /* * Look up a vnode/nfsnode by file handle. * Callers must check for mount points!! * In all cases, a pointer to a * nfsnode structure is returned. */ int nfs_nget(struct mount *mnt, nfsfh_t *fh, int fhsize, struct nfsnode **npp) { struct nfsmount *nmp; struct nfsnode *np, find, *np2; struct vnode *vp, *nvp; struct proc *p = curproc; /* XXX */ int error; nmp = VFSTONFS(mnt); loop: rw_enter_write(&nfs_hashlock); find.n_fhp = fh; find.n_fhsize = fhsize; np = RB_FIND(nfs_nodetree, &nmp->nm_ntree, &find); if (np != NULL) { rw_exit_write(&nfs_hashlock); vp = NFSTOV(np); error = vget(vp, LK_EXCLUSIVE, p); if (error) goto loop; *npp = np; return (0); } /* * getnewvnode() could recycle a vnode, potentially formerly * owned by NFS. This will cause a VOP_RECLAIM() to happen, * which will cause recursive locking, so we unlock before * calling getnewvnode() lock again afterwards, but must check * to see if this nfsnode has been added while we did not hold * the lock. */ rw_exit_write(&nfs_hashlock); error = getnewvnode(VT_NFS, mnt, &nfs_vops, &nvp); /* note that we don't have this vnode set up completely yet */ rw_enter_write(&nfs_hashlock); if (error) { *npp = NULL; rw_exit_write(&nfs_hashlock); return (error); } nvp->v_flag |= VLARVAL; np = RB_FIND(nfs_nodetree, &nmp->nm_ntree, &find); if (np != NULL) { vgone(nvp); rw_exit_write(&nfs_hashlock); goto loop; } vp = nvp; np = pool_get(&nfs_node_pool, PR_WAITOK | PR_ZERO); vp->v_data = np; /* we now have an nfsnode on this vnode */ vp->v_flag &= ~VLARVAL; np->n_vnode = vp; rw_init(&np->n_commitlock, "nfs_commitlk"); /* * Are we getting the root? If so, make sure the vnode flags * are correct */ if ((fhsize == nmp->nm_fhsize) && !bcmp(fh, nmp->nm_fh, fhsize)) { if (vp->v_type == VNON) vp->v_type = VDIR; vp->v_flag |= VROOT; } np->n_fhp = &np->n_fh; bcopy(fh, np->n_fhp, fhsize); np->n_fhsize = fhsize; np2 = RB_INSERT(nfs_nodetree, &nmp->nm_ntree, np); KASSERT(np2 == NULL); np->n_accstamp = -1; rw_exit(&nfs_hashlock); *npp = np; return (0); } int nfs_inactive(void *v) { struct vop_inactive_args *ap = v; struct nfsnode *np; struct sillyrename *sp; #ifdef DIAGNOSTIC if (prtactive && ap->a_vp->v_usecount != 0) vprint("nfs_inactive: pushing active", ap->a_vp); #endif if (ap->a_vp->v_flag & VLARVAL) /* * vnode was incompletely set up, just return * as we are throwing it away. */ return(0); #ifdef DIAGNOSTIC if (ap->a_vp->v_data == NULL) panic("NULL v_data (no nfsnode set up?) in vnode %p", ap->a_vp); #endif np = VTONFS(ap->a_vp); if (ap->a_vp->v_type != VDIR) { sp = np->n_sillyrename; np->n_sillyrename = NULL; } else sp = NULL; if (sp) { /* * Remove the silly file that was rename'd earlier */ nfs_vinvalbuf(ap->a_vp, 0, sp->s_cred, curproc); nfs_removeit(sp); crfree(sp->s_cred); vrele(sp->s_dvp); free(sp, M_NFSREQ); } np->n_flag &= (NMODIFIED | NFLUSHINPROG | NFLUSHWANT); VOP_UNLOCK(ap->a_vp, 0, ap->a_p); return (0); } /* * Reclaim an nfsnode so that it can be used for other purposes. */ int nfs_reclaim(void *v) { struct vop_reclaim_args *ap = v; struct vnode *vp = ap->a_vp; struct nfsmount *nmp; struct nfsnode *np = VTONFS(vp); #ifdef DIAGNOSTIC if (prtactive && vp->v_usecount != 0) vprint("nfs_reclaim: pushing active", vp); #endif if (ap->a_vp->v_flag & VLARVAL) /* * vnode was incompletely set up, just return * as we are throwing it away. */ return(0); #ifdef DIAGNOSTIC if (ap->a_vp->v_data == NULL) panic("NULL v_data (no nfsnode set up?) in vnode %p", ap->a_vp); #endif nmp = VFSTONFS(vp->v_mount); rw_enter_write(&nfs_hashlock); RB_REMOVE(nfs_nodetree, &nmp->nm_ntree, np); rw_exit_write(&nfs_hashlock); if (np->n_rcred) crfree(np->n_rcred); if (np->n_wcred) crfree(np->n_wcred); cache_purge(vp); pool_put(&nfs_node_pool, vp->v_data); vp->v_data = NULL; return (0); }
ocerman/TaskManager
source/TaskManager.h
/* * Copyright 2000 by <NAME> * * 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. */ #ifndef TASK_MANAGER_H #define TASK_MANAGER_H #ifdef MEM_DEBUG extern"C" void SetNewLeakChecking(bool); extern"C" void SetMallocLeakChecking(bool); #endif // MEM_DEBUG // ====== Application Signature ====== #include "signature.h" // ====== Application Name ====== #define APP_NAME "TaskManager" #define FULL_APP_NAME "Be " APP_NAME // ====== Message IDs ====== const int32 MSG_TWEAK_DESKBAR = 'mDTW'; const int32 MSG_SHOW_MAIN_WINDOW = 'mSMW'; const int32 MSG_SHOW_REPLICANT = 'mSRP'; // ====== Message Fields ====== // MSG_SHOW_REPLICANT extern const char * const MESSAGE_DATA_ID_SHOW; // bool // ====== Class Defs ====== class CTeamModel; class CTaskManagerApplication : public BApplication { public: CTaskManagerApplication(); virtual ~CTaskManagerApplication(); virtual void ReadyToRun(); virtual void AboutRequested(); virtual void ArgvReceived(int32 argc, char **argv); virtual void MessageReceived(BMessage *message); virtual BHandler *ResolveSpecifier(BMessage *message, int32 index, BMessage *specifier, int32 what, const char *property); protected: bool IncludesOption(int32 argc, char **argv, const char *option); BWindow *mainWindow; bool showMainWindow; }; #endif // TASK_MANAGER_H
fbcom/project-euler
080_square_root_digital_expansion.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # A Solution to "Square root digital expansion" – Project Euler Problem No. 80 # by <NAME> # # Sourcecode: https://github.com/fbcom/project-euler # Problem statement: https://projecteuler.net/problem=80 from decimal import * getcontext().prec = 102 # 2 places before the , and 100 decimal places after the , def sum_digits_of_sqrt(n): root = Decimal(n).sqrt() digits = str(root).replace('.', '') return sum(map(int, digits[:100])) # Testcase assert sum_digits_of_sqrt(2) == 475, "Testcase failed" # Solve solution = 0 for n in range(1, 101): if n**0.5 == int(n**0.5): continue # not irrational solution += sum_digits_of_sqrt(n) print "Solution:", solution
tschiemer/midipatcher
src/AbstractControl.cpp
#include <AbstractControl.hpp> #include <Port/AbstractPort.hpp> #include <Port/AbstractInputOutputPort.hpp> // #include <Port/MidiIn.hpp> #include <version.hpp> #include <Log.hpp> #include <Error.hpp> namespace MidiPatcher { AbstractControl::AbstractControl(PortRegistry * portRegistry){ assert(portRegistry != nullptr); PortRegistryRef = portRegistry; PortRegistryRef->subscribePortRegistryUpdateReveicer( this ); } AbstractPort * AbstractControl::getPortByIdOrKey( std::string &idOrKey ){ if (std::all_of(idOrKey.begin(), idOrKey.end(), ::isdigit)){ return PortRegistryRef->getPortById( std::stoi(idOrKey) ); } return PortRegistryRef->getPortByKey( idOrKey ); } void AbstractControl::handleCommand(std::vector<std::string> &argv){ // std::cout << "(" << argv.size() << ") "; // for(int i = 0; i < argv.size(); i++){ // std::cout << argv[i] << " "; // } // std::cout << std::endl; PortRegistryRef->runloop(); if (argv[0] == "ping"){ respond("s","pong"); return ok(); } if (argv[0] == "version"){ respond("ss", "version", VERSION.c_str()); return ok(); } if (argv[0] == "option"){ if (1 == argv.size() || argv.size() > 3){ return error("Expected: option <option-key> [<option-value>]"); } if (argv[1] == "return-ids"){ if (argv.size() == 3){ OptReturnIds = std::stoi(argv[2]); } else { respond("ssi", "option", "return-ids", OptReturnIds ? 1 : 0); } return ok(); } if (argv[1] == "notifications"){ if (argv.size() == 3){ OptNotificationsEnabled = std::stoi(argv[2]); } else { respond("ssi", "option", "notifications", OptNotificationsEnabled ? 1 : 0); } return ok(); } if (argv[1] == "autoscan-enabled"){ if (argv.size() == 3){ try { bool enabled = std::stoi(argv[2]); if (enabled){ PortRegistryRef->startAutoscan(); } else { PortRegistryRef->stopAutoscan(); } } catch (Error &e){ return error(e.what()); } } else { respond("ssi", "option", "autoscan-enabled", PortRegistryRef->isAutoscanEnabled() ? 1 : 0); } return ok(); } if (argv[1] == "autoscan-interval"){ if (argv.size() == 3){ try { PortRegistryRef->setAutoscanInterval(std::stoi(argv[2])); } catch (Error &e){ return error(e.what()); } } else { respond("ssi", "option", "autoscan-interval", PortRegistryRef->getAutoscanInterval()); } return ok(); } return error("Unknown option: " + argv[1]); } if (argv[0] == "scan"){ if (argv.size() != 1){ return error("Expected: scan"); } PortRegistryRef->rescan(); return ok(); } if (argv[0] == "portclasses"){ if (argv.size() > 1){ return error("Expected: portclasses"); } std::vector<MidiPatcher::AbstractPort::PortClassRegistryInfo*> * classes = PortRegistryRef->getPortClassRegistryInfoList(); respond("si", "portclasses", classes->size()); for(int i = 0; i < classes->size(); i++){ respond("ss", "portclasses", classes->at(i)->Key.c_str() ); } delete classes; return ok(); } if (argv[0] == "ports"){ if (argv.size() > 3){ return error("Expected: ports [#|<port-id>|<port-key>]"); } if (argv.size() == 2){ if (argv[1] == "#"){ respond("si", "ports", PortRegistryRef->getPortCount()); return ok(); } AbstractPort * port = getPortByIdOrKey(argv[1]); if (port == nullptr){ return error("No such port: " + argv[1]); } PortDescriptor * desc = port->getPortDescriptor(); respond("siiis", "ports", port->getId(), port->getType(), port->getDeviceState(), desc->toString().c_str()); delete desc; return ok(); } else { std::vector<AbstractPort*> * ports = PortRegistryRef->getAllPorts(); respond("si", "ports", ports->size()); for(int i = 0; i < ports->size(); i++){ AbstractPort * port = ports->at(i); PortDescriptor * desc = port->getPortDescriptor(); respond("siiis","ports", port->getId(), port->getType(), port->getDeviceState(), desc->toString().c_str()); delete desc; } delete ports; return ok(); } } if (argv[0] == "devstate"){ if (argv.size() > 2){ return error("Expected: devstate [<port-id>|<port-key>]"); } AbstractPort * port; if (argv.size() == 2){ port = getPortByIdOrKey(argv[1]); if (port == nullptr){ return error("No such port: " + argv[1]); } int connected = port->getDeviceState() == AbstractPort::DeviceStateConnected ? 1 : 0; if (OptReturnIds){ respond("sii", "devstate", port->getId(), connected ); } else { respond("ssi", "devstate", port->getKey().c_str(), connected ); } return ok(); } else { std::vector<AbstractPort*> * ports = PortRegistryRef->getAllPorts(); respond("si", "devstate", ports->size() ); for(int i = 0; i < ports->size(); i++){ AbstractPort * port = ports->at(i); int connected = port->getDeviceState() == AbstractPort::DeviceStateConnected ? 1 : 0; if (OptReturnIds){ respond("sii", "devstate", port->getId(), connected ); } else { respond("ssi", "devstate", port->getKey().c_str(), connected ); } } delete ports; return ok(); } } if (argv[0] == "portoption"){ if (argv.size() < 3 || 4 < argv.size()){ return error("Expected: portoption (<port-id>|<port-key>) <option> [<value>]"); } AbstractPort * port = getPortByIdOrKey(argv[1]); if (port == nullptr){ return error("No such port: " + argv[1]); } if (port->hasOption(argv[2]) == false){ return error("Port " + argv[1] + " does not have option " + argv[2]); } if (argv.size() == 3){ if (OptReturnIds){ respond("siss", "portoption", port->getId(), argv[2].c_str(), port->getOption(argv[2]).c_str()); } else { respond("ssss", "portoption", argv[1].c_str(), argv[2].c_str(), port->getOption(argv[2]).c_str()); } } else { try { port->setOption(argv[2], argv[3]); } catch( Error &e){ return error(e.what()); } } return ok(); } if (argv[0] == "register"){ if (argv.size() != 2){ return error("Expected: register <port-descriptor>"); } PortDescriptor * desc = nullptr; try { desc = PortDescriptor::fromString( argv[1] ); } catch(Error &e){ return error(e.what()); } AbstractPort * port = PortRegistryRef->getPortByKey( desc->getKey() ); if (port != nullptr){ error("Already registered key: " + desc->getKey()); } else { try { port = PortRegistryRef->registerPortFromDescriptor( *desc ); // respond("sisii", "ports", port->getId(), port->getKey().c_str(), port->getType(), port->getDeviceState()); ok(); } catch (Error &e) { error(e.what()); } } delete desc; return; } if (argv[0] == "unregister"){ if (argv.size() != 2){ return error("Expected: unregister (<port-id>|<port-key>)"); } AbstractPort * port = getPortByIdOrKey( argv[1] ); if (port == nullptr){ return error("No such port: " + argv[1]); } PortRegistryRef->unregisterPort( port ); // if (OptReturnIds){ // respond("si", "unregister", port->getId()); // } else { // respond("ss", "unregister", port->getKey().c_str()); // } // delete dynamic_cast<Port::MidiIn*>(port); delete port; return ok(); } if (argv[0] == "constate"){ if (argv.size() > 3){ return error("Expected: constate [(<port1-id>|<port1-key>) [(<port2-id>|<port2-key>)]]"); } if (argv.size() == 3){ AbstractPort * inport = getPortByIdOrKey(argv[1]); AbstractPort * outport = getPortByIdOrKey(argv[2]); if (inport == nullptr){ return error("No such port: " + argv[1]); } if (outport == nullptr){ return error("No such port: " + argv[2]); } int constate = inport->isConnectedToType(outport, AbstractPort::TypeOutput) ? 1 : 0; if (OptReturnIds){ respond("siii", "constate", inport->getId(), outport->getId(), constate ); } else { respond("sssi", "constate", argv[1].c_str(), argv[2].c_str(), constate ); } return ok(); } else if (argv.size() == 2){ AbstractPort * port = getPortByIdOrKey(argv[1]); if (port == nullptr){ return error("No such port: " + argv[1]); } std::vector<AbstractPort*> * connections = port->getConnections(AbstractPort::TypeOutput); for(int i = 0; i < connections->size(); i++){ AbstractPort * other = connections->at(i); if (OptReturnIds){ respond("siii", "constate", port->getId(), other->getId(), 1 ); } else { respond("sssi", "constate", argv[1].c_str(), other->getKey().c_str(), 1 ); } } delete connections; return ok(); } else { std::vector<AbstractPort*> * ports = PortRegistryRef->getAllPorts(AbstractPort::TypeInput); // respond("si", "constate", ports->size() ); for(int i = 0; i < ports->size(); i++){ AbstractPort * port = ports->at(i); AbstractInputPort * inport = dynamic_cast<AbstractInputPort*>(port); if (inport != nullptr){ std::vector<AbstractPort*> * connections = port->getConnections(AbstractPort::TypeOutput); for(int j = 0; j < connections->size(); j++){ AbstractPort * other = connections->at(j); if (OptReturnIds){ respond("siii", "constate", port->getId(), other->getId(), 1 ); } else { respond("sssi", "constate", port->getKey().c_str(), other->getKey().c_str(), 1 ); } } delete connections; } } delete ports; return ok(); } } if (argv[0] == "connect"){ if (argv.size() != 3){ return error("Expected: connect (<in-port-id>|<in-port-key>) (<in-port-id>|<out-port-key>)"); } AbstractInputPort * inport = dynamic_cast<AbstractInputPort*>(getPortByIdOrKey(argv[1])); AbstractOutputPort * outport = dynamic_cast<AbstractOutputPort*>(getPortByIdOrKey(argv[2])); if (inport == nullptr){ return error("No such input-port: " + argv[1]); } if (outport == nullptr){ return error("No such output-port: " + argv[2]); } if (!inport->isConnectedToType(outport, AbstractPort::TypeOutput)){ PortRegistryRef->connectPorts(inport, outport); } // if (OptReturnIds){ // respond("siii", "constate", inport->getId(), outport->getId(), 1); // } else { // respond("sssi", "constate", argv[1].c_str(), argv[2].c_str(), 1); // } return ok(); } if (argv[0] == "disconnect"){ if (argv.size() != 3){ return error("Expected: disconnect (<in-port-id>|<in-port-key>) (<in-port-id>|<out-port-key>)"); } AbstractInputPort * inport = dynamic_cast<AbstractInputPort*>(getPortByIdOrKey(argv[1])); AbstractOutputPort * outport = dynamic_cast<AbstractOutputPort*>(getPortByIdOrKey(argv[2])); if (inport == nullptr){ return error("No such input-port: " + argv[1]); } if (outport == nullptr){ return error("No such output-port: " + argv[2]); } if (inport->isConnectedToType(outport, AbstractPort::TypeOutput)){ PortRegistryRef->disconnectPorts(inport, outport); } // if (OptReturnIds){ // respond("sssi", "constate", inport->getId(), outport->getId(), 0); // } else { // respond("sssi", "constate", argv[1].c_str(), argv[2].c_str(), 0); // } return ok(); } error("Unknown command"); } void AbstractControl::ok(){ std::vector<std::string> argv; argv.push_back("OK"); respond(argv); } void AbstractControl::error(std::string msg){ std::vector<std::string> argv; argv.push_back("ERROR"); if (msg.size() > 0){ argv.push_back(msg); } respond(argv); } void AbstractControl::respond(const char * fmt, ...){ assert( fmt != nullptr ); va_list args; va_start(args, fmt); std::vector<std::string> argv; for(int i = 0; fmt[i] != '\0'; i++){ if (fmt[i] == 's'){ char * str = va_arg(args, char *); argv.push_back( str ); } else if (fmt[i] == 'i'){ int j = va_arg(args, int); argv.push_back(std::to_string(j)); } } va_end(args); if (argv[0][0] == '+'){ publishNotification(argv); } else { respond(argv); } } void AbstractControl::publishNotification(std::vector<std::string> &argv){ respond(argv); } // void AbstractControl::deviceDiscovered(AbstractPort * port){ // // PortDescriptor * desc = port->getPortDescriptor(); // // respond("sis", "+ports", port->getId(), desc->toString().c_str()); // // delete desc; // } void AbstractControl::deviceStateChanged(AbstractPort * port, AbstractPort::DeviceState_t newState){ if (OptNotificationsEnabled == false){ return; } int connected = newState == AbstractPort::DeviceStateConnected ? 1 : 0; if (OptReturnIds){ respond("sii", "+devstate", port->getId(), connected); } else { respond("ssi", "+devstate", port->getKey().c_str(), connected); } } void AbstractControl::portRegistered( AbstractPort * port ){ if (OptNotificationsEnabled == false){ return; } PortDescriptor * desc = port->getPortDescriptor(); respond("siiis", "+ports", port->getId(), port->getType(), port->getDeviceState(), desc->toString().c_str()); delete desc; } void AbstractControl::portUnregistered( AbstractPort * port ){ if (OptNotificationsEnabled == false){ return; } PortDescriptor * desc = port->getPortDescriptor(); respond("siiis", "-ports", port->getId(), port->getType(), port->getDeviceState(), desc->toString().c_str()); delete desc; } void AbstractControl::portsConnected( AbstractPort * inport, AbstractPort * outport ){ if (OptNotificationsEnabled == false){ return; } if (OptReturnIds){ respond("siii","+constate",inport->getId(), outport->getId(), 1); } else { respond("sssi","+constate",inport->getKey().c_str(), outport->getKey().c_str(), 1); } } void AbstractControl::portsDisconnected( AbstractPort * inport, AbstractPort * outport ){ if (OptNotificationsEnabled == false){ return; } if (OptReturnIds){ respond("siii","+constate",inport->getId(), outport->getId(), 0); } else { respond("sssi","+constate",inport->getKey().c_str(), outport->getKey().c_str(), 0); } } }
HeliumEdu/platform
helium/auth/tests/views/apis/testcaseuserprofileviews.py
import json from django.contrib.auth import get_user_model from django.urls import reverse from mock import mock from rest_framework import status from rest_framework.test import APITestCase from helium.auth.tests.helpers import userhelper from helium.common.services.phoneservice import HeliumPhoneError __author__ = "<NAME>" __copyright__ = "Copyright 2019, Helium Edu" __version__ = "1.4.38" class TestCaseUserProfileViews(APITestCase): def test_user_profile_login_required(self): # GIVEN userhelper.given_a_user_exists() # WHEN responses = [ self.client.get(reverse('auth_user_profile_detail')), self.client.put(reverse('auth_user_profile_detail')) ] # THEN for response in responses: self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) @mock.patch('helium.common.services.phoneservice.client.api.account.messages.create') @mock.patch('helium.auth.serializers.userprofileserializer.verify_number', return_value='+15555555555') def test_put_user_profile(self, mock_verify_number, mock_sms_messages_create): # GIVEN user = userhelper.given_a_user_exists_and_is_authenticated(self.client) self.assertIsNone(user.profile.phone) self.assertIsNone(user.profile.phone_changing) # WHEN data = { 'phone': '(555) 555-5555', } response = self.client.put(reverse('auth_user_profile_detail'), json.dumps(data), content_type='application/json') # THEN mock_verify_number.assert_called_once() mock_sms_messages_create.assert_called_once() self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertIsNone(response.data['phone']) self.assertEqual(response.data['phone_changing'], '+15555555555') user = get_user_model().objects.get(pk=user.id) self.assertIsNone(user.profile.phone) self.assertEqual(user.profile.phone_changing, response.data['phone_changing']) @mock.patch('helium.auth.serializers.userprofileserializer.verify_number') def test_put_bad_data_fails(self, mock_verify_number): # GIVEN user = userhelper.given_a_user_exists_and_is_authenticated(self.client) self.assertIsNone(user.profile.phone) self.assertIsNone(user.profile.phone_changing) mock_verify_number.side_effect = HeliumPhoneError('Invalid phone number.') # WHEN data = { 'phone': 'not-a-phone', } response = self.client.put(reverse('auth_user_profile_detail'), json.dumps(data), content_type='application/json') # THEN self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertIn('phone', response.data) def test_phone_changes_after_verification(self): # GIVEN user = userhelper.given_a_user_exists_and_is_authenticated(self.client) user.profile.phone_changing = '5555555' user.profile.phone_verification_code = 123456 user.profile.save() self.assertFalse(user.profile.phone_verified) # WHEN data = { 'phone_verification_code': user.profile.phone_verification_code, } response = self.client.put(reverse('auth_user_profile_detail'), json.dumps(data), content_type='application/json') # THEN self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['phone'], '5555555') self.assertIsNone(response.data['phone_changing']) user = get_user_model().objects.get(pk=user.id) self.assertEqual(user.profile.phone, response.data['phone']) self.assertIsNone(user.profile.phone_changing) self.assertTrue(user.profile.phone_verified) def test_remove_phone(self): # GIVEN user = userhelper.given_a_user_exists_and_is_authenticated(self.client) user.profile.phone = '5555555' user.profile.save() # WHEN data = { 'phone': '', } response = self.client.put(reverse('auth_user_profile_detail'), json.dumps(data), content_type='application/json') # THEN self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertIsNone(response.data['phone'], '5555555') user = get_user_model().objects.get(pk=user.id) self.assertIsNone(user.profile.phone) def test_invalid_phone_verification_code_fails(self): # GIVEN user = userhelper.given_a_user_exists_and_is_authenticated(self.client) user.profile.phone_changing = '5555555' user.profile.phone_verification_code = 123456 user.profile.save() # WHEN data = { 'phone_verification_code': 000000, } response = self.client.put(reverse('auth_user_profile_detail'), json.dumps(data), content_type='application/json') # THEN self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertIn('phone_verification_code', response.data) def test_put_read_only_field_does_nothing(self): # GIVEN user = userhelper.given_a_user_exists_and_is_authenticated(self.client) phone_changing = '5555555' user.profile.phone_changing = phone_changing user.profile.save() # WHEN data = { 'phone_changing': '444-4444' } response = self.client.put(reverse('auth_user_profile_detail'), json.dumps(data), content_type='application/json') # THEN user = get_user_model().objects.get(pk=user.id) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(user.profile.phone_changing, phone_changing)
INAF-CTA-AAI/grouper
grouper-misc/tierApiAuthzClient/src/ext/edu/internet2/middleware/tierApiAuthzClientExt/org/apache/commons/collections/MapUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.internet2.middleware.tierApiAuthzClientExt.org.apache.commons.collections; import java.io.PrintStream; import java.text.NumberFormat; import java.text.ParseException; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.ResourceBundle; import java.util.SortedMap; import java.util.TreeMap; import edu.internet2.middleware.tierApiAuthzClientExt.org.apache.commons.collections.map.FixedSizeMap; import edu.internet2.middleware.tierApiAuthzClientExt.org.apache.commons.collections.map.FixedSizeSortedMap; import edu.internet2.middleware.tierApiAuthzClientExt.org.apache.commons.collections.map.LazyMap; import edu.internet2.middleware.tierApiAuthzClientExt.org.apache.commons.collections.map.LazySortedMap; import edu.internet2.middleware.tierApiAuthzClientExt.org.apache.commons.collections.map.ListOrderedMap; import edu.internet2.middleware.tierApiAuthzClientExt.org.apache.commons.collections.map.MultiValueMap; import edu.internet2.middleware.tierApiAuthzClientExt.org.apache.commons.collections.map.PredicatedMap; import edu.internet2.middleware.tierApiAuthzClientExt.org.apache.commons.collections.map.PredicatedSortedMap; import edu.internet2.middleware.tierApiAuthzClientExt.org.apache.commons.collections.map.TransformedMap; import edu.internet2.middleware.tierApiAuthzClientExt.org.apache.commons.collections.map.TransformedSortedMap; import edu.internet2.middleware.tierApiAuthzClientExt.org.apache.commons.collections.map.TypedMap; import edu.internet2.middleware.tierApiAuthzClientExt.org.apache.commons.collections.map.TypedSortedMap; import edu.internet2.middleware.tierApiAuthzClientExt.org.apache.commons.collections.map.UnmodifiableMap; import edu.internet2.middleware.tierApiAuthzClientExt.org.apache.commons.collections.map.UnmodifiableSortedMap; /** * Provides utility methods and decorators for * {@link Map} and {@link SortedMap} instances. * <p> * It contains various type safe methods * as well as other useful features like deep copying. * <p> * It also provides the following decorators: * * <ul> * <li>{@link #fixedSizeMap(Map)} * <li>{@link #fixedSizeSortedMap(SortedMap)} * <li>{@link #lazyMap(Map,Factory)} * <li>{@link #lazyMap(Map,Transformer)} * <li>{@link #lazySortedMap(SortedMap,Factory)} * <li>{@link #lazySortedMap(SortedMap,Transformer)} * <li>{@link #predicatedMap(Map,Predicate,Predicate)} * <li>{@link #predicatedSortedMap(SortedMap,Predicate,Predicate)} * <li>{@link #transformedMap(Map, Transformer, Transformer)} * <li>{@link #transformedSortedMap(SortedMap, Transformer, Transformer)} * <li>{@link #typedMap(Map, Class, Class)} * <li>{@link #typedSortedMap(SortedMap, Class, Class)} * <li>{@link #multiValueMap( Map )} * <li>{@link #multiValueMap( Map, Class )} * <li>{@link #multiValueMap( Map, Factory )} * </ul> * * @since Commons Collections 1.0 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ * * @author <a href="mailto:<EMAIL>"><NAME></a> * @author <a href="mailto:<EMAIL>"><NAME></a> * @author <a href="mailto:<EMAIL>"><NAME></a> * @author <NAME> * @author <NAME> * @author <NAME> * @author <NAME> * @author <NAME> * @author <NAME> * @author <a href="mailto:<EMAIL>"><NAME></a> * @author <a href="mailto:<EMAIL>"><NAME></a> * @author <NAME> */ public class MapUtils { /** * An empty unmodifiable map. * This was not provided in JDK1.2. */ public static final Map EMPTY_MAP = UnmodifiableMap.decorate(new HashMap(1)); /** * An empty unmodifiable sorted map. * This is not provided in the JDK. */ public static final SortedMap EMPTY_SORTED_MAP = UnmodifiableSortedMap.decorate(new TreeMap()); /** * String used to indent the verbose and debug Map prints. */ private static final String INDENT_STRING = " "; /** * <code>MapUtils</code> should not normally be instantiated. */ public MapUtils() { } // Type safe getters //------------------------------------------------------------------------- /** * Gets from a Map in a null-safe manner. * * @param map the map to use * @param key the key to look up * @return the value in the Map, <code>null</code> if null map input */ public static Object getObject(final Map map, final Object key) { if (map != null) { return map.get(key); } return null; } /** * Gets a String from a Map in a null-safe manner. * <p> * The String is obtained via <code>toString</code>. * * @param map the map to use * @param key the key to look up * @return the value in the Map as a String, <code>null</code> if null map input */ public static String getString(final Map map, final Object key) { if (map != null) { Object answer = map.get(key); if (answer != null) { return answer.toString(); } } return null; } /** * Gets a Boolean from a Map in a null-safe manner. * <p> * If the value is a <code>Boolean</code> it is returned directly. * If the value is a <code>String</code> and it equals 'true' ignoring case * then <code>true</code> is returned, otherwise <code>false</code>. * If the value is a <code>Number</code> an integer zero value returns * <code>false</code> and non-zero returns <code>true</code>. * Otherwise, <code>null</code> is returned. * * @param map the map to use * @param key the key to look up * @return the value in the Map as a Boolean, <code>null</code> if null map input */ public static Boolean getBoolean(final Map map, final Object key) { if (map != null) { Object answer = map.get(key); if (answer != null) { if (answer instanceof Boolean) { return (Boolean) answer; } else if (answer instanceof String) { return new Boolean((String) answer); } else if (answer instanceof Number) { Number n = (Number) answer; return (n.intValue() != 0) ? Boolean.TRUE : Boolean.FALSE; } } } return null; } /** * Gets a Number from a Map in a null-safe manner. * <p> * If the value is a <code>Number</code> it is returned directly. * If the value is a <code>String</code> it is converted using * {@link NumberFormat#parse(String)} on the system default formatter * returning <code>null</code> if the conversion fails. * Otherwise, <code>null</code> is returned. * * @param map the map to use * @param key the key to look up * @return the value in the Map as a Number, <code>null</code> if null map input */ public static Number getNumber(final Map map, final Object key) { if (map != null) { Object answer = map.get(key); if (answer != null) { if (answer instanceof Number) { return (Number) answer; } else if (answer instanceof String) { try { String text = (String) answer; return NumberFormat.getInstance().parse(text); } catch (ParseException e) { logInfo(e); } } } } return null; } /** * Gets a Byte from a Map in a null-safe manner. * <p> * The Byte is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @return the value in the Map as a Byte, <code>null</code> if null map input */ public static Byte getByte(final Map map, final Object key) { Number answer = getNumber(map, key); if (answer == null) { return null; } else if (answer instanceof Byte) { return (Byte) answer; } return new Byte(answer.byteValue()); } /** * Gets a Short from a Map in a null-safe manner. * <p> * The Short is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @return the value in the Map as a Short, <code>null</code> if null map input */ public static Short getShort(final Map map, final Object key) { Number answer = getNumber(map, key); if (answer == null) { return null; } else if (answer instanceof Short) { return (Short) answer; } return new Short(answer.shortValue()); } /** * Gets a Integer from a Map in a null-safe manner. * <p> * The Integer is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @return the value in the Map as a Integer, <code>null</code> if null map input */ public static Integer getInteger(final Map map, final Object key) { Number answer = getNumber(map, key); if (answer == null) { return null; } else if (answer instanceof Integer) { return (Integer) answer; } return new Integer(answer.intValue()); } /** * Gets a Long from a Map in a null-safe manner. * <p> * The Long is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @return the value in the Map as a Long, <code>null</code> if null map input */ public static Long getLong(final Map map, final Object key) { Number answer = getNumber(map, key); if (answer == null) { return null; } else if (answer instanceof Long) { return (Long) answer; } return new Long(answer.longValue()); } /** * Gets a Float from a Map in a null-safe manner. * <p> * The Float is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @return the value in the Map as a Float, <code>null</code> if null map input */ public static Float getFloat(final Map map, final Object key) { Number answer = getNumber(map, key); if (answer == null) { return null; } else if (answer instanceof Float) { return (Float) answer; } return new Float(answer.floatValue()); } /** * Gets a Double from a Map in a null-safe manner. * <p> * The Double is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @return the value in the Map as a Double, <code>null</code> if null map input */ public static Double getDouble(final Map map, final Object key) { Number answer = getNumber(map, key); if (answer == null) { return null; } else if (answer instanceof Double) { return (Double) answer; } return new Double(answer.doubleValue()); } /** * Gets a Map from a Map in a null-safe manner. * <p> * If the value returned from the specified map is not a Map then * <code>null</code> is returned. * * @param map the map to use * @param key the key to look up * @return the value in the Map as a Map, <code>null</code> if null map input */ public static Map getMap(final Map map, final Object key) { if (map != null) { Object answer = map.get(key); if (answer != null && answer instanceof Map) { return (Map) answer; } } return null; } // Type safe getters with default values //------------------------------------------------------------------------- /** * Looks up the given key in the given map, converting null into the * given default value. * * @param map the map whose value to look up * @param key the key of the value to look up in that map * @param defaultValue what to return if the value is null * @return the value in the map, or defaultValue if the original value * is null or the map is null */ public static Object getObject( Map map, Object key, Object defaultValue ) { if ( map != null ) { Object answer = map.get( key ); if ( answer != null ) { return answer; } } return defaultValue; } /** * Looks up the given key in the given map, converting the result into * a string, using the default value if the the conversion fails. * * @param map the map whose value to look up * @param key the key of the value to look up in that map * @param defaultValue what to return if the value is null or if the * conversion fails * @return the value in the map as a string, or defaultValue if the * original value is null, the map is null or the string conversion * fails */ public static String getString( Map map, Object key, String defaultValue ) { String answer = getString( map, key ); if ( answer == null ) { answer = defaultValue; } return answer; } /** * Looks up the given key in the given map, converting the result into * a boolean, using the default value if the the conversion fails. * * @param map the map whose value to look up * @param key the key of the value to look up in that map * @param defaultValue what to return if the value is null or if the * conversion fails * @return the value in the map as a boolean, or defaultValue if the * original value is null, the map is null or the boolean conversion * fails */ public static Boolean getBoolean( Map map, Object key, Boolean defaultValue ) { Boolean answer = getBoolean( map, key ); if ( answer == null ) { answer = defaultValue; } return answer; } /** * Looks up the given key in the given map, converting the result into * a number, using the default value if the the conversion fails. * * @param map the map whose value to look up * @param key the key of the value to look up in that map * @param defaultValue what to return if the value is null or if the * conversion fails * @return the value in the map as a number, or defaultValue if the * original value is null, the map is null or the number conversion * fails */ public static Number getNumber( Map map, Object key, Number defaultValue ) { Number answer = getNumber( map, key ); if ( answer == null ) { answer = defaultValue; } return answer; } /** * Looks up the given key in the given map, converting the result into * a byte, using the default value if the the conversion fails. * * @param map the map whose value to look up * @param key the key of the value to look up in that map * @param defaultValue what to return if the value is null or if the * conversion fails * @return the value in the map as a number, or defaultValue if the * original value is null, the map is null or the number conversion * fails */ public static Byte getByte( Map map, Object key, Byte defaultValue ) { Byte answer = getByte( map, key ); if ( answer == null ) { answer = defaultValue; } return answer; } /** * Looks up the given key in the given map, converting the result into * a short, using the default value if the the conversion fails. * * @param map the map whose value to look up * @param key the key of the value to look up in that map * @param defaultValue what to return if the value is null or if the * conversion fails * @return the value in the map as a number, or defaultValue if the * original value is null, the map is null or the number conversion * fails */ public static Short getShort( Map map, Object key, Short defaultValue ) { Short answer = getShort( map, key ); if ( answer == null ) { answer = defaultValue; } return answer; } /** * Looks up the given key in the given map, converting the result into * an integer, using the default value if the the conversion fails. * * @param map the map whose value to look up * @param key the key of the value to look up in that map * @param defaultValue what to return if the value is null or if the * conversion fails * @return the value in the map as a number, or defaultValue if the * original value is null, the map is null or the number conversion * fails */ public static Integer getInteger( Map map, Object key, Integer defaultValue ) { Integer answer = getInteger( map, key ); if ( answer == null ) { answer = defaultValue; } return answer; } /** * Looks up the given key in the given map, converting the result into * a long, using the default value if the the conversion fails. * * @param map the map whose value to look up * @param key the key of the value to look up in that map * @param defaultValue what to return if the value is null or if the * conversion fails * @return the value in the map as a number, or defaultValue if the * original value is null, the map is null or the number conversion * fails */ public static Long getLong( Map map, Object key, Long defaultValue ) { Long answer = getLong( map, key ); if ( answer == null ) { answer = defaultValue; } return answer; } /** * Looks up the given key in the given map, converting the result into * a float, using the default value if the the conversion fails. * * @param map the map whose value to look up * @param key the key of the value to look up in that map * @param defaultValue what to return if the value is null or if the * conversion fails * @return the value in the map as a number, or defaultValue if the * original value is null, the map is null or the number conversion * fails */ public static Float getFloat( Map map, Object key, Float defaultValue ) { Float answer = getFloat( map, key ); if ( answer == null ) { answer = defaultValue; } return answer; } /** * Looks up the given key in the given map, converting the result into * a double, using the default value if the the conversion fails. * * @param map the map whose value to look up * @param key the key of the value to look up in that map * @param defaultValue what to return if the value is null or if the * conversion fails * @return the value in the map as a number, or defaultValue if the * original value is null, the map is null or the number conversion * fails */ public static Double getDouble( Map map, Object key, Double defaultValue ) { Double answer = getDouble( map, key ); if ( answer == null ) { answer = defaultValue; } return answer; } /** * Looks up the given key in the given map, converting the result into * a map, using the default value if the the conversion fails. * * @param map the map whose value to look up * @param key the key of the value to look up in that map * @param defaultValue what to return if the value is null or if the * conversion fails * @return the value in the map as a number, or defaultValue if the * original value is null, the map is null or the map conversion * fails */ public static Map getMap( Map map, Object key, Map defaultValue ) { Map answer = getMap( map, key ); if ( answer == null ) { answer = defaultValue; } return answer; } // Type safe primitive getters //------------------------------------------------------------------------- /** * Gets a boolean from a Map in a null-safe manner. * <p> * If the value is a <code>Boolean</code> its value is returned. * If the value is a <code>String</code> and it equals 'true' ignoring case * then <code>true</code> is returned, otherwise <code>false</code>. * If the value is a <code>Number</code> an integer zero value returns * <code>false</code> and non-zero returns <code>true</code>. * Otherwise, <code>false</code> is returned. * * @param map the map to use * @param key the key to look up * @return the value in the Map as a Boolean, <code>false</code> if null map input */ public static boolean getBooleanValue(final Map map, final Object key) { Boolean booleanObject = getBoolean(map, key); if (booleanObject == null) { return false; } return booleanObject.booleanValue(); } /** * Gets a byte from a Map in a null-safe manner. * <p> * The byte is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @return the value in the Map as a byte, <code>0</code> if null map input */ public static byte getByteValue(final Map map, final Object key) { Byte byteObject = getByte(map, key); if (byteObject == null) { return 0; } return byteObject.byteValue(); } /** * Gets a short from a Map in a null-safe manner. * <p> * The short is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @return the value in the Map as a short, <code>0</code> if null map input */ public static short getShortValue(final Map map, final Object key) { Short shortObject = getShort(map, key); if (shortObject == null) { return 0; } return shortObject.shortValue(); } /** * Gets an int from a Map in a null-safe manner. * <p> * The int is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @return the value in the Map as an int, <code>0</code> if null map input */ public static int getIntValue(final Map map, final Object key) { Integer integerObject = getInteger(map, key); if (integerObject == null) { return 0; } return integerObject.intValue(); } /** * Gets a long from a Map in a null-safe manner. * <p> * The long is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @return the value in the Map as a long, <code>0L</code> if null map input */ public static long getLongValue(final Map map, final Object key) { Long longObject = getLong(map, key); if (longObject == null) { return 0L; } return longObject.longValue(); } /** * Gets a float from a Map in a null-safe manner. * <p> * The float is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @return the value in the Map as a float, <code>0.0F</code> if null map input */ public static float getFloatValue(final Map map, final Object key) { Float floatObject = getFloat(map, key); if (floatObject == null) { return 0f; } return floatObject.floatValue(); } /** * Gets a double from a Map in a null-safe manner. * <p> * The double is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @return the value in the Map as a double, <code>0.0</code> if null map input */ public static double getDoubleValue(final Map map, final Object key) { Double doubleObject = getDouble(map, key); if (doubleObject == null) { return 0d; } return doubleObject.doubleValue(); } // Type safe primitive getters with default values //------------------------------------------------------------------------- /** * Gets a boolean from a Map in a null-safe manner, * using the default value if the the conversion fails. * <p> * If the value is a <code>Boolean</code> its value is returned. * If the value is a <code>String</code> and it equals 'true' ignoring case * then <code>true</code> is returned, otherwise <code>false</code>. * If the value is a <code>Number</code> an integer zero value returns * <code>false</code> and non-zero returns <code>true</code>. * Otherwise, <code>defaultValue</code> is returned. * * @param map the map to use * @param key the key to look up * @param defaultValue return if the value is null or if the * conversion fails * @return the value in the Map as a Boolean, <code>defaultValue</code> if null map input */ public static boolean getBooleanValue(final Map map, final Object key, boolean defaultValue) { Boolean booleanObject = getBoolean(map, key); if (booleanObject == null) { return defaultValue; } return booleanObject.booleanValue(); } /** * Gets a byte from a Map in a null-safe manner, * using the default value if the the conversion fails. * <p> * The byte is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @param defaultValue return if the value is null or if the * conversion fails * @return the value in the Map as a byte, <code>defaultValue</code> if null map input */ public static byte getByteValue(final Map map, final Object key, byte defaultValue) { Byte byteObject = getByte(map, key); if (byteObject == null) { return defaultValue; } return byteObject.byteValue(); } /** * Gets a short from a Map in a null-safe manner, * using the default value if the the conversion fails. * <p> * The short is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @param defaultValue return if the value is null or if the * conversion fails * @return the value in the Map as a short, <code>defaultValue</code> if null map input */ public static short getShortValue(final Map map, final Object key, short defaultValue) { Short shortObject = getShort(map, key); if (shortObject == null) { return defaultValue; } return shortObject.shortValue(); } /** * Gets an int from a Map in a null-safe manner, * using the default value if the the conversion fails. * <p> * The int is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @param defaultValue return if the value is null or if the * conversion fails * @return the value in the Map as an int, <code>defaultValue</code> if null map input */ public static int getIntValue(final Map map, final Object key, int defaultValue) { Integer integerObject = getInteger(map, key); if (integerObject == null) { return defaultValue; } return integerObject.intValue(); } /** * Gets a long from a Map in a null-safe manner, * using the default value if the the conversion fails. * <p> * The long is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @param defaultValue return if the value is null or if the * conversion fails * @return the value in the Map as a long, <code>defaultValue</code> if null map input */ public static long getLongValue(final Map map, final Object key, long defaultValue) { Long longObject = getLong(map, key); if (longObject == null) { return defaultValue; } return longObject.longValue(); } /** * Gets a float from a Map in a null-safe manner, * using the default value if the the conversion fails. * <p> * The float is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @param defaultValue return if the value is null or if the * conversion fails * @return the value in the Map as a float, <code>defaultValue</code> if null map input */ public static float getFloatValue(final Map map, final Object key, float defaultValue) { Float floatObject = getFloat(map, key); if (floatObject == null) { return defaultValue; } return floatObject.floatValue(); } /** * Gets a double from a Map in a null-safe manner, * using the default value if the the conversion fails. * <p> * The double is obtained from the results of {@link #getNumber(Map,Object)}. * * @param map the map to use * @param key the key to look up * @param defaultValue return if the value is null or if the * conversion fails * @return the value in the Map as a double, <code>defaultValue</code> if null map input */ public static double getDoubleValue(final Map map, final Object key, double defaultValue) { Double doubleObject = getDouble(map, key); if (doubleObject == null) { return defaultValue; } return doubleObject.doubleValue(); } // Conversion methods //------------------------------------------------------------------------- /** * Gets a new Properties object initialised with the values from a Map. * A null input will return an empty properties object. * * @param map the map to convert to a Properties object, may not be null * @return the properties object */ public static Properties toProperties(final Map map) { Properties answer = new Properties(); if (map != null) { for (Iterator iter = map.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); Object key = entry.getKey(); Object value = entry.getValue(); answer.put(key, value); } } return answer; } /** * Creates a new HashMap using data copied from a ResourceBundle. * * @param resourceBundle the resource bundle to convert, may not be null * @return the hashmap containing the data * @throws NullPointerException if the bundle is null */ public static Map toMap(final ResourceBundle resourceBundle) { Enumeration enumeration = resourceBundle.getKeys(); Map map = new HashMap(); while (enumeration.hasMoreElements()) { String key = (String) enumeration.nextElement(); Object value = resourceBundle.getObject(key); map.put(key, value); } return map; } // Printing methods //------------------------------------------------------------------------- /** * Prints the given map with nice line breaks. * <p> * This method prints a nicely formatted String describing the Map. * Each map entry will be printed with key and value. * When the value is a Map, recursive behaviour occurs. * <p> * This method is NOT thread-safe in any special way. You must manually * synchronize on either this class or the stream as required. * * @param out the stream to print to, must not be null * @param label The label to be used, may be <code>null</code>. * If <code>null</code>, the label is not output. * It typically represents the name of the property in a bean or similar. * @param map The map to print, may be <code>null</code>. * If <code>null</code>, the text 'null' is output. * @throws NullPointerException if the stream is <code>null</code> */ public static void verbosePrint( final PrintStream out, final Object label, final Map map) { verbosePrintInternal(out, label, map, new ArrayStack(), false); } /** * Prints the given map with nice line breaks. * <p> * This method prints a nicely formatted String describing the Map. * Each map entry will be printed with key, value and value classname. * When the value is a Map, recursive behaviour occurs. * <p> * This method is NOT thread-safe in any special way. You must manually * synchronize on either this class or the stream as required. * * @param out the stream to print to, must not be null * @param label The label to be used, may be <code>null</code>. * If <code>null</code>, the label is not output. * It typically represents the name of the property in a bean or similar. * @param map The map to print, may be <code>null</code>. * If <code>null</code>, the text 'null' is output. * @throws NullPointerException if the stream is <code>null</code> */ public static void debugPrint( final PrintStream out, final Object label, final Map map) { verbosePrintInternal(out, label, map, new ArrayStack(), true); } // Implementation methods //------------------------------------------------------------------------- /** * Logs the given exception to <code>System.out</code>. * <p> * This method exists as Jakarta Collections does not depend on logging. * * @param ex the exception to log */ protected static void logInfo(final Exception ex) { System.out.println("INFO: Exception: " + ex); } /** * Implementation providing functionality for {@link #debugPrint} and for * {@link #verbosePrint}. This prints the given map with nice line breaks. * If the debug flag is true, it additionally prints the type of the object * value. If the contents of a map include the map itself, then the text * <em>(this Map)</em> is printed out. If the contents include a * parent container of the map, the the text <em>(ancestor[i] Map)</em> is * printed, where i actually indicates the number of levels which must be * traversed in the sequential list of ancestors (e.g. father, grandfather, * great-grandfather, etc). * * @param out the stream to print to * @param label the label to be used, may be <code>null</code>. * If <code>null</code>, the label is not output. * It typically represents the name of the property in a bean or similar. * @param map the map to print, may be <code>null</code>. * If <code>null</code>, the text 'null' is output * @param lineage a stack consisting of any maps in which the previous * argument is contained. This is checked to avoid infinite recursion when * printing the output * @param debug flag indicating whether type names should be output. * @throws NullPointerException if the stream is <code>null</code> */ private static void verbosePrintInternal( final PrintStream out, final Object label, final Map map, final ArrayStack lineage, final boolean debug) { printIndent(out, lineage.size()); if (map == null) { if (label != null) { out.print(label); out.print(" = "); } out.println("null"); return; } if (label != null) { out.print(label); out.println(" = "); } printIndent(out, lineage.size()); out.println("{"); lineage.push(map); for (Iterator it = map.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); Object childKey = entry.getKey(); Object childValue = entry.getValue(); if (childValue instanceof Map && !lineage.contains(childValue)) { verbosePrintInternal( out, (childKey == null ? "null" : childKey), (Map) childValue, lineage, debug); } else { printIndent(out, lineage.size()); out.print(childKey); out.print(" = "); final int lineageIndex = lineage.indexOf(childValue); if (lineageIndex == -1) { out.print(childValue); } else if (lineage.size() - 1 == lineageIndex) { out.print("(this Map)"); } else { out.print( "(ancestor[" + (lineage.size() - 1 - lineageIndex - 1) + "] Map)"); } if (debug && childValue != null) { out.print(' '); out.println(childValue.getClass().getName()); } else { out.println(); } } } lineage.pop(); printIndent(out, lineage.size()); out.println(debug ? "} " + map.getClass().getName() : "}"); } /** * Writes indentation to the given stream. * * @param out the stream to indent */ private static void printIndent(final PrintStream out, final int indent) { for (int i = 0; i < indent; i++) { out.print(INDENT_STRING); } } // Misc //----------------------------------------------------------------------- /** * Inverts the supplied map returning a new HashMap such that the keys of * the input are swapped with the values. * <p> * This operation assumes that the inverse mapping is well defined. * If the input map had multiple entries with the same value mapped to * different keys, the returned map will map one of those keys to the * value, but the exact key which will be mapped is undefined. * * @param map the map to invert, may not be null * @return a new HashMap containing the inverted data * @throws NullPointerException if the map is null */ public static Map invertMap(Map map) { Map out = new HashMap(map.size()); for (Iterator it = map.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); out.put(entry.getValue(), entry.getKey()); } return out; } //----------------------------------------------------------------------- /** * Protects against adding null values to a map. * <p> * This method checks the value being added to the map, and if it is null * it is replaced by an empty string. * <p> * This could be useful if the map does not accept null values, or for * receiving data from a source that may provide null or empty string * which should be held in the same way in the map. * <p> * Keys are not validated. * * @param map the map to add to, may not be null * @param key the key * @param value the value, null converted to "" * @throws NullPointerException if the map is null */ public static void safeAddToMap(Map map, Object key, Object value) throws NullPointerException { if (value == null) { map.put(key, ""); } else { map.put(key, value); } } //----------------------------------------------------------------------- /** * Puts all the keys and values from the specified array into the map. * <p> * This method is an alternative to the {@link java.util.Map#putAll(java.util.Map)} * method and constructors. It allows you to build a map from an object array * of various possible styles. * <p> * If the first entry in the object array implements {@link java.util.Map.Entry} * or {@link KeyValue} then the key and value are added from that object. * If the first entry in the object array is an object array itself, then * it is assumed that index 0 in the sub-array is the key and index 1 is the value. * Otherwise, the array is treated as keys and values in alternate indices. * <p> * For example, to create a color map: * <pre> * Map colorMap = MapUtils.putAll(new HashMap(), new String[][] { * {"RED", "#FF0000"}, * {"GREEN", "#00FF00"}, * {"BLUE", "#0000FF"} * }); * </pre> * or: * <pre> * Map colorMap = MapUtils.putAll(new HashMap(), new String[] { * "RED", "#FF0000", * "GREEN", "#00FF00", * "BLUE", "#0000FF" * }); * </pre> * or: * <pre> * Map colorMap = MapUtils.putAll(new HashMap(), new Map.Entry[] { * new DefaultMapEntry("RED", "#FF0000"), * new DefaultMapEntry("GREEN", "#00FF00"), * new DefaultMapEntry("BLUE", "#0000FF") * }); * </pre> * * @param map the map to populate, must not be null * @param array an array to populate from, null ignored * @return the input map * @throws NullPointerException if map is null * @throws IllegalArgumentException if sub-array or entry matching used and an * entry is invalid * @throws ClassCastException if the array contents is mixed * @since Commons Collections 3.2 */ public static Map putAll(Map map, Object[] array) { map.size(); // force NPE if (array == null || array.length == 0) { return map; } Object obj = array[0]; if (obj instanceof Map.Entry) { for (int i = 0; i < array.length; i++) { Map.Entry entry = (Map.Entry) array[i]; map.put(entry.getKey(), entry.getValue()); } } else if (obj instanceof KeyValue) { for (int i = 0; i < array.length; i++) { KeyValue keyval = (KeyValue) array[i]; map.put(keyval.getKey(), keyval.getValue()); } } else if (obj instanceof Object[]) { for (int i = 0; i < array.length; i++) { Object[] sub = (Object[]) array[i]; if (sub == null || sub.length < 2) { throw new IllegalArgumentException("Invalid array element: " + i); } map.put(sub[0], sub[1]); } } else { for (int i = 0; i < array.length - 1;) { map.put(array[i++], array[i++]); } } return map; } //----------------------------------------------------------------------- /** * Null-safe check if the specified map is empty. * <p> * Null returns true. * * @param map the map to check, may be null * @return true if empty or null * @since Commons Collections 3.2 */ public static boolean isEmpty(Map map) { return (map == null || map.isEmpty()); } /** * Null-safe check if the specified map is not empty. * <p> * Null returns false. * * @param map the map to check, may be null * @return true if non-null and non-empty * @since Commons Collections 3.2 */ public static boolean isNotEmpty(Map map) { return !MapUtils.isEmpty(map); } // Map decorators //----------------------------------------------------------------------- /** * Returns a synchronized map backed by the given map. * <p> * You must manually synchronize on the returned buffer's iterator to * avoid non-deterministic behavior: * * <pre> * Map m = MapUtils.synchronizedMap(myMap); * Set s = m.keySet(); // outside synchronized block * synchronized (m) { // synchronized on MAP! * Iterator i = s.iterator(); * while (i.hasNext()) { * process (i.next()); * } * } * </pre> * * This method uses the implementation in {@link java.util.Collections Collections}. * * @param map the map to synchronize, must not be null * @return a synchronized map backed by the given map * @throws IllegalArgumentException if the map is null */ public static Map synchronizedMap(Map map) { return Collections.synchronizedMap(map); } /** * Returns an unmodifiable map backed by the given map. * <p> * This method uses the implementation in the decorators subpackage. * * @param map the map to make unmodifiable, must not be null * @return an unmodifiable map backed by the given map * @throws IllegalArgumentException if the map is null */ public static Map unmodifiableMap(Map map) { return UnmodifiableMap.decorate(map); } /** * Returns a predicated (validating) map backed by the given map. * <p> * Only objects that pass the tests in the given predicates can be added to the map. * Trying to add an invalid object results in an IllegalArgumentException. * Keys must pass the key predicate, values must pass the value predicate. * It is important not to use the original map after invoking this method, * as it is a backdoor for adding invalid objects. * * @param map the map to predicate, must not be null * @param keyPred the predicate for keys, null means no check * @param valuePred the predicate for values, null means no check * @return a predicated map backed by the given map * @throws IllegalArgumentException if the Map is null */ public static Map predicatedMap(Map map, Predicate keyPred, Predicate valuePred) { return PredicatedMap.decorate(map, keyPred, valuePred); } /** * Returns a typed map backed by the given map. * <p> * Only keys and values of the specified types can be added to the map. * * @param map the map to limit to a specific type, must not be null * @param keyType the type of keys which may be added to the map, must not be null * @param valueType the type of values which may be added to the map, must not be null * @return a typed map backed by the specified map * @throws IllegalArgumentException if the Map or Class is null */ public static Map typedMap(Map map, Class keyType, Class valueType) { return TypedMap.decorate(map, keyType, valueType); } /** * Returns a transformed map backed by the given map. * <p> * This method returns a new map (decorating the specified map) that * will transform any new entries added to it. * Existing entries in the specified map will not be transformed. * If you want that behaviour, see {@link TransformedMap#decorateTransform}. * <p> * Each object is passed through the transformers as it is added to the * Map. It is important not to use the original map after invoking this * method, as it is a backdoor for adding untransformed objects. * <p> * If there are any elements already in the map being decorated, they * are NOT transformed. * * @param map the map to transform, must not be null, typically empty * @param keyTransformer the transformer for the map keys, null means no transformation * @param valueTransformer the transformer for the map values, null means no transformation * @return a transformed map backed by the given map * @throws IllegalArgumentException if the Map is null */ public static Map transformedMap(Map map, Transformer keyTransformer, Transformer valueTransformer) { return TransformedMap.decorate(map, keyTransformer, valueTransformer); } /** * Returns a fixed-sized map backed by the given map. * Elements may not be added or removed from the returned map, but * existing elements can be changed (for instance, via the * {@link Map#put(Object,Object)} method). * * @param map the map whose size to fix, must not be null * @return a fixed-size map backed by that map * @throws IllegalArgumentException if the Map is null */ public static Map fixedSizeMap(Map map) { return FixedSizeMap.decorate(map); } /** * Returns a "lazy" map whose values will be created on demand. * <p> * When the key passed to the returned map's {@link Map#get(Object)} * method is not present in the map, then the factory will be used * to create a new object and that object will become the value * associated with that key. * <p> * For instance: * <pre> * Factory factory = new Factory() { * public Object create() { * return new Date(); * } * } * Map lazyMap = MapUtils.lazyMap(new HashMap(), factory); * Object obj = lazyMap.get("test"); * </pre> * * After the above code is executed, <code>obj</code> will contain * a new <code>Date</code> instance. Furthermore, that <code>Date</code> * instance is the value for the <code>"test"</code> key in the map. * * @param map the map to make lazy, must not be null * @param factory the factory for creating new objects, must not be null * @return a lazy map backed by the given map * @throws IllegalArgumentException if the Map or Factory is null */ public static Map lazyMap(Map map, Factory factory) { return LazyMap.decorate(map, factory); } /** * Returns a "lazy" map whose values will be created on demand. * <p> * When the key passed to the returned map's {@link Map#get(Object)} * method is not present in the map, then the factory will be used * to create a new object and that object will become the value * associated with that key. The factory is a {@link Transformer} * that will be passed the key which it must transform into the value. * <p> * For instance: * <pre> * Transformer factory = new Transformer() { * public Object transform(Object mapKey) { * return new File(mapKey); * } * } * Map lazyMap = MapUtils.lazyMap(new HashMap(), factory); * Object obj = lazyMap.get("C:/dev"); * </pre> * * After the above code is executed, <code>obj</code> will contain * a new <code>File</code> instance for the C drive dev directory. * Furthermore, that <code>File</code> instance is the value for the * <code>"C:/dev"</code> key in the map. * <p> * If a lazy map is wrapped by a synchronized map, the result is a simple * synchronized cache. When an object is not is the cache, the cache itself * calls back to the factory Transformer to populate itself, all within the * same synchronized block. * * @param map the map to make lazy, must not be null * @param transformerFactory the factory for creating new objects, must not be null * @return a lazy map backed by the given map * @throws IllegalArgumentException if the Map or Transformer is null */ public static Map lazyMap(Map map, Transformer transformerFactory) { return LazyMap.decorate(map, transformerFactory); } /** * Returns a map that maintains the order of keys that are added * backed by the given map. * <p> * If a key is added twice, the order is determined by the first add. * The order is observed through the keySet, values and entrySet. * * @param map the map to order, must not be null * @return an ordered map backed by the given map * @throws IllegalArgumentException if the Map is null */ public static Map orderedMap(Map map) { return ListOrderedMap.decorate(map); } /** * Creates a mult-value map backed by the given map which returns * collections of type ArrayList. * * @param map the map to decorate * @return a multi-value map backed by the given map which returns ArrayLists of values. * @see MultiValueMap * @since Commons Collections 3.2 */ public static Map multiValueMap(Map map) { return MultiValueMap.decorate(map); } /** * Creates a multi-value map backed by the given map which returns * collections of the specified type. * * @param map the map to decorate * @param collectionClass the type of collections to return from the map (must contain public no-arg constructor * and extend Collection). * @return a multi-value map backed by the given map which returns collections of the specified type * @see MultiValueMap * @since Commons Collections 3.2 */ public static Map multiValueMap(Map map, Class collectionClass) { return MultiValueMap.decorate(map, collectionClass); } /** * Creates a multi-value map backed by the given map which returns * collections created by the specified collection factory. * * @param map the map to decorate * @param collectionFactory a factor which creates collection objects * @return a multi-value map backed by the given map which returns collections * created by the specified collection factory * @see MultiValueMap * @since Commons Collections 3.2 */ public static Map multiValueMap(Map map, Factory collectionFactory) { return MultiValueMap.decorate(map, collectionFactory); } // SortedMap decorators //----------------------------------------------------------------------- /** * Returns a synchronized sorted map backed by the given sorted map. * <p> * You must manually synchronize on the returned buffer's iterator to * avoid non-deterministic behavior: * * <pre> * Map m = MapUtils.synchronizedSortedMap(myMap); * Set s = m.keySet(); // outside synchronized block * synchronized (m) { // synchronized on MAP! * Iterator i = s.iterator(); * while (i.hasNext()) { * process (i.next()); * } * } * </pre> * * This method uses the implementation in {@link java.util.Collections Collections}. * * @param map the map to synchronize, must not be null * @return a synchronized map backed by the given map * @throws IllegalArgumentException if the map is null */ public static Map synchronizedSortedMap(SortedMap map) { return Collections.synchronizedSortedMap(map); } /** * Returns an unmodifiable sorted map backed by the given sorted map. * <p> * This method uses the implementation in the decorators subpackage. * * @param map the sorted map to make unmodifiable, must not be null * @return an unmodifiable map backed by the given map * @throws IllegalArgumentException if the map is null */ public static Map unmodifiableSortedMap(SortedMap map) { return UnmodifiableSortedMap.decorate(map); } /** * Returns a predicated (validating) sorted map backed by the given map. * <p> * Only objects that pass the tests in the given predicates can be added to the map. * Trying to add an invalid object results in an IllegalArgumentException. * Keys must pass the key predicate, values must pass the value predicate. * It is important not to use the original map after invoking this method, * as it is a backdoor for adding invalid objects. * * @param map the map to predicate, must not be null * @param keyPred the predicate for keys, null means no check * @param valuePred the predicate for values, null means no check * @return a predicated map backed by the given map * @throws IllegalArgumentException if the SortedMap is null */ public static SortedMap predicatedSortedMap(SortedMap map, Predicate keyPred, Predicate valuePred) { return PredicatedSortedMap.decorate(map, keyPred, valuePred); } /** * Returns a typed sorted map backed by the given map. * <p> * Only keys and values of the specified types can be added to the map. * * @param map the map to limit to a specific type, must not be null * @param keyType the type of keys which may be added to the map, must not be null * @param valueType the type of values which may be added to the map, must not be null * @return a typed map backed by the specified map */ public static SortedMap typedSortedMap(SortedMap map, Class keyType, Class valueType) { return TypedSortedMap.decorate(map, keyType, valueType); } /** * Returns a transformed sorted map backed by the given map. * <p> * This method returns a new sorted map (decorating the specified map) that * will transform any new entries added to it. * Existing entries in the specified map will not be transformed. * If you want that behaviour, see {@link TransformedSortedMap#decorateTransform}. * <p> * Each object is passed through the transformers as it is added to the * Map. It is important not to use the original map after invoking this * method, as it is a backdoor for adding untransformed objects. * <p> * If there are any elements already in the map being decorated, they * are NOT transformed. * * @param map the map to transform, must not be null, typically empty * @param keyTransformer the transformer for the map keys, null means no transformation * @param valueTransformer the transformer for the map values, null means no transformation * @return a transformed map backed by the given map * @throws IllegalArgumentException if the SortedMap is null */ public static SortedMap transformedSortedMap(SortedMap map, Transformer keyTransformer, Transformer valueTransformer) { return TransformedSortedMap.decorate(map, keyTransformer, valueTransformer); } /** * Returns a fixed-sized sorted map backed by the given sorted map. * Elements may not be added or removed from the returned map, but * existing elements can be changed (for instance, via the * {@link Map#put(Object,Object)} method). * * @param map the map whose size to fix, must not be null * @return a fixed-size map backed by that map * @throws IllegalArgumentException if the SortedMap is null */ public static SortedMap fixedSizeSortedMap(SortedMap map) { return FixedSizeSortedMap.decorate(map); } /** * Returns a "lazy" sorted map whose values will be created on demand. * <p> * When the key passed to the returned map's {@link Map#get(Object)} * method is not present in the map, then the factory will be used * to create a new object and that object will become the value * associated with that key. * <p> * For instance: * * <pre> * Factory factory = new Factory() { * public Object create() { * return new Date(); * } * } * SortedMap lazy = MapUtils.lazySortedMap(new TreeMap(), factory); * Object obj = lazy.get("test"); * </pre> * * After the above code is executed, <code>obj</code> will contain * a new <code>Date</code> instance. Furthermore, that <code>Date</code> * instance is the value for the <code>"test"</code> key. * * @param map the map to make lazy, must not be null * @param factory the factory for creating new objects, must not be null * @return a lazy map backed by the given map * @throws IllegalArgumentException if the SortedMap or Factory is null */ public static SortedMap lazySortedMap(SortedMap map, Factory factory) { return LazySortedMap.decorate(map, factory); } /** * Returns a "lazy" sorted map whose values will be created on demand. * <p> * When the key passed to the returned map's {@link Map#get(Object)} * method is not present in the map, then the factory will be used * to create a new object and that object will become the value * associated with that key. The factory is a {@link Transformer} * that will be passed the key which it must transform into the value. * <p> * For instance: * <pre> * Transformer factory = new Transformer() { * public Object transform(Object mapKey) { * return new File(mapKey); * } * } * SortedMap lazy = MapUtils.lazySortedMap(new TreeMap(), factory); * Object obj = lazy.get("C:/dev"); * </pre> * * After the above code is executed, <code>obj</code> will contain * a new <code>File</code> instance for the C drive dev directory. * Furthermore, that <code>File</code> instance is the value for the * <code>"C:/dev"</code> key in the map. * <p> * If a lazy map is wrapped by a synchronized map, the result is a simple * synchronized cache. When an object is not is the cache, the cache itself * calls back to the factory Transformer to populate itself, all within the * same synchronized block. * * @param map the map to make lazy, must not be null * @param transformerFactory the factory for creating new objects, must not be null * @return a lazy map backed by the given map * @throws IllegalArgumentException if the Map or Transformer is null */ public static SortedMap lazySortedMap(SortedMap map, Transformer transformerFactory) { return LazySortedMap.decorate(map, transformerFactory); } }
tootedom/tomcat-memcached-response-filter
src/main/java/org/greencheek/web/filter/memcached/io/ResizableByteBufferNoBoundsCheckingBackedOutputStream.java
<reponame>tootedom/tomcat-memcached-response-filter package org.greencheek.web.filter.memcached.io; import java.io.IOException; import java.io.OutputStream; import java.nio.BufferOverflowException; import java.nio.ByteBuffer; public class ResizableByteBufferNoBoundsCheckingBackedOutputStream extends OutputStream { private final ResizeableByteBuffer byteBuffer; public ResizableByteBufferNoBoundsCheckingBackedOutputStream(int initialCapacity) { this(initialCapacity,ResizeableByteBuffer.MAX_ARRAY_SIZE); } public ResizableByteBufferNoBoundsCheckingBackedOutputStream(int initialCapacity, int maxCapacity) { this.byteBuffer = new ResizeableByteBuffer(initialCapacity,maxCapacity); } public ResizeableByteBuffer getBuffer() { return byteBuffer; } public int size() { return byteBuffer.size(); } public void reset() { byteBuffer.reset(); } public byte[] getBuf() { return byteBuffer.getBuf(); } public byte[] toByteArray() { return byteBuffer.toByteArray(); } public ByteBuffer toByteBuffer() { return byteBuffer.toByteBuffer(); } public void append(byte b) { byteBuffer.append(b); if(!byteBuffer.canWrite()) { throw new BufferOverflowException(); } } public void append(byte[] bytes) { byteBuffer.append(bytes); if(!byteBuffer.canWrite()) { throw new BufferOverflowException(); } } public void append(byte[] b, int off, int len) { byteBuffer.append(b,off,len); if(!byteBuffer.canWrite()) { throw new BufferOverflowException(); } } @Override public void write(byte[] b, int off, int len) throws IOException { try { append(b, off, len); } catch(BufferOverflowException e) { throw new IOException(e.getMessage(),e); } } @Override public void write(int b) throws IOException { try { append((byte) b); } catch (BufferOverflowException e) { throw new IOException(e.getMessage(),e); } } @Override public void write(byte[] b) throws IOException { if(b==null) throw new NullPointerException(); write(b,0,b.length); } }
lijgame/boost
libs/tr1/test/test_unordered_map.cpp
<filename>libs/tr1/test/test_unordered_map.cpp<gh_stars>100-1000 // (C) Copyright <NAME> 2008. // Use, modification and distribution are subject to 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) // These are the headers included by the Boost.TR1 implementation, // by including these directly we probe for problems with cyclic // dependencies when the TR1 headers are in the include search path. #ifdef TEST_STD_HEADERS #include <unordered_map> #else #include <boost/tr1/unordered_map.hpp> #endif #include "unordered_concepts.hpp" #include "boost/concept_archetype.hpp" int main() { typedef boost::copy_constructible_archetype<boost::assignable_archetype<> > value_type; typedef boost::default_constructible_unary_function_archetype<value_type, std::size_t> func_type; typedef boost::default_constructible_binary_predicate_archetype<value_type, value_type> pred_type; typedef std::tr1::unordered_map<value_type, value_type, func_type, pred_type> hash_map_type; typedef std::tr1::unordered_multimap<value_type, value_type, func_type, pred_type> hash_multimap_type; boost::function_requires<boost::UniqueUnorderedContainer<hash_map_type> >(); boost::function_requires<boost::MultiUnorderedContainer<hash_multimap_type> >(); do{ // unordered_map specific functions: typedef hash_map_type::key_type key_type; typedef hash_map_type::hasher hasher; typedef hash_map_type::key_equal key_equal; typedef hash_map_type::local_iterator local_iterator; typedef hash_map_type::const_local_iterator const_local_iterator; typedef hash_map_type::value_type value_type; typedef hash_map_type::iterator iterator; typedef hash_map_type::const_iterator const_iterator; typedef hash_map_type::size_type size_type; typedef hash_map_type::allocator_type allocator_type; typedef boost::input_iterator_archetype<value_type> input_iterator; input_iterator i = boost::static_object<input_iterator>::get(); input_iterator j = i; size_type n = 1; const hasher& hf = boost::static_object<hasher>::get(); const key_equal& eq = boost::static_object<key_equal>::get(); //value_type const& t = boost::static_object<value_type>::get(); //key_type const& k = boost::static_object<key_type>::get(); allocator_type const& a = boost::static_object<allocator_type>::get(); hash_map_type x1(n, hf, eq, a); hash_map_type x2(i, j, n, hf, eq, a); swap(x1, x2); std::tr1::swap(x1, x2); }while(0); do{ // unordered_map specific functions: typedef hash_multimap_type::key_type key_type; typedef hash_multimap_type::hasher hasher; typedef hash_multimap_type::key_equal key_equal; typedef hash_multimap_type::local_iterator local_iterator; typedef hash_multimap_type::const_local_iterator const_local_iterator; typedef hash_multimap_type::value_type value_type; typedef hash_multimap_type::iterator iterator; typedef hash_multimap_type::const_iterator const_iterator; typedef hash_multimap_type::size_type size_type; typedef hash_multimap_type::allocator_type allocator_type; typedef boost::input_iterator_archetype<value_type> input_iterator; input_iterator i = boost::static_object<input_iterator>::get(); input_iterator j = i; size_type n = 1; const hasher& hf = boost::static_object<hasher>::get(); const key_equal& eq = boost::static_object<key_equal>::get(); //value_type const& t = boost::static_object<value_type>::get(); //key_type const& k = boost::static_object<key_type>::get(); allocator_type const& a = boost::static_object<allocator_type>::get(); hash_multimap_type x1(n, hf, eq, a); hash_multimap_type x2(i, j, n, hf, eq, a); swap(x1, x2); std::tr1::swap(x1, x2); }while(0); }
haizimen/STelephoneGoods
app/src/main/java/com/phone1000/stelephonegoods/activities/IdCardCertificationActivity.java
package com.phone1000.stelephonegoods.activities; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.phone1000.stelephonegoods.R; public class IdCardCertificationActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_id_card_certification); } }
solitardj9/timeline-service
timelineService/src/main/java/com/solitardj9/timelineService/application/timelineSyncManager/service/impl/TimelineSyncManagerImpl.java
package com.solitardj9.timelineService.application.timelineSyncManager.service.impl; import java.sql.Timestamp; import java.util.List; import java.util.TreeMap; import javax.annotation.PostConstruct; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.solitardj9.timelineService.application.replicationManager.service.ReplicationManager; import com.solitardj9.timelineService.application.timelineManager.model.PutValue; import com.solitardj9.timelineService.application.timelineManager.model.PutValues; import com.solitardj9.timelineService.application.timelineManager.model.Remove; import com.solitardj9.timelineService.application.timelineManager.model.RemoveByBefore; import com.solitardj9.timelineService.application.timelineManager.model.RemoveByPeriod; import com.solitardj9.timelineService.application.timelineManager.model.RemoveByTimes; import com.solitardj9.timelineService.application.timelineManager.service.TimelineManager; import com.solitardj9.timelineService.application.timelineManager.service.exception.ExceptionTimelineConflictFailure; import com.solitardj9.timelineService.application.timelineManager.service.exception.ExceptionTimelineInternalFailure; import com.solitardj9.timelineService.application.timelineManager.service.exception.ExceptionTimelineResourceNotFound; import com.solitardj9.timelineService.application.timelineSyncManager.service.TimelineSyncManager; import com.solitardj9.timelineService.application.timelineSyncManager.service.data.TimelineMetadata; import com.solitardj9.timelineService.application.timelineSyncManager.service.data.TimelineSyncManagerParamsEnum.TimelineClusterInfo; import com.solitardj9.timelineService.service.serviceInstancesManager.service.ServiceInstancesManager; import com.solitardj9.timelineService.systemInterface.httpInterface.service.HttpProxyAdaptor; import com.solitardj9.timelineService.systemInterface.inMemoryInterface.model.InMemoryInstance; import com.solitardj9.timelineService.systemInterface.inMemoryInterface.service.InMemoryManager; import com.solitardj9.timelineService.systemInterface.inMemoryInterface.service.impl.exception.ExceptionHazelcastDataStructureCreationFailure; import com.solitardj9.timelineService.systemInterface.inMemoryInterface.service.impl.exception.ExceptionHazelcastDataStructureNotFoundFailure; @Service("timelineSyncManager") public class TimelineSyncManagerImpl implements TimelineSyncManager { private static final Logger logger = LoggerFactory.getLogger(TimelineSyncManagerImpl.class); @Autowired TimelineManager timelineManager; @Autowired ReplicationManager replicationManager; @Autowired InMemoryManager inMemoryManager; @Autowired ServiceInstancesManager serviceInstancesManager; @Autowired HttpProxyAdaptor httpProxyAdaptor; private Integer backupCount = 2; private Boolean readBackupData = true; //private ObjectMapper om = new ObjectMapper(); @PostConstruct public void init() { // InMemoryInstance inMemoryInstance = new InMemoryInstance(TimelineClusterInfo.TIMELINE_METADATA.getMap(), backupCount, readBackupData, null, null); try { inMemoryManager.addMap(inMemoryInstance); } catch (ExceptionHazelcastDataStructureCreationFailure | ExceptionHazelcastDataStructureNotFoundFailure e) { logger.error("[TimelineSyncManager].init : error = " + e); } } /* private TimelineExistStatus exists(String timeline) { // if (!timelineManager.containTimeline(timeline)) { try { Boolean isExist = inMemoryManager.getMap(TimelineClusterInfo.TIMELINE_METADATA.getMap()).containsKey(timeline); if (isExist) { return TimelineExistStatus.CLUSTER; } else { return TimelineExistStatus.NONE; } } catch (ExceptionHazelcastDataStructureNotFoundFailure e) { logger.error("[TimelineSyncManager].isValidTimeline : error = " + e); return TimelineExistStatus.ERROR; } } return TimelineExistStatus.LOCAL; } private TreeMap<Long, String> getTimelineFromCluster(String timeline) throws ExceptionTimelineResourceNotFound { // Map<String, ServiceInstance> serviceInstances = serviceInstancesManager.getOnlineServiceInstancesWithoutMe(); ServiceInstance selectedServiceInstance = serviceInstances.get((serviceInstances.keySet().toArray())[0]); String scheme = "http"; String ip = selectedServiceInstance.getIp(); Integer port = selectedServiceInstance.getPort(); String url = ip + ":" + port.toString(); String path = "timeline-service/timelines/{timeline}/values"; path = path.replace("{timeline}", timeline); HttpHeaders headers = new HttpHeaders(); headers.add("Content-Type", "application/json"); Map<String, Object> queryParams = new HashMap<>(); queryParams.put("type", "get"); ResponseEntity<String> response = httpProxyAdaptor.executeHttpProxy(scheme, url, path, queryParams, HttpMethod.GET, headers, null); String responseBody = response.getBody(); TreeMap<Long, String> retMap = new TreeMap<>(); try { ResponseTimelineValues responseObj = om.readValue(responseBody, ResponseTimelineValues.class); if (responseObj.getStatus().equals(200)) { return responseObj.getValues(); } else { throw new ExceptionTimelineResourceNotFound(); } } catch (JsonProcessingException e) { logger.error("[TimelineSyncManager].getTimelineFromCluster : error = " + e); return retMap; } } //*/ @Override public void addTimeline(String timeline) throws ExceptionTimelineConflictFailure, ExceptionTimelineInternalFailure { // String addedTimeline = null; try { addedTimeline = timelineManager.addTimeline(timeline); } catch (ExceptionTimelineConflictFailure e) { throw new ExceptionTimelineConflictFailure(); } if (addedTimeline != null) { replicationManager.replicateAddTimeline(addedTimeline); TimelineMetadata timelineMetadata = new TimelineMetadata(addedTimeline, new Timestamp(System.currentTimeMillis())); try { inMemoryManager.getMap(TimelineClusterInfo.TIMELINE_METADATA.getMap()).put(addedTimeline, timelineMetadata); } catch (ExceptionHazelcastDataStructureNotFoundFailure e) { logger.error("[TimelineSyncManager].addTimeline : error = " + e); } } } @Override public void deleteTimeline(String timeline) throws ExceptionTimelineResourceNotFound { // String deletedTimeline = null; try { deletedTimeline = timelineManager.deleteTimeline(timeline); } catch (ExceptionTimelineResourceNotFound e) { throw new ExceptionTimelineResourceNotFound(); } if (deletedTimeline != null) { replicationManager.replicateDeleteTimeline(deletedTimeline); } } @Override public void put(String timeline, Long time, String value) throws ExceptionTimelineResourceNotFound, ExceptionTimelineInternalFailure { // PutValue puttedValue = null; try { puttedValue = timelineManager.put(timeline, time, value); } catch (ExceptionTimelineResourceNotFound e) { throw new ExceptionTimelineResourceNotFound(); } catch (ExceptionTimelineInternalFailure e) { throw new ExceptionTimelineInternalFailure(); } if (puttedValue != null) { replicationManager.replicatePut(puttedValue); } } @Override public void putAll(String timeline, TreeMap<Long, String> values) throws ExceptionTimelineResourceNotFound, ExceptionTimelineInternalFailure { // PutValues puttedValues = null; try { puttedValues = timelineManager.putAll(timeline, values); } catch (ExceptionTimelineResourceNotFound e) { throw new ExceptionTimelineResourceNotFound(); } catch (ExceptionTimelineInternalFailure e) { throw new ExceptionTimelineInternalFailure(); } if (puttedValues != null) { replicationManager.replicatePutAll(puttedValues); } } @Override public void update(String timeline, Long time, String value) throws ExceptionTimelineResourceNotFound, ExceptionTimelineInternalFailure { // PutValue updatedValue = null; try { updatedValue = timelineManager.update(timeline, time, value); } catch (ExceptionTimelineResourceNotFound e) { throw new ExceptionTimelineResourceNotFound(); } catch (ExceptionTimelineInternalFailure e) { throw new ExceptionTimelineInternalFailure(); } if (updatedValue != null) { replicationManager.replicateUpdate(updatedValue); } } @Override public void updateAll(String timeline, TreeMap<Long, String> values) throws ExceptionTimelineResourceNotFound, ExceptionTimelineInternalFailure { // PutValues updatedValues = null; try { updatedValues = timelineManager.updateAll(timeline, values); } catch (ExceptionTimelineResourceNotFound e) { throw new ExceptionTimelineResourceNotFound(); } catch (ExceptionTimelineInternalFailure e) { throw new ExceptionTimelineInternalFailure(); } if (updatedValues != null) { replicationManager.replicateUpdateAll(updatedValues); } } @Override public void remove(String timeline, Long time) throws ExceptionTimelineResourceNotFound, ExceptionTimelineInternalFailure { // Remove removed = null; try { removed = timelineManager.remove(timeline, time); } catch (ExceptionTimelineResourceNotFound e) { throw new ExceptionTimelineResourceNotFound(); } catch (ExceptionTimelineInternalFailure e) { throw new ExceptionTimelineInternalFailure(); } if (removed != null) { replicationManager.replicateRemove(removed); } } @Override public void removeByTimes(String timeline, List<Long> times) throws ExceptionTimelineResourceNotFound, ExceptionTimelineInternalFailure { // RemoveByTimes removedByTimes = null; try { removedByTimes = timelineManager.removeByTimes(timeline, times); } catch (ExceptionTimelineResourceNotFound e) { throw new ExceptionTimelineResourceNotFound(); } catch (ExceptionTimelineInternalFailure e) { throw new ExceptionTimelineInternalFailure(); } if (removedByTimes != null) { replicationManager.replicateRemoveByTimes(removedByTimes); } } @Override public void removeByPeriod(String timeline, Long fromTime, Long toTime) throws ExceptionTimelineResourceNotFound { // RemoveByPeriod removedByPeriod = null; try { removedByPeriod = timelineManager.removeByPeriod(timeline, fromTime, toTime); } catch (ExceptionTimelineResourceNotFound e) { throw new ExceptionTimelineResourceNotFound(); } if (removedByPeriod != null) { replicationManager.replicateRemoveByPeriod(removedByPeriod); } } @Override public void removeByBefore(String timeline, Long toTime) throws ExceptionTimelineResourceNotFound { // RemoveByBefore removedByBefore = null; try { removedByBefore = timelineManager.removeByBefore(timeline, toTime); } catch (ExceptionTimelineResourceNotFound e) { throw new ExceptionTimelineResourceNotFound(); } if (removedByBefore != null) { replicationManager.replicateRemoveByBefore(removedByBefore); } } @Override public void clear(String timeline) throws ExceptionTimelineResourceNotFound, ExceptionTimelineInternalFailure { // String clearedTmeline = null; try { clearedTmeline = timelineManager.clear(timeline); } catch (ExceptionTimelineResourceNotFound e) { throw new ExceptionTimelineResourceNotFound(); } catch (ExceptionTimelineInternalFailure e) { throw new ExceptionTimelineInternalFailure(); } if (clearedTmeline != null) { replicationManager.replicateClear(clearedTmeline); } } }
krynju/openmct
src/plugins/summaryWidget/test/ConditionEvaluatorSpec.js
define(['../src/ConditionEvaluator'], function (ConditionEvaluator) { describe('A Summary Widget Rule Evaluator', function () { var evaluator, testEvaluator, testOperation, mockCache, mockTestCache, mockComposition, mockConditions, mockConditionsEmpty, mockConditionsUndefined, mockConditionsAnyTrue, mockConditionsAllTrue, mockConditionsAnyFalse, mockConditionsAllFalse, mockOperations; beforeEach(function () { mockCache = { a: { alpha: 3, beta: 9, gamma: 'Testing 1 2 3' }, b: { alpha: 44, beta: 23, gamma: 'Hello World' }, c: { foo: 'bar', iAm: 'The Walrus', creature: { type: 'Centaur' } } }; mockTestCache = { a: { alpha: 1, beta: 1, gamma: 'Testing 4 5 6' }, b: { alpha: 2, beta: 2, gamma: 'Goodbye world' } }; mockComposition = { a: {}, b: {}, c: {} }; mockConditions = [{ object: 'a', key: 'alpha', operation: 'greaterThan', values: [2] },{ object: 'b', key: 'gamma', operation: 'lessThan', values: [5] }]; mockConditionsEmpty = [{ object: '', key: '', operation: '', values: [] }]; mockConditionsUndefined = [{ object: 'No Such Object', key: '', operation: '', values: [] },{ object: 'a', key: 'No Such Key', operation: '', values: [] },{ object: 'a', key: 'alpha', operation: 'No Such Operation', values: [] },{ object: 'all', key: 'Nonexistent Field', operation: 'Random Operation', values: [] },{ object: 'any', key: 'Nonexistent Field', operation: 'Whatever Operation', values: [] }]; mockConditionsAnyTrue = [{ object: 'any', key: 'alpha', operation: 'greaterThan', values: [5] }]; mockConditionsAnyFalse = [{ object: 'any', key: 'alpha', operation: 'greaterThan', values: [1000] }]; mockConditionsAllFalse = [{ object: 'all', key: 'alpha', operation: 'greaterThan', values: [5] }]; mockConditionsAllTrue = [{ object: 'all', key: 'alpha', operation: 'greaterThan', values: [0] }]; mockOperations = { greaterThan: { operation: function (input) { return input[0] > input[1]; }, text: 'is greater than', appliesTo: ['number'], inputCount: 1, getDescription: function (values) { return ' > ' + values [0]; } }, lessThan: { operation: function (input) { return input[0] < input[1]; }, text: 'is less than', appliesTo: ['number'], inputCount: 1 }, textContains: { operation: function (input) { return input[0] && input[1] && input[0].includes(input[1]); }, text: 'text contains', appliesTo: ['string'], inputCount: 1 }, textIsExactly: { operation: function (input) { return input[0] === input[1]; }, text: 'text is exactly', appliesTo: ['string'], inputCount: 1 }, isHalfHorse: { operation: function (input) { return input[0].type === 'Centaur'; }, text: 'is Half Horse', appliesTo: ['mythicalCreature'], inputCount: 0, getDescription: function () { return 'is half horse'; } } }; evaluator = new ConditionEvaluator(mockCache, mockComposition); testEvaluator = new ConditionEvaluator(mockCache, mockComposition); evaluator.operations = mockOperations; }); it('evaluates a condition when it has no configuration', function () { expect(evaluator.execute(mockConditionsEmpty, 'any')).toEqual(false); expect(evaluator.execute(mockConditionsEmpty, 'all')).toEqual(false); }); it('correctly evaluates a set of conditions', function () { expect(evaluator.execute(mockConditions, 'any')).toEqual(true); expect(evaluator.execute(mockConditions, 'all')).toEqual(false); }); it('correctly evaluates conditions involving "any telemetry"', function () { expect(evaluator.execute(mockConditionsAnyTrue, 'any')).toEqual(true); expect(evaluator.execute(mockConditionsAnyFalse, 'any')).toEqual(false); }); it('correctly evaluates conditions involving "all telemetry"', function () { expect(evaluator.execute(mockConditionsAllTrue, 'any')).toEqual(true); expect(evaluator.execute(mockConditionsAllFalse, 'any')).toEqual(false); }); it('handles malformed conditions gracefully', function () { //if no conditions are fully defined, should return false for any mode expect(evaluator.execute(mockConditionsUndefined, 'any')).toEqual(false); expect(evaluator.execute(mockConditionsUndefined, 'all')).toEqual(false); //these conditions are true: evaluator should ignore undefined conditions, //and evaluate the rule as true mockConditionsUndefined.push({ object: 'a', key: 'gamma', operation: 'textContains', values: ['Testing'] }); expect(evaluator.execute(mockConditionsUndefined, 'any')).toEqual(true); mockConditionsUndefined.push({ object: 'c', key: 'iAm', operation: 'textContains', values: ['Walrus'] }); expect(evaluator.execute(mockConditionsUndefined, 'all')).toEqual(true); }); it('gets the keys for possible operations', function () { expect(evaluator.getOperationKeys()).toEqual( ['greaterThan', 'lessThan', 'textContains', 'textIsExactly', 'isHalfHorse'] ); }); it('gets output text for a given operation', function () { expect(evaluator.getOperationText('isHalfHorse')).toEqual('is Half Horse'); }); it('correctly returns whether an operation applies to a given type', function () { expect(evaluator.operationAppliesTo('isHalfHorse', 'mythicalCreature')).toEqual(true); expect(evaluator.operationAppliesTo('isHalfHorse', 'spaceJunk')).toEqual(false); }); it('returns the HTML input type associated with a given data type', function () { expect(evaluator.getInputTypeById('string')).toEqual('text'); }); it('gets the number of inputs required for a given operation', function () { expect(evaluator.getInputCount('isHalfHorse')).toEqual(0); expect(evaluator.getInputCount('greaterThan')).toEqual(1); }); it('gets a human-readable description of a condition', function () { expect(evaluator.getOperationDescription('isHalfHorse')).toEqual('is half horse'); expect(evaluator.getOperationDescription('greaterThan', [1])).toEqual(' > 1'); }); it('allows setting a substitute cache for testing purposes, and toggling its use', function () { evaluator.setTestDataCache(mockTestCache); evaluator.useTestData(true); expect(evaluator.execute(mockConditions, 'any')).toEqual(false); expect(evaluator.execute(mockConditions, 'all')).toEqual(false); mockConditions.push({ object: 'a', key: 'gamma', operation: 'textContains', values: ['4 5 6'] }); expect(evaluator.execute(mockConditions, 'any')).toEqual(true); expect(evaluator.execute(mockConditions, 'all')).toEqual(false); mockConditions.pop(); evaluator.useTestData(false); expect(evaluator.execute(mockConditions, 'any')).toEqual(true); expect(evaluator.execute(mockConditions, 'all')).toEqual(false); }); it('supports all required operations', function () { //equal to testOperation = testEvaluator.operations.equalTo.operation; expect(testOperation([33, 33])).toEqual(true); expect(testOperation([55, 147])).toEqual(false); //not equal to testOperation = testEvaluator.operations.notEqualTo.operation; expect(testOperation([33, 33])).toEqual(false); expect(testOperation([55, 147])).toEqual(true); //greater than testOperation = testEvaluator.operations.greaterThan.operation; expect(testOperation([100, 33])).toEqual(true); expect(testOperation([33, 33])).toEqual(false); expect(testOperation([55, 147])).toEqual(false); //less than testOperation = testEvaluator.operations.lessThan.operation; expect(testOperation([100, 33])).toEqual(false); expect(testOperation([33, 33])).toEqual(false); expect(testOperation([55, 147])).toEqual(true); //greater than or equal to testOperation = testEvaluator.operations.greaterThanOrEq.operation; expect(testOperation([100, 33])).toEqual(true); expect(testOperation([33, 33])).toEqual(true); expect(testOperation([55, 147])).toEqual(false); //less than or equal to testOperation = testEvaluator.operations.lessThanOrEq.operation; expect(testOperation([100, 33])).toEqual(false); expect(testOperation([33, 33])).toEqual(true); expect(testOperation([55, 147])).toEqual(true); //between testOperation = testEvaluator.operations.between.operation; expect(testOperation([100, 33, 66])).toEqual(false); expect(testOperation([1, 33, 66])).toEqual(false); expect(testOperation([45, 33, 66])).toEqual(true); //not between testOperation = testEvaluator.operations.notBetween.operation; expect(testOperation([100, 33, 66])).toEqual(true); expect(testOperation([1, 33, 66])).toEqual(true); expect(testOperation([45, 33, 66])).toEqual(false); //text contains testOperation = testEvaluator.operations.textContains.operation; expect(testOperation(['Testing', 'tin'])).toEqual(true); expect(testOperation(['Testing', 'bind'])).toEqual(false); //text does not contain testOperation = testEvaluator.operations.textDoesNotContain.operation; expect(testOperation(['Testing', 'tin'])).toEqual(false); expect(testOperation(['Testing', 'bind'])).toEqual(true); //text starts with testOperation = testEvaluator.operations.textStartsWith.operation; expect(testOperation(['Testing', 'Tes'])).toEqual(true); expect(testOperation(['Testing', 'ting'])).toEqual(false); //text ends with testOperation = testEvaluator.operations.textEndsWith.operation; expect(testOperation(['Testing', 'Tes'])).toEqual(false); expect(testOperation(['Testing', 'ting'])).toEqual(true); //text is exactly testOperation = testEvaluator.operations.textIsExactly.operation; expect(testOperation(['Testing', 'Testing'])).toEqual(true); expect(testOperation(['Testing', 'Test'])).toEqual(false); //undefined testOperation = testEvaluator.operations.isUndefined.operation; expect(testOperation([1])).toEqual(false); expect(testOperation([])).toEqual(true); //isDefined testOperation = testEvaluator.operations.isDefined.operation; expect(testOperation([1])).toEqual(true); expect(testOperation([])).toEqual(false); }); it('can produce a description for all supported operations', function () { testEvaluator.getOperationKeys().forEach(function (key) { expect(testEvaluator.getOperationDescription(key, [])).toBeDefined(); }); }); }); });
fabio-d/fuchsia-stardock
src/ui/scenic/tests/gfx_integration_tests/pixel_test.cc
// Copyright 2022 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/ui/scenic/tests/gfx_integration_tests/pixel_test.h" #include <fuchsia/ui/policy/cpp/fidl.h> #include <zircon/status.h> namespace integration_tests { EmbedderView::EmbedderView(scenic::ViewContext context, fuchsia::ui::views::ViewHolderToken view_holder_token) : binding_(this, std::move(context.session_and_listener_request.second)), session_(std::move(context.session_and_listener_request.first)), view_(&session_, std::move(context.view_token), "View"), top_node_(&session_), view_holder_(&session_, std::move(view_holder_token), "ViewHolder") { binding_.set_error_handler([](zx_status_t status) { FX_LOGS(FATAL) << "Session listener binding: " << zx_status_get_string(status); }); view_.AddChild(top_node_); // Call |Session::Present| in order to flush events having to do with // creation of |view_| and |top_node_|. session_.Present(0, [](auto) {}); } void EmbedderView::EmbedView( std::function<void(fuchsia::ui::gfx::ViewState)> view_state_changed_callback) { view_state_changed_callback_ = std::move(view_state_changed_callback); top_node_.Attach(view_holder_); session_.Present(0, [](auto) {}); } void EmbedderView::OnScenicEvent(std::vector<fuchsia::ui::scenic::Event> events) { for (const auto& event : events) { if (event.Which() == fuchsia::ui::scenic::Event::Tag::kGfx && event.gfx().Which() == fuchsia::ui::gfx::Event::Tag::kViewPropertiesChanged) { const auto& evt = event.gfx().view_properties_changed(); view_holder_.SetViewProperties(std::move(evt.properties)); session_.Present(0, [](auto) {}); } else if (event.Which() == fuchsia::ui::scenic::Event::Tag::kGfx && event.gfx().Which() == fuchsia::ui::gfx::Event::Tag::kViewStateChanged) { const auto& evt = event.gfx().view_state_changed(); if (evt.view_holder_id == view_holder_.id()) { // Clients of |EmbedderView| *must* set a view state changed // callback. Failure to do so is a usage error. FX_CHECK(view_state_changed_callback_); view_state_changed_callback_(evt.state); } } } } void PixelTest::SetUp() { realm_ = std::make_unique<RealmRoot>(SetupRealm()); scenic_ = realm_->Connect<fuchsia::ui::scenic::Scenic>(); scenic_.set_error_handler([](zx_status_t status) { FAIL() << "Lost connection to Scenic: " << zx_status_get_string(status); }); annotation_registry_ = realm_->Connect<fuchsia::ui::annotation::Registry>(); annotation_registry_.set_error_handler([](zx_status_t status) { FAIL() << "Lost connection to Annotation Registry: " << zx_status_get_string(status); }); } fuchsia::ui::views::ViewToken PixelTest::CreatePresentationViewToken(bool clobber) { auto [view_token, view_holder_token] = scenic::ViewTokenPair::New(); auto presenter = realm()->Connect<fuchsia::ui::policy::Presenter>(); presenter.set_error_handler( [](zx_status_t status) { FAIL() << "presenter: " << zx_status_get_string(status); }); if (clobber) { presenter->PresentOrReplaceView(std::move(view_holder_token), nullptr); } else { presenter->PresentView(std::move(view_holder_token), nullptr); } return std::move(view_token); } scenic::ViewContext PixelTest::CreatePresentationContext(bool clobber) { FX_CHECK(scenic()) << "Scenic is not connected."; return { .session_and_listener_request = scenic::CreateScenicSessionPtrAndListenerRequest(scenic()), .view_token = CreatePresentationViewToken(clobber), }; } DisplayDimensions PixelTest::GetDisplayDimensions() { DisplayDimensions display_dimensions; scenic_->GetDisplayInfo([this, &display_dimensions](fuchsia::ui::gfx::DisplayInfo display_info) { display_dimensions = {.width = static_cast<float>(display_info.width_in_px), .height = static_cast<float>(display_info.height_in_px)}; QuitLoop(); }); RunLoop(); return display_dimensions; } void PixelTest::Present(scenic::Session* session, zx::time present_time) { session->Present(0, [this](auto) { QuitLoop(); }); ASSERT_FALSE(RunLoopWithTimeout(kPresentTimeout)); } scenic::Screenshot PixelTest::TakeScreenshot() { fuchsia::ui::scenic::ScreenshotData screenshot_out; scenic_->TakeScreenshot( [this, &screenshot_out](fuchsia::ui::scenic::ScreenshotData screenshot, bool status) { EXPECT_TRUE(status) << "Failed to take screenshot"; screenshot_out = std::move(screenshot); QuitLoop(); }); EXPECT_FALSE(RunLoopWithTimeout(kScreenshotTimeout)) << "Timed out waiting for screenshot."; return scenic::Screenshot(screenshot_out); } void PixelTest::RunUntilIndirectPresent(scenic::TestView* view) { // Typical sequence of events: // 1. We set up a view bound as a |SessionListener|. // 2. The view sends its initial |Present| to get itself connected, without // a callback. // 3. We call |RunUntilIndirectPresent| which sets a present callback on our // |TestView|. // 4. |RunUntilIndirectPresent| runs the message loop, which allows the view to // receive a Scenic event telling us our metrics. // 5. In response, the view sets up the scene graph with the test scene. // 6. The view calls |Present| with the callback set in |RunUntilIndirectPresent|. // 7. The still-running message loop eventually dispatches the present // callback, which quits the loop. view->set_present_callback([this](auto) { QuitLoop(); }); ASSERT_FALSE(RunLoopWithTimeout(kIndirectPresentTimeout)); } std::unique_ptr<RootSession> PixelTest::SetUpTestSession() { auto test_session = std::make_unique<RootSession>(scenic(), GetDisplayDimensions()); test_session->session.set_error_handler([](auto) { FAIL() << "Session terminated."; }); return test_session; } } // namespace integration_tests
AprilXiaoyanLiu/whitenoise-system
synth/tests/test_quail.py
<reponame>AprilXiaoyanLiu/whitenoise-system import subprocess import os import pytest import pandas as pd from diffprivlib.models import LogisticRegression as DPLR try: from snsynth.preprocessors import BaseTransformer from snsynth.pytorch import PytorchDPSynthesizer from snsynth.pytorch.nn import PATECTGAN from snsynth import QUAILSynthesizer except Exception as e: import logging test_logger = logging.getLogger(__name__) test_logger.warning(f"Requires torch and torchdp {e}") git_root_dir = ( subprocess.check_output("git rev-parse --show-toplevel".split(" ")) .decode("utf-8") .strip() ) meta_path = os.path.join(git_root_dir, os.path.join("datasets", "PUMS.yaml")) csv_path = os.path.join(git_root_dir, os.path.join("datasets", "PUMS.csv")) df = pd.read_csv(csv_path) del df["income"] @pytest.mark.torch class TestQUAIL: def setup(self): def QuailClassifier(epsilon): return DPLR(epsilon=epsilon) def QuailSynth(epsilon): return PytorchDPSynthesizer( epsilon=epsilon, preprocessor=None, gan=PATECTGAN(loss="cross_entropy", batch_size=50, pac=1), ) self.quail = QUAILSynthesizer( 10.0, QuailSynth, QuailClassifier, "married", eps_split=0.8 ) def test_fit(self): categorical_columns = [col for col in df.columns if col != "married"] self.quail.fit( df, categorical_columns=categorical_columns, transformer=BaseTransformer ) assert self.quail.private_synth def test_sample(self): categorical_columns = [col for col in df.columns if col != "married"] self.quail.fit( df, categorical_columns=categorical_columns, transformer=BaseTransformer ) sample_size = len(df) synth_data = self.quail.sample(sample_size) assert synth_data.shape == df.shape
jjcm/soci-backend
models/url_test.go
<filename>models/url_test.go package models import "testing" func TestWeCanCheckIfAUrlIsAvailable(t *testing.T) { setupTestingDB() isAvaiable, _ := URLIsAvailable("anything") if !isAvaiable { t.Errorf("Because the database is empty, any url should be available") } // cool, now let's create a post and the URL should not be available anymore author, _ := UserFactory("<EMAIL>", "", "password", 0) p, _ := author.CreatePost("Post Title", "post-title", "lorem ipsum", "image", 0, 0) // now the URL for the existing post should be taken isAvaiable, _ = URLIsAvailable(p.URL) if isAvaiable { t.Errorf("The URL for a built post should be taken, but the system said it's available") } }
Albert-Ma/bert-fine-tuned-gain
pytorch-pretrained-BERT/scripts/preprocess_onto.py
<filename>pytorch-pretrained-BERT/scripts/preprocess_onto.py import argparse from tqdm import tqdm from pytorch_pretrained_bert.tokenization import BertTokenizer def preprocess(sentence, tokenizer, max_seq_length): # print(sentence) sent = [line.split()[3] for line in sentence if (not line.strip().startswith("#") and not len(line.strip()) == 0)] # tokenize word to sub token and store ori_to_token_map orig_to_tok_map = [] tokens = [] for i, word in enumerate(sent): token = tokenizer.tokenize(word) orig_to_tok_map.append(len(tokens)) tokens.extend(token) orig_to_tok_map.append(len(tokens)) # print(tokens) if len(tokens) > max_seq_length: return -1 else: return sentence def main(tokenizer): with open(args.input_file, 'r', encoding='utf-8') as f: sentences = [] current_sentence = [] lines = f.readlines() document_length = 0 document_num = 0 max_document_length = 0 in_document = False for i, line in enumerate(tqdm(lines)): if line.strip().startswith("#begin"): current_sentence.append(line) in_document = True continue elif line.strip().startswith("#end"): current_sentence.append(line) if len(current_sentence) > max_document_length: max_document_length = len(current_sentence) document_length += len(current_sentence) document_num += 1 res = preprocess(current_sentence, tokenizer, args.max_seq_length) if res == -1: print("drop sentence cause length greater than max_seq_length") else: sentences.append(current_sentence) current_sentence = [] in_document = False elif len(line.strip()) != 0 and in_document: current_sentence.append(line) elif len(line.strip()) == 0 and in_document: current_sentence.append(line) print("file:{}, document num:{}, average length:{}, max length: {}". format(args.input_file, document_num, document_length/document_num, max_document_length)) with open(args.output_file, 'w') as output_file: for sentence in sentences: for token_line in sentence: output_file.write("{}".format(token_line)) output_file.write("\n") if __name__ == "__main__": parser = argparse.ArgumentParser() ## Required parameters parser.add_argument("--input_file", default=None, type=str, required=True) parser.add_argument("--output_file", default=None, type=str, required=True) parser.add_argument("--bert_model", default=None, type=str, required=True, help="Bert pre-trained model selected in the list: bert-base-uncased, " "bert-large-uncased, bert-base-cased, bert-base-multilingual, bert-base-chinese.") ## Other parameters parser.add_argument("--do_lower_case", action='store_true', help="Set this flag if you are using an uncased model.") parser.add_argument("--max_seq_length", default=128, type=int, help="The maximum total input sequence length after WordPiece tokenization. Sequences longer " "than this will be truncated, and sequences shorter than this will be padded.") args = parser.parse_args() tokenizer = BertTokenizer.from_pretrained(args.bert_model, do_lower_case=args.do_lower_case) main(tokenizer)
tmeralli-tehtris/open-vm-tools-security-research
open-vm-tools/services/plugins/dndcp/dnd/dndInt.h
/********************************************************* * Copyright (C) 2005 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * dndInt.h -- * * Private functions for the Drag and Drop library. */ #ifndef __DND_INT_H__ #define __DND_INT_H__ #include "vm_basic_types.h" #include "unicodeTypes.h" typedef struct { const uint8 *pos; size_t unreadLen; } BufRead; Bool DnDDataContainsIllegalCharacters(const char *data, const size_t dataSize, const char *illegalChars); Bool DnDPrependFileRoot(ConstUnicode fileRoot, char delimiter, char **src, size_t *srcSize); Bool DnDRootDirUsable(ConstUnicode pathName); Bool DnDSetPermissionsOnRootDir(ConstUnicode pathName); Bool DnDStagingDirectoryUsable(ConstUnicode pathName); Bool DnDSetPermissionsOnStagingDir(ConstUnicode pathName); Bool DnDReadBuffer(BufRead *b, void *out, size_t len); Bool DnDSlideBuffer(BufRead *b, size_t len); #endif /* __DND_INT_H__ */
shahbagdadi/py-algo-n-ds
arrays/minOpsToZero/Solution.py
<filename>arrays/minOpsToZero/Solution.py from typing import List class Solution: def minOperations(self, nums: List[int], x: int) -> int: total = sum(nums) l , w, mw = 0 , 0, -1 for r in range(len(nums)) : w += nums[r] while w > total - x and l <= r : w -= nums[l] l += 1 if w == total-x : mw = max(mw,r-l+1) return len(nums)-mw if mw != -1 else -1 s = Solution() ip = [1,1,4,2,3] ans = s.minOperations(ip,5) print(ans)
Amourspirit/ooo_uno_tmpl
ooobuild/lo/document/cmis_property.py
<filename>ooobuild/lo/document/cmis_property.py<gh_stars>0 # coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # 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. # # Struct Class # this is a auto generated file generated by Cheetah # Namespace: com.sun.star.document # Libre Office Version: 7.3 from ooo.oenv.env_const import UNO_NONE import typing class CmisProperty(object): """ Struct Class specifies a CMIS property. See Also: `API CmisProperty <https://api.libreoffice.org/docs/idl/ref/structcom_1_1sun_1_1star_1_1document_1_1CmisProperty.html>`_ """ __ooo_ns__: str = 'com.sun.star.document' __ooo_full_ns__: str = 'com.sun.star.document.CmisProperty' __ooo_type_name__: str = 'struct' typeName: str = 'com.sun.star.document.CmisProperty' """Literal Constant ``com.sun.star.document.CmisProperty``""" def __init__(self, Id: typing.Optional[str] = '', Name: typing.Optional[str] = '', Type: typing.Optional[str] = '', Updatable: typing.Optional[bool] = False, Required: typing.Optional[bool] = False, MultiValued: typing.Optional[bool] = False, OpenChoice: typing.Optional[bool] = False, Choices: typing.Optional[object] = None, Value: typing.Optional[object] = None) -> None: """ Constructor Arguments: Id (str, optional): Id value. Name (str, optional): Name value. Type (str, optional): Type value. Updatable (bool, optional): Updatable value. Required (bool, optional): Required value. MultiValued (bool, optional): MultiValued value. OpenChoice (bool, optional): OpenChoice value. Choices (object, optional): Choices value. Value (object, optional): Value value. """ super().__init__() if isinstance(Id, CmisProperty): oth: CmisProperty = Id self.Id = oth.Id self.Name = oth.Name self.Type = oth.Type self.Updatable = oth.Updatable self.Required = oth.Required self.MultiValued = oth.MultiValued self.OpenChoice = oth.OpenChoice self.Choices = oth.Choices self.Value = oth.Value return kargs = { "Id": Id, "Name": Name, "Type": Type, "Updatable": Updatable, "Required": Required, "MultiValued": MultiValued, "OpenChoice": OpenChoice, "Choices": Choices, "Value": Value, } self._init(**kargs) def _init(self, **kwargs) -> None: self._id = kwargs["Id"] self._name = kwargs["Name"] self._type = kwargs["Type"] self._updatable = kwargs["Updatable"] self._required = kwargs["Required"] self._multi_valued = kwargs["MultiValued"] self._open_choice = kwargs["OpenChoice"] self._choices = kwargs["Choices"] self._value = kwargs["Value"] @property def Id(self) -> str: """ unique ID of the Cmis property """ return self._id @Id.setter def Id(self, value: str) -> None: self._id = value @property def Name(self) -> str: """ specifies the display name of the CMIS property. """ return self._name @Name.setter def Name(self, value: str) -> None: self._name = value @property def Type(self) -> str: """ type of the property """ return self._type @Type.setter def Type(self, value: str) -> None: self._type = value @property def Updatable(self) -> bool: """ specifies if the property is updatable. """ return self._updatable @Updatable.setter def Updatable(self, value: bool) -> None: self._updatable = value @property def Required(self) -> bool: """ specifies if the property is required and can not be empty. """ return self._required @Required.setter def Required(self, value: bool) -> None: self._required = value @property def MultiValued(self) -> bool: """ specifies if the property has multiple value """ return self._multi_valued @MultiValued.setter def MultiValued(self, value: bool) -> None: self._multi_valued = value @property def OpenChoice(self) -> bool: """ specifies if the property value can be freely set or is restricted from a list of choices. """ return self._open_choice @OpenChoice.setter def OpenChoice(self, value: bool) -> None: self._open_choice = value @property def Choices(self) -> object: """ specifies the possible choices of the values. """ return self._choices @Choices.setter def Choices(self, value: object) -> None: self._choices = value @property def Value(self) -> object: """ specifies value of the property """ return self._value @Value.setter def Value(self, value: object) -> None: self._value = value __all__ = ['CmisProperty']
Conjoint-ly/turf-analysis-ui
templates/new/services/export.js
export default { exportGGraphAsPicture(chart, filename) { if (typeof chart !== 'undefined') { if (navigator.msSaveBlob) { navigator.msSaveBlob(window.dataURItoBlob(chart.getImageURI()), filename); } else { const link = document.createElement('a'); link.href = chart.getImageURI(); link.download = filename; document.body.appendChild(link); link.click(); document.body.removeChild(link); } } }, };
Guardians-DSC/Front-HoCo
src/services/api.js
/* eslint-disable no-unused-vars */ import axios from 'axios' const api = axios.create({ baseURL: process.env.REACT_APP_BASE_URL, }) export const getCredits = async () => { // const response = await api.get('/creditos') // console.log(response) return { creditos: 11, maximo: 22, } // return response.data } export const getCreditsPerCategory = async () => { // const response = await api.get('/categorias/creditos') // console.log(response) return [ { categoria: 'Projeto', acumulado: 12, maximo: 18, }, { categoria: 'Monitoria', acumulado: 8, maximo: 16, }, { categoria: 'Evento', acumulado: 2, maximo: 18, }, { categoria: 'init. científica', acumulado: 8, maximo: 16, }, { categoria: 'Estágio', acumulado: 15, maximo: 16, }, { categoria: 'Caesi', acumulado: 9, maximo: 16, }, { categoria: 'Atv. extensão', acumulado: 1, maximo: 14, }, { categoria: 'Atv. profissionais', acumulado: 1, maximo: 16, }, { categoria: 'outros', acumulado: 2, maximo: 16, }, ] // return response.data } export const getRankCategories = async () => { // const response = await api.get('/categorias/top') return [ { categoria: 'Projeto', porcentagem: 0.45, }, { categoria: 'Evento', porcentagem: 0.2, }, { categoria: 'Monitoria', porcentagem: 0.1, }, { categoria: 'Caesi', porcentagem: 0.2, }, ] // return response.data } export const registerActivity = async (activityData) => { const response = await api.post('/atividade', { activityData }) console.log('Dados enviados:', activityData) return response.data } export const getActivities = async () => { // const response = await api.get('/atividades') return [ { id: 129087124908, titulo: 'Projeto ePol', horas: 0, creditos: 12, categoria: 'projeto', certificado: { titulo: 'meu_certificado.jpeg', previewURL: 'https://giphy.com/embed/6ZorD2fyy1nj8GqunP', }, }, { id: 129087124901, titulo: 'CodeSQ', horas: 0, creditos: 12, categoria: 'projeto', certificado: { titulo: 'meu_certificado.jpeg', previewURL: 'https://giphy.com/embed/6ZorD2fyy1nj8GqunP', }, }, { id: 13231321312312, titulo: 'Andromedevi', horas: 135, creditos: 1, categoria: 'evento', certificado: { titulo: 'meu_certificado.jpeg', previewURL: 'https://giphy.com/embed/6ZorD2fyy1nj8GqunP', }, }, { id: 132313123312, titulo: 'Hacktoberfest', horas: 20, creditos: 0, categoria: 'evento', certificado: { titulo: 'meu_certificado.jpeg', previewURL: 'https://giphy.com/embed/6ZorD2fyy1nj8GqunP', }, }, { id: 13231321312318, titulo: 'Projeto ePoli', horas: 0, creditos: 12, categoria: 'caesi', certificado: { titulo: 'meu_certificado.jpeg', previewURL: 'https://giphy.com/embed/6ZorD2fyy1nj8GqunP', }, }, { id: 13231321312310, titulo: 'Andromedev', horas: 135, creditos: 0, categoria: 'inic. cientifica', certificado: { titulo: 'meu_certificado.jpeg', previewURL: 'https://giphy.com/embed/6ZorD2fyy1nj8GqunP', }, }, { id: 23231321312312, titulo: 'semana acadêmica', horas: 10, creditos: 0, categoria: 'evento', certificado: { titulo: 'meu_certificado.jpeg', previewURL: 'https://giphy.com/embed/6ZorD2fyy1nj8GqunP', }, }, ] // return response.data } export const editActivity = async (activityID, data) => { const response = await api.patch(`/atividade?id=${activityID}`, data) console.log(response) } export const deleteActivity = async (activityID, data) => { const response = await api.delete(`/atividade?id=${activityID}`) console.log(response) }
yimiqidage/study-by-boot
src/main/java/com/annotations/repeatable/Book2.java
<gh_stars>0 package com.annotations.repeatable; import java.util.Arrays; /** * Authors 的另一种写法,直接在Authors中定义多个Author注解对象 */ @Authors({@Author(name="张三Book2"),@Author(name="李四Book2"),@Author(name="王五Book2")}) public class Book2 { public static void main(String[] args) { Authors authors = Book2.class.getAnnotation(Authors.class); Author[] auArr =authors.value(); Arrays.asList(auArr).stream().forEach(t->{ //打印注解的内容 System.out.println(t.name()); }); } }
xDamneDx/Epic-React
bookshelf/scripts/update-branch.js
const {updateExerciseBranch, spawnSync} = require('./utils') process.env.HUSKY_SKIP_HOOKS = 1 updateExerciseBranch(spawnSync('git rev-parse --abbrev-ref HEAD'))
jhnbrns/sfc-controller
plugins/controller/utils.go
// Copyright (c) 2018 Cisco and/or its affiliates. // // 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 controller import ( // "fmt" // "github.com/ligato/sfc-controller/plugins/controller/model" // "github.com/ligato/sfc-controller/plugins/controller/vppagent" "strings" "fmt" ) // ConnPodName extracts the pod name from the pod/interface string func ConnPodName(connPodInterfaceString string) string { n := strings.Index(connPodInterfaceString, "/") if n == -1 { return "" } return connPodInterfaceString[0:n] } // ConnInterfaceName extracts the interface from the pod/interface string func ConnInterfaceName(connPodInterfaceString string) string { n := strings.Index(connPodInterfaceString, "/") if n == -1 { return "" } return connPodInterfaceString[n+1:] } // ConnPodInterfaceNames returns 2 strings (pod, interface) func ConnPodInterfaceNames(connPodInterfaceString string) (string, string) { n := strings.Index(connPodInterfaceString, "/") if n == -1 { return "", "" } return connPodInterfaceString[0:n], connPodInterfaceString[n+1:] } // NodeInterfaceNames returns 2 strings (node, interface) func NodeInterfaceNames(nodePodInterfaceString string) (string, string) { return ConnPodInterfaceNames(nodePodInterfaceString) } // ConnPodInterfaceSlashToUScore changes the / to a _ func ConnPodInterfaceSlashToUScore(connPodInterfaceString string) string { s0, s1 := ConnPodInterfaceNames(connPodInterfaceString) return fmt.Sprintf("%s_%s", s0, s1) } func ipAddressArraysEqual(a1 []string, a2 []string) bool { if len(a1) != len(a2) { return false } foundCount := 0 for _, e1 := range a1 { for _, e2 := range a2 { if e1 == e2 { foundCount++ break } } } if foundCount != len(a1) { return false } return true }
SpencerL-Y/SESL
include/smack/sesl/mem_manage/MemoryManager.h
#include <cstdlib> #include <iostream> #include <set> #include "smack/sesl/ast/BoogieAst.h" #ifndef MEMORYMANAGER_H #define MEMORYMANAGER_H namespace smack { class MemoryManager { private: std::set<const Expr*> pointers; public: void registerPointer(const Expr* pointer); void clearMemory(); }; typedef std::shared_ptr<MemoryManager> MemoryManagerPtr; } #endif
Floritte/Game-Engine-Samples
tests/Raytracing.cpp
#include "Raytracing.h" #include <GraphicsCore.h> #include "Backends/Vulkan/VulkanTexture.h" #include "Backends/Vulkan/VulkanContext.h" #include "Backends/Vulkan/VulkanRaytracingPipeline.h" using namespace SmolEngine; int main(int argc, char** argv) { EditorCameraCreateInfo cameraCI = {}; Camera* camera = new EditorCamera(&cameraCI); WindowCreateInfo windoInfo = {}; { windoInfo.bFullscreen = false; windoInfo.bVSync = false; windoInfo.Height = 480; windoInfo.Width = 720; windoInfo.Title = "Raytracing"; } GraphicsContextCreateInfo info = {}; info.ResourcesFolder = "../resources/"; info.pWindowCI = &windoInfo; info.eFeaturesFlags = {}; auto context = GraphicsContext::Create(&info); context->SetEventCallback([&](Event& e) { camera->OnEvent(e); }); RaytracingPipelineCreateInfo rtCreateInfo{}; rtCreateInfo.ShaderRayGenPath = info.ResourcesFolder + "Shaders/Reflections.rgen"; rtCreateInfo.ShaderCloseHitPath = info.ResourcesFolder + "Shaders/Reflections.rchit"; rtCreateInfo.ShaderMissPath = info.ResourcesFolder + "Shaders/Reflections.rmiss"; rtCreateInfo.Buffers[2].bGlobal = false; rtCreateInfo.Buffers[666].bGlobal = false; //rtCreateInfo.Buffers[666].Size = sizeof(VulkanRaytracingPipeline::ObjDesc) * 1000; //rtCreateInfo.Buffers[667].Size = sizeof(glm::vec4) * 1000; rtCreateInfo.Buffers[667].bGlobal = false; rtCreateInfo.VertexStride = sizeof(PBRVertex); rtCreateInfo.MaxRayRecursionDepth = 2; Ref<RaytracingPipeline> rtPipeline = RaytracingPipeline::Create(); rtPipeline->Build(&rtCreateInfo); glm::mat4 model, model2, model3; Utils::ComposeTransform(glm::vec3(0), glm::vec3(0), glm::vec3(1), model); Utils::ComposeTransform(glm::vec3(2, 0, 0), glm::vec3(0), glm::vec3(1), model3); Utils::ComposeTransform(glm::vec3(-2), glm::vec3(0), glm::vec3(10, 0.2, 10), model2); //Ref<Mesh> sponza = Mesh::Create(); //sponza->LoadFromFile("Assets/sponza_small.gltf"); // //auto& [mesh, view2] = MeshPool::GetCube(); //auto& [mesh2, view] = MeshPool::GetSphere(); // //RaytracingPipelineSceneInfo sceneCI{}; //sceneCI.Scene.push_back({ sponza , {model } }); // //rtPipeline->CreateScene(&sceneCI); Ref<Texture> storageTex = Texture::Create(); { TextureCreateInfo texCI{}; texCI.Width = 720; texCI.Height = 480; storageTex->LoadAsStorage(&texCI); rtPipeline->UpdateTexture(storageTex, 1); } while (context->IsOpen()) { context->ProcessEvents(); float deltaTime = context->CalculateDeltaTime(); if (context->IsWindowMinimized()) continue; camera->OnUpdate(deltaTime); context->BeginFrame(deltaTime); { struct CameraProperties { glm::mat4 viewProj; glm::mat4 viewInverse; glm::mat4 projInverse; } camData; camData.viewProj = camera->GetProjection() * camera->GetViewMatrix(); camData.projInverse = glm::inverse(camera->GetProjection()); camData.viewInverse = glm::inverse(camera->GetViewMatrix()); rtPipeline->UpdateBuffer(2, sizeof(CameraProperties), &camData); rtPipeline->SetCommandBuffer(); // default rtPipeline->Dispatch(720, 480); VkImageSubresourceRange subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }; auto& swapchain = VulkanContext::GetSwapchain(); auto cmd = VulkanContext::GetCurrentVkCmdBuffer(); // Prepare current swap chain image as transfer destination VulkanTexture::SetImageLayout( cmd, swapchain.GetCurrentImage(), VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, subresourceRange); // Prepare ray tracing output image as transfer source VulkanTexture::SetImageLayout( cmd, storageTex->Cast<VulkanTexture>()->GetVkImage(), VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, subresourceRange); VkImageCopy copyRegion{}; copyRegion.srcSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }; copyRegion.srcOffset = { 0, 0, 0 }; copyRegion.dstSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }; copyRegion.dstOffset = { 0, 0, 0 }; copyRegion.extent = { 720, 480, 1 }; vkCmdCopyImage(cmd, storageTex->Cast<VulkanTexture>()->GetVkImage(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, swapchain.GetCurrentImage(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &copyRegion); // Transition swap chain image back for presentation VulkanTexture::SetImageLayout( cmd, swapchain.GetCurrentImage(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, subresourceRange); // Transition ray tracing output image back to general layout VulkanTexture::SetImageLayout( cmd, storageTex->Cast<VulkanTexture>()->GetVkImage(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL, subresourceRange); } context->SwapBuffers(); } }
FlavioFalcao/open-source-search-engine
looptest.cpp
<filename>looptest.cpp #include "gb-include.h" #include "Loop.h" #include <pthread.h> #include <sys/types.h> // pid_t static pthread_attr_t s_attr; static void *startUp ( void *state ) ; static pid_t s_pid; int main ( int argc , char *argv[] ) { s_pid = getpid(); if ( ! g_loop.init() ) { log(" main::Loop init failed" ); return 1; } // start a thread if ( pthread_attr_init( &s_attr ) ) fprintf (stderr,"Threads::init: pthread_attr_init: error\n"); if ( pthread_attr_setdetachstate(&s_attr,PTHREAD_CREATE_DETACHED) ) fprintf ( stderr,"Threads::init: pthread_attr_setdeatcte:\n"); pthread_t tid1, tid2; int err = pthread_create ( &tid1 , &s_attr, startUp, (void *)2) ; if ( err != 0 ) return -1; // pause for signals to queue up //sleep(1); // run the loop if ( ! g_loop.runLoop() ) { log(" main::runLoop failed" ); return 1; } return 0; } void *startUp ( void *state ) { // sleep sleep(2); // put low priroity first long niceness; for ( long i = 0 ; i < 16 ; i++ ) { if ( i < 8 ) niceness = 0; else niceness = 1; sigval_t svt; svt.sival_int = (int)niceness ; //(int)(t->m_state); // fd; fprintf(stderr,"queuing niceness of %li\n",niceness); sigqueue ( s_pid , GB_SIGRTMIN + 1 + niceness, svt ); } }
zipated/src
ios/chrome/browser/web/resources/credential_manager.js
<reponame>zipated/src // Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview JavaScript implementation of the credential management API * defined at http://w3c.github.io/webappsec-credential-management * This is a minimal implementation that sends data to the app side to * integrate with the password manager. When loaded, installs the API onto * the window.navigator.object. */ // TODO(crbug.com/435046) After get, store, preventSilentAccess are // implemented app-side, make sure that all tests at // https://w3c-test.org/credential-management/idl.https.html // pass. // TODO(crbug.com/435046) Declare Credential, PasswordCredential, // FederatedCredential and CredentialsContainer as classes once iOS9 is no // longer supported. // Namespace for credential management. __gCrWeb must have already // been defined. __gCrWeb.credentialManager = { /** * Used to apply unique promiseId fields to messages sent to host. * Those IDs can be later used to call a corresponding resolver/rejecter. * @private {number} */ nextId_: 0, /** * Stores the functions for resolving Promises returned by * navigator.credentials method calls. A resolver for a call with * promiseId: |id| is stored at resolvers_[id]. * @type {!Object<number, function(?Credential)|function()>} * @private */ resolvers_: {}, /** * Stores the functions for rejecting Promises returned by * navigator.credentials method calls. A rejecter for a call with * promiseId: |id| is stored at rejecters_[id]. * @type {!Object<number, function(?Error)>} * @private */ rejecters_: {} }; __gCrWeb['credentialManager'] = __gCrWeb.credentialManager; /** * Creates and returns a Promise with given |promiseId|. The Promise's executor * function stores resolver and rejecter functions in * __gCrWeb['credentialManager'] under the key |promiseId| so they can be called * from the host after executing app side code. * @param {number} promiseId The number assigned to newly created Promise. * @return {!Promise<?Credential>|!Promise<!Credential>|!Promise<void>} * The created Promise. * @private */ __gCrWeb.credentialManager.createPromise_ = function(promiseId) { return new Promise(function(resolve, reject) { __gCrWeb.credentialManager.resolvers_[promiseId] = resolve; __gCrWeb.credentialManager.rejecters_[promiseId] = reject; }); }; /** * Sends a message to the app side, invoking |command| with the given |options|. * @param {string} command The name of the invoked command. * @param {Object} options A dictionary of additional properties to forward to * the app. * @return {!Promise<?Credential>|!Promise<!Credential>|!Promise<void>} * A promise to be returned by the calling method. * @private */ __gCrWeb.credentialManager.invokeOnHost_ = function(command, options) { var promiseId = __gCrWeb.credentialManager.nextId_++; var message = { 'command': command, 'promiseId': promiseId }; if (options) { Object.assign(message, options); } __gCrWeb.message.invokeOnHost(message); return __gCrWeb.credentialManager.createPromise_(promiseId); }; /** * The Credential interface, for more information see * https://w3c.github.io/webappsec-credential-management/#the-credential-interface * @constructor */ function Credential() { /** @type {string} */ this.id; /** @type {string} */ this.type; } Object.defineProperty(Credential.prototype, Symbol.toStringTag, { value: 'Credential' }); /** * PasswordCredential interace, for more information see * https://w3c.github.io/webappsec-credential-management/#passwordcredential-interface * @extends {Credential} * @param {PasswordCredentialInit} init Either a PasswordCredentialData or * HTMLFormElement to create PasswordCredential from. * @constructor */ function PasswordCredential(init) { // TODO(crbug.com/435046): When iOS9 is no longer supported, change vars to // |let| and |const| and declare at assignment. /** @type {!PasswordCredentialData} */ var data; var elements; var elementIndex; var newPasswordObserved; var field; var name; var autocompleteTokens; var token; var tokenIndex; if (init instanceof HTMLFormElement) { // Performs following steps: // https://www.w3.org/TR/credential-management-1/#abstract-opdef-create-a-passwordcredential-from-an-htmlformelement data = /** @type {!PasswordCredentialData} */ ({}); elements = init.querySelectorAll( // all submittable elements 'button, input, object, select, textarea'); newPasswordObserved = false; for (elementIndex = 0; elementIndex < elements.length; elementIndex++) { field = elements.item(elementIndex); if (!field.hasAttribute('autocomplete')) { continue; } name = field.name; if (!init[name]) { continue; } autocompleteTokens = field.getAttribute('autocomplete').split(' '); for (tokenIndex = 0; tokenIndex < autocompleteTokens.length; tokenIndex++) { token = autocompleteTokens[tokenIndex]; if (token.toLowerCase() === '<PASSWORD>-password') { data.password = init[name].value; newPasswordObserved = true; } if (token.toLowerCase() === '<PASSWORD>') { if (!newPasswordObserved) { data.password = init[name].value; } } if (token.toLowerCase() === 'photo') { data.iconURL = init[name].value; } if (token.toLowerCase() === 'name') { data.name = init[name].value; } if (token.toLowerCase() === 'nickname') { data.name = init[name].value; } if (token.toLowerCase() === 'username') { data.id = init[name].value; } } } } else { // |init| was not HTMLFormElement so assuming it is PasswordCredentialData. // Not checking with instanceof because any dictionary with required fields // should be accepted. data = /** @type {!PasswordCredentialData} */ (init); } // Perform following steps: // https://w3c.github.io/webappsec-credential-management/#abstract-opdef-create-a-passwordcredential-from-passwordcredentialdata if (!data.id || typeof data.id != 'string') { throw new TypeError('id must be a non-empty string'); } if (!data.password || typeof data.password != 'string') { throw new TypeError('password must be a non-empty string'); } if (data.iconURL && !data.iconURL.startsWith('https://')) { throw new SyntaxError('invalid iconURL'); } /** @type {string} */ this._id = data.id; /** @type {string} */ this._type = 'password'; /** @type {string} */ this._password = <PASSWORD>; /** @type {string} */ this._iconURL = (data.iconURL ? data.iconURL : ''); /** @type {string} */ this._name = (data.name ? data.name : ''); } PasswordCredential.prototype = { __proto__: Credential.prototype }; Object.defineProperty(PasswordCredential, 'prototype', { writable: false }); PasswordCredential.prototype.constructor = PasswordCredential; Object.defineProperties( PasswordCredential.prototype, { 'constructor': { enumerable: false }, 'id' : { get: /** @this {PasswordCredential} */ function() { return this._id; } }, 'type' : { get: /** @this {PasswordCredential} */ function() { return this._type; } }, 'password': { get: /** @this {PasswordCredential} */ function() { if (!(this instanceof PasswordCredential)) { throw new TypeError('attempting to get a property on prototype'); } return this._password; }, configurable: true, enumerable: true }, 'iconURL' : { get: /** @this {PasswordCredential} */ function() { return this._iconURL; } }, 'name' : { get: /** @this {PasswordCredential} */ function() { return this._name; } } } ); Object.defineProperty(PasswordCredential.prototype, Symbol.toStringTag, { value: 'PasswordCredential' }); /** * FederatedCredential interface, for more information see * https://w3c.github.io/webappsec-credential-management/#federatedcredential-interface * @param {FederatedCredentialInit} init Dictionary to create * FederatedCredential from. * @extends {Credential} * @constructor */ function FederatedCredential(init) { if (!init.id || typeof init.id != 'string') { throw new TypeError('id must be a non-empty string'); } if (!init.provider || typeof init.provider != 'string') { throw new TypeError('provider must be a non-empty string'); } if (!init.provider.startsWith('https://') && !init.provider.startsWith('http://')) { throw new SyntaxError('invalid provider URL'); } if (init.iconURL && !init.iconURL.startsWith('https://')) { throw new SyntaxError('invalid iconURL'); } /** @type {string} */ this._id = init.id; /** @type {string} */ this._type = 'federated'; /** @type {string} */ this._name = (init.name ? init.name : ''); /** @type {string} */ this._iconURL = (init.iconURL ? init.iconURL : ''); /** @type {string} */ this._provider = init.provider.replace(/\/$/, ''); // strip trailing slash /** @type {?string} */ this._protocol = (init.protocol ? init.protocol : ''); } FederatedCredential.prototype = { __proto__: Credential.prototype }; Object.defineProperty(FederatedCredential, 'prototype', { writable: false }); FederatedCredential.prototype.constructor = FederatedCredential; Object.defineProperties( FederatedCredential.prototype, { 'constructor': { enumerable: false }, 'id' : { get: /** @this {FederatedCredential} */ function() { return this._id; } }, 'type' : { get: /** @this {FederatedCredential} */ function() { return this._type; } }, 'provider': { get: /** @this {FederatedCredential} */ function() { if (!(this instanceof FederatedCredential)) { throw new TypeError('attempting to get a property on prototype'); } return this._provider; }, configurable: true, enumerable: true }, 'protocol': { get: /** @this {FederatedCredential} */ function() { if (!(this instanceof FederatedCredential)) { throw new TypeError('attempting to get a property on prototype'); } return this._protocol; }, configurable: true, enumerable: true }, 'iconURL' : { get: /** @this {FederatedCredential} */ function() { return this._iconURL; } }, 'name' : { get: /** @this {FederatedCredential} */ function() { return this._name; } } } ); Object.defineProperty(FederatedCredential.prototype, Symbol.toStringTag, { value: 'FederatedCredential' }); /** * CredentialData dictionary * https://w3c.github.io/webappsec-credential-management/#dictdef-credentialdata * @dict * @typedef {{id: string}} */ var CredentialData; /** * PasswordCredentialData used for constructing PasswordCredential objects * https://w3c.github.io/webappsec-credential-management/#dictdef-passwordcredentialdata * @dict * @typedef {{ * id: string, * name: string, * iconURL: string, * password: string * }} */ var PasswordCredentialData; /** * Either PasswordCredentialData or HTMLFormElement used for constructing * a new PasswordCredential * https://www.w3.org/TR/credential-management-1/#typedefdef-passwordcredentialinit * @typedef {!PasswordCredentialData|HTMLFormElement} */ var PasswordCredentialInit; /** * FederatedCredentialInit used for constructing FederatedCredential objects * https://w3c.github.io/webappsec-credential-management/#dictdef-federatedcredentialinit * @dict * @typedef {{ * id: string, * name: string, * iconURL: string, * provider: string, * protocol: string * }} */ var FederatedCredentialInit; /** * The CredentialRequestOptions dictionary, for more information see * https://w3c.github.io/webappsec-credential-management/#credentialrequestoptions-dictionary * @dict * @typedef {{mediation: string}} */ var CredentialRequestOptions; /** * The FederatedCredentialRequestOptions dictionary, for more information see * https://w3c.github.io/webappsec-credential-management/#dictdef-federatedcredentialrequestoptions * @dict * @typedef {{ * providers: !Array<string>, * protocols: !Array<string> * }} */ var FederatedCredentialRequestOptions; /** * The CredentialCreationOptions dictionary, for more information see * https://w3c.github.io/webappsec-credential-management/#credentialcreationoptions-dictionary * @dict * @typedef {{ * password: ?PasswordCredentialInit, * federated: ?FederatedCredentialInit * }} */ var CredentialCreationOptions; /** * Implements the public Credential Management API. For more information, see * https://w3c.github.io/webappsec-credential-management/#credentialscontainer * @constructor */ function CredentialsContainer() {} Object.defineProperty(CredentialsContainer, 'prototype', { writable: false }); CredentialsContainer.prototype.constructor = CredentialsContainer; Object.defineProperty( CredentialsContainer.prototype, 'constructor', { enumerable: false }); Object.defineProperty(CredentialsContainer.prototype, Symbol.toStringTag, { value: 'CredentialsContainer' }); /** * Performs the Request A Credential action described at * https://w3c.github.io/webappsec-credential-management/#abstract-opdef-request-a-credential * @param {!CredentialRequestOptions} options An optional dictionary of * parameters for the request. * @return {!Promise<?Credential>} A promise for retrieving the result * of the request. */ CredentialsContainer.prototype.get = function(options) { return __gCrWeb.credentialManager.invokeOnHost_( 'credentials.get', options); }; /** * Performs the Store A Credential action described at * https://w3c.github.io/webappsec-credential-management/#abstract-opdef-store-a-credential * @param {!Credential} credential A credential object to store. * @return {!Promise<void>} A promise for retrieving the result * of the request. */ CredentialsContainer.prototype.store = function(credential) { return __gCrWeb.credentialManager.invokeOnHost_( 'credentials.store', credential); }; /** * Performs the Prevent Silent Access action described at * https://w3c.github.io/webappsec-credential-management/#abstract-opdef-prevent-silent-access * @return {!Promise<void>} A promise for retrieving the result * of the request. */ CredentialsContainer.prototype.preventSilentAccess = function() { return __gCrWeb.credentialManager.invokeOnHost_( 'credentials.preventSilentAccess', {}); }; /** * Performs the Create A Credential action described at * https://w3c.github.io/webappsec-credential-management/#abstract-opdef-create-a-credential * @param {!CredentialCreationOptions} options An optional dictionary of * of params for creating a new Credential object. * @return {!Promise<?Credential>} A promise for retrieving the result * of the request. */ CredentialsContainer.prototype.create = function(options) { // According to // https://w3c.github.io/webappsec-credential-management/#abstract-opdef-create-a-credential, // we should also check for secure context. Instead it is done only in // browser-side methods. Since public JS interface is exposed, user can create // a Credential using a constructor anyway. return new Promise(function(resolve, reject) { try { if (options && options.password && !options.federated) { resolve(new PasswordCredential(options.password)); return; } if (options && options.federated && !options.password) { resolve(new FederatedCredential(options.federated)); return; } } catch (err) { reject(err); return; } reject(Object.create(DOMException.prototype, { name: {value: DOMException.NOT_SUPPORTED_ERR}, message: {value: 'Invalid CredentialRequestOptions'} })); }); }; /** * Install the public interface. * @type {!CredentialsContainer} */ window.navigator.credentials = new CredentialsContainer();
yankay/autoscaler
vertical-pod-autoscaler/e2e/vendor/github.com/google/cadvisor/collector/config.go
// Copyright 2015 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package collector import ( "time" "encoding/json" "github.com/google/cadvisor/info/v1" ) type Config struct { // the endpoint to hit to scrape metrics Endpoint EndpointConfig `json:"endpoint"` // holds information about different metrics that can be collected MetricsConfig []MetricConfig `json:"metrics_config"` } // metricConfig holds information extracted from the config file about a metric type MetricConfig struct { // the name of the metric Name string `json:"name"` // enum type for the metric type MetricType v1.MetricType `json:"metric_type"` // metric units to display on UI and in storage (eg: MB, cores) // this is only used for display. Units string `json:"units"` // data type of the metric (eg: int, float) DataType v1.DataType `json:"data_type"` // the frequency at which the metric should be collected PollingFrequency time.Duration `json:"polling_frequency"` // the regular expression that can be used to extract the metric Regex string `json:"regex"` } type Prometheus struct { // the endpoint to hit to scrape metrics Endpoint EndpointConfig `json:"endpoint"` // the frequency at which metrics should be collected PollingFrequency time.Duration `json:"polling_frequency"` // holds names of different metrics that can be collected MetricsConfig []string `json:"metrics_config"` } type EndpointConfig struct { // The full URL of the endpoint to reach URL string // A configuration in which an actual URL is constructed from, using the container's ip address URLConfig URLConfig } type URLConfig struct { // the protocol to use for connecting to the endpoint. Eg 'http' or 'https' Protocol string `json:"protocol"` // the port to use for connecting to the endpoint. Eg '8778' Port json.Number `json:"port"` // the path to use for the endpoint. Eg '/metrics' Path string `json:"path"` } func (ec *EndpointConfig) UnmarshalJSON(b []byte) error { url := "" config := URLConfig{ Protocol: "http", Port: "8000", } if err := json.Unmarshal(b, &url); err == nil { ec.URL = url return nil } err := json.Unmarshal(b, &config) if err == nil { ec.URLConfig = config return nil } return err }
hanhansoul/hadoop-with-comments
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/GetGroupsForTesting.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.client; import java.io.IOException; import java.io.PrintStream; import java.net.InetSocketAddress; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.tools.GetGroupsBase; import org.apache.hadoop.tools.GetUserMappingsProtocol; import org.apache.hadoop.util.ToolRunner; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.ipc.YarnRPC; import org.apache.hadoop.yarn.server.api.ResourceManagerAdministrationProtocol; public class GetGroupsForTesting extends GetGroupsBase { public GetGroupsForTesting(Configuration conf) { super(conf); } public GetGroupsForTesting(Configuration conf, PrintStream out) { super(conf, out); } @Override protected InetSocketAddress getProtocolAddress(Configuration conf) throws IOException { return conf.getSocketAddr(YarnConfiguration.RM_ADMIN_ADDRESS, YarnConfiguration.DEFAULT_RM_ADMIN_ADDRESS, YarnConfiguration.DEFAULT_RM_ADMIN_PORT); } @Override public void setConf(Configuration conf) { conf = new YarnConfiguration(conf); super.setConf(conf); } @Override protected GetUserMappingsProtocol getUgmProtocol() throws IOException { Configuration conf = getConf(); final InetSocketAddress addr = conf.getSocketAddr( YarnConfiguration.RM_ADMIN_ADDRESS, YarnConfiguration.DEFAULT_RM_ADMIN_ADDRESS, YarnConfiguration.DEFAULT_RM_ADMIN_PORT); final YarnRPC rpc = YarnRPC.create(conf); ResourceManagerAdministrationProtocol adminProtocol = (ResourceManagerAdministrationProtocol) rpc.getProxy( ResourceManagerAdministrationProtocol.class, addr, getConf()); return adminProtocol; } public static void main(String[] argv) throws Exception { int res = ToolRunner.run(new GetGroupsForTesting(new YarnConfiguration()), argv); System.exit(res); } }
bioinsilico/3DBIONOTES
app/lib/network_ppi_manager/network_manager.rb
<reponame>bioinsilico/3DBIONOTES module NetworkPpiManager module NetworkManager include GlobalTools::FetchParserTools include ProteinManager::FetchSequenceInfo include Interactome3dManager::FetchInteractome3d include ComputingTools::BiopythonInterfaceLib::BiopythonInterfaceTools def getNetwrokFromAcc(accs,organism,has_structure_flag=true,job=nil) query_acc = {} _nodes = {} accs.split(",").each do |a| query_acc[a] = true end if query_acc.length == 1 then has_structure_flag=true end url = Settings.GS_Interactome3D+"&dataset="+organism+"&ids="+accs html = getUrl(url) pairs = html.split("textarea")[1].split(">")[1].chop.chop.chop.split("\n") job.init_status(2*pairs.length,step=1) if(job) edges = [] aux_update = 0 pairs.each do |p| x = p.split(/\s/) if query_acc.key? x[0] and query_acc.key? x[1] then e = Interactome3dInteraction.where("(accA=\"#{x[0]}\" and accB=\"#{x[1]}\") or (accB=\"#{x[0]}\" and accA=\"#{x[1]}\")")[0] if not e.nil? then _nodes[x[0]]=true _nodes[x[1]]=true else edges.push({accA:x[0],accB:x[1],type:nil,file:nil}) _nodes[x[0]]=true _nodes[x[1]]=true end elsif (query_acc.key? x[0] or query_acc.key? x[1]) and has_structure_flag then e = Interactome3dInteraction.where("(accA=\"#{x[0]}\" and accB=\"#{x[1]}\") or (accB=\"#{x[0]}\" and accA=\"#{x[1]}\")")[0] if not e.nil? then _nodes[x[0]]=true _nodes[x[1]]=true end end aux_update += 1 job.update_status(dn=5) if(job and aux_update % 5 == 0) end pairs.each do |p| x = p.split(/\s/) if _nodes.key? x[0] and _nodes.key? x[1] then e = Interactome3dInteraction.where("(accA=\"#{x[0]}\" and accB=\"#{x[1]}\") or (accB=\"#{x[0]}\" and accA=\"#{x[1]}\")")[0] if not e.nil? then getPDBstructre(e[:file],"interaction") edges.push({accA:e[:accA],accB:e[:accB],type:e[:model_type],file:e[:file]}) else edges.push({accA:x[0],accB:x[1],type:nil,file:nil}) end end aux_update += 1 job.update_status(dn=5) if(job and aux_update % 5 == 0) end _nodes = _nodes.keys() nodes = [] _nodes.each do |x| e = Interactome3dProtein.order('coverage DESC').find_by(acc:x) if e.nil? then nodes.push({acc:x,type:nil,file:nil}) else getPDBstructre(e[:file],"protein") nodes.push({acc:x,type:e[:model_type],file:e[:file]}) end end return nodes,edges end def optionSelectorArray(network_graph,uniprot) accs = [] selector_array = {} network_graph[:nodes].each do |n| accs.push(n['acc']) end network_graph[:nodes].each do |n| selector_array[n['acc']] = optionNode(n,uniprot[n['acc']]) end network_graph[:edges].each do |e| unless e['file'].nil? then selector_array[e['accA']+":"+e['accB']] = optionEdge(e,uniprot[e['accA']],uniprot[e['accB']]) end end return selector_array end def optionEdge(edge,accA,accB) options = [] file_val = edge['file'].gsub '.','__' v = accA key = 'accA' ch = "A" options.push(["#{v['gene_symbol']}, #{v['definition']} / #{edge[key]}", {'uniprot'=>edge[key],'acc'=>edge[key],'file'=>edge['file'],'pdb'=>edge['file'],'pdbList'=>'/interactome_pdb/'+edge['file'].to_s,'chain'=>ch, 'uniprotLength'=>v['sequence'].length, 'uniprotTitle'=>v['definition'], 'organism'=>v['organism'], 'origin'=>'interactome3d', 'gene_symbol'=>v['gene_symbol'], 'path'=>'interactome3d:'+file_val}.to_json]) v = accB key = 'accB' ch = "B" options.push(["#{v['gene_symbol']}, #{v['definition']} / #{edge[key]}", {'acc'=>edge[key],'file'=>edge['file'],'pdb'=>edge['file'],'pdbList'=>'/interactome_pdb/'+edge['file'].to_s,'chain'=>ch,'uniprot'=>edge[key], 'uniprotLength'=>v['sequence'].length, 'uniprotTitle'=>v['definition'], 'organism'=>v['organism'], 'origin'=>'interactome3d', 'gene_symbol'=>v['gene_symbol'], 'path'=>'interactome3d:'+file_val}.to_json]) return options end def optionNode(node,uniprot) n = node v = uniprot ch = nil unless n['file'].nil? then r = n['file'].split("-") if r[1] == "MDL" then ch = "A" elsif r[1] == "EXP" then ch = r[2].split("_")[1].split(".")[0] else raise "INTERACTOME3D FORMAT ERROR "+r[1] end end file_val = "null" unless n['file'].nil? then file_val = n['file'].gsub '.','__' end return [["#{v['gene_symbol']}, #{v['definition']} / #{n['acc']}", {'acc'=>n['acc'],'file'=>n['file'],'pdb'=>n['file'],'pdbList'=>'/interactome_pdb/'+n['file'].to_s,'chain'=>ch,'uniprot'=>n['acc'], 'uniprotLength'=>v['sequence'].length, 'uniprotTitle'=>v['definition'], 'organism'=>v['organism'], 'origin'=>'interactome3d', 'gene_symbol'=>v['gene_symbol'], 'path'=>'interactome3d:'+file_val}.to_json]] end def getAlignments(nodes,edges,sequences,job=nil) alignment = {} n_status = nodes.length + edges.length job.init_status(n_status,step=2) if(job) nodes.each do |n| begin unless n[:file].nil? then r = n[:file].split("-") if r[1] == "MDL" then ch = "A" elsif r[1] == "EXP" then ch = r[2].split("_")[1].split(".")[0] else raise "INTERACTOME3D FORMAT ERROR "+r[1] end if sequences.key? r[0] then _align = alignPDBstructre(n[:file],{ch=>sequences[r[0]]['sequence']},{ch=>r[0]}) _null = runBiopythonInterface(n[:file],"interactome3d") alignment[ n[:file] ] = _align end job.update_info(n[:file]) if(job) end job.update_status() if(job) rescue Exception => e raise "Interactome3D file: "+n[:file]+"\nMessage: "+e.message+"\nTrace: "+JSON.parse(e.backtrace.inspect).join("\n") end end edges.each do |n| unless n[:file].nil? then r = n[:file].split("-") begin if sequences.key? r[0] and sequences.key? r[1] then _align = alignPDBstructre(n[:file],{"A"=>sequences[r[0]]['sequence'],"B"=>sequences[r[1]]['sequence']},{"A"=>r[0],"B"=>r[1]}) _null = runBiopythonInterface(n[:file],"interactome3d") alignment[ n[:file] ] = _align end rescue Exception => e raise "Interactome3D file: "+n[:file]+"\nMessage: "+e.message+"\nTrace: "+JSON.parse(e.backtrace.inspect).join("\n") end job.update_info(n[:file]) if(job) end job.update_status() if(job) end return alignment end end end
18612643035/website
gatsby-ssr.js
<gh_stars>0 // gatsby-ssr.js 配置页面预渲染(主要用于添加渲染组件到页面中,比如百度地图脚本) const React = require('react'); // exports.onRenderBody = ( // { setHeadComponents, setPostBodyComponents }, // ) => { // // const BAIDU_MAP_SCRIPT = ( // // <script // // key={`baidu-map-scripts`} // // src={'http://api.map.baidu.com/api?v=2.0&ak=j5nHekcXufbYWroRN8F0iWO8rNuAqYrX'} // // /> // // ); // // setHeadComponents([BAIDU_MAP_SCRIPT]); // };
rirl/bit
e2e/flows/export-eject.e2e.3.js
<reponame>rirl/bit import chai, { expect } from 'chai'; import path from 'path'; import Helper from '../e2e-helper'; import BitsrcTester, { username, supportTestingOnBitsrc } from '../bitsrc-tester'; import { BASE_WEB_DOMAIN } from '../../src/constants'; chai.use(require('chai-fs')); (supportTestingOnBitsrc ? describe : describe.skip)( `export --eject functionality using ${BASE_WEB_DOMAIN}`, function () { this.timeout(0); const helper = new Helper(); const bitsrcTester = new BitsrcTester(); let scopeName; before(() => { return bitsrcTester .loginToBitSrc() .then(() => bitsrcTester.createScope()) .then((scope) => { scopeName = scope; }); }); after(() => { return bitsrcTester.deleteScope(scopeName); }); describe('as author', () => { before(() => { helper.reInitLocalScope(); helper.createComponentBarFoo(); helper.addComponentBarFoo(); helper.tagAllComponents(); helper.exportAllComponents(`${username}.${scopeName} --eject`); }); it('should delete the original component files from the file-system', () => { expect(path.join(helper.localScopePath, 'bar', 'foo.js')).not.to.be.a.path(); }); it('should have the component files as a package (in node_modules)', () => { expect( path.join(helper.localScopePath, 'node_modules', '@bit', `${username}.${scopeName}.bar.foo`, 'foo.js') ).to.be.a.path(); }); it('should delete the component from bit.map', () => { const bitMap = helper.readBitMap(); Object.keys(bitMap).forEach((id) => { expect(id).not.to.have.string('foo'); }); }); }); } );
lejeunel/glia
src/sshmt/main_pred_mlp.cxx
#include "util/text_cmd.hxx" #include "alg/nn.hxx" #include "util/stats.hxx" #include "util/mp.hxx" #include "util/text_io.hxx" using namespace glia; #define EIGEN_DONT_PARALLELIZE std::vector<std::string> modelFiles; std::string featMinMaxFile; std::vector<double> bcModelDistributorArgs; std::vector<std::string> featFiles; int nNodeLayer1; int nNodeLayer2; std::vector<std::string> predFiles; bool operation () { std::vector<std::vector<FVal>> featMinMax; if (!featMinMaxFile.empty()) { readData(featMinMax, featMinMaxFile); } std::shared_ptr<opt::TFunction<std::vector<FVal>>> f; if (modelFiles.size() == 1) { f = std::make_shared<alg::MLP2v>( nNodeLayer1, nNodeLayer2, modelFiles.front()); } else { f = std::make_shared<alg::EnsembleMLP2v>( nNodeLayer1, nNodeLayer2, modelFiles, opt::ThresholdModelDistributor<FVal>( bcModelDistributorArgs[0], bcModelDistributorArgs[1], bcModelDistributorArgs[2])); } std::vector<double> preds; for (int i = 0; i < featFiles.size(); ++i) { std::vector<std::vector<FVal>> samples; readData(samples, featFiles[i]); int n = samples.size(); preds.resize(n); parfor(0, n, true, [&featMinMax, &preds, &samples, &f](int i) { if (!featMinMax.empty()) { stats::rescale(samples[i], featMinMax, -1.0, 1.0); } samples[i].push_back(1.0); // Do not forget to append 1 for bias preds[i] = f->operator()(samples[i]); }, 0); writeData(predFiles[i], preds, "\n"); } return true; } int main (int argc, char* argv[]) { Eigen::initParallel(); bpo::options_description opts("Usage"); opts.add_options() ("help", "Print usage info") ("m", bpo::value<std::vector<std::string>>(&modelFiles)->required(), "Trained model file(s)") ("fmm", bpo::value<std::string>(&featMinMaxFile), "Input feature min/max file name (ignore to not rescale)") ("md", bpo::value<std::vector<double>>(&bcModelDistributorArgs), "Boundary classifier distributor argument(s) " "(e.g. --md 0 --md 1 --md areaMedian)") ("f", bpo::value<std::vector<std::string>>(&featFiles)->required(), "Input feature files") ("nn1", bpo::value<int>(&nNodeLayer1)->required(), "Number of nodes in hidden layer 1") ("nn2", bpo::value<int>(&nNodeLayer2)->required(), "Number of nodes in hidden layer 2") ("p", bpo::value<std::vector<std::string>>(&predFiles)->required(), "Output prediction files"); return parse(argc, argv, opts) && operation()? EXIT_SUCCESS: EXIT_FAILURE; }
MadRatSRP/intellij-obsolete-plugins
IDEtalk/core/src/jetbrains/communicator/core/commands/NamedUserCommand.java
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package jetbrains.communicator.core.commands; import javax.swing.*; /** * @author Kir * * Named commands are used in actions. */ public interface NamedUserCommand extends UserCommand { String getName(); Icon getIcon(); }
Slach/gramework
subroute.go
<reponame>Slach/gramework<filename>subroute.go package gramework import "fmt" // GET registers a handler for a GET request to the given route func (r *SubRouter) GET(route string, handler interface{}) *SubRouter { route = r.prefixedRoute(route) if r.parent != nil { r.parent.handleReg(MethodGET, route, handler) } return r } func (r *SubRouter) determineHandler(handler interface{}) func(*Context) { return r.parent.determineHandler(handler) } // JSON register internal handler that sets json content type // and serves given handler with GET method func (r *SubRouter) JSON(route string, handler interface{}) *SubRouter { route = r.prefixedRoute(route) if r.parent != nil { h := r.parent.determineHandler(handler) r.parent.handleReg(MethodGET, route, jsonHandler(h)) } return r } // DELETE registers a handler for a DELETE request to the given route func (r *SubRouter) DELETE(route string, handler interface{}) *SubRouter { route = r.prefixedRoute(route) if r.parent != nil { r.parent.handleReg(MethodDELETE, route, handler) } return r } // HEAD registers a handler for a HEAD request to the given route func (r *SubRouter) HEAD(route string, handler interface{}) *SubRouter { route = r.prefixedRoute(route) if r.parent != nil { r.parent.handleReg(MethodHEAD, route, handler) } return r } // ServeFile serves a file on a given route func (r *SubRouter) ServeFile(route, file string) *SubRouter { route = r.prefixedRoute(route) r.parent.handleReg(MethodGET, route, func(ctx *Context) { ctx.SendFile(file) }) return r } // OPTIONS registers a handler for a OPTIONS request to the given route func (r *SubRouter) OPTIONS(route string, handler interface{}) *SubRouter { route = r.prefixedRoute(route) if r.parent != nil { r.parent.handleReg(MethodOPTIONS, route, handler) } return r } // PUT registers a handler for a PUT request to the given route func (r *SubRouter) PUT(route string, handler interface{}) *SubRouter { route = r.prefixedRoute(route) if r.parent != nil { r.parent.handleReg(MethodPUT, route, handler) } return r } // POST registers a handler for a POST request to the given route func (r *SubRouter) POST(route string, handler interface{}) *SubRouter { route = r.prefixedRoute(route) if r.parent != nil { r.parent.handleReg(MethodPOST, route, handler) } return r } // PATCH registers a handler for a PATCH request to the given route func (r *SubRouter) PATCH(route string, handler interface{}) *SubRouter { route = r.prefixedRoute(route) if r.parent != nil { r.parent.handleReg(MethodPATCH, route, handler) } return r } func (r *SubRouter) handleReg(method, route string, handler interface{}) { r.parent.handleReg(method, route, handler) } // Sub let you quickly register subroutes with given prefix // like app.Sub("v1").Sub("users").GET("view/:id", "hi").DELETE("delete/:id", "hi"), // that give you /v1/users/view/:id and /v1/users/delete/:id registered func (r *SubRouter) Sub(path string) *SubRouter { return &SubRouter{ parent: r, prefix: r.prefixedRoute(path), } } func (r *SubRouter) prefixedRoute(route string) string { if r.prefix[len(r.prefix)-1] != '/' && route[0] != '/' { return fmt.Sprintf("%s/%s", r.prefix, route) } return fmt.Sprintf("%s%s", r.prefix, route) } // HTTP returns SubRouter for http requests with given r.prefix func (r *SubRouter) HTTP() *SubRouter { switch parent := r.parent.(type) { case *SubRouter: return parent.HTTP() case *Router: return &SubRouter{ parent: parent, prefix: r.prefix, } default: Errorf("[HIGH SEVERITY BUG]: unreachable case found! Expected *SubRouter or *Router, got %T! Returning nil!", parent) Errorf("Please report the bug on https://github.com/gramework/gramework ASAP!") return nil } } // HTTPS returns SubRouter for https requests with given r.prefix func (r *SubRouter) HTTPS() *SubRouter { switch parent := r.parent.(type) { case *SubRouter: return parent.HTTPS() case *Router: return &SubRouter{ parent: parent, prefix: r.prefix, } default: Errorf("[HIGH SEVERITY BUG]: unreachable case found! Expected *SubRouter or *Router, got %T! Returning nil!", parent) Errorf("Please report the bug on https://github.com/gramework/gramework ASAP!") return nil } } // ToTLSHandler returns handler that redirects user to HTTP scheme func (r *SubRouter) ToTLSHandler() func(*Context) { return func(ctx *Context) { ctx.ToTLS() } } // Forbidden is a shortcut for ctx.Forbidden func (r *SubRouter) Forbidden(ctx *Context) { ctx.Forbidden() } // Redir sends 301 redirect to the given url // // it's equivalent to // // ctx.Redirect(url, 301) func (r *SubRouter) Redir(route, url string) { r.GET(route, func(ctx *Context) { ctx.Redirect(route, redirectCode) }) }
jroovers/dynamo
dynamo-frontend/src/test/java/com/ocs/dynamo/ui/component/ServiceBasedDetailsEditGridTest.java
package com.ocs.dynamo.ui.component; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import com.ocs.dynamo.domain.TestEntity; import com.ocs.dynamo.domain.TestEntity2; import com.ocs.dynamo.domain.model.AttributeModel; import com.ocs.dynamo.domain.model.EntityModel; import com.ocs.dynamo.domain.model.EntityModelFactory; import com.ocs.dynamo.domain.model.impl.EntityModelFactoryImpl; import com.ocs.dynamo.service.TestEntityService; import com.ocs.dynamo.test.BaseMockitoTest; import com.ocs.dynamo.ui.composite.layout.FormOptions; import com.ocs.dynamo.ui.provider.IdBasedDataProvider; import com.vaadin.flow.component.UI; public class ServiceBasedDetailsEditGridTest extends BaseMockitoTest { private EntityModelFactory factory = new EntityModelFactoryImpl(); @Mock private UI ui; private TestEntity e1; private TestEntity e2; private TestEntity2 parent; @Mock private TestEntityService service; @BeforeEach public void setUp() { e1 = new TestEntity(1, "Kevin", 12L); e1.setId(1); e2 = new TestEntity(2, "Bob", 14L); e2.setId(2); parent = new TestEntity2(); } /** * Test a grid in editable mode */ @Test public void testEditable() { EntityModel<TestEntity> em = factory.getModel(TestEntity.class); ServiceBasedDetailsEditGrid<Integer, TestEntity, Integer, TestEntity2> grid = createGrid(em, em.getAttributeModel("testEntities"), false, false, new FormOptions().setShowRemoveButton(true)); assertTrue(grid.getAddButton().isVisible()); assertFalse(grid.getSearchDialogButton().isVisible()); grid.setValue(parent); } /** * Test read only with search functionality */ @Test @SuppressWarnings({ "unchecked" }) public void testReadOnlyWithSearch() { EntityModel<TestEntity> em = factory.getModel(TestEntity.class); ServiceBasedDetailsEditGrid<Integer, TestEntity, Integer, TestEntity2> grid = createGrid(em, null, false, true, new FormOptions().setDetailsGridSearchMode(true)); grid.setService(service); IdBasedDataProvider<Integer, TestEntity> provider = (IdBasedDataProvider<Integer, TestEntity>) grid.getGrid().getDataProvider(); assertEquals(0, provider.getSize()); // adding is not possible assertFalse(grid.getAddButton().isVisible()); // but bringing up the search dialog is assertTrue(grid.getSearchDialogButton().isVisible()); } @Test public void testReadOnly() { EntityModel<TestEntity> em = factory.getModel(TestEntity.class); ServiceBasedDetailsEditGrid<Integer, TestEntity, Integer, TestEntity2> grid = createGrid(em, em.getAttributeModel("testEntities"), true, false, new FormOptions()); assertFalse(grid.getAddButton().isVisible()); assertFalse(grid.getSearchDialogButton().isVisible()); } private ServiceBasedDetailsEditGrid<Integer, TestEntity, Integer, TestEntity2> createGrid(EntityModel<TestEntity> em, AttributeModel am, boolean viewMode, boolean readOnly, FormOptions fo) { if (readOnly) { fo.setReadOnly(true); } ServiceBasedDetailsEditGrid<Integer, TestEntity, Integer, TestEntity2> table = new ServiceBasedDetailsEditGrid<Integer, TestEntity, Integer, TestEntity2>( service, em, am, viewMode, fo); table.setCreateEntitySupplier(() -> new TestEntity()); table.initContent(); return table; } }
eep60b/etlexamples
data-preparation/data-implementation/src/test/java/com/etlsolutions/examples/data/specific/person/PersonalDetailEntityTest.java
<reponame>eep60b/etlexamples<gh_stars>0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.etlsolutions.examples.data.specific.person; import com.etlsolutions.examples.data.specific.person.PersonalProfile; import com.etlsolutions.examples.data.specific.person.DateOfBirth; import com.etlsolutions.examples.data.specific.person.PersonalTitle; import com.etlsolutions.examples.data.specific.person.PersonalDetailEntity; import com.etlsolutions.examples.data.specific.person.FamilyName; import com.etlsolutions.examples.data.specific.person.GivenName; import com.etlsolutions.examples.data.api.PersonalDetail; import com.etlsolutions.examples.data.specific.communication.EmailEntity; import com.etlsolutions.examples.data.specific.communication.TelephoneEnitity; import java.util.Date; import org.junit.Test; import static org.junit.Assert.*; import org.junit.Before; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; /** * Test of class PersonalDetailEntity. * * @author <NAME> * * @since 1.0.0 * * @version 1.0.0 */ @RunWith(PowerMockRunner.class) @PrepareForTest({PersonalDetailEntity.class, TelephoneEnitity.class, EmailEntity.class}) public final class PersonalDetailEntityTest { private final PersonalTitle personTitleColumn = new PersonalTitle("Me."); private final PersonalTitle personTitleColumn1 = new PersonalTitle("Rx."); private final GivenName givenNameColumn = new GivenName("Ton"); private final GivenName givenNameColumn2 = new GivenName("knla"); private final FamilyName familyNameColumn = new FamilyName("Snigh"); private final FamilyName familyNameColumn3 = new FamilyName("Piioap"); private final DateOfBirth dateOfBirthColumn = new DateOfBirth(new Date(new Date(0).getTime() + 365L * 24L * 3600L * 30L + 24L * 3600L * 190L)); private final DateOfBirth dateOfBirthColumn4 = new DateOfBirth(new Date(new Date(0).getTime() + 365L * 24L * 3600L * 30L + 24L * 3600L * 100L)); private final PersonalProfile personalProfileColumn = new PersonalProfile(new byte[]{1, 16, 92}); private final PersonalProfile personalProfileColumn5 = new PersonalProfile(new byte[]{61, 39, 82}); private final PersonalDetail personalDetail = Mockito.mock(PersonalDetail.class); private final PersonalDetailEntity instance = new PersonalDetailEntity(personTitleColumn, givenNameColumn, familyNameColumn, dateOfBirthColumn, personalProfileColumn); private final PersonalDetailEntity instance00 = new PersonalDetailEntity(personTitleColumn, givenNameColumn, familyNameColumn, dateOfBirthColumn, personalProfileColumn); private final PersonalDetailEntity instance01 = new PersonalDetailEntity(personTitleColumn1, givenNameColumn, familyNameColumn, dateOfBirthColumn, personalProfileColumn); private final PersonalDetailEntity instance02 = new PersonalDetailEntity(personTitleColumn, givenNameColumn2, familyNameColumn, dateOfBirthColumn, personalProfileColumn); private final PersonalDetailEntity instance03 = new PersonalDetailEntity(personTitleColumn, givenNameColumn, familyNameColumn3, dateOfBirthColumn, personalProfileColumn); private final PersonalDetailEntity instance04 = new PersonalDetailEntity(personTitleColumn, givenNameColumn, familyNameColumn, dateOfBirthColumn4, personalProfileColumn); private final PersonalDetailEntity instance05 = new PersonalDetailEntity(personTitleColumn, givenNameColumn, familyNameColumn, dateOfBirthColumn, personalProfileColumn5); private PersonalDetailEntity instance06; @Before public void setUp() { Mockito.when(personalDetail.getDateOfBirth()).thenReturn(new Date(new Date(0).getTime() + 365L * 24L * 3600L * 30L + 24L * 3600L * 190L)); Mockito.when(personalDetail.getFamilyName()).thenReturn("Snigh"); Mockito.when(personalDetail.getGivenName()).thenReturn("Ton"); Mockito.when(personalDetail.getProfile()).thenReturn(new byte[]{1, 16, 92}); Mockito.when(personalDetail.getTitle()).thenReturn("Me."); instance06 = new PersonalDetailEntity(personalDetail); } /** * Test of getDateOfBirth method. */ @Test public void testGetDateOfBirth() { assertEquals(new Date(new Date(0).getTime() + 365L * 24L * 3600L * 30L + 24L * 3600L * 190L), instance.getDateOfBirth()); } /** * Test of getFamilyName method. */ @Test public void testGetFamilyName() { assertEquals("Snigh", instance.getFamilyName()); assertEquals("Snigh", instance06.getFamilyName()); } /** * Test of getGivenName method. */ @Test public void testGetGivenName() { assertEquals("Ton", instance.getGivenName()); assertEquals("Ton", instance06.getGivenName()); } /** * Test of getTitle method. */ @Test public void testGetTitle() { assertEquals("Me.", instance.getTitle()); assertEquals("Me.", instance06.getTitle()); } /** * Test of getProfile method. */ @Test public void testGetProfile() { assertArrayEquals(new byte[]{1, 16, 92}, instance.getProfile()); assertArrayEquals(new byte[]{1, 16, 92}, instance06.getProfile()); } /** * Test of hasSameConstraint method. */ @Test public void testHasSameConstraint() { assertTrue(instance.hasSameConstraint(instance)); assertTrue(instance.hasSameConstraint(instance00)); assertTrue(instance.hasSameConstraint(instance01)); assertTrue(instance.hasSameConstraint(instance02)); assertTrue(instance.hasSameConstraint(instance03)); assertTrue(instance.hasSameConstraint(instance04)); assertTrue(instance.hasSameConstraint(instance06)); assertTrue(instance.hasSameConstraint(personalDetail)); assertFalse(instance.hasSameConstraint(instance05)); } /** * Test of hasSameParameters method. */ @Test public void testHasSameParameters() { assertTrue(instance.hasSameParameters(instance)); assertTrue(instance.hasSameParameters(instance00)); assertTrue(instance.hasSameParameters(instance06)); assertTrue(instance.hasSameParameters(personalDetail)); assertFalse(instance.hasSameParameters(instance01)); assertFalse(instance.hasSameParameters(instance02)); assertFalse(instance.hasSameParameters(instance03)); assertFalse(instance.hasSameParameters(instance04)); assertFalse(instance.hasSameParameters(instance05)); } /** * Test of hashCode method. */ @Test public void testHashCode() { assertEquals(instance00.hashCode(), instance.hashCode()); assertEquals(instance05.hashCode(), instance.hashCode()); assertEquals(instance06.hashCode(), instance.hashCode()); assertNotEquals(instance01.hashCode(), instance.hashCode()); assertNotEquals(instance02.hashCode(), instance.hashCode()); assertNotEquals(instance03.hashCode(), instance.hashCode()); assertNotEquals(instance04.hashCode(), instance.hashCode()); } /** * Test of equals method. */ @Test @SuppressWarnings("ObjectEqualsNull") public void testEquals() { assertTrue(instance.equals(instance)); assertTrue(instance.equals(instance00)); assertFalse(instance.equals(instance01)); assertFalse(instance.equals(instance02)); assertFalse(instance.equals(instance03)); assertFalse(instance.equals(instance04)); assertFalse(instance.equals(instance05)); assertFalse(instance.equals(instance06)); assertFalse(instance.equals(personalDetail)); assertFalse(instance.equals(null)); } /** * Test of toString method. */ @Test public void testToString() { assertEquals("PersonalDetailEntity{title=Me., given name=Ton, family name=Snigh}", instance.toString()); } }
ripter/js1k
2016/public/scripted/battle_trap_1100_c.js
!function(){ function n(n){ c.fillStyle="#001f3f", c.fillRect(0,0,a.width,a.height), c.fillStyle="#01FF70", n.forEach( function(n,a){ c.fillText(n,100,100+75*a), console.log(n) } ) } function t(a){ function t(n){ return 5===o.length&&o.shift(), o.push(n), o } function e(o,r){ var c=a[o],u=c[r]; if(a.length!==o){ if(c.length===r) return setTimeout( e.bind(0,o+1,0), 2e3 ); n(t(u)), setTimeout(e.bind(0,o,r+1),1e3) } } var o=[];e(0,0)} function e(){return 0|20*Math.random()+1} function o(){return 0|4*Math.random()+1} function r(n,a){ var t,o=["I spotted a "+a.name+".",e()+n.bab>=a.ac?"The "+a.name+" was no match for me!":"I managed to flee."];return e()+a.bab>n.ac&&(t=a.dmg(),n.hp-=t,o.push("I took "+t+" damage.")),o } function u(n,a){ var t=["I see a "+a.name],r=e()+n.bab;return r>=a.ac?(t.push("I found some gold coins!"),n.gold+=o()):(t.push("It was a trap!"),r=a.dmg(),n.hp-=r,t.push("I took "+r+" damage.")),t } function f(){ for(var n,a,t=[],e={ hp:11,bab:5,ac:17,gold:0 }, c={name:"Goblin",bab:2,ac:13,dmg:o}, f={name:"strange rocks",ac:13,dmg:o}; e.hp>0; ) a=o(), 1===a&&(n=r(e,c)), 2===a&&(n=u(e,f)), t.push(n); return t } c.font="36px Papyrus, fantasy"; var i=f(); t(i) }();
squeeny/BaseMod
mod/src/main/java/basemod/BaseMod.java
<reponame>squeeny/BaseMod package basemod; import basemod.abstracts.*; import basemod.eventUtil.AddEventParams; import basemod.eventUtil.EventUtils; import basemod.helpers.RelicType; import basemod.helpers.dynamicvariables.BlockVariable; import basemod.helpers.dynamicvariables.DamageVariable; import basemod.helpers.dynamicvariables.MagicNumberVariable; import basemod.interfaces.*; import basemod.patches.com.megacrit.cardcrawl.helpers.TopPanel.TopPanelHelper; import basemod.patches.com.megacrit.cardcrawl.screens.select.GridCardSelectScreen.GridCardSelectScreenFields; import basemod.patches.com.megacrit.cardcrawl.unlock.UnlockTracker.CountModdedUnlockCards; import basemod.patches.whatmod.WhatMod; import basemod.screens.ModalChoiceScreen; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.Version; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.glutils.FrameBuffer; import com.evacipated.cardcrawl.modthespire.Loader; import com.evacipated.cardcrawl.modthespire.ModInfo; import com.evacipated.cardcrawl.modthespire.lib.SpireConfig; import com.evacipated.cardcrawl.modthespire.lib.SpireField; import com.evacipated.cardcrawl.modthespire.lib.SpireInitializer; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.megacrit.cardcrawl.audio.Sfx; import com.megacrit.cardcrawl.audio.SoundMaster; import com.megacrit.cardcrawl.cards.AbstractCard; import com.megacrit.cardcrawl.cards.CardGroup; import com.megacrit.cardcrawl.cards.DamageInfo; import com.megacrit.cardcrawl.characters.AbstractPlayer; import com.megacrit.cardcrawl.characters.AbstractPlayer.PlayerClass; import com.megacrit.cardcrawl.core.AbstractCreature; import com.megacrit.cardcrawl.core.CardCrawlGame; import com.megacrit.cardcrawl.core.Settings; import com.megacrit.cardcrawl.daily.mods.RedCards; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.events.AbstractEvent; import com.megacrit.cardcrawl.helpers.*; import com.megacrit.cardcrawl.integrations.steam.SteamIntegration; import com.megacrit.cardcrawl.localization.*; import com.megacrit.cardcrawl.monsters.AbstractMonster; import com.megacrit.cardcrawl.monsters.MonsterGroup; import com.megacrit.cardcrawl.monsters.MonsterInfo; import com.megacrit.cardcrawl.potions.AbstractPotion; import com.megacrit.cardcrawl.powers.AbstractPower; import com.megacrit.cardcrawl.relics.AbstractRelic; import com.megacrit.cardcrawl.relics.Circlet; import com.megacrit.cardcrawl.rewards.RewardItem; import com.megacrit.cardcrawl.rewards.RewardSave; import com.megacrit.cardcrawl.rooms.AbstractRoom; import com.megacrit.cardcrawl.screens.charSelect.CharacterOption; import com.megacrit.cardcrawl.screens.custom.CustomMod; import com.megacrit.cardcrawl.screens.custom.CustomModeCharacterButton; import com.megacrit.cardcrawl.shop.ShopScreen; import com.megacrit.cardcrawl.shop.StorePotion; import com.megacrit.cardcrawl.shop.StoreRelic; import com.megacrit.cardcrawl.unlock.AbstractUnlock; import com.megacrit.cardcrawl.unlock.UnlockTracker; import javassist.ClassPool; import javassist.CtClass; import javassist.NotFoundException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.clapper.util.classutil.*; import java.io.File; import java.io.IOException; import java.lang.reflect.*; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.function.Predicate; import java.util.stream.Collectors; @SpireInitializer public class BaseMod { public static final Logger logger = LogManager.getLogger(BaseMod.class.getName()); private static final int BADGES_PER_ROW = 16; private static final float BADGES_X = 640.0f; private static final float BADGES_Y = 250.0f; public static final float BADGE_W = 40.0f; public static final float BADGE_H = 40.0f; public static final int DEFAULT_MAX_HAND_SIZE = 10; @SuppressWarnings("unused") public static int MAX_HAND_SIZE = DEFAULT_MAX_HAND_SIZE; private static HashMap<Type, String> typeMaps; private static HashMap<Type, Type> typeTokens; private static ArrayList<ModBadge> modBadges; private static ArrayList<ISubscriber> toRemove; private static ArrayList<StartActSubscriber> startActSubscribers; private static ArrayList<PostCampfireSubscriber> postCampfireSubscribers; private static ArrayList<PostDrawSubscriber> postDrawSubscribers; private static ArrayList<PostExhaustSubscriber> postExhaustSubscribers; private static ArrayList<OnCardUseSubscriber> onCardUseSubscribers; private static ArrayList<PostDungeonInitializeSubscriber> postDungeonInitializeSubscribers; private static ArrayList<PostEnergyRechargeSubscriber> postEnergyRechargeSubscribers; private static ArrayList<PostInitializeSubscriber> postInitializeSubscribers; private static ArrayList<PreMonsterTurnSubscriber> preMonsterTurnSubscribers; private static ArrayList<RenderSubscriber> renderSubscribers; private static ArrayList<PreRenderSubscriber> preRenderSubscribers; private static ArrayList<PostRenderSubscriber> postRenderSubscribers; private static ArrayList<ModelRenderSubscriber> modelRenderSubscribers; private static ArrayList<PreStartGameSubscriber> preStartGameSubscribers; private static ArrayList<StartGameSubscriber> startGameSubscribers; private static ArrayList<PreUpdateSubscriber> preUpdateSubscribers; private static ArrayList<PostUpdateSubscriber> postUpdateSubscribers; private static ArrayList<PostDungeonUpdateSubscriber> postDungeonUpdateSubscribers; private static ArrayList<PreDungeonUpdateSubscriber> preDungeonUpdateSubscribers; private static ArrayList<PostPlayerUpdateSubscriber> postPlayerUpdateSubscribers; private static ArrayList<PrePlayerUpdateSubscriber> prePlayerUpdateSubscribers; private static ArrayList<PostCreateStartingDeckSubscriber> postCreateStartingDeckSubscribers; private static ArrayList<PostCreateStartingRelicsSubscriber> postCreateStartingRelicsSubscribers; private static ArrayList<PostCreateShopRelicSubscriber> postCreateShopRelicSubscribers; private static ArrayList<PostCreateShopPotionSubscriber> postCreateShopPotionSubscribers; private static ArrayList<EditCardsSubscriber> editCardsSubscribers; private static ArrayList<EditRelicsSubscriber> editRelicsSubscribers; private static ArrayList<EditCharactersSubscriber> editCharactersSubscribers; private static ArrayList<EditStringsSubscriber> editStringsSubscribers; private static ArrayList<AddAudioSubscriber> addAudioSubscribers; private static ArrayList<EditKeywordsSubscriber> editKeywordsSubscribers; private static ArrayList<PostBattleSubscriber> postBattleSubscribers; private static ArrayList<SetUnlocksSubscriber> setUnlocksSubscribers; private static ArrayList<PostPotionUseSubscriber> postPotionUseSubscribers; private static ArrayList<PrePotionUseSubscriber> prePotionUseSubscribers; private static ArrayList<PotionGetSubscriber> potionGetSubscribers; private static ArrayList<RelicGetSubscriber> relicGetSubscribers; private static ArrayList<PostPowerApplySubscriber> postPowerApplySubscribers; private static ArrayList<OnPowersModifiedSubscriber> onPowersModifiedSubscribers; private static ArrayList<PostDeathSubscriber> postDeathSubscribers; private static ArrayList<OnStartBattleSubscriber> startBattleSubscribers; private static ArrayList<AddCustomModeModsSubscriber> addCustomModeModsSubscribers; private static ArrayList<MaxHPChangeSubscriber> maxHPChangeSubscribers; private static ArrayList<PreRoomRenderSubscriber> preRoomRenderSubscribers; private static ArrayList<OnPlayerLoseBlockSubscriber> onPlayerLoseBlockSubscribers; private static ArrayList<OnPlayerDamagedSubscriber> onPlayerDamagedSubscribers; private static ArrayList<OnCreateDescriptionSubscriber> onCreateDescriptionSubscribers; private static ArrayList<AbstractCard> redToAdd; private static ArrayList<String> redToRemove; private static ArrayList<AbstractCard> greenToAdd; private static ArrayList<String> greenToRemove; private static ArrayList<AbstractCard> blueToAdd; private static ArrayList<String> blueToRemove; private static ArrayList<AbstractCard> purpleToAdd; private static ArrayList<String> purpleToRemove; private static ArrayList<AbstractCard> colorlessToAdd; private static ArrayList<String> colorlessToRemove; private static ArrayList<AbstractCard> curseToAdd; private static ArrayList<String> curseToRemove; private static ArrayList<AbstractCard> customToAdd; private static ArrayList<String> customToRemove; private static ArrayList<AbstractCard.CardColor> customToRemoveColors; private static HashMap<AbstractCard.CardColor, HashMap<String, AbstractRelic>> customRelicPools; private static HashMap<AbstractCard.CardColor, ArrayList<AbstractRelic>> customRelicLists; private static HashMap<String, Pair<Predicate<AbstractCard>, AbstractRelic>> customBottleRelics; private static ArrayList<String> potionsToRemove; private static int lastBaseCharacterIndex = -1; public static HashMap<PlayerClass, String> playerSelectButtonMap; public static HashMap<PlayerClass, String> customModeCharacterButtonMap; public static HashMap<PlayerClass, String> playerPortraitMap; public static HashMap<String, DynamicVariable> cardDynamicVariableMap = new HashMap<>(); private static HashMap<String, Class<? extends AbstractPotion>> potionClassMap; private static HashMap<String, Color> potionHybridColorMap; private static HashMap<String, Color> potionLiquidColorMap; private static HashMap<String, Color> potionSpotsColorMap; private static HashMap<String, AbstractPlayer.PlayerClass> potionPlayerClassMap; private static HashMap<String, Class<? extends AbstractPower>> powerMap; private static HashMap<String, Sfx> audioToAdd; private static HashMap<String, String> keywordProperNames; private static HashMap<String, String> keywordUniqueNames; private static HashMap<String, String> keywordUniquePrefixes; public static ArrayList<String> encounterList; public static HashMap<String, String> underScoreEncounterIDs; public static HashMap<String, String> underScoreCardIDs; public static HashMap<String, String> underScorePotionIDs; public static HashMap<String, String> underScorePowerIDs; public static HashMap<String, String> underScoreEventIDs; public static HashMap<String, String> underScoreRelicIDs; private static HashMap<AbstractCard.CardColor, com.badlogic.gdx.graphics.Color> colorBgColorMap; private static HashMap<AbstractCard.CardColor, com.badlogic.gdx.graphics.Color> colorBackColorMap; private static HashMap<AbstractCard.CardColor, com.badlogic.gdx.graphics.Color> colorFrameColorMap; private static HashMap<AbstractCard.CardColor, com.badlogic.gdx.graphics.Color> colorFrameOutlineColorMap; private static HashMap<AbstractCard.CardColor, com.badlogic.gdx.graphics.Color> colorDescBoxColorMap; private static HashMap<AbstractCard.CardColor, com.badlogic.gdx.graphics.Color> colorTrailVfxMap; private static HashMap<AbstractCard.CardColor, com.badlogic.gdx.graphics.Color> colorGlowColorMap; private static HashMap<AbstractCard.CardColor, Integer> colorCardCountMap; private static HashMap<AbstractCard.CardColor, Integer> colorCardSeenCountMap; private static HashMap<AbstractCard.CardColor, String> colorAttackBgMap; private static HashMap<AbstractCard.CardColor, String> colorSkillBgMap; private static HashMap<AbstractCard.CardColor, String> colorPowerBgMap; private static HashMap<AbstractCard.CardColor, String> colorEnergyOrbMap; private static HashMap<AbstractCard.CardColor, String> colorCardEnergyOrbMap; private static HashMap<AbstractCard.CardColor, String> colorAttackBgPortraitMap; private static HashMap<AbstractCard.CardColor, String> colorSkillBgPortraitMap; private static HashMap<AbstractCard.CardColor, String> colorPowerBgPortraitMap; private static HashMap<AbstractCard.CardColor, String> colorEnergyOrbPortraitMap; private static HashMap<AbstractCard.CardColor, com.badlogic.gdx.graphics.Texture> colorAttackBgTextureMap; private static HashMap<AbstractCard.CardColor, com.badlogic.gdx.graphics.Texture> colorSkillBgTextureMap; private static HashMap<AbstractCard.CardColor, com.badlogic.gdx.graphics.Texture> colorPowerBgTextureMap; private static HashMap<AbstractCard.CardColor, com.badlogic.gdx.graphics.Texture> colorEnergyOrbTextureMap; private static HashMap<AbstractCard.CardColor, com.badlogic.gdx.graphics.Texture> colorAttackBgPortraitTextureMap; private static HashMap<AbstractCard.CardColor, com.badlogic.gdx.graphics.Texture> colorSkillBgPortraitTextureMap; private static HashMap<AbstractCard.CardColor, com.badlogic.gdx.graphics.Texture> colorPowerBgPortraitTextureMap; private static HashMap<AbstractCard.CardColor, com.badlogic.gdx.graphics.Texture> colorEnergyOrbPortraitTextureMap; private static HashMap<AbstractCard.CardColor, TextureAtlas.AtlasRegion> colorCardEnergyOrbAtlasRegionMap; private static HashMap<AbstractPlayer.PlayerClass, HashMap<Integer, CustomUnlockBundle>> unlockBundles; private static HashMap<AbstractPlayer.PlayerClass, ArrayList<String>> unlockCards; private static HashMap<AbstractPlayer.PlayerClass, Integer> maxUnlockLevel; private static HashMap<String, CustomSavableRaw> customSaveFields = new HashMap<>(); private static OrthographicCamera animationCamera; private static ModelBatch batch; private static Environment animationEnvironment; private static FrameBuffer animationBuffer; private static Texture animationTexture; private static TextureRegion animationTextureRegion; public static final String CONFIG_FILE = "basemod-config"; private static SpireConfig config; public static final String save_path = "saves" + File.separator; public static DevConsole console; public static Gson gson; public static boolean modSettingsUp = false; // Map generation public static float mapPathDensityMultiplier = 1.0f; public static ModalChoiceScreen modalChoiceScreen = new ModalChoiceScreen(); // // Initialization // private static SpireConfig makeConfig() { Properties defaultProperties = new Properties(); defaultProperties.setProperty("console-key", "`"); defaultProperties.setProperty("autocomplete-enabled", Boolean.toString(true)); defaultProperties.setProperty("whatmod-enabled", Boolean.toString(true)); try { SpireConfig retConfig = new SpireConfig(BaseModInit.MODNAME, CONFIG_FILE, defaultProperties); return retConfig; } catch (IOException e) { return null; } } private static String getString(String key) { return config.getString(key); } static void setString(String key, String value) { config.setString(key, value); try { config.save(); } catch (IOException e) { e.printStackTrace(); } } private static Boolean getBoolean(String key) { return config.getBool(key); } static void setBoolean(String key, Boolean value) { config.setBool(key, value); try { config.save(); } catch (IOException e) { e.printStackTrace(); } } private static void setProperties() { // if config can't be loaded leave things at defaults if (config == null) { return; } String consoleKey = getString("console-key"); if (consoleKey != null) { DevConsole.toggleKey = Keys.valueOf(consoleKey); } Boolean consoleEnabled = getBoolean("console-enabled"); if (consoleEnabled != null) { DevConsole.enabled = consoleEnabled; } Boolean autoCompleteEnabled = getBoolean("autocomplete-enabled"); if (autoCompleteEnabled != null) { AutoComplete.enabled = autoCompleteEnabled; } Boolean whatmodEnabled = getBoolean("whatmod-enabled"); if (whatmodEnabled != null) { WhatMod.enabled = whatmodEnabled; } } public static boolean isBaseGameCharacter(AbstractPlayer c) { return isBaseGameCharacter(c.chosenClass); } public static boolean isBaseGameCharacter(AbstractPlayer.PlayerClass chosenClass) { int index = -1; for (AbstractPlayer player : CardCrawlGame.characterManager.getAllCharacters()) { ++index; if (player.chosenClass == chosenClass) { break; } } return index <= lastBaseCharacterIndex; } public static boolean isBaseGameCardColor(AbstractCard.CardColor color) { return color.compareTo(AbstractCard.CardColor.CURSE) <= 0; } // initialize - public static void initialize() { System.out.println("libgdx version " + Version.VERSION); modBadges = new ArrayList<>(); initializeGson(); initializeTypeMaps(); initializeSubscriptions(); initializeCardLists(); initializeCharacterMap(); initializeColorMap(); initializeRelicPool(); initializeUnlocks(); initializePotionMap(); initializePotionList(); initializePowerMap(); initializeUnderscorePowerIDs(); audioToAdd = new HashMap<>(); keywordProperNames = new HashMap<>(); keywordUniqueNames = new HashMap<>(); keywordUniquePrefixes = new HashMap<>(); BaseModInit baseModInit = new BaseModInit(); BaseMod.subscribe(baseModInit); config = makeConfig(); setProperties(); console = new DevConsole(); } // setupAnimationGfx - private static void setupAnimationGfx() { animationCamera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); animationCamera.near = 1.0f; animationCamera.far = 300.0f; animationCamera.position.z = 200.0f; animationCamera.update(); batch = new ModelBatch(); animationEnvironment = new Environment(); animationEnvironment.set(new ColorAttribute(ColorAttribute.AmbientLight, 1f, 1f, 1f, 1f)); animationBuffer = new FrameBuffer(Format.RGBA8888, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false); } // initializeGson - private static void initializeGson() { logger.info("initializeGson"); GsonBuilder gsonBuilder = new GsonBuilder(); gson = gsonBuilder.create(); } // initializeTypeTokens - private static void initializeTypeMaps() { logger.info("initializeTypeMaps"); typeMaps = new HashMap<>(); typeTokens = new HashMap<>(); for (Field f : LocalizedStrings.class.getDeclaredFields()) { Type type = f.getGenericType(); if (type instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) type; Type[] typeArgs = pType.getActualTypeArguments(); if (typeArgs.length == 2 && typeArgs[0].equals(String.class) && typeArgs[1].getTypeName().startsWith("com.megacrit.cardcrawl.localization.") && typeArgs[1].getTypeName().endsWith("Strings")) { logger.info("Registered " + typeArgs[1].getTypeName().replace("com.megacrit.cardcrawl.localization.", "")); typeMaps.put(typeArgs[1], f.getName()); ParameterizedType p = com.google.gson.internal.$Gson$Types.newParameterizedTypeWithOwner(null, Map.class, String.class, typeArgs[1]); typeTokens.put(typeArgs[1], p); } } } } // initializeSubscriptions - private static void initializeSubscriptions() { toRemove = new ArrayList<>(); startActSubscribers = new ArrayList<>(); postCampfireSubscribers = new ArrayList<>(); postDrawSubscribers = new ArrayList<>(); postExhaustSubscribers = new ArrayList<>(); onCardUseSubscribers = new ArrayList<>(); postDungeonInitializeSubscribers = new ArrayList<>(); postEnergyRechargeSubscribers = new ArrayList<>(); postInitializeSubscribers = new ArrayList<>(); preMonsterTurnSubscribers = new ArrayList<>(); renderSubscribers = new ArrayList<>(); preRenderSubscribers = new ArrayList<>(); postRenderSubscribers = new ArrayList<>(); modelRenderSubscribers = new ArrayList<>(); preStartGameSubscribers = new ArrayList<>(); startGameSubscribers = new ArrayList<>(); preUpdateSubscribers = new ArrayList<>(); postUpdateSubscribers = new ArrayList<>(); postDungeonUpdateSubscribers = new ArrayList<>(); preDungeonUpdateSubscribers = new ArrayList<>(); postPlayerUpdateSubscribers = new ArrayList<>(); prePlayerUpdateSubscribers = new ArrayList<>(); postCreateStartingDeckSubscribers = new ArrayList<>(); postCreateStartingRelicsSubscribers = new ArrayList<>(); postCreateShopRelicSubscribers = new ArrayList<>(); postCreateShopPotionSubscribers = new ArrayList<>(); editCardsSubscribers = new ArrayList<>(); editRelicsSubscribers = new ArrayList<>(); editCharactersSubscribers = new ArrayList<>(); editStringsSubscribers = new ArrayList<>(); addAudioSubscribers = new ArrayList<>(); editKeywordsSubscribers = new ArrayList<>(); postBattleSubscribers = new ArrayList<>(); setUnlocksSubscribers = new ArrayList<>(); postPotionUseSubscribers = new ArrayList<>(); prePotionUseSubscribers = new ArrayList<>(); potionGetSubscribers = new ArrayList<>(); relicGetSubscribers = new ArrayList<>(); postPowerApplySubscribers = new ArrayList<>(); onPowersModifiedSubscribers = new ArrayList<>(); postDeathSubscribers = new ArrayList<>(); startBattleSubscribers = new ArrayList<>(); addCustomModeModsSubscribers = new ArrayList<>(); maxHPChangeSubscribers = new ArrayList<>(); preRoomRenderSubscribers = new ArrayList<>(); onPlayerLoseBlockSubscribers = new ArrayList<>(); onPlayerDamagedSubscribers = new ArrayList<>(); onCreateDescriptionSubscribers = new ArrayList<>(); } // initializeCardLists - private static void initializeCardLists() { redToAdd = new ArrayList<>(); redToRemove = new ArrayList<>(); greenToAdd = new ArrayList<>(); greenToRemove = new ArrayList<>(); blueToAdd = new ArrayList<>(); blueToRemove = new ArrayList<>(); purpleToAdd = new ArrayList<>(); purpleToRemove = new ArrayList<>(); colorlessToAdd = new ArrayList<>(); colorlessToRemove = new ArrayList<>(); curseToAdd = new ArrayList<>(); curseToRemove = new ArrayList<>(); customToAdd = new ArrayList<>(); customToRemove = new ArrayList<>(); customToRemoveColors = new ArrayList<>(); } // initializeCharacterMap - private static void initializeCharacterMap() { playerSelectButtonMap = new HashMap<>(); customModeCharacterButtonMap = new HashMap<>(); playerPortraitMap = new HashMap<>(); } // initializeColorMap - private static void initializeColorMap() { colorBgColorMap = new HashMap<>(); colorBackColorMap = new HashMap<>(); colorFrameColorMap = new HashMap<>(); colorFrameOutlineColorMap = new HashMap<>(); colorDescBoxColorMap = new HashMap<>(); colorTrailVfxMap = new HashMap<>(); colorGlowColorMap = new HashMap<>(); colorCardCountMap = new HashMap<>(); colorCardSeenCountMap = new HashMap<>(); colorAttackBgMap = new HashMap<>(); colorSkillBgMap = new HashMap<>(); colorPowerBgMap = new HashMap<>(); colorEnergyOrbMap = new HashMap<>(); colorCardEnergyOrbMap = new HashMap<>(); colorAttackBgPortraitMap = new HashMap<>(); colorSkillBgPortraitMap = new HashMap<>(); colorPowerBgPortraitMap = new HashMap<>(); colorEnergyOrbPortraitMap = new HashMap<>(); colorAttackBgTextureMap = new HashMap<>(); colorSkillBgTextureMap = new HashMap<>(); colorPowerBgTextureMap = new HashMap<>(); colorEnergyOrbTextureMap = new HashMap<>(); colorAttackBgPortraitTextureMap = new HashMap<>(); colorSkillBgPortraitTextureMap = new HashMap<>(); colorPowerBgPortraitTextureMap = new HashMap<>(); colorEnergyOrbPortraitTextureMap = new HashMap<>(); colorCardEnergyOrbAtlasRegionMap = new HashMap<>(); } private static void initializeRelicPool() { customRelicPools = new HashMap<>(); customRelicLists = new HashMap<>(); customBottleRelics = new HashMap<>(); } // initializeUnlocks private static void initializeUnlocks() { unlockBundles = new HashMap<>(); unlockCards = new HashMap<>(); maxUnlockLevel = new HashMap<>(); } private static void initializePotionMap() { potionClassMap = new HashMap<>(); potionHybridColorMap = new HashMap<>(); potionLiquidColorMap = new HashMap<>(); potionSpotsColorMap = new HashMap<>(); potionPlayerClassMap = new HashMap<>(); } private static void initializePotionList() { potionsToRemove = new ArrayList<>(); } // Finds potions that have IDs with spaces in them and maps those IDs with // underscores instead of spaces to the original id public static void initializeUnderscorePotionIDs() { logger.info("initializeUnderscorePotionIDs"); underScorePotionIDs = new HashMap<>(); // Not actually unchecked @SuppressWarnings("unchecked") // This has to be LocalizedStrings and not PotionHelper.potions, because // PotionHelper.potions is empty on the games startup Map<String, PotionStrings> potions = (Map<String, PotionStrings>) (ReflectionHacks .getPrivateStatic(LocalizedStrings.class, "potions")); if (potions != null) { for (String key : potions.keySet()) { if (key.contains(" ")) { underScorePotionIDs.put(key.replace(' ', '_'), key); } } } } // Finds events that have IDs with spaces in them and maps those IDs with // underscores instead of spaces to the original id public static void initializeUnderscoreEventIDs() { logger.info("initializeUnderscoreEventIDs"); underScoreEventIDs = new HashMap<>(); // Not actually unchecked @SuppressWarnings("unchecked") Map<String, EventStrings> events = (Map<String, EventStrings>) (ReflectionHacks .getPrivateStatic(LocalizedStrings.class, "events")); if (events != null) { for (String key : events.keySet()) { if (key.contains(" ")) { underScoreEventIDs.put(key.replace(' ', '_'), key); } } } } // Add Sfx in audio map to SoundMaster private static void addAudioToSoundMaster(SoundMaster __instance) { @SuppressWarnings("unchecked") HashMap<String, Sfx> map = (HashMap<String, Sfx>) ReflectionHacks.getPrivate(__instance, SoundMaster.class, "map"); if (map != null) { map.putAll(audioToAdd); logger.info("Added " + audioToAdd.size() + " sounds"); audioToAdd.clear(); } else { logger.warn("Unexpectedly failed to add sounds."); } ReflectionHacks.setPrivate(__instance, SoundMaster.class, "map", map); } static void initializeEncounters() { // maybe change this to use LocalizedStrings instead (like // initializeUnderScorePotionIDs) logger.info("initializeEncounters"); encounterList = new ArrayList<>(); // Construct Encounters try { Field[] fields = MonsterHelper.class.getDeclaredFields(); for (Field f : fields) { // All encounters are public static final Strings // Currently, there are no false positives because the encounters are the only // public static final Strings in the MonsterHelper class. If this changes, the // other constants have to be manually blacklisted here if (f.getType() == String.class) { int mods = f.getModifiers(); if (Modifier.isStatic(mods) && Modifier.isPublic(mods) && Modifier.isFinal(mods)) { encounterList.add((String) f.get(null)); } } } } catch (Exception ex) { ex.printStackTrace(); } // Finds encounters that have IDs with spaces in them and maps those IDs with // underscores instead of spaces to the original id underScoreEncounterIDs = new HashMap<>(); for (String id : encounterList) { if (id.contains(" ")) { underScoreEncounterIDs.put(id.replace(' ', '_'), id); } } } // Finds cards that have IDs with spaces in them and maps those IDs with // underscores instead of spaces to the original id public static void initializeUnderscoreCardIDs() { logger.info("initializeUnderscoreCardIDs"); underScoreCardIDs = new HashMap<>(); for (String key : CardLibrary.cards.keySet()) { if (key.contains(" ")) { underScoreCardIDs.put(key.replace(' ', '_'), key); } } } // Finds relics that have IDs with spaces in them and maps those IDs with // underscores instead of spaces to the original id public static void initializeUnderscoreRelicIDs() { logger.info("initializeUnderscoreRelicIDs"); underScoreRelicIDs = new HashMap<>(); for (String id : listAllRelicIDs()) { if (id.contains(" ")) { underScoreRelicIDs.put(id.replace(' ', '_'), id); } } } private static void initializePowerMap() { logger.info("initializePowerMap"); powerMap = new HashMap<>(); ClassFinder finder = new ClassFinder(); try { ClassPool pool = Loader.getClassPool(); CtClass ctCls = pool.get(AbstractPower.class.getName()); String url = ctCls.getURL().getFile(); int i = url.lastIndexOf('!'); url = url.substring(0, i); URL locationURL = new URL(url); finder.add(new File(locationURL.toURI())); ClassFilter filter = new AndClassFilter( new NotClassFilter(new InterfaceOnlyClassFilter()), new NotClassFilter(new AbstractClassFilter()), new RegexClassFilter("com\\.megacrit\\.cardcrawl\\.powers\\..+") ); Collection<ClassInfo> foundClasses = new ArrayList<>(); finder.findClasses(foundClasses, filter); for (ClassInfo classInfo : foundClasses) { if (classInfo.getClassName().contains("$")) { continue; } try { if (!CloneablePowerInterface.class.isAssignableFrom(BaseMod.class.getClassLoader().loadClass(classInfo.getClassName()))) { logger.warn(String.format("Power (%s) isn't Cloneable", classInfo.getClassName())); } for (FieldInfo fieldInfo : classInfo.getFields()) { if (fieldInfo.getName().equals("POWER_ID") && fieldInfo.getValue() instanceof String) { powerMap.put((String) fieldInfo.getValue(), (Class<? extends AbstractPower>) BaseMod.class.getClassLoader().loadClass(classInfo.getClassName())); break; } } } catch (ClassNotFoundException e) { System.out.println("ERROR: Failed to load power class: " + classInfo.getClassName()); } } } catch (URISyntaxException | MalformedURLException | NotFoundException e) { e.printStackTrace(); } } // Finds powers that have IDs with spaces in them and maps those IDs with // underscores instead of spaces to the original id public static void initializeUnderscorePowerIDs() { logger.info("initializeUnderscorePowerIDs"); underScorePowerIDs = new HashMap<>(); for (String key : powerMap.keySet()) { if (key.contains(" ")) { underScorePowerIDs.put(key.replace(' ', '_'), key); } } } // // Mod badges // public static void registerModBadge(Texture t, String name, String author, String desc, ModPanel settingsPanel) { logger.info("registerModBadge : " + name); int modBadgeCount = modBadges.size(); int col = (modBadgeCount % BADGES_PER_ROW); int row = (modBadgeCount / BADGES_PER_ROW); float x = (BADGES_X * Settings.scale) + (col * BADGE_W * Settings.scale); float y = (BADGES_Y * Settings.scale) - (row * BADGE_H * Settings.scale); ModBadge badge = new ModBadge(t, x, y, name, author, desc, settingsPanel); modBadges.add(badge); } public static String colorString(String input, String colorValue) { StringBuilder retVal = new StringBuilder(); Scanner s = new Scanner(input); while (s.hasNext()) { retVal.append("[").append(colorValue).append("]").append(s.next()); retVal.append(" "); } s.close(); return retVal.toString().trim(); } // // Localization // @SuppressWarnings({ "unchecked", "rawtypes" }) private static void loadJsonStrings(Type stringType, String jsonString) { logger.info("loadJsonStrings: " + stringType.getTypeName()); String typeMap = typeMaps.get(stringType); Type typeToken = typeTokens.get(stringType); String modName = BaseMod.findCallingModName(); Map localizationStrings = (Map) ReflectionHacks.getPrivateStatic(LocalizedStrings.class, typeMap); Map map = new HashMap(gson.fromJson(jsonString, typeToken)); if (stringType.equals(CardStrings.class) || stringType.equals(RelicStrings.class)) { Map map2 = new HashMap(); for (Object k : map.keySet()) { map2.put(modName == null ? k : modName + ":" + k, map.get(k)); } localizationStrings.putAll(map2); } else { localizationStrings.putAll(map); } ReflectionHacks.setPrivateStaticFinal(LocalizedStrings.class, typeMap, localizationStrings); } // loadCustomRelicStrings - loads custom RelicStrings from provided JSON // should be done inside the callback of an implementation of // EditStringsSubscriber public static void loadCustomStrings(Class<?> stringType, String jsonString) { loadJsonStrings(stringType, jsonString); } public static void loadCustomStringsFile(Class<?> stringType, String filepath) { loadJsonStrings(stringType, Gdx.files.internal(filepath).readString(String.valueOf(StandardCharsets.UTF_8))); } // // Cards // // red add - public static ArrayList<AbstractCard> getRedCardsToAdd() { return redToAdd; } // red remove - public static ArrayList<String> getRedCardsToRemove() { return redToRemove; } // green add - public static ArrayList<AbstractCard> getGreenCardsToAdd() { return greenToAdd; } // green remove - public static ArrayList<String> getGreenCardsToRemove() { return greenToRemove; } // blue add - public static ArrayList<AbstractCard> getBlueCardsToAdd() { return blueToAdd; } // blue remove - public static ArrayList<String> getBlueCardsToRemove() { return blueToRemove; } // purple add - public static ArrayList<AbstractCard> getPurpleCardsToAdd() { return purpleToAdd; } // purple remove - public static ArrayList<String> getPurpleCardsToRemove() { return purpleToRemove; } // colorless add - public static ArrayList<AbstractCard> getColorlessCardsToAdd() { return colorlessToAdd; } // colorless remove - public static ArrayList<String> getColorlessCardsToRemove() { return colorlessToRemove; } // curse add - public static ArrayList<AbstractCard> getCurseCardsToAdd() { return curseToAdd; } // curse remove - public static ArrayList<String> getCurseCardsToRemove() { return curseToRemove; } // custom add - public static ArrayList<AbstractCard> getCustomCardsToAdd() { return customToAdd; } // custom remove - public static ArrayList<String> getCustomCardsToRemove() { return customToRemove; } // custom remove colors - public static ArrayList<AbstractCard.CardColor> getCustomCardsToRemoveColors() { return customToRemoveColors; } // add audio to add public static void addAudio(String audioKey, String file) { FileHandle sfxFile = Gdx.files.internal(file); // Ensure audio is valid file if (sfxFile != null && sfxFile.exists()) { Sfx audioSfx = new Sfx(file, false); audioToAdd.put(audioKey, audioSfx); } else { logger.warn("Audio file: " + file + " was not found."); } } // add card public static void addCard(AbstractCard card) { switch (card.color) { case RED: redToAdd.add(card); break; case GREEN: greenToAdd.add(card); break; case BLUE: blueToAdd.add(card); break; case PURPLE: purpleToAdd.add(card); break; case COLORLESS: colorlessToAdd.add(card); break; case CURSE: curseToAdd.add(card); break; default: customToAdd.add(card); break; } } // remove card public static void removeCard(String card, AbstractCard.CardColor color) { switch (color) { case RED: redToRemove.add(card); break; case GREEN: greenToRemove.add(card); break; case BLUE: blueToRemove.add(card); break; case PURPLE: purpleToRemove.add(card); case COLORLESS: colorlessToRemove.add(card); break; case CURSE: curseToRemove.add(card); break; default: customToRemove.add(card); customToRemoveColors.add(color); break; } } public static void addDynamicVariable(DynamicVariable dv) { cardDynamicVariableMap.put(dv.key(), dv); } /** * Modifies the damage done by a card by seeing if the card is a CustomCard and * if so, going ahead and calling the damage modification method default * implementation leaves the damage the same * * @param player * the player casting this card * @param mo * the monster this card is targetting (may be null for multiTarget) * @param c * the card being cast * @param tmp * the current damage amount * @return the modified damage amount */ public static float calculateCardDamage(AbstractPlayer player, AbstractMonster mo, AbstractCard c, float tmp) { if (c instanceof CustomCard) { float newVal = ((CustomCard) c).calculateModifiedCardDamage(player, mo, tmp); if ((int) newVal != c.baseDamage) { c.isDamageModified = true; } return newVal; } else { return tmp; } } /* * same as above but without the monster */ public static float calculateCardDamage(AbstractPlayer player, AbstractCard c, float tmp) { return calculateCardDamage(player, null, c, tmp); } // // Relics // // these adders and removers prevent modders from having to deal with // RelicLibrary's need to keep track // of counts and multiple lists by abstracting it away to simple addRelic // and removeRelic calls // // add relic - public static void addRelic(AbstractRelic relic, RelicType type) { switch (type) { case SHARED: RelicLibrary.add(relic); break; case RED: RelicLibrary.addRed(relic); break; case GREEN: RelicLibrary.addGreen(relic); break; case BLUE: RelicLibrary.addBlue(relic); break; case PURPLE: RelicLibrary.addPurple(relic); break; default: logger.info("tried to add relic of unsupported type: " + relic + " " + type); return; } if (relic instanceof CustomBottleRelic) { registerBottleRelic(((CustomBottleRelic) relic).isOnCard(), relic); } } // remove relic - @SuppressWarnings("unchecked") public static void removeRelic(AbstractRelic relic, RelicType type) { // note that this has to use reflection hacks to change the private // variables in RelicLibrary to successfully remove the relics // // this could be accomplished without reflection hacks by creating a // @SpirePatch to enable relic removal functionality // // as of right now I'm not sure which method is preferable // removeCard is using the @SpirePatch method switch (type) { case SHARED: HashMap<String, AbstractRelic> sharedRelics = (HashMap<String, AbstractRelic>) ReflectionHacks .getPrivateStatic(RelicLibrary.class, "sharedRelics"); if (sharedRelics.containsKey(relic.relicId)) { sharedRelics.remove(relic.relicId); RelicLibrary.totalRelicCount--; removeRelicFromTierList(relic); } break; case RED: HashMap<String, AbstractRelic> redRelics = (HashMap<String, AbstractRelic>) ReflectionHacks .getPrivateStatic(RelicLibrary.class, "redRelics"); if (redRelics.containsKey(relic.relicId)) { redRelics.remove(relic.relicId); RelicLibrary.totalRelicCount--; removeRelicFromTierList(relic); } break; case GREEN: HashMap<String, AbstractRelic> greenRelics = (HashMap<String, AbstractRelic>) ReflectionHacks .getPrivateStatic(RelicLibrary.class, "greenRelics"); if (greenRelics.containsKey(relic.relicId)) { greenRelics.remove(relic.relicId); RelicLibrary.totalRelicCount--; removeRelicFromTierList(relic); } break; case BLUE: HashMap<String, AbstractRelic> blueRelics = (HashMap<String, AbstractRelic>) ReflectionHacks .getPrivateStatic(RelicLibrary.class, "blueRelics"); if (blueRelics.containsKey(relic.relicId)) { blueRelics.remove(relic.relicId); RelicLibrary.totalRelicCount--; removeRelicFromTierList(relic); } break; case PURPLE: HashMap<String, AbstractRelic> purpleRelics = (HashMap<String, AbstractRelic>) ReflectionHacks .getPrivateStatic(RelicLibrary.class, "purpleRelics"); if (purpleRelics.containsKey(relic.relicId)) { purpleRelics.remove(relic.relicId); RelicLibrary.totalRelicCount--; removeRelicFromTierList(relic); } break; default: logger.info("tried to remove relic of unsupported type: " + relic + " " + type); } } // remove custom relic - @SuppressWarnings("unchecked") public static void removeRelicFromCustomPool(AbstractRelic relic, AbstractCard.CardColor color) { if (relic == null) return; if (customRelicPools.containsKey(color)){ if (customRelicPools.get(color).containsKey(relic.relicId)) { customRelicPools.get(color).remove(relic.relicId); --RelicLibrary.totalRelicCount; removeRelicFromTierList(relic); } } if (customRelicLists.containsKey(color)){ if (customRelicLists.get(color).contains(relic)){ customRelicLists.get(color).remove(relic); } } } public static void registerBottleRelic(Predicate<AbstractCard> isOnCard, AbstractRelic relic) { customBottleRelics.put(relic.relicId, new Pair<>(isOnCard, relic)); } public static void registerBottleRelic(SpireField<Boolean> isOnCard, AbstractRelic relic) { customBottleRelics.put(relic.relicId, new Pair<>(isOnCard::get, relic)); } // addRelicToCustomPool - public static void addRelicToCustomPool(AbstractRelic relic, AbstractCard.CardColor color) { if (customRelicPools.containsKey(color)) { if (UnlockTracker.isRelicSeen(relic.relicId)) { RelicLibrary.seenRelics++; } relic.isSeen = UnlockTracker.isRelicSeen(relic.relicId); customRelicPools.get(color).put(relic.relicId, relic); RelicLibrary.addToTierList(relic); customRelicLists.get(color).add(relic); if (relic instanceof CustomBottleRelic) { registerBottleRelic(((CustomBottleRelic) relic).isOnCard(), relic); } } else { logger.error("could not add relic to non existent custom pool: " + color); } } // getRelicsInCustomPool - public static HashMap<String, AbstractRelic> getRelicsInCustomPool(AbstractCard.CardColor color) { return customRelicPools.get(color); } // getAllCustomRelics - public static HashMap<AbstractCard.CardColor, HashMap<String, AbstractRelic>> getAllCustomRelics() { return customRelicPools; } // getCustomRelic - public static AbstractRelic getCustomRelic(String key) { for (HashMap<String, AbstractRelic> map : BaseMod.getAllCustomRelics().values()) { if (map.containsKey(key)) { return map.get(key); } } return new Circlet(); } public static Collection<Pair<Predicate<AbstractCard>, AbstractRelic>> getBottledRelicList() { return customBottleRelics.values(); } private static void removeRelicFromTierList(AbstractRelic relic) { switch (relic.tier) { case STARTER: RelicLibrary.starterList.remove(relic); break; case COMMON: RelicLibrary.commonList.remove(relic); break; case UNCOMMON: RelicLibrary.uncommonList.remove(relic); break; case RARE: RelicLibrary.rareList.remove(relic); break; case SHOP: RelicLibrary.shopList.remove(relic); break; case SPECIAL: RelicLibrary.specialList.remove(relic); break; case BOSS: RelicLibrary.bossList.remove(relic); break; case DEPRECATED: logger.info(relic.relicId + " is deprecated."); break; default: logger.info(relic.relicId + "is undefined tier."); } } // force remove relic - public static void removeRelic(AbstractRelic relic) { removeRelic(relic, RelicType.SHARED); removeRelic(relic, RelicType.RED); removeRelic(relic, RelicType.GREEN); removeRelic(relic, RelicType.BLUE); removeRelic(relic, RelicType.PURPLE); } // lists the IDs of all Relics from all pools. The casts are actually not // unchecked @SuppressWarnings("unchecked") public static ArrayList<String> listAllRelicIDs() { // Set to prevent duplicates HashSet<String> relicIDs = new HashSet<>(); HashMap<String, AbstractRelic> sharedRelics = (HashMap<String, AbstractRelic>) ReflectionHacks .getPrivateStatic(RelicLibrary.class, "sharedRelics"); if (sharedRelics != null) { relicIDs.addAll(sharedRelics.keySet()); } HashMap<String, AbstractRelic> redRelics = (HashMap<String, AbstractRelic>) ReflectionHacks .getPrivateStatic(RelicLibrary.class, "redRelics"); if (redRelics != null) { relicIDs.addAll(redRelics.keySet()); } HashMap<String, AbstractRelic> greenRelics = (HashMap<String, AbstractRelic>) ReflectionHacks .getPrivateStatic(RelicLibrary.class, "greenRelics"); if (greenRelics != null) { relicIDs.addAll(greenRelics.keySet()); } HashMap<String, AbstractRelic> blueRelics = (HashMap<String, AbstractRelic>) ReflectionHacks .getPrivateStatic(RelicLibrary.class, "blueRelics"); if (blueRelics != null) { relicIDs.addAll(blueRelics.keySet()); } HashMap<String, AbstractRelic> purpleRelics = (HashMap<String, AbstractRelic>) ReflectionHacks .getPrivateStatic(RelicLibrary.class, "purpleRelics"); if (purpleRelics != null) { relicIDs.addAll(purpleRelics.keySet()); } if (getAllCustomRelics() != null) { for (HashMap<String, AbstractRelic> e : getAllCustomRelics().values()) { if (e != null) { relicIDs.addAll(e.keySet()); } } } // But return ArrayList to maintain backwards compatibility return new ArrayList<>(relicIDs); } private static HashMap<RewardItem.RewardType, LoadCustomReward> customRewardOnLoadConsumers = new HashMap<>(); private static HashMap<RewardItem.RewardType, SaveCustomReward> customRewardOnSaveConsumers = new HashMap<>(); public static void registerCustomReward(CustomReward.RewardType type, LoadCustomReward onLoad, SaveCustomReward onSave) { customRewardOnLoadConsumers.put(type, onLoad); customRewardOnSaveConsumers.put(type, onSave); } public static CustomReward loadCustomRewardFromSave(RewardSave rewardSave) { return customRewardOnLoadConsumers.get(RewardItem.RewardType.valueOf(rewardSave.type)).onLoad(rewardSave); } public static RewardSave saveCustomReward(CustomReward reward) { return customRewardOnSaveConsumers.get(reward.type).onSave(reward); } public static boolean customRewardTypeExists(RewardItem.RewardType type){ return customRewardOnSaveConsumers.containsKey(type) && customRewardOnLoadConsumers.containsKey(type); } public interface LoadCustomReward { CustomReward onLoad(RewardSave rewardSave); } public interface SaveCustomReward { RewardSave onSave(CustomReward reward); } // // Events // // Additional documentation can be found in EventUtils. public static void addEvent(String eventID, Class<? extends AbstractEvent> eventClass) { addEvent(new AddEventParams.Builder(eventID, eventClass).create()); } public static void addEvent(String eventID, Class<? extends AbstractEvent> eventClass, String dungeonID) { addEvent( new AddEventParams.Builder(eventID, eventClass) .dungeonID(dungeonID) .create() ); } public static void addEvent(AddEventParams params) { EventUtils.registerEvent( params.eventID, params.eventClass, params.playerClass, params.dungeonIDs.toArray(new String[0]), params.spawnCondition, params.overrideEventID, params.bonusCondition, params.eventType ); } //implemented to avoid issues if someone uses them. @Deprecated //Labeled as deprecated because changes here will have no impact on what events appear. public static HashMap<String, Class<? extends AbstractEvent>> getEventList(String dungeonID) { return EventUtils.getDungeonEvents(dungeonID); } public static Class<? extends AbstractEvent> getEvent(String eventID) { return EventUtils.getEventClass(eventID); } // // Top Panel // public static void addTopPanelItem(TopPanelItem topPanelItem) { TopPanelHelper.topPanelGroup.addPanelItem(topPanelItem); } public static void removeTopPanelItem(TopPanelItem topPanelItem){ TopPanelHelper.topPanelGroup.removePanelItem(topPanelItem); } // // Monsters // // Key: Encounter ID // Value: Encounter nice name private static HashMap<String, String> customMonsterNames = new HashMap<>(); // Key: Encounter ID private static HashMap<String, GetMonsterGroup> customMonsters = new HashMap<>(); // Key: Dungeon ID // Value: Encounter ID private static HashMap<String, List<MonsterInfo>> customMonsterEncounters = new HashMap<>(); // Key: Dungeon ID // Value: Encounter ID private static HashMap<String, List<MonsterInfo>> customStrongMonsterEncounters = new HashMap<>(); // Key: Dungeon ID // Value: Encounter ID private static HashMap<String, List<MonsterInfo>> customEliteEncounters = new HashMap<>(); public interface GetMonsterGroup { MonsterGroup get(); } public interface GetMonster { AbstractMonster get(); } private static String autoCalculateMonsterName(GetMonsterGroup group) { StringBuilder ret = new StringBuilder(); if (AbstractDungeon.monsterRng == null) { Settings.seed = 0L; AbstractDungeon.generateSeeds(); } MonsterGroup monsters = group.get(); boolean first = true; for (AbstractMonster monster : monsters.monsters) { if (!first) { ret.append(", "); } first = false; ret.append(monster.name); } return ret.toString(); } public static void addMonster(String encounterID, GetMonster monster) { addMonster(encounterID, () -> new MonsterGroup(monster.get())); } public static void addMonster(String encounterID, String name, GetMonster monster) { addMonster(encounterID, name, () -> new MonsterGroup(monster.get())); } public static void addMonster(String encounterID, GetMonsterGroup group) { addMonster(encounterID, autoCalculateMonsterName(group), group); } public static void addMonster(String encounterID, String name, GetMonsterGroup group) { customMonsters.put(encounterID, group); customMonsterNames.put(encounterID, name); encounterList.add(encounterID); if (encounterID.contains(" ")) { underScoreEncounterIDs.put(encounterID.replace(' ', '_'), encounterID); } } public static MonsterGroup getMonster(String encounterID) { GetMonsterGroup getter = customMonsters.get(encounterID); if (getter == null) { return null; } return getter.get(); } public static String getMonsterName(String encounterID) { return customMonsterNames.getOrDefault(encounterID, ""); } public static boolean customMonsterExists(String encounterID) { return customMonsters.containsKey(encounterID); } public static void addEliteEncounter(String dungeonID, MonsterInfo encounter) { if (!customEliteEncounters.containsKey(dungeonID)) { customEliteEncounters.put(dungeonID, new ArrayList<>()); } customEliteEncounters.get(dungeonID).add(encounter); } public static void addStrongMonsterEncounter(String dungeonID, MonsterInfo encounter) { if (!customStrongMonsterEncounters.containsKey(dungeonID)) { customStrongMonsterEncounters.put(dungeonID, new ArrayList<>()); } customStrongMonsterEncounters.get(dungeonID).add(encounter); } public static void addMonsterEncounter(String dungeonID, MonsterInfo encounter) { if (!customMonsterEncounters.containsKey(dungeonID)) { customMonsterEncounters.put(dungeonID, new ArrayList<>()); } customMonsterEncounters.get(dungeonID).add(encounter); } public static List<MonsterInfo> getEliteEncounters(String dungeonID) { if (customEliteEncounters.containsKey(dungeonID)) { return customEliteEncounters.get(dungeonID); } return new ArrayList<>(); } public static List<MonsterInfo> getStrongMonsterEncounters(String dungeonID) { if (customStrongMonsterEncounters.containsKey(dungeonID)) { return customStrongMonsterEncounters.get(dungeonID); } return new ArrayList<>(); } public static List<MonsterInfo> getMonsterEncounters(String dungeonID) { if (customMonsterEncounters.containsKey(dungeonID)) { return customMonsterEncounters.get(dungeonID); } return new ArrayList<>(); } // // Bosses // private static HashMap<String, List<BossInfo>> customBosses = new HashMap<>(); public static class BossInfo { public final String id; private final String bossMap; private final String bossMapOutline; private BossInfo(String id, String mapIcon, String mapIconOutline) { this.id = id; bossMap = mapIcon; bossMapOutline = mapIconOutline; } public Texture loadBossMap() { return ImageMaster.loadImage(bossMap); } public Texture loadBossMapOutline() { return ImageMaster.loadImage(bossMapOutline); } } public static void addBoss(String dungeon, String bossID, String mapIcon, String mapIconOutline) { if (!customBosses.containsKey(dungeon)) { customBosses.put(dungeon, new ArrayList<>()); } BossInfo info = new BossInfo(bossID, mapIcon, mapIconOutline); customBosses.get(dungeon).add(info); } public static List<String> getBossIDs(String dungeonID) { if (customBosses.containsKey(dungeonID)) { return customBosses.get(dungeonID).stream() .map(info -> info.id) .collect(Collectors.toList()); } return new ArrayList<>(); } public static BossInfo getBossInfo(String bossID) { if (bossID == null) { return null; } for (List<BossInfo> infos : customBosses.values()) { for (BossInfo info : infos) { if (bossID.equals(info.id)) { return info; } } } return null; } // // Keywords // public static void addKeyword(String[] names, String description) { addKeyword(null, names, description); } public static void addKeyword(String proper, String[] names, String description) { addKeyword(null, proper, names, description); } public static void addKeyword(String modID, String proper, String[] names, String description) { if (modID != null && !modID.isEmpty()) { if (!modID.endsWith(":")) { modID = modID + ":"; } String uniqueParent = names[0]; for (int i=0; i<names.length; ++i) { names[i] = modID + names[i]; } for (String name : names) { keywordUniqueNames.put(name, uniqueParent); keywordUniquePrefixes.put(name, modID); } } String parent = names[0]; if (proper != null) { keywordProperNames.put(parent, proper); } for (String name : names) { GameDictionary.keywords.put(name, description); GameDictionary.parentWord.put(name, parent); } } public static String getKeywordProper(String keyword) { return keywordProperNames.get(keyword); } public static String getKeywordUnique(String keyword) { return keywordUniqueNames.get(keyword); } public static boolean keywordIsUnique(String keyword) { return keywordUniqueNames.containsKey(keyword); } public static String getKeywordPrefix(String keyword) { return keywordUniquePrefixes.get(keyword); } public static String getKeywordTitle(String keyword) { keyword = GameDictionary.parentWord.get(keyword); String title = getKeywordProper(keyword); if (title != null) { return title; } return TipHelper.capitalize(keyword); } public static String getKeywordDescription(String keyword) { keyword = GameDictionary.parentWord.get(keyword); return GameDictionary.keywords.get(keyword); } // // Unlocks // // add new unlock bundle public static void addUnlockBundle(CustomUnlockBundle bundle, AbstractPlayer.PlayerClass c, int unlockLevel) { if (bundle == null) { return; } if (!unlockBundles.containsKey(c)) { HashMap<Integer, CustomUnlockBundle> newBundles = new HashMap<>(); newBundles.put(unlockLevel, bundle); unlockBundles.put(c, newBundles); } else { HashMap<Integer, CustomUnlockBundle> bundles = unlockBundles.get(c); bundles.put(unlockLevel, bundle); } if (bundle.unlockType == AbstractUnlock.UnlockType.CARD) { if (!unlockCards.containsKey(c)) unlockCards.put(c, new ArrayList<>()); for (String s : bundle.getUnlockIDs()) { if (!unlockCards.get(c).contains(s)) unlockCards.get(c).add(s); } } if (maxUnlockLevel.containsKey(c)) { maxUnlockLevel.put(c, Math.max(maxUnlockLevel.get(c), unlockLevel)); } else { maxUnlockLevel.put(c, unlockLevel); } } // remove old unlock bundle public static void removeUnlockBundle(AbstractPlayer.PlayerClass c, int unlockLevel) { if (unlockBundles.containsKey(c)) { unlockBundles.get(c).remove(unlockLevel); } } // get unlock bundle for class and level public static CustomUnlockBundle getUnlockBundleFor(AbstractPlayer.PlayerClass c, int unlockLevel) { HashMap<Integer, CustomUnlockBundle> levelMap = unlockBundles.get(c); if (levelMap == null) { return null; } return levelMap.get(unlockLevel); } // get list of unlocks (cards) public static ArrayList<String> getUnlockCards(AbstractPlayer.PlayerClass c) { return unlockCards.get(c); } // get the number of unlock levels for class public static int getMaxUnlockLevel(AbstractPlayer p) { return getMaxUnlockLevel(p.chosenClass); } public static int getMaxUnlockLevel(AbstractPlayer.PlayerClass c) { if (maxUnlockLevel.containsKey(c)) { return maxUnlockLevel.get(c); } return 0; } // // Characters // public static AbstractPlayer findCharacter(AbstractPlayer.PlayerClass playerClass) { for (AbstractPlayer character : CardCrawlGame.characterManager.getAllCharacters()) { if (character.chosenClass == playerClass) { return character; } } return null; } public static List<AbstractPlayer> getModdedCharacters() { return CardCrawlGame.characterManager.getAllCharacters().subList(lastBaseCharacterIndex+1, CardCrawlGame.characterManager.getAllCharacters().size()); } // add character - the String characterID *must* be the exact same as what // you put in the PlayerClass enum public static void addCharacter(AbstractPlayer character, String selectButtonPath, String portraitPath, PlayerClass characterID, String customModeButtonPath) { CardCrawlGame.characterManager.getAllCharacters().add(character); playerSelectButtonMap.put(characterID, selectButtonPath); customModeCharacterButtonMap.put(characterID, customModeButtonPath); playerPortraitMap.put(characterID, portraitPath); } public static void addCharacter(AbstractPlayer character, String selectButtonPath, String portraitPath, PlayerClass characterID) { addCharacter(character, selectButtonPath, portraitPath, characterID, null); } public static TextureAtlas.AtlasRegion getCardSmallEnergy() { if (AbstractDungeon.player == null) { return AbstractCard.orb_red; } return AbstractDungeon.player.getOrb(); } public static TextureAtlas.AtlasRegion getCardSmallEnergy(AbstractCard card) { switch (card.color) { case RED: return AbstractCard.orb_red; case GREEN: return AbstractCard.orb_green; case BLUE: return AbstractCard.orb_blue; case PURPLE: return AbstractCard.orb_purple; case COLORLESS: return getCardSmallEnergy(); // for colorless cards, use the player color default: return getCardEnergyOrbAtlasRegion(card.color); } } // convert a playerClass into the player select button public static String getPlayerButton(PlayerClass playerClass) { return playerSelectButtonMap.get(playerClass); } // convert a playerClass into the custom mode player select button public static String getCustomModePlayerButton(PlayerClass playerClass) { return customModeCharacterButtonMap.get(playerClass); } // convert a playerClass into the player portrait public static String getPlayerPortrait(PlayerClass playerClass) { return playerPortraitMap.get(playerClass); } // generate character options for CharacterSelectScreen based on added // players public static ArrayList<CharacterOption> generateCharacterOptions() { ArrayList<CharacterOption> options = new ArrayList<>(); for (AbstractPlayer character : getModdedCharacters()) { CharacterOption option = new CharacterOption( character.getLocalizedCharacterName(), CardCrawlGame.characterManager.recreateCharacter(character.chosenClass), ImageMaster.loadImage(playerSelectButtonMap.get(character.chosenClass)), ImageMaster.loadImage(playerPortraitMap.get(character.chosenClass)) ); options.add(option); } // Sort alphabetically by character name options.sort(Comparator.comparing(o -> o.name)); return options; } // generate character options for CustomModeScreen based on added players public static ArrayList<CustomModeCharacterButton> generateCustomCharacterOptions() { ArrayList<CustomModeCharacterButton> options = new ArrayList<>(); for (AbstractPlayer character : getModdedCharacters()) { options.add(new CustomModeCharacterButton(CardCrawlGame.characterManager.setChosenCharacter(character.chosenClass), false)); } return options; } // // Colors // // add a color - public static void addColor(AbstractCard.CardColor color, Color everythingColor, String attackBg, String skillBg, String powerBg, String energyOrb, String attackBgPortrait, String skillBgPortrait, String powerBgPortrait, String energyOrbPortrait, String cardEnergyOrb) { addColor(color, everythingColor, everythingColor, everythingColor, everythingColor, everythingColor, everythingColor, everythingColor, attackBg, skillBg, powerBg, energyOrb, attackBgPortrait, skillBgPortrait, powerBgPortrait, energyOrbPortrait, cardEnergyOrb); } public static void addColor(AbstractCard.CardColor color, com.badlogic.gdx.graphics.Color bgColor, com.badlogic.gdx.graphics.Color backColor, com.badlogic.gdx.graphics.Color frameColor, com.badlogic.gdx.graphics.Color frameOutlineColor, com.badlogic.gdx.graphics.Color descBoxColor, com.badlogic.gdx.graphics.Color trailVfxColor, com.badlogic.gdx.graphics.Color glowColor, String attackBg, String skillBg, String powerBg, String energyOrb, String attackBgPortrait, String skillBgPortrait, String powerBgPortrait, String energyOrbPortrait) { addColor(color, bgColor, backColor, frameColor, frameOutlineColor, descBoxColor, trailVfxColor, glowColor, attackBg, skillBg, powerBg, energyOrb, attackBgPortrait, skillBgPortrait, powerBgPortrait, energyOrbPortrait, null); } public static void addColor(AbstractCard.CardColor color, com.badlogic.gdx.graphics.Color bgColor, com.badlogic.gdx.graphics.Color backColor, com.badlogic.gdx.graphics.Color frameColor, com.badlogic.gdx.graphics.Color frameOutlineColor, com.badlogic.gdx.graphics.Color descBoxColor, com.badlogic.gdx.graphics.Color trailVfxColor, com.badlogic.gdx.graphics.Color glowColor, String attackBg, String skillBg, String powerBg, String energyOrb, String attackBgPortrait, String skillBgPortrait, String powerBgPortrait, String energyOrbPortrait, String cardEnergyOrb) { colorBgColorMap.put(color, bgColor); colorBackColorMap.put(color, backColor); colorFrameColorMap.put(color, frameColor); colorFrameOutlineColorMap.put(color, frameOutlineColor); colorDescBoxColorMap.put(color, descBoxColor); colorTrailVfxMap.put(color, trailVfxColor); colorGlowColorMap.put(color, glowColor); colorCardCountMap.put(color, 0); colorCardSeenCountMap.put(color, 0); colorAttackBgMap.put(color, attackBg); colorSkillBgMap.put(color, skillBg); colorPowerBgMap.put(color, powerBg); colorEnergyOrbMap.put(color, energyOrb); colorAttackBgPortraitMap.put(color, attackBgPortrait); colorSkillBgPortraitMap.put(color, skillBgPortrait); colorPowerBgPortraitMap.put(color, powerBgPortrait); colorEnergyOrbPortraitMap.put(color, energyOrbPortrait); colorCardEnergyOrbMap.put(color, cardEnergyOrb); customRelicPools.put(color, new HashMap<>()); customRelicLists.put(color, new ArrayList<>()); } // remove a custom color - // removing existing colors not currently supported public static void removeColor(AbstractCard.CardColor color) { colorBgColorMap.remove(color); colorBackColorMap.remove(color); colorFrameColorMap.remove(color); colorFrameOutlineColorMap.remove(color); colorDescBoxColorMap.remove(color); colorTrailVfxMap.remove(color); colorGlowColorMap.remove(color); colorCardCountMap.remove(color); colorCardSeenCountMap.remove(color); colorAttackBgMap.remove(color); colorSkillBgMap.remove(color); colorPowerBgMap.remove(color); colorEnergyOrbMap.remove(color); colorCardEnergyOrbMap.remove(color); colorAttackBgPortraitMap.remove(color); colorSkillBgPortraitMap.remove(color); colorPowerBgPortraitMap.remove(color); colorEnergyOrbPortraitMap.remove(color); customRelicPools.remove(color); customRelicLists.remove(color, new ArrayList<AbstractRelic>()); } public static List<AbstractCard.CardColor> getCardColors() { return new ArrayList<>(colorTrailVfxMap.keySet()); } // convert a color into a background color public static com.badlogic.gdx.graphics.Color getBgColor(AbstractCard.CardColor color) { return colorBgColorMap.get(color); } // convert a color into a back color public static com.badlogic.gdx.graphics.Color getBackColor(AbstractCard.CardColor color) { return colorBackColorMap.get(color); } // convert a color into a frame color public static com.badlogic.gdx.graphics.Color getFrameColor(AbstractCard.CardColor color) { return colorFrameColorMap.get(color); } // convert a color into a frame outline color public static com.badlogic.gdx.graphics.Color getFrameOutlineColor(AbstractCard.CardColor color) { return colorFrameOutlineColorMap.get(color); } // convert a color into a desc box color public static com.badlogic.gdx.graphics.Color getDescBoxColor(AbstractCard.CardColor color) { return colorDescBoxColorMap.get(color); } // convert a color into a trail vfx color public static com.badlogic.gdx.graphics.Color getTrailVfxColor(AbstractCard.CardColor color) { return colorTrailVfxMap.get(color); } // increment the card count for a color public static void incrementCardCount(AbstractCard.CardColor color) { Integer count = colorCardCountMap.get(color); //System.out.println("incrementing card count for " + color + " to " + colorCardCountMap.get(color)); if (count != null) { colorCardCountMap.put(color, count + 1); } else { colorCardCountMap.put(color, 0); } } // decrement the card count for a color public static void decrementCardCount(AbstractCard.CardColor color) { Integer count = colorCardCountMap.get(color); if (count != null) { colorCardCountMap.put(color, count - 1); if (colorCardCountMap.get(color) < 0) { colorCardCountMap.remove(color); } } } // get card count for a color public static int getCardCount(AbstractCard.CardColor color) { Integer count = colorCardCountMap.get(color); if (count == null) { return -1; } return count; } // increment the seen card count for a color public static void incrementSeenCardCount(AbstractCard.CardColor color) { Integer count = colorCardSeenCountMap.get(color); if (count != null) { colorCardSeenCountMap.put(color, count + 1); } else { colorCardSeenCountMap.put(color, 0); } } // get seen card count for a color public static int getSeenCardCount(AbstractCard.CardColor color) { Integer count = colorCardSeenCountMap.get(color); if (count == null) { return -1; } return count; } // convert a color into a glow color public static com.badlogic.gdx.graphics.Color getGlowColor(AbstractCard.CardColor color) { return colorGlowColorMap.get(color); } // convert a color into an attack background texture path public static String getAttackBg(AbstractCard.CardColor color) { return colorAttackBgMap.get(color); } // convert a color into an skill background texture path public static String getSkillBg(AbstractCard.CardColor color) { return colorSkillBgMap.get(color); } // convert a color into an power background texture path public static String getPowerBg(AbstractCard.CardColor color) { return colorPowerBgMap.get(color); } // convert a color into an energy texture path public static String getEnergyOrb(AbstractCard.CardColor color) { return colorEnergyOrbMap.get(color); } // convert a color into an attack background portrait texture path public static String getAttackBgPortrait(AbstractCard.CardColor color) { return colorAttackBgPortraitMap.get(color); } // convert a color into an skill background portrait texture path public static String getSkillBgPortrait(AbstractCard.CardColor color) { return colorSkillBgPortraitMap.get(color); } // convert a color into an power background portrait texture path public static String getPowerBgPortrait(AbstractCard.CardColor color) { return colorPowerBgPortraitMap.get(color); } // convert a color into an energy portrait texture path public static String getEnergyOrbPortrait(AbstractCard.CardColor color) { return colorEnergyOrbPortraitMap.get(color); } // convert a color into an attack background texture public static com.badlogic.gdx.graphics.Texture getAttackBgTexture(AbstractCard.CardColor color) { return colorAttackBgTextureMap.get(color); } // convert a color into an skill background texture public static com.badlogic.gdx.graphics.Texture getSkillBgTexture(AbstractCard.CardColor color) { return colorSkillBgTextureMap.get(color); } // convert a color into an power background texture public static com.badlogic.gdx.graphics.Texture getPowerBgTexture(AbstractCard.CardColor color) { return colorPowerBgTextureMap.get(color); } // convert a color into an energy texture public static com.badlogic.gdx.graphics.Texture getEnergyOrbTexture(AbstractCard.CardColor color) { return colorEnergyOrbTextureMap.get(color); } // convert a color into an energy texture path public static TextureAtlas.AtlasRegion getCardEnergyOrbAtlasRegion(AbstractCard.CardColor color) { TextureAtlas.AtlasRegion orb = colorCardEnergyOrbAtlasRegionMap.get(color); if (orb != null) return orb; String orbFile = colorCardEnergyOrbMap.get(color); if (orbFile != null) { Texture orbTexture = ImageMaster.loadImage(orbFile); int tw = orbTexture.getWidth(); int th = orbTexture.getHeight(); orb = new TextureAtlas.AtlasRegion(orbTexture, 0, 0, tw, th); colorCardEnergyOrbAtlasRegionMap.put(color, orb); return orb; } else { return AbstractCard.orb_red; } } // convert a color into an attack background texture public static com.badlogic.gdx.graphics.Texture getAttackBgPortraitTexture(AbstractCard.CardColor color) { return colorAttackBgPortraitTextureMap.get(color); } // convert a color into an skill background texture public static com.badlogic.gdx.graphics.Texture getSkillBgPortraitTexture(AbstractCard.CardColor color) { return colorSkillBgPortraitTextureMap.get(color); } // convert a color into an power background texture public static com.badlogic.gdx.graphics.Texture getPowerBgPortraitTexture(AbstractCard.CardColor color) { return colorPowerBgPortraitTextureMap.get(color); } // convert a color into an energy texture public static com.badlogic.gdx.graphics.Texture getEnergyOrbPortraitTexture(AbstractCard.CardColor color) { return colorEnergyOrbPortraitTextureMap.get(color); } // save a attack background texture for a color public static void saveAttackBgTexture(AbstractCard.CardColor color, com.badlogic.gdx.graphics.Texture tex) { colorAttackBgTextureMap.put(color, tex); } // save a skill background texture for a color public static void saveSkillBgTexture(AbstractCard.CardColor color, com.badlogic.gdx.graphics.Texture tex) { colorSkillBgTextureMap.put(color, tex); } // save a power background texture for a color public static void savePowerBgTexture(AbstractCard.CardColor color, com.badlogic.gdx.graphics.Texture tex) { colorPowerBgTextureMap.put(color, tex); } // save an energy orb texture for a color public static void saveEnergyOrbTexture(AbstractCard.CardColor color, com.badlogic.gdx.graphics.Texture tex) { colorEnergyOrbTextureMap.put(color, tex); } // save a attack background texture for a color public static void saveAttackBgPortraitTexture(AbstractCard.CardColor color, com.badlogic.gdx.graphics.Texture tex) { colorAttackBgPortraitTextureMap.put(color, tex); } // save a skill background texture for a color public static void saveSkillBgPortraitTexture(AbstractCard.CardColor color, com.badlogic.gdx.graphics.Texture tex) { colorSkillBgPortraitTextureMap.put(color, tex); } // save a power background texture for a color public static void savePowerBgPortraitTexture(AbstractCard.CardColor color, com.badlogic.gdx.graphics.Texture tex) { colorPowerBgPortraitTextureMap.put(color, tex); } // save an energy orb texture for a color public static void saveEnergyOrbPortraitTexture(AbstractCard.CardColor color, com.badlogic.gdx.graphics.Texture tex) { colorEnergyOrbPortraitTextureMap.put(color, tex); } // // Potions // public static ArrayList<String> getPotionsToRemove() { return potionsToRemove; } public static void removePotion(String potionID) { potionsToRemove.add(potionID); } // add the Potion to the map public static void addPotion(Class<? extends AbstractPotion> potionClass, Color liquidColor, Color hybridColor, Color spotsColor, String potionID) { addPotion(potionClass, liquidColor, hybridColor, spotsColor, potionID, null); } public static void addPotion(Class<? extends AbstractPotion> potionClass, Color liquidColor, Color hybridColor, Color spotsColor, String potionID, AbstractPlayer.PlayerClass playerClass) { potionClassMap.put(potionID, potionClass); potionLiquidColorMap.put(potionID, liquidColor); potionHybridColorMap.put(potionID, hybridColor); potionSpotsColorMap.put(potionID, spotsColor); potionPlayerClassMap.put(potionID, playerClass); } // return Class corresponding to potionID public static Class<? extends AbstractPotion> getPotionClass(String potionID) { return potionClassMap.get(potionID); } // return Colors corresponding to potionID public static Color getPotionLiquidColor(String potionID) { return potionLiquidColorMap.get(potionID); } public static Color getPotionHybridColor(String potionID) { return potionHybridColorMap.get(potionID); } public static Color getPotionSpotsColor(String potionID) { return potionSpotsColorMap.get(potionID); } public static AbstractPlayer.PlayerClass getPotionPlayerClass(String potionID) { return potionPlayerClassMap.get(potionID); } // get all potion IDs public static Set<String> getPotionIDs() { return potionClassMap.keySet(); } // // Powers // public static void addPower(Class<? extends AbstractPower> powerClass, String powerID) { powerMap.put(powerID, powerClass); if (powerID.contains(" ")) { underScorePowerIDs.put(powerID.replace(' ', '_'), powerID); } } public static Class<? extends AbstractPower> getPowerClass(String powerID) { return powerMap.get(powerID); } public static Set<String> getPowerKeys() { return powerMap.keySet(); } // // Save files // public static <T> void addSaveField(String key, CustomSavableRaw saveField) { customSaveFields.put(key, saveField); } public static Map<String, CustomSavableRaw> getSaveFields() { return customSaveFields; } // // Rich Presence // public static void setRichPresence(String msg) { if (CardCrawlGame.publisherIntegration == null) { return; } if (!(CardCrawlGame.publisherIntegration instanceof SteamIntegration)) { return; } try { Method m = SteamIntegration.class.getDeclaredMethod("setRichPresenceData", String.class, String.class); m.setAccessible(true); m.invoke(CardCrawlGame.publisherIntegration, "status", msg); m.invoke(CardCrawlGame.publisherIntegration, "steam_display", "#Status"); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } // // Publishers // // publishStartAct - public static void publishStartAct() { logger.info("publishStartAct"); for (StartActSubscriber sub : startActSubscribers) { sub.receiveStartAct(); } unsubscribeLaterHelper(StartActSubscriber.class); } // publishPostCampfire - false allows an additional option to be selected public static boolean publishPostCampfire() { logger.info("publishPostCampfire"); boolean campfireDone = true; for (PostCampfireSubscriber sub : postCampfireSubscribers) { if (!sub.receivePostCampfire()) { campfireDone = false; } } unsubscribeLaterHelper(PostCampfireSubscriber.class); return campfireDone; } // publishPostDraw - public static void publishPostDraw(AbstractCard c) { logger.info("publishPostDraw"); for (PostDrawSubscriber sub : postDrawSubscribers) { sub.receivePostDraw(c); } unsubscribeLaterHelper(PostDrawSubscriber.class); } // publishPostExhaust - public static void publishPostExhaust(AbstractCard c) { logger.info("publishPostExhaust"); for (PostExhaustSubscriber sub : postExhaustSubscribers) { sub.receivePostExhaust(c); } unsubscribeLaterHelper(PostExhaustSubscriber.class); } // publishPostDungeonInitialize - public static void publishPostDungeonInitialize() { logger.info("publishPostDungeonInitialize"); for (PostDungeonInitializeSubscriber sub : postDungeonInitializeSubscribers) { sub.receivePostDungeonInitialize(); } unsubscribeLaterHelper(PostDungeonInitializeSubscriber.class); } // publishPostEnergyRecharge - public static void publishPostEnergyRecharge() { logger.info("publishPostEnergyRecharge"); for (PostEnergyRechargeSubscriber sub : postEnergyRechargeSubscribers) { sub.receivePostEnergyRecharge(); } unsubscribeLaterHelper(PostEnergyRechargeSubscriber.class); } // publishPostInitialize - public static void publishPostInitialize() { logger.info("publishPostInitialize"); // setup the necessary bits for custom animations to work setupAnimationGfx(); // Publish for (PostInitializeSubscriber sub : postInitializeSubscribers) { sub.receivePostInitialize(); } unsubscribeLaterHelper(PostInitializeSubscriber.class); } // publishPreMonsterTurn - false skips monster turn public static boolean publishPreMonsterTurn(AbstractMonster m) { logger.info("publishPreMonsterTurn"); boolean takeTurn = true; for (PreMonsterTurnSubscriber sub : preMonsterTurnSubscribers) { if (!sub.receivePreMonsterTurn(m)) { takeTurn = false; } } unsubscribeLaterHelper(PreMonsterTurnSubscriber.class); return takeTurn; } // publishRender - public static void publishRender(SpriteBatch sb) { for (RenderSubscriber sub : renderSubscribers) { sub.receiveRender(sb); } unsubscribeLaterHelper(RenderSubscriber.class); } // publishAnimationRender - public static void publishAnimationRender(SpriteBatch sb) { if (modelRenderSubscribers.size() > 0) { // custom animations sb.end(); CardCrawlGame.psb.begin(); CardCrawlGame.psb.setBlendFunction(GL20.GL_ONE, GL20.GL_ONE_MINUS_SRC_ALPHA); CardCrawlGame.psb.draw(animationTextureRegion, 0, 0); CardCrawlGame.psb.setBlendFunction(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA); CardCrawlGame.psb.end(); sb.begin(); } } // publishPreRender - public static void publishPreRender(OrthographicCamera camera) { for (PreRenderSubscriber sub : preRenderSubscribers) { sub.receiveCameraRender(camera); } if (modelRenderSubscribers.size() > 0) { // custom animations animationBuffer.begin(); Gdx.gl.glClearColor(0f, 0f, 0f, 0f); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); batch.begin(animationCamera); for (ModelRenderSubscriber sub : modelRenderSubscribers) { sub.receiveModelRender(batch, animationEnvironment); } batch.end(); animationBuffer.end(); animationTexture = animationBuffer.getColorBufferTexture(); animationTextureRegion = new TextureRegion(animationTexture); animationTextureRegion.flip(false, true); } unsubscribeLaterHelper(PreRenderSubscriber.class); unsubscribeLaterHelper(ModelRenderSubscriber.class); } // publishPostRender - public static void publishPostRender(SpriteBatch sb) { for (PostRenderSubscriber sub : postRenderSubscribers) { sub.receivePostRender(sb); } unsubscribeLaterHelper(PostRenderSubscriber.class); } // publishPreStartGame - public static void publishPreStartGame() { logger.info("publishPreStartGame"); MAX_HAND_SIZE = DEFAULT_MAX_HAND_SIZE; // Publish for (PreStartGameSubscriber sub : preStartGameSubscribers) { sub.receivePreStartGame(); } unsubscribeLaterHelper(PreStartGameSubscriber.class); } public static void publishStartGame() { logger.info("publishStartGame"); for (StartGameSubscriber sub : startGameSubscribers) { sub.receiveStartGame(); } logger.info("mapDensityMultiplier: " + mapPathDensityMultiplier); unsubscribeLaterHelper(StartGameSubscriber.class); } // publishPreUpdate - public static void publishPreUpdate() { for (PreUpdateSubscriber sub : preUpdateSubscribers) { sub.receivePreUpdate(); } unsubscribeLaterHelper(PreUpdateSubscriber.class); } // publishPostUpdate - public static void publishPostUpdate() { for (PostUpdateSubscriber sub : postUpdateSubscribers) { sub.receivePostUpdate(); } unsubscribeLaterHelper(PostUpdateSubscriber.class); } // publishPostDungeonUpdate - public static void publishPostDungeonUpdate() { for(PostDungeonUpdateSubscriber sub : postDungeonUpdateSubscribers) { sub.receivePostDungeonUpdate(); } unsubscribeLaterHelper(PostDungeonUpdateSubscriber.class); } // publishPreDungeonUpdate - public static void publishPreDungeonUpdate() { for(PreDungeonUpdateSubscriber sub : preDungeonUpdateSubscribers) { sub.receivePreDungeonUpdate(); } unsubscribeLaterHelper(PreDungeonUpdateSubscriber.class); } // publishPostPlayerUpdate - public static void publishPostPlayerUpdate() { for(PostPlayerUpdateSubscriber sub : postPlayerUpdateSubscribers) { sub.receivePostPlayerUpdate(); } unsubscribeLaterHelper(PostPlayerUpdateSubscriber.class); } // publishPrePlayerUpdate - public static void publishPrePlayerUpdate() { for(PrePlayerUpdateSubscriber sub : prePlayerUpdateSubscribers) { sub.receivePrePlayerUpdate(); } unsubscribeLaterHelper(PrePlayerUpdateSubscriber.class); } // publishPostCreateStartingDeck - public static void publishPostCreateStartingDeck(PlayerClass chosenClass, CardGroup cards) { logger.info("postCreateStartingDeck for: " + chosenClass); for (PostCreateStartingDeckSubscriber sub : postCreateStartingDeckSubscribers) { logger.info("postCreateStartingDeck modifying starting deck for: " + sub); sub.receivePostCreateStartingDeck(chosenClass, cards); } StringBuilder logString = new StringBuilder("postCreateStartingDeck adding [ "); for (AbstractCard card : cards.group) { logString.append(card.cardID).append(" "); } logString.append("]"); logger.info(logString.toString()); unsubscribeLaterHelper(PostCreateStartingDeckSubscriber.class); } // publishPostCreateStartingRelics - public static void publishPostCreateStartingRelics(PlayerClass chosenClass, ArrayList<String> relics) { logger.info("postCreateStartingRelics for: " + chosenClass); for (PostCreateStartingRelicsSubscriber sub : postCreateStartingRelicsSubscribers) { logger.info("postCreateStartingRelics modifying starting relics for: " + sub); sub.receivePostCreateStartingRelics(chosenClass, relics); } StringBuilder logString = new StringBuilder("postCreateStartingRelics adding [ "); for (String relic : relics) { logString.append(relic).append(" "); } logString.append("]"); logger.info(logString.toString()); // mark as seen for (String relic : relics) { UnlockTracker.markRelicAsSeen(relic); } AbstractDungeon.relicsToRemoveOnStart.addAll(relics); unsubscribeLaterHelper(PostCreateStartingRelicsSubscriber.class); } // publishPostCreateShopRelic - public static void publishPostCreateShopRelics(ArrayList<StoreRelic> relics, ShopScreen screenInstance) { logger.info("postCreateShopRelics for: " + relics); for (PostCreateShopRelicSubscriber sub : postCreateShopRelicSubscribers) { sub.receiveCreateShopRelics(relics, screenInstance); } unsubscribeLaterHelper(PostCreateShopRelicSubscriber.class); } // publishPostCreateShopPotion - public static void publishPostCreateShopPotions(ArrayList<StorePotion> potions, ShopScreen screenInstance) { logger.info("postCreateShopPotions for: " + potions); for (PostCreateShopPotionSubscriber sub : postCreateShopPotionSubscribers) { sub.receiveCreateShopPotions(potions, screenInstance); } unsubscribeLaterHelper(PostCreateShopPotionSubscriber.class); } // publishEditCards - public static void publishEditCards() { logger.info("begin editing cards"); BaseMod.addDynamicVariable(new DamageVariable()); BaseMod.addDynamicVariable(new BlockVariable()); BaseMod.addDynamicVariable(new MagicNumberVariable()); for (EditCardsSubscriber sub : editCardsSubscribers) { sub.receiveEditCards(); } unsubscribeLaterHelper(EditCardsSubscriber.class); } // publishEditRelics - public static void publishEditRelics() { logger.info("begin editing relics"); for (EditRelicsSubscriber sub : editRelicsSubscribers) { sub.receiveEditRelics(); } unsubscribeLaterHelper(EditRelicsSubscriber.class); } // publishEditCharacters - public static void publishEditCharacters() { logger.info("begin editing characters"); lastBaseCharacterIndex = CardCrawlGame.characterManager.getAllCharacters().size() - 1; for (EditCharactersSubscriber sub : editCharactersSubscribers) { sub.receiveEditCharacters(); } unsubscribeLaterHelper(EditCharactersSubscriber.class); } // publishEditStrings - public static void publishEditStrings() { logger.info("begin editing localization strings"); EventUtils.loadBaseEvents(); String path = String.format("localization/basemod/%s/customMods.json", Settings.language.name().toLowerCase()); if (!Gdx.files.internal(path).exists()) { path = String.format("localization/basemod/%s/customMods.json", Settings.GameLanguage.ENG.name().toLowerCase()); } BaseMod.loadCustomStringsFile(RunModStrings.class, path); for (EditStringsSubscriber sub : editStringsSubscribers) { sub.receiveEditStrings(); } unsubscribeLaterHelper(EditStringsSubscriber.class); } // publishAddAudio - public static void publishAddAudio(SoundMaster __instance) { logger.info("begin adding custom sounds"); for (AddAudioSubscriber sub : addAudioSubscribers) { sub.receiveAddAudio(); } BaseMod.addAudioToSoundMaster(__instance); unsubscribeLaterHelper(AddAudioSubscriber.class); } // publishPostBattle - public static void publishPostBattle(AbstractRoom battleRoom) { logger.info("publish post combat"); for (PostBattleSubscriber sub : postBattleSubscribers) { sub.receivePostBattle(battleRoom); } unsubscribeLaterHelper(PostBattleSubscriber.class); } public static void publishStartBattle(AbstractRoom room){ logger.info("publish start battle"); for (OnStartBattleSubscriber sub : startBattleSubscribers) { sub.receiveOnBattleStart(room); } unsubscribeLaterHelper(OnStartBattleSubscriber.class); } // publishPostRefresh - public static void publishPostRefresh() { logger.info("publish post refresh - refreshing unlocks"); for (SetUnlocksSubscriber sub : setUnlocksSubscribers) { sub.receiveSetUnlocks(); } CountModdedUnlockCards.enabled = true; CountModdedUnlockCards.countModdedUnlocks(); //call it manually, as the count occurs during refresh normally. unsubscribeLaterHelper(SetUnlocksSubscriber.class); } // publishOnCardUse - public static void publishOnCardUse(AbstractCard c) { logger.info("publish on card use: " + (c == null ? "null" : c.cardID)); for (OnCardUseSubscriber sub : onCardUseSubscribers) { sub.receiveCardUsed(c); } unsubscribeLaterHelper(OnCardUseSubscriber.class); } // publishPostUsePotion - public static void publishPostPotionUse(AbstractPotion p) { logger.info("publish on post potion use"); for (PostPotionUseSubscriber sub : postPotionUseSubscribers) { sub.receivePostPotionUse(p); } unsubscribeLaterHelper(PostPotionUseSubscriber.class); } // publishPostPotionUse - public static void publishPrePotionUse(AbstractPotion p) { logger.info("publish on pre potion use"); for (PrePotionUseSubscriber sub : prePotionUseSubscribers) { sub.receivePrePotionUse(p); } unsubscribeLaterHelper(PrePotionUseSubscriber.class); } // publishPotionGet - public static void publishPotionGet(AbstractPotion p) { logger.info("publish on potion get"); for (PotionGetSubscriber sub : potionGetSubscribers) { sub.receivePotionGet(p); } unsubscribeLaterHelper(PotionGetSubscriber.class); } // publishRelicGet - public static void publishRelicGet(AbstractRelic r) { logger.info("publish on relic get"); for (RelicGetSubscriber sub : relicGetSubscribers) { sub.receiveRelicGet(r); } unsubscribeLaterHelper(RelicGetSubscriber.class); } // publishPostPowerApply public static void publishPostPowerApply(AbstractPower p, AbstractCreature target, AbstractCreature source) { logger.info("publish on post power apply"); for (PostPowerApplySubscriber sub : postPowerApplySubscribers) { sub.receivePostPowerApplySubscriber(p, target, source); } unsubscribeLaterHelper(PostPowerApplySubscriber.class); } // publishEditKeywords public static void publishEditKeywords() { logger.info("editting keywords"); addKeyword(new String[] { "[E]" }, GameDictionary.TEXT[0]); for (EditKeywordsSubscriber sub : editKeywordsSubscribers) { sub.receiveEditKeywords(); } unsubscribeLaterHelper(EditKeywordsSubscriber.class); } // publishOnPowersModified public static void publishOnPowersModified() { logger.info("powers modified"); for (OnPowersModifiedSubscriber sub : onPowersModifiedSubscribers) { sub.receivePowersModified(); } unsubscribeLaterHelper(OnPowersModifiedSubscriber.class); } // publishPostDeath - Is triggered on death and victory public static void publishPostDeath() { logger.info("publishPostDeath"); for (PostDeathSubscriber sub : postDeathSubscribers) { sub.receivePostDeath(); } unsubscribeLaterHelper(PostDeathSubscriber.class); } public static void publishAddCustomModeMods(List<CustomMod> modList) { logger.info("publishAddCustomModeMods"); CustomMod charMod = new CustomMod("Modded Character Cards", "p", false); for (AbstractPlayer character : getModdedCharacters()) { CustomMod mod = new CustomMod(RedCards.ID, "g", true); mod.ID = character.chosenClass.name() + charMod.name; mod.name = String.format(charMod.name, character.getLocalizedCharacterName()); mod.description = String.format(charMod.description, character.getLocalizedCharacterName()); String label = FontHelper.colorString("[" + mod.name + "]", mod.color) + " " + mod.description; ReflectionHacks.setPrivate(mod, CustomMod.class, "label", label); float height = -FontHelper.getSmartHeight(FontHelper.charDescFont, label, 1050.0F * Settings.scale, 32.0F * Settings.scale) + 70.0F * Settings.scale; ReflectionHacks.setPrivate(mod, CustomMod.class, "height", height); insertCustomMod(modList, mod); } for (AddCustomModeModsSubscriber sub : addCustomModeModsSubscribers) { List<CustomMod> tmpModList = new ArrayList<>(); sub.receiveCustomModeMods(tmpModList); tmpModList.forEach(m -> insertCustomMod(modList, m)); } unsubscribeLaterHelper(AddCustomModeModsSubscriber.class); } private static void insertCustomMod(List<CustomMod> modList, CustomMod mod) { int lastIndex = modList.size(); for (int i=0; i<modList.size(); ++i) { if (modList.get(i).color.equals(mod.color)) { lastIndex = i + 1; } } modList.add(lastIndex, mod); } public static int publishMaxHPChange(int amount) { logger.info("publishMaxHPChange"); for (MaxHPChangeSubscriber sub : maxHPChangeSubscribers) { amount = sub.receiveMapHPChange(amount); } unsubscribeLaterHelper(PostDeathSubscriber.class); return amount; } public static void publishPreRoomRender(SpriteBatch sb) { for(PreRoomRenderSubscriber sub : preRoomRenderSubscribers) { sub.receivePreRoomRender(sb); } } // publishOnPlayerLoseBlock public static int publishOnPlayerLoseBlock(int amount) { logger.info("publish on Player Lose Block"); for (OnPlayerLoseBlockSubscriber sub : onPlayerLoseBlockSubscribers) { amount = sub.receiveOnPlayerLoseBlock(amount); } unsubscribeLaterHelper(OnPlayerLoseBlockSubscriber.class); return amount; } public static int publishOnPlayerDamaged(int amount, DamageInfo info) { logger.info("publish on Player Damaged"); for (OnPlayerDamagedSubscriber sub : onPlayerDamagedSubscribers) { amount = sub.receiveOnPlayerDamaged(amount, info); } unsubscribeLaterHelper(OnPlayerDamagedSubscriber.class); return amount; } public static String publishOnCreateDescription(String rawDescription, AbstractCard card) { //logger.info("publish on card description initialized"); //too much logging? for (OnCreateDescriptionSubscriber sub : onCreateDescriptionSubscribers) { rawDescription = sub.receiveCreateCardDescription(rawDescription, card); } unsubscribeLaterHelper(OnCreateDescriptionSubscriber.class); return rawDescription; } // // Subscription handlers // // unsubscribes all elements of toRemove that are of type removalClass private static void unsubscribeLaterHelper(Class<? extends ISubscriber> removalClass) { for (ISubscriber sub : toRemove) { if (removalClass.isInstance(sub)) { unsubscribe(sub, removalClass); } } } private static <T> void subscribeIfInstance(ArrayList<T> list, ISubscriber sub, Class<T> clazz) { if (clazz.isInstance(sub)) { list.add(clazz.cast(sub)); } } private static <T> void unsubscribeIfInstance(ArrayList<T> list, ISubscriber sub, Class<T> clazz) { if (clazz.isInstance(sub)) { list.remove(clazz.cast(sub)); } } // subscribe - // will subscribe to all lists this sub implements public static void subscribe(ISubscriber sub) { subscribeIfInstance(startActSubscribers, sub, StartActSubscriber.class); subscribeIfInstance(postCampfireSubscribers, sub, PostCampfireSubscriber.class); subscribeIfInstance(postDrawSubscribers, sub, PostDrawSubscriber.class); subscribeIfInstance(postExhaustSubscribers, sub, PostExhaustSubscriber.class); subscribeIfInstance(onCardUseSubscribers, sub, OnCardUseSubscriber.class); subscribeIfInstance(postDungeonInitializeSubscribers, sub, PostDungeonInitializeSubscriber.class); subscribeIfInstance(postEnergyRechargeSubscribers, sub, PostEnergyRechargeSubscriber.class); subscribeIfInstance(postInitializeSubscribers, sub, PostInitializeSubscriber.class); subscribeIfInstance(preMonsterTurnSubscribers, sub, PreMonsterTurnSubscriber.class); subscribeIfInstance(renderSubscribers, sub, RenderSubscriber.class); subscribeIfInstance(preRenderSubscribers, sub, PreRenderSubscriber.class); subscribeIfInstance(postRenderSubscribers, sub, PostRenderSubscriber.class); subscribeIfInstance(modelRenderSubscribers, sub, ModelRenderSubscriber.class); subscribeIfInstance(preStartGameSubscribers, sub, PreStartGameSubscriber.class); subscribeIfInstance(startGameSubscribers, sub, StartGameSubscriber.class); subscribeIfInstance(preUpdateSubscribers, sub, PreUpdateSubscriber.class); subscribeIfInstance(postUpdateSubscribers, sub, PostUpdateSubscriber.class); subscribeIfInstance(postDungeonUpdateSubscribers, sub, PostDungeonUpdateSubscriber.class); subscribeIfInstance(preDungeonUpdateSubscribers, sub, PreDungeonUpdateSubscriber.class); subscribeIfInstance(postPlayerUpdateSubscribers, sub, PostPlayerUpdateSubscriber.class); subscribeIfInstance(prePlayerUpdateSubscribers, sub, PrePlayerUpdateSubscriber.class); subscribeIfInstance(postCreateStartingDeckSubscribers, sub, PostCreateStartingDeckSubscriber.class); subscribeIfInstance(postCreateStartingRelicsSubscribers, sub, PostCreateStartingRelicsSubscriber.class); subscribeIfInstance(postCreateShopRelicSubscribers, sub, PostCreateShopRelicSubscriber.class); subscribeIfInstance(postCreateShopPotionSubscribers, sub, PostCreateShopPotionSubscriber.class); subscribeIfInstance(editCardsSubscribers, sub, EditCardsSubscriber.class); subscribeIfInstance(addAudioSubscribers, sub, AddAudioSubscriber.class); subscribeIfInstance(editRelicsSubscribers, sub, EditRelicsSubscriber.class); subscribeIfInstance(editCharactersSubscribers, sub, EditCharactersSubscriber.class); subscribeIfInstance(editStringsSubscribers, sub, EditStringsSubscriber.class); subscribeIfInstance(editKeywordsSubscribers, sub, EditKeywordsSubscriber.class); subscribeIfInstance(postBattleSubscribers, sub, PostBattleSubscriber.class); subscribeIfInstance(setUnlocksSubscribers, sub, SetUnlocksSubscriber.class); subscribeIfInstance(postPotionUseSubscribers, sub, PostPotionUseSubscriber.class); subscribeIfInstance(prePotionUseSubscribers, sub, PrePotionUseSubscriber.class); subscribeIfInstance(potionGetSubscribers, sub, PotionGetSubscriber.class); subscribeIfInstance(relicGetSubscribers, sub, RelicGetSubscriber.class); subscribeIfInstance(postPowerApplySubscribers, sub, PostPowerApplySubscriber.class); subscribeIfInstance(onPowersModifiedSubscribers, sub, OnPowersModifiedSubscriber.class); subscribeIfInstance(postDeathSubscribers, sub, PostDeathSubscriber.class); subscribeIfInstance(startBattleSubscribers, sub, OnStartBattleSubscriber.class); subscribeIfInstance(addCustomModeModsSubscribers, sub, AddCustomModeModsSubscriber.class); subscribeIfInstance(maxHPChangeSubscribers, sub, MaxHPChangeSubscriber.class); subscribeIfInstance(preRoomRenderSubscribers, sub, PreRoomRenderSubscriber.class); subscribeIfInstance(onPlayerLoseBlockSubscribers, sub, OnPlayerLoseBlockSubscriber.class); subscribeIfInstance(onPlayerDamagedSubscribers, sub, OnPlayerDamagedSubscriber.class); subscribeIfInstance(onCreateDescriptionSubscribers, sub, OnCreateDescriptionSubscriber.class); } // subscribe - // only subscribers to a specific list public static void subscribe(ISubscriber sub, Class<? extends ISubscriber> additionClass) { if (additionClass.equals(StartActSubscriber.class)) { startActSubscribers.add((StartActSubscriber) sub); } else if (additionClass.equals(PostCampfireSubscriber.class)) { postCampfireSubscribers.add((PostCampfireSubscriber) sub); } else if (additionClass.equals(PostDrawSubscriber.class)) { postDrawSubscribers.add((PostDrawSubscriber) sub); } else if (additionClass.equals(PostExhaustSubscriber.class)) { postExhaustSubscribers.add((PostExhaustSubscriber) sub); } else if (additionClass.equals(OnCardUseSubscriber.class)) { onCardUseSubscribers.add((OnCardUseSubscriber) sub); } else if (additionClass.equals(PostDungeonInitializeSubscriber.class)) { postDungeonInitializeSubscribers.add((PostDungeonInitializeSubscriber) sub); } else if (additionClass.equals(PostEnergyRechargeSubscriber.class)) { postEnergyRechargeSubscribers.add((PostEnergyRechargeSubscriber) sub); } else if (additionClass.equals(PostInitializeSubscriber.class)) { postInitializeSubscribers.add((PostInitializeSubscriber) sub); } else if (additionClass.equals(PreMonsterTurnSubscriber.class)) { preMonsterTurnSubscribers.add((PreMonsterTurnSubscriber) sub); } else if (additionClass.equals(RenderSubscriber.class)) { renderSubscribers.add((RenderSubscriber) sub); } else if (additionClass.equals(PreRenderSubscriber.class)) { preRenderSubscribers.add((PreRenderSubscriber) sub); } else if (additionClass.equals(PostRenderSubscriber.class)) { postRenderSubscribers.add((PostRenderSubscriber) sub); } else if (additionClass.equals(ModelRenderSubscriber.class)) { modelRenderSubscribers.add((ModelRenderSubscriber) sub); } else if (additionClass.equals(PreStartGameSubscriber.class)) { preStartGameSubscribers.add((PreStartGameSubscriber) sub); } else if (additionClass.equals(StartGameSubscriber.class)) { startGameSubscribers.add((StartGameSubscriber) sub); } else if (additionClass.equals(PreUpdateSubscriber.class)) { preUpdateSubscribers.add((PreUpdateSubscriber) sub); } else if (additionClass.equals(PostUpdateSubscriber.class)) { postUpdateSubscribers.add((PostUpdateSubscriber) sub); } else if (additionClass.equals(PostDungeonUpdateSubscriber.class)) { postDungeonUpdateSubscribers.add((PostDungeonUpdateSubscriber) sub); } else if (additionClass.equals(PreDungeonUpdateSubscriber.class)) { preDungeonUpdateSubscribers.add((PreDungeonUpdateSubscriber) sub); } else if (additionClass.equals(PostPlayerUpdateSubscriber.class)) { postPlayerUpdateSubscribers.add((PostPlayerUpdateSubscriber) sub); } else if (additionClass.equals(PrePlayerUpdateSubscriber.class)) { prePlayerUpdateSubscribers.add((PrePlayerUpdateSubscriber) sub); } else if (additionClass.equals(PostCreateStartingDeckSubscriber.class)) { postCreateStartingDeckSubscribers.add((PostCreateStartingDeckSubscriber) sub); } else if (additionClass.equals(PostCreateStartingRelicsSubscriber.class)) { postCreateStartingRelicsSubscribers.add((PostCreateStartingRelicsSubscriber) sub); } else if (additionClass.equals(PostCreateShopRelicSubscriber.class)) { postCreateShopRelicSubscribers.add((PostCreateShopRelicSubscriber) sub); } else if (additionClass.equals(PostCreateShopPotionSubscriber.class)) { postCreateShopPotionSubscribers.add((PostCreateShopPotionSubscriber) sub); } else if (additionClass.equals(EditCardsSubscriber.class)) { editCardsSubscribers.add((EditCardsSubscriber) sub); } else if (additionClass.equals(EditRelicsSubscriber.class)) { editRelicsSubscribers.add((EditRelicsSubscriber) sub); } else if (additionClass.equals(EditCharactersSubscriber.class)) { editCharactersSubscribers.add((EditCharactersSubscriber) sub); } else if (additionClass.equals(EditStringsSubscriber.class)) { editStringsSubscribers.add((EditStringsSubscriber) sub); } else if (additionClass.equals(EditKeywordsSubscriber.class)) { editKeywordsSubscribers.add((EditKeywordsSubscriber) sub); } else if (additionClass.equals(PostBattleSubscriber.class)) { postBattleSubscribers.add((PostBattleSubscriber) sub); } else if (additionClass.equals(SetUnlocksSubscriber.class)) { setUnlocksSubscribers.add((SetUnlocksSubscriber) sub); } else if (additionClass.equals(PostPotionUseSubscriber.class)) { postPotionUseSubscribers.add((PostPotionUseSubscriber) sub); } else if (additionClass.equals(PrePotionUseSubscriber.class)) { prePotionUseSubscribers.add((PrePotionUseSubscriber) sub); } else if (additionClass.equals(PotionGetSubscriber.class)) { potionGetSubscribers.add((PotionGetSubscriber) sub); } else if (additionClass.equals(RelicGetSubscriber.class)) { relicGetSubscribers.add((RelicGetSubscriber) sub); } else if (additionClass.equals(PostPowerApplySubscriber.class)) { postPowerApplySubscribers.add((PostPowerApplySubscriber) sub); } else if (additionClass.equals(OnPowersModifiedSubscriber.class)) { onPowersModifiedSubscribers.add((OnPowersModifiedSubscriber) sub); } else if (additionClass.equals(PostDeathSubscriber.class)) { postDeathSubscribers.add((PostDeathSubscriber) sub); } else if (additionClass.equals(OnStartBattleSubscriber.class)) { startBattleSubscribers.add((OnStartBattleSubscriber) sub); } else if (additionClass.equals(AddCustomModeModsSubscriber.class)) { addCustomModeModsSubscribers.add((AddCustomModeModsSubscriber) sub); } else if (additionClass.equals(MaxHPChangeSubscriber.class)) { maxHPChangeSubscribers.add((MaxHPChangeSubscriber) sub); } else if (additionClass.equals(PreRoomRenderSubscriber.class)) { preRoomRenderSubscribers.add((PreRoomRenderSubscriber) sub); } else if (additionClass.equals(OnPlayerLoseBlockSubscriber.class)) { onPlayerLoseBlockSubscribers.add((OnPlayerLoseBlockSubscriber) sub); } else if (additionClass.equals(OnPlayerDamagedSubscriber.class)) { onPlayerDamagedSubscribers.add((OnPlayerDamagedSubscriber) sub); } else if (additionClass.equals(OnCreateDescriptionSubscriber.class)) { onCreateDescriptionSubscribers.add((OnCreateDescriptionSubscriber) sub); } } // unsubscribe - // will unsubscribe from all lists this sub implements public static void unsubscribe(ISubscriber sub) { unsubscribeIfInstance(startActSubscribers, sub, StartActSubscriber.class); unsubscribeIfInstance(postCampfireSubscribers, sub, PostCampfireSubscriber.class); unsubscribeIfInstance(postDrawSubscribers, sub, PostDrawSubscriber.class); unsubscribeIfInstance(postExhaustSubscribers, sub, PostExhaustSubscriber.class); unsubscribeIfInstance(onCardUseSubscribers, sub, OnCardUseSubscriber.class); unsubscribeIfInstance(postDungeonInitializeSubscribers, sub, PostDungeonInitializeSubscriber.class); unsubscribeIfInstance(postEnergyRechargeSubscribers, sub, PostEnergyRechargeSubscriber.class); unsubscribeIfInstance(postInitializeSubscribers, sub, PostInitializeSubscriber.class); unsubscribeIfInstance(preMonsterTurnSubscribers, sub, PreMonsterTurnSubscriber.class); unsubscribeIfInstance(renderSubscribers, sub, RenderSubscriber.class); unsubscribeIfInstance(preRenderSubscribers, sub, PreRenderSubscriber.class); unsubscribeIfInstance(postRenderSubscribers, sub, PostRenderSubscriber.class); unsubscribeIfInstance(modelRenderSubscribers, sub, ModelRenderSubscriber.class); unsubscribeIfInstance(preStartGameSubscribers, sub, PreStartGameSubscriber.class); unsubscribeIfInstance(startGameSubscribers, sub, StartGameSubscriber.class); unsubscribeIfInstance(preUpdateSubscribers, sub, PreUpdateSubscriber.class); unsubscribeIfInstance(postUpdateSubscribers, sub, PostUpdateSubscriber.class); unsubscribeIfInstance(postDungeonUpdateSubscribers, sub, PostDungeonUpdateSubscriber.class); unsubscribeIfInstance(preDungeonUpdateSubscribers, sub, PreDungeonUpdateSubscriber.class); unsubscribeIfInstance(postPlayerUpdateSubscribers, sub, PostPlayerUpdateSubscriber.class); unsubscribeIfInstance(prePlayerUpdateSubscribers, sub, PrePlayerUpdateSubscriber.class); unsubscribeIfInstance(postCreateStartingDeckSubscribers, sub, PostCreateStartingDeckSubscriber.class); unsubscribeIfInstance(postCreateStartingRelicsSubscribers, sub, PostCreateStartingRelicsSubscriber.class); unsubscribeIfInstance(postCreateShopRelicSubscribers, sub, PostCreateShopRelicSubscriber.class); unsubscribeIfInstance(postCreateShopPotionSubscribers, sub, PostCreateShopPotionSubscriber.class); unsubscribeIfInstance(editCardsSubscribers, sub, EditCardsSubscriber.class); unsubscribeIfInstance(editRelicsSubscribers, sub, EditRelicsSubscriber.class); unsubscribeIfInstance(editCharactersSubscribers, sub, EditCharactersSubscriber.class); unsubscribeIfInstance(editStringsSubscribers, sub, EditStringsSubscriber.class); unsubscribeIfInstance(editKeywordsSubscribers, sub, EditKeywordsSubscriber.class); unsubscribeIfInstance(postBattleSubscribers, sub, PostBattleSubscriber.class); unsubscribeIfInstance(setUnlocksSubscribers, sub, SetUnlocksSubscriber.class); unsubscribeIfInstance(postPotionUseSubscribers, sub, PostPotionUseSubscriber.class); unsubscribeIfInstance(prePotionUseSubscribers, sub, PrePotionUseSubscriber.class); unsubscribeIfInstance(potionGetSubscribers, sub, PotionGetSubscriber.class); unsubscribeIfInstance(relicGetSubscribers, sub, RelicGetSubscriber.class); unsubscribeIfInstance(postPowerApplySubscribers, sub, PostPowerApplySubscriber.class); unsubscribeIfInstance(onPowersModifiedSubscribers, sub, OnPowersModifiedSubscriber.class); unsubscribeIfInstance(postDeathSubscribers, sub, PostDeathSubscriber.class); unsubscribeIfInstance(startBattleSubscribers, sub, OnStartBattleSubscriber.class); unsubscribeIfInstance(addCustomModeModsSubscribers, sub, AddCustomModeModsSubscriber.class); unsubscribeIfInstance(maxHPChangeSubscribers, sub, MaxHPChangeSubscriber.class); unsubscribeIfInstance(preRoomRenderSubscribers, sub, PreRoomRenderSubscriber.class); unsubscribeIfInstance(onPlayerLoseBlockSubscribers, sub, OnPlayerLoseBlockSubscriber.class); unsubscribeIfInstance(onPlayerDamagedSubscribers, sub, OnPlayerDamagedSubscriber.class); unsubscribeIfInstance(onCreateDescriptionSubscribers, sub, OnCreateDescriptionSubscriber.class); } // unsubscribe - // only unsubscribe from a specific list public static void unsubscribe(ISubscriber sub, Class<? extends ISubscriber> removalClass) { if (removalClass.equals(StartActSubscriber.class)) { startActSubscribers.remove(sub); } else if (removalClass.equals(PostCampfireSubscriber.class)) { postCampfireSubscribers.remove(sub); } else if (removalClass.equals(PostDrawSubscriber.class)) { postDrawSubscribers.remove(sub); } else if (removalClass.equals(PostExhaustSubscriber.class)) { postExhaustSubscribers.remove(sub); } else if (removalClass.equals(OnCardUseSubscriber.class)) { onCardUseSubscribers.remove(sub); } else if (removalClass.equals(PostDungeonInitializeSubscriber.class)) { postDungeonInitializeSubscribers.remove(sub); } else if (removalClass.equals(PostEnergyRechargeSubscriber.class)) { postEnergyRechargeSubscribers.remove(sub); } else if (removalClass.equals(PostInitializeSubscriber.class)) { postInitializeSubscribers.remove(sub); } else if (removalClass.equals(PreMonsterTurnSubscriber.class)) { preMonsterTurnSubscribers.remove(sub); } else if (removalClass.equals(RenderSubscriber.class)) { renderSubscribers.remove(sub); } else if (removalClass.equals(PreRenderSubscriber.class)) { preRenderSubscribers.remove(sub); } else if (removalClass.equals(PostRenderSubscriber.class)) { postRenderSubscribers.remove(sub); } else if (removalClass.equals(ModelRenderSubscriber.class)) { modelRenderSubscribers.remove(sub); } else if (removalClass.equals(PreStartGameSubscriber.class)) { preStartGameSubscribers.remove(sub); } else if (removalClass.equals(StartGameSubscriber.class)) { startGameSubscribers.remove(sub); } else if (removalClass.equals(PreUpdateSubscriber.class)) { preUpdateSubscribers.remove(sub); } else if (removalClass.equals(PostUpdateSubscriber.class)) { postUpdateSubscribers.remove(sub); } else if (removalClass.equals(PostDungeonUpdateSubscriber.class)) { postDungeonUpdateSubscribers.remove(sub); } else if (removalClass.equals(PreDungeonUpdateSubscriber.class)) { preDungeonUpdateSubscribers.remove(sub); } else if (removalClass.equals(PostPlayerUpdateSubscriber.class)) { postPlayerUpdateSubscribers.remove(sub); } else if (removalClass.equals(PrePlayerUpdateSubscriber.class)) { prePlayerUpdateSubscribers.remove(sub); } else if (removalClass.equals(PostCreateStartingDeckSubscriber.class)) { postCreateStartingDeckSubscribers.remove(sub); } else if (removalClass.equals(PostCreateStartingRelicsSubscriber.class)) { postCreateStartingRelicsSubscribers.remove(sub); } else if (removalClass.equals(PostCreateShopRelicSubscriber.class)) { postCreateShopRelicSubscribers.remove(sub); } else if (removalClass.equals(PostCreateShopPotionSubscriber.class)) { postCreateShopPotionSubscribers.remove(sub); } else if (removalClass.equals(EditCardsSubscriber.class)) { editCardsSubscribers.remove(sub); } else if (removalClass.equals(EditRelicsSubscriber.class)) { editRelicsSubscribers.remove(sub); } else if (removalClass.equals(EditCharactersSubscriber.class)) { editCharactersSubscribers.remove(sub); } else if (removalClass.equals(EditStringsSubscriber.class)) { editStringsSubscribers.remove(sub); } else if (removalClass.equals(EditKeywordsSubscriber.class)) { editKeywordsSubscribers.remove(sub); } else if (removalClass.equals(AddAudioSubscriber.class)) { addAudioSubscribers.remove(sub); } else if (removalClass.equals(PostBattleSubscriber.class)) { postBattleSubscribers.remove(sub); } else if (removalClass.equals(SetUnlocksSubscriber.class)) { setUnlocksSubscribers.remove(sub); } else if (removalClass.equals(PostPotionUseSubscriber.class)) { postPotionUseSubscribers.remove(sub); } else if (removalClass.equals(PrePotionUseSubscriber.class)) { prePotionUseSubscribers.remove(sub); } else if (removalClass.equals(PotionGetSubscriber.class)) { potionGetSubscribers.remove(sub); } else if (removalClass.equals(RelicGetSubscriber.class)) { relicGetSubscribers.remove(sub); } else if (removalClass.equals(PostPowerApplySubscriber.class)) { postPowerApplySubscribers.remove(sub); } else if (removalClass.equals(OnPowersModifiedSubscriber.class)) { onPowersModifiedSubscribers.remove(sub); } else if (removalClass.equals(PostDeathSubscriber.class)) { postDeathSubscribers.remove(sub); } else if (removalClass.equals(OnStartBattleSubscriber.class)) { startBattleSubscribers.remove(sub); } else if (removalClass.equals(AddCustomModeModsSubscriber.class)) { addCustomModeModsSubscribers.remove(sub); } else if (removalClass.equals(MaxHPChangeSubscriber.class)) { maxHPChangeSubscribers.remove(sub); } else if (removalClass.equals(PreRoomRenderSubscriber.class)) { preRoomRenderSubscribers.remove(sub); } else if (removalClass.equals(OnPlayerLoseBlockSubscriber.class)) { onPlayerLoseBlockSubscribers.remove(sub); } else if (removalClass.equals(OnPlayerDamagedSubscriber.class)) { onPlayerDamagedSubscribers.remove(sub); } else if (removalClass.equals(OnCreateDescriptionSubscriber.class)) { onCreateDescriptionSubscribers.remove(sub); } } // unsubscribeLater - public static void unsubscribeLater(ISubscriber sub) { toRemove.add(sub); } public static String convertToModID(String id) { String modName = BaseMod.findCallingModName(); return convertToModID(modName, id); } public static String convertToModID(String modID, String id) { if (modID == null && (id.startsWith("slaythespire:") || id.startsWith("sts:") || id.startsWith(":"))) { return id.substring(id.indexOf(':') + 1); } else if (modID != null && !id.startsWith(modID + ":")) { id = modID + ":" + id; } return id; } public static boolean hasModID(String id) { for (ModInfo info : Loader.MODINFOS) { String modID = null; if (info.ID != null && !info.ID.isEmpty()) { modID = info.ID; } else { modID = info.Name; } if (id.startsWith(modID + ":")) { return true; } } return false; } public static String findCallingModName() { return null; } @SuppressWarnings("unused") /** * Open a {@link com.megacrit.cardcrawl.screens.select.GridCardSelectScreen} for selecting cards. * Executes a callback function with the cards selected once selection is completed. Method must * be called after {@link AbstractDungeon} has been initialized * * @param group Group of cards to select from * @param numCards Number of cards to select * @param tipMsg Tip message displayed at the bottom of the screen * @param callback Callback function that is executed once card selection is complete. This function * is not executed if the card selection is canceled/skipped. * * Example callback function: (cards) -> { cards.forEach(c -> logger.debug(c.cardID)); } */ public static void openCustomGridScreen(CardGroup group, int numCards, String tipMsg, GridCardSelectScreenFields.GridCallback callback) { logger.debug("Opening custom grid screen"); String gridCancelText = CardCrawlGame.languagePack.getUIString("CardRewardScreen").TEXT[0]; AbstractDungeon.gridSelectScreen.open(group, numCards, tipMsg, false); AbstractDungeon.overlayMenu.cancelButton.show(gridCancelText); AbstractDungeon.dynamicBanner.hide(); GridCardSelectScreenFields.forCustomReward.set(AbstractDungeon.gridSelectScreen, true); GridCardSelectScreenFields.customCallback.set(AbstractDungeon.gridSelectScreen, callback); } }
microsoftgraph/msgraph-beta-sdk-java
src/main/java/com/microsoft/graph/requests/VendorRequestBuilder.java
<reponame>microsoftgraph/msgraph-beta-sdk-java<filename>src/main/java/com/microsoft/graph/requests/VendorRequestBuilder.java // Template Source: BaseEntityRequestBuilder.java.tt // ------------------------------------------------------------------------------ // 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.requests; import com.microsoft.graph.http.IRequestBuilder; import com.microsoft.graph.core.ClientException; import com.microsoft.graph.models.Vendor; import com.microsoft.graph.requests.CurrencyRequestBuilder; import com.microsoft.graph.requests.PaymentMethodRequestBuilder; import com.microsoft.graph.requests.PaymentTermRequestBuilder; import com.microsoft.graph.requests.PictureCollectionRequestBuilder; import com.microsoft.graph.requests.PictureRequestBuilder; import java.util.Arrays; import java.util.EnumSet; import javax.annotation.Nullable; import javax.annotation.Nonnull; import com.microsoft.graph.core.IBaseClient; import com.microsoft.graph.http.BaseRequestBuilder; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Vendor Request Builder. */ public class VendorRequestBuilder extends BaseRequestBuilder<Vendor> { /** * The request builder for the Vendor * * @param requestUrl the request URL * @param client the service client * @param requestOptions the options for this request */ public VendorRequestBuilder(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) { super(requestUrl, client, requestOptions); } /** * Creates the request * * @param requestOptions the options for this request * @return the VendorRequest instance */ @Nonnull public VendorRequest buildRequest(@Nullable final com.microsoft.graph.options.Option... requestOptions) { return buildRequest(getOptions(requestOptions)); } /** * Creates the request with specific requestOptions instead of the existing requestOptions * * @param requestOptions the options for this request * @return the VendorRequest instance */ @Nonnull public VendorRequest buildRequest(@Nonnull final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) { return new com.microsoft.graph.requests.VendorRequest(getRequestUrl(), getClient(), requestOptions); } /** * Gets the request builder for Currency * * @return the CurrencyRequestBuilder instance */ @Nonnull public CurrencyRequestBuilder currency() { return new CurrencyRequestBuilder(getRequestUrlWithAdditionalSegment("currency"), getClient(), null); } /** * Gets the request builder for PaymentMethod * * @return the PaymentMethodRequestBuilder instance */ @Nonnull public PaymentMethodRequestBuilder paymentMethod() { return new PaymentMethodRequestBuilder(getRequestUrlWithAdditionalSegment("paymentMethod"), getClient(), null); } /** * Gets the request builder for PaymentTerm * * @return the PaymentTermRequestBuilder instance */ @Nonnull public PaymentTermRequestBuilder paymentTerm() { return new PaymentTermRequestBuilder(getRequestUrlWithAdditionalSegment("paymentTerm"), getClient(), null); } /** * Gets a request builder for the Picture collection * * @return the collection request builder */ @Nonnull public PictureCollectionRequestBuilder picture() { return new PictureCollectionRequestBuilder(getRequestUrlWithAdditionalSegment("picture"), getClient(), null); } /** * Gets a request builder for the Picture item * * @return the request builder * @param id the item identifier */ @Nonnull public PictureRequestBuilder picture(@Nonnull final String id) { return new PictureRequestBuilder(getRequestUrlWithAdditionalSegment("picture") + "/" + id, getClient(), null); } }
vuzzan/openclinic
src/com/model/dao/KetquaXnDlg.java
package com.model.dao; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.eclipse.swt.widgets.Dialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Monitor; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.wb.swt.SWTResourceManager; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import com.openclinic.utils.Utils; import com.DbHelper; public class KetquaXnDlg extends Dialog { static Logger logger = LogManager.getLogger(KetquaXnDlg.class.getName()); protected Object result; protected Shell shell; private Text txtCS_ID; private Text txtDV_ID; private Text txtMA_DVKT; private Text txtTEN_DVKT; private Text txtCS_NAME; private Text txtCS_VALUE; private Text txtCS_RANGE1; private Text txtCS_RANGE2; private Text txtCS_DEFAULT; private Text txtIMAGE_URL; private Text txtMA_MAY; private Text txtMO_TA; private Text txtKET_LUAN; private Text txtSTS; public KetquaXn objKetquaXn; Button btnNewButtonSaveKetquaXn; public int intTypeDlgKetquaXn; public static final int TYPE_DLG_VIEW = 1; public static final int TYPE_DLG_EDIT = 2; /** * Create the dialog. * @param parent * @param style */ public KetquaXnDlg(Shell parent, int style) { super(parent, style); setText("SWT Dialog"); } /** * Open the dialog. * @return the result */ public Object open() { createContents(); shell.open(); shell.layout(); Display display = getParent().getDisplay(); // Monitor primary = display.getPrimaryMonitor(); Rectangle bounds = primary.getBounds(); Rectangle rect = shell.getBounds(); int x = bounds.x + (bounds.width - rect.width) / 2; int y = bounds.y + (bounds.height - rect.height) / 2; shell.setLocation(x, y); // while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } return result; } /** * Create contents of the dialog. */ private void createContents() { shell = new Shell(getParent(), SWT.SHELL_TRIM | SWT.BORDER | SWT.PRIMARY_MODAL); shell.setSize(450, 300); shell.setText("KetquaXnDlg EDIT/NEW"); shell.setLayout(new GridLayout(2, false)); shell.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if(e.keyCode==SWT.ESC){ objKetquaXn = null; } } }); Label lbltxtCS_ID = new Label(shell, SWT.NONE); lbltxtCS_ID.setFont(SWTResourceManager.getFont("Tahoma", 10, SWT.NORMAL)); lbltxtCS_ID.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lbltxtCS_ID.setText("CS_ID :"); txtCS_ID = new Text(shell, SWT.BORDER); txtCS_ID.setFont(SWTResourceManager.getFont("Tahoma", 10, SWT.NORMAL)); txtCS_ID.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); txtCS_ID.setText("CS_ID"); txtCS_ID.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { keyPressKetquaXnDlg(e); } }); Label lbltxtDV_ID = new Label(shell, SWT.NONE); lbltxtDV_ID.setFont(SWTResourceManager.getFont("Tahoma", 10, SWT.NORMAL)); lbltxtDV_ID.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lbltxtDV_ID.setText("DV_ID :"); txtDV_ID = new Text(shell, SWT.BORDER); txtDV_ID.setFont(SWTResourceManager.getFont("Tahoma", 10, SWT.NORMAL)); txtDV_ID.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); txtDV_ID.setText("DV_ID"); txtDV_ID.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { keyPressKetquaXnDlg(e); } }); Label lbltxtMA_DVKT = new Label(shell, SWT.NONE); lbltxtMA_DVKT.setFont(SWTResourceManager.getFont("Tahoma", 10, SWT.NORMAL)); lbltxtMA_DVKT.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lbltxtMA_DVKT.setText("MA_DVKT :"); txtMA_DVKT = new Text(shell, SWT.BORDER); txtMA_DVKT.setFont(SWTResourceManager.getFont("Tahoma", 10, SWT.NORMAL)); txtMA_DVKT.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); txtMA_DVKT.setText("MA_DVKT"); txtMA_DVKT.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { keyPressKetquaXnDlg(e); } }); Label lbltxtTEN_DVKT = new Label(shell, SWT.NONE); lbltxtTEN_DVKT.setFont(SWTResourceManager.getFont("Tahoma", 10, SWT.NORMAL)); lbltxtTEN_DVKT.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lbltxtTEN_DVKT.setText("TEN_DVKT :"); txtTEN_DVKT = new Text(shell, SWT.BORDER); txtTEN_DVKT.setFont(SWTResourceManager.getFont("Tahoma", 10, SWT.NORMAL)); txtTEN_DVKT.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); txtTEN_DVKT.setText("TEN_DVKT"); txtTEN_DVKT.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { keyPressKetquaXnDlg(e); } }); Label lbltxtCS_NAME = new Label(shell, SWT.NONE); lbltxtCS_NAME.setFont(SWTResourceManager.getFont("Tahoma", 10, SWT.NORMAL)); lbltxtCS_NAME.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lbltxtCS_NAME.setText("CS_NAME :"); txtCS_NAME = new Text(shell, SWT.BORDER); txtCS_NAME.setFont(SWTResourceManager.getFont("Tahoma", 10, SWT.NORMAL)); txtCS_NAME.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); txtCS_NAME.setText("CS_NAME"); txtCS_NAME.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { keyPressKetquaXnDlg(e); } }); Label lbltxtCS_VALUE = new Label(shell, SWT.NONE); lbltxtCS_VALUE.setFont(SWTResourceManager.getFont("Tahoma", 10, SWT.NORMAL)); lbltxtCS_VALUE.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lbltxtCS_VALUE.setText("CS_VALUE :"); txtCS_VALUE = new Text(shell, SWT.BORDER); txtCS_VALUE.setFont(SWTResourceManager.getFont("Tahoma", 10, SWT.NORMAL)); txtCS_VALUE.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); txtCS_VALUE.setText("CS_VALUE"); txtCS_VALUE.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { keyPressKetquaXnDlg(e); } }); Label lbltxtCS_RANGE1 = new Label(shell, SWT.NONE); lbltxtCS_RANGE1.setFont(SWTResourceManager.getFont("Tahoma", 10, SWT.NORMAL)); lbltxtCS_RANGE1.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lbltxtCS_RANGE1.setText("CS_RANGE1 :"); txtCS_RANGE1 = new Text(shell, SWT.BORDER); txtCS_RANGE1.setFont(SWTResourceManager.getFont("Tahoma", 10, SWT.NORMAL)); txtCS_RANGE1.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); txtCS_RANGE1.setText("CS_RANGE1"); txtCS_RANGE1.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { keyPressKetquaXnDlg(e); } }); Label lbltxtCS_RANGE2 = new Label(shell, SWT.NONE); lbltxtCS_RANGE2.setFont(SWTResourceManager.getFont("Tahoma", 10, SWT.NORMAL)); lbltxtCS_RANGE2.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lbltxtCS_RANGE2.setText("CS_RANGE2 :"); txtCS_RANGE2 = new Text(shell, SWT.BORDER); txtCS_RANGE2.setFont(SWTResourceManager.getFont("Tahoma", 10, SWT.NORMAL)); txtCS_RANGE2.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); txtCS_RANGE2.setText("CS_RANGE2"); txtCS_RANGE2.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { keyPressKetquaXnDlg(e); } }); Label lbltxtCS_DEFAULT = new Label(shell, SWT.NONE); lbltxtCS_DEFAULT.setFont(SWTResourceManager.getFont("Tahoma", 10, SWT.NORMAL)); lbltxtCS_DEFAULT.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lbltxtCS_DEFAULT.setText("CS_DEFAULT :"); txtCS_DEFAULT = new Text(shell, SWT.BORDER); txtCS_DEFAULT.setFont(SWTResourceManager.getFont("Tahoma", 10, SWT.NORMAL)); txtCS_DEFAULT.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); txtCS_DEFAULT.setText("CS_DEFAULT"); txtCS_DEFAULT.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { keyPressKetquaXnDlg(e); } }); Label lbltxtIMAGE_URL = new Label(shell, SWT.NONE); lbltxtIMAGE_URL.setFont(SWTResourceManager.getFont("Tahoma", 10, SWT.NORMAL)); lbltxtIMAGE_URL.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lbltxtIMAGE_URL.setText("IMAGE_URL :"); txtIMAGE_URL = new Text(shell, SWT.BORDER); txtIMAGE_URL.setFont(SWTResourceManager.getFont("Tahoma", 10, SWT.NORMAL)); txtIMAGE_URL.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); txtIMAGE_URL.setText("IMAGE_URL"); txtIMAGE_URL.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { keyPressKetquaXnDlg(e); } }); Label lbltxtMA_MAY = new Label(shell, SWT.NONE); lbltxtMA_MAY.setFont(SWTResourceManager.getFont("Tahoma", 10, SWT.NORMAL)); lbltxtMA_MAY.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lbltxtMA_MAY.setText("MA_MAY :"); txtMA_MAY = new Text(shell, SWT.BORDER); txtMA_MAY.setFont(SWTResourceManager.getFont("Tahoma", 10, SWT.NORMAL)); txtMA_MAY.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); txtMA_MAY.setText("MA_MAY"); txtMA_MAY.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { keyPressKetquaXnDlg(e); } }); Label lbltxtMO_TA = new Label(shell, SWT.NONE); lbltxtMO_TA.setFont(SWTResourceManager.getFont("Tahoma", 10, SWT.NORMAL)); lbltxtMO_TA.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lbltxtMO_TA.setText("MO_TA :"); txtMO_TA = new Text(shell, SWT.BORDER); txtMO_TA.setFont(SWTResourceManager.getFont("Tahoma", 10, SWT.NORMAL)); txtMO_TA.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); txtMO_TA.setText("MO_TA"); txtMO_TA.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { keyPressKetquaXnDlg(e); } }); Label lbltxtKET_LUAN = new Label(shell, SWT.NONE); lbltxtKET_LUAN.setFont(SWTResourceManager.getFont("Tahoma", 10, SWT.NORMAL)); lbltxtKET_LUAN.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lbltxtKET_LUAN.setText("KET_LUAN :"); txtKET_LUAN = new Text(shell, SWT.BORDER); txtKET_LUAN.setFont(SWTResourceManager.getFont("Tahoma", 10, SWT.NORMAL)); txtKET_LUAN.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); txtKET_LUAN.setText("KET_LUAN"); txtKET_LUAN.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { keyPressKetquaXnDlg(e); } }); Label lbltxtSTS = new Label(shell, SWT.NONE); lbltxtSTS.setFont(SWTResourceManager.getFont("Tahoma", 10, SWT.NORMAL)); lbltxtSTS.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lbltxtSTS.setText("STS :"); txtSTS = new Text(shell, SWT.BORDER); txtSTS.setFont(SWTResourceManager.getFont("Tahoma", 10, SWT.NORMAL)); txtSTS.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); txtSTS.setText("STS"); txtSTS.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { keyPressKetquaXnDlg(e); } }); new Label(shell, SWT.NONE); btnNewButtonSaveKetquaXn = new Button(shell, SWT.NONE); btnNewButtonSaveKetquaXn.setImage(SWTResourceManager.getImage(KetquaXnDlg.class, "/png/file-2x.png")); btnNewButtonSaveKetquaXn.setFont(SWTResourceManager.getFont("Tahoma", 12, SWT.BOLD)); btnNewButtonSaveKetquaXn.setText("Save"); btnNewButtonSaveKetquaXn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { saveKetquaXnDlg(); } }); loadKetquaXnDlgData(); } private void saveKetquaXnDlg(){ if(intTypeDlgKetquaXn==TYPE_DLG_VIEW){ return; } if(objKetquaXn == null){ objKetquaXn = new KetquaXn(); } if(objKetquaXn!=null){ // Integer = true objKetquaXn.CS_ID = Utils.getInt( txtCS_ID.getText() ); // Integer = true objKetquaXn.DV_ID = Utils.getInt( txtDV_ID.getText() ); // String = false objKetquaXn.MA_DVKT = txtMA_DVKT.getText(); // String = false objKetquaXn.TEN_DVKT = txtTEN_DVKT.getText(); // String = false objKetquaXn.CS_NAME = txtCS_NAME.getText(); // String = false objKetquaXn.CS_VALUE = txtCS_VALUE.getText(); // String = false objKetquaXn.CS_RANGE1 = txtCS_RANGE1.getText(); // String = false objKetquaXn.CS_RANGE2 = txtCS_RANGE2.getText(); // String = false objKetquaXn.CS_DEFAULT = txtCS_DEFAULT.getText(); // String = false objKetquaXn.IMAGE_URL = txtIMAGE_URL.getText(); // String = false objKetquaXn.MA_MAY = txtMA_MAY.getText(); // String = false objKetquaXn.MO_TA = txtMO_TA.getText(); // String = false objKetquaXn.KET_LUAN = txtKET_LUAN.getText(); // Integer = true objKetquaXn.STS = Utils.getInt( txtSTS.getText() ); } if(DbHelper.checkPhanQuyen(DbHelper.UPDATE, "ketqua_xn")==false){ logger.info("DON'T HAVE UPDATE RIGHT"); } else if(DbHelper.checkPhanQuyen(DbHelper.INSERT, "ketqua_xn")==false){ logger.info("DON'T HAVE INSERT RIGHT"); } else{ objKetquaXn.insert(); } shell.close(); } public void setKetquaXnDlgData(KetquaXn obj) { this.objKetquaXn = obj; } public void loadKetquaXnDlgData(){ if(intTypeDlgKetquaXn==TYPE_DLG_VIEW){ btnNewButtonSaveKetquaXn.setEnabled(false); } else{ btnNewButtonSaveKetquaXn.setEnabled(true); } if(DbHelper.checkPhanQuyen(DbHelper.READ, "ketqua_xn")==false){ logger.info("DON'T HAVE READ RIGHT"); return; } if(objKetquaXn != null){ if(objKetquaXn.CS_ID==null) txtCS_ID.setText(""); else txtCS_ID.setText(""+objKetquaXn.CS_ID.toString()); if(objKetquaXn.DV_ID==null) txtDV_ID.setText(""); else txtDV_ID.setText(""+objKetquaXn.DV_ID.toString()); if(objKetquaXn.MA_DVKT==null) txtMA_DVKT.setText(""); else txtMA_DVKT.setText(""+objKetquaXn.MA_DVKT.toString()); if(objKetquaXn.TEN_DVKT==null) txtTEN_DVKT.setText(""); else txtTEN_DVKT.setText(""+objKetquaXn.TEN_DVKT.toString()); if(objKetquaXn.CS_NAME==null) txtCS_NAME.setText(""); else txtCS_NAME.setText(""+objKetquaXn.CS_NAME.toString()); if(objKetquaXn.CS_VALUE==null) txtCS_VALUE.setText(""); else txtCS_VALUE.setText(""+objKetquaXn.CS_VALUE.toString()); if(objKetquaXn.CS_RANGE1==null) txtCS_RANGE1.setText(""); else txtCS_RANGE1.setText(""+objKetquaXn.CS_RANGE1.toString()); if(objKetquaXn.CS_RANGE2==null) txtCS_RANGE2.setText(""); else txtCS_RANGE2.setText(""+objKetquaXn.CS_RANGE2.toString()); if(objKetquaXn.CS_DEFAULT==null) txtCS_DEFAULT.setText(""); else txtCS_DEFAULT.setText(""+objKetquaXn.CS_DEFAULT.toString()); if(objKetquaXn.IMAGE_URL==null) txtIMAGE_URL.setText(""); else txtIMAGE_URL.setText(""+objKetquaXn.IMAGE_URL.toString()); if(objKetquaXn.MA_MAY==null) txtMA_MAY.setText(""); else txtMA_MAY.setText(""+objKetquaXn.MA_MAY.toString()); if(objKetquaXn.MO_TA==null) txtMO_TA.setText(""); else txtMO_TA.setText(""+objKetquaXn.MO_TA.toString()); if(objKetquaXn.KET_LUAN==null) txtKET_LUAN.setText(""); else txtKET_LUAN.setText(""+objKetquaXn.KET_LUAN.toString()); if(objKetquaXn.STS==null) txtSTS.setText(""); else txtSTS.setText(""+objKetquaXn.STS.toString()); } } protected void keyPressKetquaXnDlg(KeyEvent e) { if(e.keyCode==13){ saveKetquaXnDlg(); } } }
joschi/JadConf
src/test/java/com/github/joschi/jadconfig/validators/StringLowercaseValidatorTest.java
<filename>src/test/java/com/github/joschi/jadconfig/validators/StringLowercaseValidatorTest.java package com.github.joschi.jadconfig.validators; import com.github.joschi.jadconfig.ValidationException; import org.junit.Before; import org.junit.Test; /** * Unit tests for {@link StringLowercaseValidator} * * @author jschalanda */ public class StringLowercaseValidatorTest { private StringLowercaseValidator validator; @Before public void setUp() { validator = new StringLowercaseValidator(); } @Test public void testValidate() throws ValidationException { validator.validate("Test", ""); validator.validate("Test", "test"); validator.validate("Test", "1234"); validator.validate("Test", "test1234"); } @Test(expected = ValidationException.class) public void testValidateUppercaseString() throws ValidationException { validator.validate("Test", "TEST"); } @Test(expected = ValidationException.class) public void testValidateMixedCaseString() throws ValidationException { validator.validate("Test", "Test1234"); } @Test public void testValidateNull() throws ValidationException { validator.validate("Test", null); } }
reels-research/iOS-Private-Frameworks
LinkPresentation.framework/LPHTMLVideoComponent.h
/* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/LinkPresentation.framework/LinkPresentation */ @interface LPHTMLVideoComponent : LPHTMLComponent <DOMEventListener> { bool _isVisible; WebScriptObject * _isVisibleFunction; DOMElement * _muteButton; DOMElement * _muteButtonContainer; DOMElement * _playButton; LPVideo * _video; DOMHTMLVideoElement * _videoElement; DOMElement * _videoOverlay; DOMElement * _videoPosterFrame; bool _wasPlayingWhenHidden; DOMHTMLIFrameElement * _youTubeContainerElement; } @property (readonly, copy) NSString *debugDescription; @property (readonly, copy) NSString *description; @property (readonly) unsigned long long hash; @property (getter=isMuted, nonatomic) bool muted; @property (readonly) Class superclass; + (id)ruleDictionaryForStyle:(id)arg1; + (id)styleSet; - (void).cxx_destruct; - (void)buildComponentWithPosterFrame:(id)arg1 posterFrameStyle:(id)arg2; - (id)createVideoElement; - (void)handleEvent:(id)arg1; - (id)initWithVideo:(id)arg1 style:(id)arg2 posterFrame:(id)arg3 posterFrameStyle:(id)arg4 themePath:(id)arg5 generator:(id)arg6; - (bool)isMuted; - (bool)isPlaying; - (bool)isVisible; - (void)pause; - (void)play; - (id)resolvedVideoElement; - (void)setMuted:(bool)arg1; - (bool)shouldAutoPlay; - (void)togglePlaying; - (void)updateVisibility; - (id)youTubeParametersForVideoURL:(id)arg1; @end
lucksonk/mda-studio
src/main/java/za/co/enigma/turing/mda/jee/xsd/connector/AdminobjectType.java
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2017.04.22 at 12:40:30 PM SAST // package za.co.enigma.turing.mda.jee.xsd.connector; import java.util.ArrayList; import java.util.List; 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; /** * * * The adminobjectType specifies information about an * administered object. Administered objects are specific to a * messaging style or message provider. This contains * information on the Java type of the interface implemented by * an administered object, its Java class name and its * configuration properties. * * * * <p>Java class for adminobjectType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="adminobjectType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="adminobject-interface" type="{http://xmlns.jcp.org/xml/ns/javaee}fully-qualified-classType"/> * &lt;element name="adminobject-class" type="{http://xmlns.jcp.org/xml/ns/javaee}fully-qualified-classType"/> * &lt;element name="config-property" type="{http://xmlns.jcp.org/xml/ns/javaee}config-propertyType" maxOccurs="unbounded" minOccurs="0"/> * &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 = "adminobjectType", propOrder = { "adminobjectInterface", "adminobjectClass", "configProperty" }) public class AdminobjectType { @XmlElement(name = "adminobject-interface", required = true) protected FullyQualifiedClassType adminobjectInterface; @XmlElement(name = "adminobject-class", required = true) protected FullyQualifiedClassType adminobjectClass; @XmlElement(name = "config-property") protected List<ConfigPropertyType> configProperty; @XmlAttribute(name = "id") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected java.lang.String id; /** * Gets the value of the adminobjectInterface property. * * @return * possible object is * {@link FullyQualifiedClassType } * */ public FullyQualifiedClassType getAdminobjectInterface() { return adminobjectInterface; } /** * Sets the value of the adminobjectInterface property. * * @param value * allowed object is * {@link FullyQualifiedClassType } * */ public void setAdminobjectInterface(FullyQualifiedClassType value) { this.adminobjectInterface = value; } /** * Gets the value of the adminobjectClass property. * * @return * possible object is * {@link FullyQualifiedClassType } * */ public FullyQualifiedClassType getAdminobjectClass() { return adminobjectClass; } /** * Sets the value of the adminobjectClass property. * * @param value * allowed object is * {@link FullyQualifiedClassType } * */ public void setAdminobjectClass(FullyQualifiedClassType value) { this.adminobjectClass = value; } /** * Gets the value of the configProperty property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the configProperty property. * * <p> * For example, to add a new item, do as follows: * <pre> * getConfigProperty().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ConfigPropertyType } * * */ public List<ConfigPropertyType> getConfigProperty() { if (configProperty == null) { configProperty = new ArrayList<ConfigPropertyType>(); } return this.configProperty; } /** * Gets the value of the id property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setId(java.lang.String value) { this.id = value; } }
howkymike/Wirtualny-dziekanat
client/src/components/CourseDetailsComponent/CourseDetailsFacultyPanel.js
import React, { useEffect, useState } from 'react'; import { FormGroup, Label, Input, Row, Col, TabPane } from 'reactstrap'; const CourseDetailsFacultyPanel = props => { const { state, dispatch, faculties, fields } = props; const [faculty, setFaculty] = useState(""); const [field, setField] = useState(""); useEffect(() => { if(!state.fieldOfStudy && faculties[0]) { setFaculty(faculties[0].name); setField(fields[0].name); } const fos = fields.find( value => value.id === state.fieldOfStudy); if(fos) { setFaculty(fos.faculty.name); setField(fos.name); } }, [faculties, fields, state.fieldOfStudy]); useEffect(() => { const fos = fields.filter(value => value.faculty.id === faculty); if(fos.length) { dispatch({ type: "fieldOfStudy", payload: fos[0].id }); } }, [faculty, fields, dispatch]); return( <TabPane tabId={ 1 }> <Row form> <Col> <FormGroup> <Label for="facultySelect">Wydział</Label> <Input placeholder="Wydział" value={ faculty } readOnly/> </FormGroup> </Col> </Row> <Row form> <Col> <FormGroup> <Label for="facultySelect">Kierunek</Label> <Input placeholder="Kierunek" value={ field } readOnly/> </FormGroup> </Col> </Row> <Row form> <Col> <FormGroup> <Label for="semester">Semestr</Label> <Input placeholder="Semestr" value={ state.semester } readOnly /> </FormGroup> </Col> </Row> </TabPane> ); } export default CourseDetailsFacultyPanel;
IThawk/learnCode
javaBase/distribute-demo/src/main/java/com/gupaoedu/vip/FastJsonSeriliazer.java
<reponame>IThawk/learnCode<filename>javaBase/distribute-demo/src/main/java/com/gupaoedu/vip/FastJsonSeriliazer.java<gh_stars>1-10 package com.gupaoedu.vip; import com.alibaba.fastjson.JSON; /** * 腾讯课堂搜索 咕泡学院 * 加群获取视频:608583947 * 风骚的Michael 老师 */ public class FastJsonSeriliazer implements ISerializer{ @Override public <T> byte[] serialize(T obj) { return JSON.toJSONString(obj).getBytes(); } @Override public <T> T deserialize(byte[] data, Class<T> clazz) { return (T)JSON.parseObject(new String(data),clazz); } }
envimate/httpmate
examples/aws-lambda/src/main/java/com/envimate/httpmate/examples/awslambda/usecases/HelloUseCase.java
<filename>examples/aws-lambda/src/main/java/com/envimate/httpmate/examples/awslambda/usecases/HelloUseCase.java /* * Copyright (c) 2019 envimate GmbH - https://envimate.com/. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.envimate.httpmate.examples.awslambda.usecases; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; public final class HelloUseCase { public HelloResponse sayHello(final HelloRequest request) { final ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Berlin")); final String date = DateTimeFormatter.ISO_LOCAL_DATE.format(now); return new HelloResponse("Hello Dear " + request.name, date); } }
KITE-2018/kite-ndn-cxx
ndn-cxx/net/ethernet.hpp
<gh_stars>1-10 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2014-2018 Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & <NAME>, Sorbonne University, * Washington University in St. Louis, * Beijing Institute of Technology, * The University of Memphis. * * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions). * * ndn-cxx library is free software: you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later version. * * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received copies of the GNU General Public License and GNU Lesser * General Public License along with ndn-cxx, e.g., in COPYING.md file. If not, see * <http://www.gnu.org/licenses/>. * * See AUTHORS.md for complete list of ndn-cxx authors and contributors. */ #ifndef NDN_NET_ETHERNET_HPP #define NDN_NET_ETHERNET_HPP #include <array> #include <cstdint> #include <functional> #include <string> namespace ndn { namespace ethernet { const uint16_t ETHERTYPE_NDN = 0x8624; const size_t ADDR_LEN = 6; ///< Octets in one Ethernet address const size_t TYPE_LEN = 2; ///< Octets in Ethertype field const size_t HDR_LEN = 14; ///< Total octets in Ethernet header (without 802.1Q tag) const size_t TAG_LEN = 4; ///< Octets in 802.1Q tag (TPID + priority + VLAN) const size_t MIN_DATA_LEN = 46; ///< Min octets in Ethernet payload (assuming no 802.1Q tag) const size_t MAX_DATA_LEN = 1500; ///< Max octets in Ethernet payload const size_t CRC_LEN = 4; ///< Octets in Ethernet frame check sequence /** \brief represents an Ethernet hardware address */ class Address : public std::array<uint8_t, ADDR_LEN> { public: /// Constructs a null Ethernet address (00:00:00:00:00:00) Address(); /// Constructs a new Ethernet address with the given octets Address(uint8_t a1, uint8_t a2, uint8_t a3, uint8_t a4, uint8_t a5, uint8_t a6); /// Constructs a new Ethernet address with the given octets explicit Address(const uint8_t octets[ADDR_LEN]); /// True if this is a broadcast address (ff:ff:ff:ff:ff:ff) bool isBroadcast() const; /// True if this is a multicast address bool isMulticast() const; /// True if this is a null address (00:00:00:00:00:00) bool isNull() const; /** * \brief Converts the address to a human-readable string * * \param sep A character used to visually separate the octets, * usually ':' (the default value) or '-' */ std::string toString(char sep = ':') const; /** * \brief Creates an Address from a string containing an Ethernet address * in hexadecimal notation, with colons or hyphens as separators * * \param str The string to be parsed * \return Always an instance of Address, which will be null * if the parsing fails */ static Address fromString(const std::string& str); }; /// Returns the Ethernet broadcast address (ff:ff:ff:ff:ff:ff) Address getBroadcastAddress(); /// Returns the default Ethernet multicast address for NDN Address getDefaultMulticastAddress(); std::ostream& operator<<(std::ostream& o, const Address& a); } // namespace ethernet } // namespace ndn namespace std { // specialize std::hash<> for ethernet::Address template<> struct hash<ndn::ethernet::Address> { size_t operator()(const ndn::ethernet::Address& a) const noexcept; }; } // namespace std #endif // NDN_NET_ETHERNET_HPP
npocmaka/Windows-Server-2003
tools/bcdazzle.js
<reponame>npocmaka/Windows-Server-2003 /* Dazzle.js: Usage: Dazzle.js [-e env_templ.xml] [-man buildmanager Identity] [-m macros_file] Get a list of machines For each machine create an alias for each depot on the machine, except root. BC1 jporkka1\bldcon1 _x86 _fre _x86fre _postbuild _root _inetsrv BC2 jporkka1\bldcon2 _x86 _fre _x86fre _ds _sdktools BC3 jporkka1\bldcon3 _x86 _fre _x86fre _termsrv */ var DEFAULT_IDENTITY_BM = "BuildManager"; var DEFAULT_IDENTITY_BUILDER = "Build"; Error.prototype.toString = Error_ToString; var g_FSObj = new ActiveXObject("Scripting.FileSystemObject"); // Parse input Parameter List var g_aBuildManagers = new Array(); var g_aServersFiles = new Array(); var g_aMacrosFiles = new Array(); var g_hMacrosWritten = new Object(); ParseArguments(WScript.Arguments); main(); WScript.Quit(0); function main() { var PrivateData; var objFile; var objMacroFile; var i; var strMacroFileName; var strFileName; var strCmdLine; for(i = 0; i < g_aBuildManagers.length; ++i) { WScript.Echo("Build manager: " + g_aBuildManagers[i].strMachine + "\\" + g_aBuildManagers[i].strMachineIdentity); PrivateData = GetEnvironment(g_aBuildManagers[i].strMachine, g_aBuildManagers[i].strMachineIdentity); if (PrivateData) { strFileName = CreateConfigFileName("Servers", g_aBuildManagers[i].strMachine, g_aBuildManagers[i].strMachineIdentity); g_aServersFiles[g_aServersFiles.length] = strFileName; objFile = g_FSObj.CreateTextFile(strFileName, true); objFile.WriteLine("######################################################"); objFile.WriteLine("# Servers for build manager: " + g_aBuildManagers[i].strMachine + "\\" + g_aBuildManagers[i].strMachineIdentity); if (!strMacroFileName) { strMacroFileName = CreateConfigFileName("Macros", g_aBuildManagers[i].strMachine, g_aBuildManagers[i].strMachineIdentity); objMacroFile = g_FSObj.CreateTextFile(strMacroFileName, true); WriteMacro(objMacroFile, 'root', null); WriteMacro(objMacroFile, 'postbuild', null); } WriteServerInfo(objFile, objMacroFile, PrivateData); objFile.Close(); } } strCmdLine = "BCDazzle.exe "; if (objMacroFile) { objMacroFile.Close(); strCmdLine += " -m " + strMacroFileName; } if (g_aServersFiles.length) strCmdLine += " -s " + g_aServersFiles.join(" -s "); if (g_aMacrosFiles.length) strCmdLine += " -m " + g_aMacrosFiles.join(" -m "); var objShell; objShell = WScript.CreateObject( "WScript.Shell" ) WScript.Echo("Running " + strCmdLine); objShell.Run(strCmdLine, 1); } // macro com ( _com ) "CD /d %sdxroot%\\com\n" function WriteMacro(objMacroFile, strDepotName, strDepotPath) { if (!g_hMacrosWritten[strDepotName]) { g_hMacrosWritten[strDepotName] = true; objMacroFile.WriteLine('macro ' + strDepotName + ' ( _' + strDepotName + ' ) "cd /d %sdxroot%' + (strDepotPath ? '\\\\' + strDepotPath : '') + '\\n"'); } } function CreateConfigFileName(strName, strMachine, strMachineIdentity) { var strResult = g_FSObj.GetSpecialFolder(2) + "\\" + strName + "_" + strMachine + "_" + strMachineIdentity + ".txt"; return strResult; } function ParseArguments(Arguments) { var strArg; var chArg0; var chArg1; var argn; var objBM; for(argn = 0; argn < Arguments.length; argn++) { strArg = Arguments(argn); chArg0 = strArg.charAt(0); chArg1 = strArg.toLowerCase().slice(1); if (chArg0 != '-' && chArg0 != '/') Usage(1); else { switch(chArg1) { case 'e': if (argn + 1 < Arguments.length) objBM = LoadEnvironmentTemplate(Arguments(argn + 1)); else Usage(2); if (!objBM) Usage(3); g_aBuildManagers[g_aBuildManagers.length] = objBM; argn++; break; case 'man': objBM = new Object; if (argn + 2 < Arguments.length) { objBM.strMachine = Arguments(argn + 1); objBM.strMachineIdentity = Arguments(argn + 2); } else Usage(4); g_aBuildManagers[g_aBuildManagers.length] = objBM; argn += 2; break; case 'm': if (argn + 1 < Arguments.length) g_aMacrosFiles[g_aMacrosFiles.length] = Arguments(argn + 1); else Usage(5); argn++; break; default: Usage(4); break; } } } } // MyEval(expr) // evaluating uneval'ed objects creates a bunch of junk local variables. // by putting the eval call in a little subroutine, we avoid keeping those // locals around. function MyEval(expr) { try { return eval(expr); } catch(ex) { throw ex; } } function Error_ToString() { var i; var str = 'Exception('; /* Only some error messages get filled in for "ex". Specifically the text for disk full never seems to get set by functions such as CreateTextFile(). */ if (this.number != null && this.description == "") { switch(this.number) { case -2147024784: this.description = "There is not enough space on the disk."; break; case -2147024894: this.description = "The system cannot find the file specified."; break; case -2147023585: this.description = "There are currently no logon servers available to service the logon request."; break; case -2147023170: this.description = "The remote procedure call failed."; break; case -2147024837: this.description = "An unexpected network error occurred"; break; case -2147024890: this.description = "The handle is invalid."; break; default: this.description = "Error text not set for (" + this.number + ")"; break; } } for(i in this) { str += i + ": " + this[i] + " "; } return str + ")"; } function WriteServerInfo(objFile, objMacroFile, PrivateData) { var i; var j; var strLine; var aMachines = PrivateData.objEnviron.Machine; var strDepotName; for(i = 0; i < aMachines.length; ++i) { strLine = aMachines[i].Name + " " + aMachines[i].Name + "\\BldCon_" + aMachines[i].Identity + " _" + PrivateData.objConfig.Options.BuildType + " _" + PrivateData.objConfig.Options.Platform; if (PrivateData.objConfig.Options.Aliases) strLine += " " + PrivateData.objConfig.Options.Aliases; if (aMachines[i].Aliases) strLine += " " + aMachines[i].Aliases; if (aMachines[i].Name == PrivateData.objEnviron.BuildManager.PostBuildMachine) strLine += " _root _postbuild"; for(j = 0; j < aMachines[i].Depot.length; ++j) { strDepotName = aMachines[i].Depot[j].toLowerCase(); if (strDepotName != 'root') { strLine += " _" + strDepotName; WriteMacro(objMacroFile, strDepotName, strDepotName); } } objFile.WriteLine(strLine); } } function GetEnvironment(strMachineName, strIdentity) { var strMode; var obj; var PrivateData = new Object(); try { WScript.Echo("Attempting connection to " + strMachineName + "\\" + strIdentity); obj = new ActiveXObject('MTScript.Proxy'); obj.ConnectToMTScript(strMachineName, strIdentity, false); strMode = obj.Exec('getpublic', 'PublicData.strMode'); strMode = MyEval(strMode); if (strMode == 'idle') { WScript.Echo(strMachineName + "\\" + strIdentity + " is currently idle"); return null; } PrivateData.objConfig = obj.Exec('getpublic', 'PrivateData.objConfig'); PrivateData.objConfig = MyEval(PrivateData.objConfig); PrivateData.objEnviron = obj.Exec('getpublic', 'PrivateData.objEnviron'); PrivateData.objEnviron = MyEval(PrivateData.objEnviron); var result; WScript.Echo("Starting Remote Razzle Windows..."); result = obj.Exec('remote',''); WScript.Echo("Remote result is " + result); return PrivateData; } catch(ex) { WScript.Echo("CaptureLogsManager '" + strMachineName + "\\" + strIdentity + "' failed, ex=" + ex); } return null; } function LoadEnvironmentTemplate(strEnviroURL) { var xml = new ActiveXObject('Microsoft.XMLDOM'); var err = new Error(); var node; var objBM = new Object(); fStandaloneMode = false; xml.async = false; // It's unlikely they have the schema file available for this template, // so we turn off schema validation right now. The script engine will // validate it when we start the build. xml.validateOnParse = false; xml.resolveExternals = false; if (!xml.load(strEnviroURL) || !xml.documentElement) { err.description = 'Error loading the environment template ' + strEnviroURL; err.details = xml.parseError.reason; throw(err); } node = xml.documentElement.selectSingleNode('BuildManager'); if (!node) { err.description = 'Invalid environment template file (BuildManager tag missing): ' + strEnviroURL; throw(err); } objBM.strMachine = node.getAttribute("Name"); objBM.strMachineIdentity = node.getAttribute("Identity"); if (!objBM.strMachine) { err.description = 'Invalid environment template file (BuildManager tag badly formatted): ' + strEnviroURL; throw(err); } if (!objBM.strMachineIdentity) objBM.strMachineIdentity = DEFAULT_IDENTITY_BM; if (objBM.strMachine.toLowerCase() == '%localmachine%' || objBM.strMachine.toLowerCase() == '%remotemachine%') { err.description = 'Sorry, cannot use the local machine or remote machine templates from this script'; throw(err); } return objBM; } function Usage(x) { WScript.Echo(''); WScript.Echo('Usage: dazzle [-e env_template.xml] [-man bldmgr identity] [-m macros]'); WScript.Echo(''); WScript.Echo(' -e env_template.xml : Use the specific environment template to find the build machines'); WScript.Echo(' -man bldmgr identity : Query "bldmgr" with "identity" for list of'); WScript.Echo(' build machines instead of template files.'); WScript.Echo(' -m macros.txt : Load the macros file.'); WScript.Echo(''); WScript.Echo(' You may specify multiple -e, -man and -m options.'); WScript.Echo(''); WScript.Quit(1); }
MrsTrier/RememberArt
Pods/gRPC-Core/src/core/lib/slice/percent_encoding.cc
version https://git-lfs.github.com/spec/v1 oid sha256:e6b36e23df39a0dae2c59b6d9122c3db4b0dba9e9f6588a51a55f090654591fb size 5494
klen/muffin-example
setup.py
<reponame>klen/muffin-example<gh_stars>1-10 """Setup the application.""" from pathlib import Path from setuptools import setup requirements = (Path(__file__).parent / 'requirements.txt').read_text().split('\n') setup( install_requires=[line for line in requirements if line and not line.startswith('#')] )
ghsecuritylab/tomato_egg
release/src/linux/linux/arch/mips/lasat/prom.h
<filename>release/src/linux/linux/arch/mips/lasat/prom.h #ifndef PROM_H #define PROM_H extern void (* prom_display)(const char *string, int pos, int clear); extern void (* prom_monitor)(void); extern void (* prom_printf)(const char * fmt, ...); #endif
tejasvinu/hetu-core
presto-main/src/test/java/io/prestosql/operator/TestFilterAndProjectOperator.java
/* * 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.prestosql.operator; import com.google.common.collect.ImmutableList; import io.airlift.units.DataSize; import io.prestosql.metadata.Metadata; import io.prestosql.operator.project.PageProcessor; import io.prestosql.spi.Page; import io.prestosql.spi.function.BuiltInFunctionHandle; import io.prestosql.spi.function.Signature; import io.prestosql.spi.plan.PlanNodeId; import io.prestosql.spi.relation.RowExpression; import io.prestosql.sql.gen.ExpressionCompiler; import io.prestosql.sql.gen.PageFunctionCompiler; import io.prestosql.testing.MaterializedResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; import java.util.function.Supplier; import static io.airlift.concurrent.Threads.daemonThreadsNamed; import static io.airlift.units.DataSize.Unit.BYTE; import static io.airlift.units.DataSize.Unit.KILOBYTE; import static io.prestosql.RowPagesBuilder.rowPagesBuilder; import static io.prestosql.SessionTestUtils.TEST_SESSION; import static io.prestosql.metadata.MetadataManager.createTestMetadataManager; import static io.prestosql.operator.OperatorAssertion.assertOperatorEquals; import static io.prestosql.operator.OperatorAssertion.assertOperatorEqualsWithStateComparison; import static io.prestosql.spi.function.OperatorType.ADD; import static io.prestosql.spi.function.OperatorType.BETWEEN; import static io.prestosql.spi.function.OperatorType.EQUAL; import static io.prestosql.spi.type.BigintType.BIGINT; import static io.prestosql.spi.type.BooleanType.BOOLEAN; import static io.prestosql.spi.type.VarcharType.VARCHAR; import static io.prestosql.sql.relational.Expressions.call; import static io.prestosql.sql.relational.Expressions.constant; import static io.prestosql.sql.relational.Expressions.field; import static io.prestosql.testing.TestingTaskContext.createTaskContext; import static java.util.concurrent.Executors.newCachedThreadPool; import static java.util.concurrent.Executors.newScheduledThreadPool; @Test(singleThreaded = true) public class TestFilterAndProjectOperator { private ExecutorService executor; private ScheduledExecutorService scheduledExecutor; private DriverContext driverContext; @BeforeMethod public void setUp() { executor = newCachedThreadPool(daemonThreadsNamed("test-executor-%s")); scheduledExecutor = newScheduledThreadPool(2, daemonThreadsNamed("test-scheduledExecutor-%s")); driverContext = createTaskContext(executor, scheduledExecutor, TEST_SESSION) .addPipelineContext(0, true, true, false) .addDriverContext(); } @AfterMethod(alwaysRun = true) public void tearDown() { executor.shutdownNow(); scheduledExecutor.shutdownNow(); } @Test public void test() { List<Page> input = rowPagesBuilder(VARCHAR, BIGINT) .addSequencePage(100, 0, 0) .build(); RowExpression filter = call(BETWEEN.getFunctionName().toString(), new BuiltInFunctionHandle(Signature.internalOperator(BETWEEN, BOOLEAN.getTypeSignature(), ImmutableList.of(BIGINT.getTypeSignature(), BIGINT.getTypeSignature(), BIGINT.getTypeSignature()))), BOOLEAN, field(1, BIGINT), constant(10L, BIGINT), constant(19L, BIGINT)); RowExpression field0 = field(0, VARCHAR); RowExpression add5 = call(ADD.getFunctionName().toString(), new BuiltInFunctionHandle(Signature.internalOperator(ADD, BIGINT.getTypeSignature(), ImmutableList.of(BIGINT.getTypeSignature(), BIGINT.getTypeSignature()))), BIGINT, field(1, BIGINT), constant(5L, BIGINT)); Metadata metadata = createTestMetadataManager(); ExpressionCompiler compiler = new ExpressionCompiler(metadata, new PageFunctionCompiler(metadata, 0)); Supplier<PageProcessor> processor = compiler.compilePageProcessor(Optional.of(filter), ImmutableList.of(field0, add5)); OperatorFactory operatorFactory = new FilterAndProjectOperator.FilterAndProjectOperatorFactory( 0, new PlanNodeId("test"), processor, ImmutableList.of(VARCHAR, BIGINT), new DataSize(0, BYTE), 0); MaterializedResult expected = MaterializedResult.resultBuilder(driverContext.getSession(), VARCHAR, BIGINT) .row("10", 15L) .row("11", 16L) .row("12", 17L) .row("13", 18L) .row("14", 19L) .row("15", 20L) .row("16", 21L) .row("17", 22L) .row("18", 23L) .row("19", 24L) .build(); assertOperatorEquals(operatorFactory, driverContext, input, expected); } @Test public void testSnapshot() { List<Page> input = rowPagesBuilder(VARCHAR, BIGINT) .addSequencePage(100, 0, 0) .addSequencePage(100, 0, 0) .addSequencePage(100, 0, 0) .build(); RowExpression filter = call( BETWEEN.getFunctionName().toString(), new BuiltInFunctionHandle(Signature.internalOperator(BETWEEN, BOOLEAN.getTypeSignature(), ImmutableList.of(BIGINT.getTypeSignature(), BIGINT.getTypeSignature(), BIGINT.getTypeSignature()))), BOOLEAN, field(1, BIGINT), constant(10L, BIGINT), constant(19L, BIGINT)); RowExpression field0 = field(0, VARCHAR); RowExpression add5 = call( ADD.getFunctionName().toString(), new BuiltInFunctionHandle(Signature.internalOperator(ADD, BIGINT.getTypeSignature(), ImmutableList.of(BIGINT.getTypeSignature(), BIGINT.getTypeSignature()))), BIGINT, field(1, BIGINT), constant(5L, BIGINT)); Metadata metadata = createTestMetadataManager(); ExpressionCompiler compiler = new ExpressionCompiler(metadata, new PageFunctionCompiler(metadata, 0)); Supplier<PageProcessor> processor = compiler.compilePageProcessor(Optional.of(filter), ImmutableList.of(field0, add5)); OperatorFactory operatorFactory = new FilterAndProjectOperator.FilterAndProjectOperatorFactory( 0, new PlanNodeId("test"), processor, ImmutableList.of(VARCHAR, BIGINT), new DataSize(0, BYTE), 0); MaterializedResult expected = MaterializedResult.resultBuilder(driverContext.getSession(), VARCHAR, BIGINT) .row("10", 15L) .row("11", 16L) .row("12", 17L) .row("13", 18L) .row("14", 19L) .row("15", 20L) .row("16", 21L) .row("17", 22L) .row("18", 23L) .row("19", 24L) .row("10", 15L) .row("11", 16L) .row("12", 17L) .row("13", 18L) .row("14", 19L) .row("15", 20L) .row("16", 21L) .row("17", 22L) .row("18", 23L) .row("19", 24L) .row("10", 15L) .row("11", 16L) .row("12", 17L) .row("13", 18L) .row("14", 19L) .row("15", 20L) .row("16", 21L) .row("17", 22L) .row("18", 23L) .row("19", 24L) .build(); assertOperatorEqualsWithStateComparison(operatorFactory, driverContext, input, expected, false, ImmutableList.of(), true, createExpectedMapping()); } private Map<String, Object> createExpectedMapping() { Map<String, Object> expectedMapping = new HashMap<>(); Map<String, Object> mergingOutputMapping = new HashMap<>(); Map<String, Object> pageBuilderMapping = new HashMap<>(); List<Map<String, Object>> blockBuildersMapping = new ArrayList<>(); Map<String, Object> longArrayBlockBuilderMapping = new HashMap<>(); Map<String, Object> variableWidthBlockBuilderMapping = new HashMap<>(); Map<String, Object> longArrayBlockBuilderStatusMapping = new HashMap<>(); Map<String, Object> variableWidthBlockBuilderStatusMapping = new HashMap<>(); Map<String, Object> longArrayBlockBuilderStatusPageBuilderStatusMapping = new HashMap<>(); expectedMapping.put("operatorContext", 0); expectedMapping.put("pageProcessorMemoryContext", 0L); expectedMapping.put("outputMemoryContext", 388L); expectedMapping.put("mergingOutput", mergingOutputMapping); expectedMapping.put("finishing", false); mergingOutputMapping.put("pageBuilder", pageBuilderMapping); mergingOutputMapping.put("finishing", false); pageBuilderMapping.put("blockBuilders", blockBuildersMapping); pageBuilderMapping.put("pageBuilderStatus", 0L); pageBuilderMapping.put("declaredPositions", 0); blockBuildersMapping.add(variableWidthBlockBuilderMapping); blockBuildersMapping.add(longArrayBlockBuilderMapping); variableWidthBlockBuilderMapping.put("blockBuilderStatus", variableWidthBlockBuilderStatusMapping); variableWidthBlockBuilderMapping.put("initialized", false); variableWidthBlockBuilderMapping.put("initialEntryCount", 8); variableWidthBlockBuilderMapping.put("initialSliceOutputSize", 256); variableWidthBlockBuilderMapping.put("sliceOutput", Collections.emptyList()); variableWidthBlockBuilderMapping.put("hasNullValue", false); variableWidthBlockBuilderMapping.put("valueIsNull", Collections.emptyList()); variableWidthBlockBuilderMapping.put("offsets", Arrays.asList(0)); variableWidthBlockBuilderMapping.put("positions", 0); variableWidthBlockBuilderMapping.put("currentEntrySize", 0); variableWidthBlockBuilderMapping.put("arraysRetainedSizeInBytes", 36L); longArrayBlockBuilderMapping.put("blockBuilderStatus", longArrayBlockBuilderStatusMapping); longArrayBlockBuilderMapping.put("initialized", false); longArrayBlockBuilderMapping.put("positionCount", 0); longArrayBlockBuilderMapping.put("hasNullValue", false); longArrayBlockBuilderMapping.put("hasNonNullValue", false); longArrayBlockBuilderMapping.put("valueIsNull", Collections.emptyList()); longArrayBlockBuilderMapping.put("values", Collections.emptyList()); longArrayBlockBuilderMapping.put("retainedSizeInBytes", 128L); variableWidthBlockBuilderStatusMapping.put("pageBuilderStatus", 0L); variableWidthBlockBuilderStatusMapping.put("currentSize", 0); longArrayBlockBuilderStatusMapping.put("pageBuilderStatus", 0L); longArrayBlockBuilderStatusMapping.put("currentSize", 0); return expectedMapping; } @Test public void testMergeOutput() { List<Page> input = rowPagesBuilder(VARCHAR, BIGINT) .addSequencePage(100, 0, 0) .addSequencePage(100, 0, 0) .addSequencePage(100, 0, 0) .addSequencePage(100, 0, 0) .build(); RowExpression filter = call(EQUAL.getFunctionName().toString(), new BuiltInFunctionHandle(Signature.internalOperator(EQUAL, BOOLEAN.getTypeSignature(), ImmutableList.of(BIGINT.getTypeSignature(), BIGINT.getTypeSignature()))), BOOLEAN, field(1, BIGINT), constant(10L, BIGINT)); Metadata metadata = createTestMetadataManager(); ExpressionCompiler compiler = new ExpressionCompiler(metadata, new PageFunctionCompiler(metadata, 0)); Supplier<PageProcessor> processor = compiler.compilePageProcessor(Optional.of(filter), ImmutableList.of(field(1, BIGINT))); OperatorFactory operatorFactory = new FilterAndProjectOperator.FilterAndProjectOperatorFactory( 0, new PlanNodeId("test"), processor, ImmutableList.of(BIGINT), new DataSize(64, KILOBYTE), 2); List<Page> expected = rowPagesBuilder(BIGINT) .row(10L) .row(10L) .row(10L) .row(10L) .build(); assertOperatorEquals(operatorFactory, ImmutableList.of(BIGINT), driverContext, input, expected); } }
Kevin030796/hcm-petrosida
org.taowi.hcm.payroll/src/org/taowi/hcm/core/model/MHCEmployee.java
<reponame>Kevin030796/hcm-petrosida<filename>org.taowi.hcm.payroll/src/org/taowi/hcm/core/model/MHCEmployee.java package org.taowi.hcm.core.model; import java.sql.ResultSet; import java.util.Properties; import org.taowi.hcm.core.model.MEmployee; import org.taowi.hcm.payroll.model.MHCPayrollTrigger; public class MHCEmployee extends MEmployee{ /** * */ private static final long serialVersionUID = 6373653534751748382L; public MHCEmployee(Properties ctx, int HC_Employee_ID, String trxName) { super(ctx, HC_Employee_ID, trxName); } public MHCEmployee(Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } /** * After Save * @param newRecord new * @param success success * @return true if can be saved */ protected boolean afterSave (boolean newRecord, boolean success) { if(newRecord) return true; if(is_ValueChanged(COLUMNNAME_HC_Religion_ID) || is_ValueChanged(COLUMNNAME_HC_TaxStatus_ID)){ String columnName = null; if(is_ValueChanged(COLUMNNAME_HC_Religion_ID)) columnName = COLUMNNAME_HC_Religion_ID; else if(is_ValueChanged(COLUMNNAME_HC_TaxStatus_ID)) columnName = COLUMNNAME_HC_TaxStatus_ID; String oldValue = (String) get_ValueOld(columnName); String newValue = (String) get_Value(columnName); MHCPayrollTrigger trigger = new MHCPayrollTrigger(getCtx(), 0, get_TrxName()); trigger.setAD_Org_ID(getAD_Org_ID()); trigger.setEffectiveDateFrom(getEffectiveDateFrom()); trigger.setHC_Employee_ID(getHC_Employee_ID()); trigger.setColumnName(columnName); trigger.setOldValue(oldValue); trigger.setNewValue(newValue); trigger.saveEx(); } return true; } }