repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
DanielPollithy/bluetooth_drone
drone.py
284
from multiprocessing import Process import client import drone_poller def run(): p = Process(target=drone_poller.run) p.start() client.run() p.join() if __name__ == '__main__': try: run() except KeyboardInterrupt: print('[x] quitting...')
gpl-3.0
xushiwei/fibjs
vender/src/v8/src/compiler/js-generic-lowering.cc
20876
// Copyright 2014 the V8 project 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/code-stubs.h" #include "src/compiler/common-operator.h" #include "src/compiler/graph-inl.h" #include "src/compiler/js-generic-lowering.h" #include "src/compiler/machine-operator.h" #include "src/compiler/node-aux-data-inl.h" #include "src/compiler/node-properties-inl.h" #include "src/unique.h" namespace v8 { namespace internal { namespace compiler { // TODO(mstarzinger): This is a temporary workaround for non-hydrogen stubs for // which we don't have an interface descriptor yet. Use ReplaceWithICStubCall // once these stub have been made into a HydrogenCodeStub. template <typename T> static CodeStubInterfaceDescriptor* GetInterfaceDescriptor(Isolate* isolate, T* stub) { CodeStub::Major key = static_cast<CodeStub*>(stub)->MajorKey(); CodeStubInterfaceDescriptor* d = isolate->code_stub_interface_descriptor(key); stub->InitializeInterfaceDescriptor(d); return d; } // TODO(mstarzinger): This is a temporary shim to be able to call an IC stub // which doesn't have an interface descriptor yet. It mimics a hydrogen code // stub for the underlying IC stub code. class LoadICStubShim : public HydrogenCodeStub { public: LoadICStubShim(Isolate* isolate, ContextualMode contextual_mode) : HydrogenCodeStub(isolate), contextual_mode_(contextual_mode) { i::compiler::GetInterfaceDescriptor(isolate, this); } virtual Handle<Code> GenerateCode() V8_OVERRIDE { ExtraICState extra_state = LoadIC::ComputeExtraICState(contextual_mode_); return LoadIC::initialize_stub(isolate(), extra_state); } virtual void InitializeInterfaceDescriptor( CodeStubInterfaceDescriptor* descriptor) V8_OVERRIDE { Register registers[] = { InterfaceDescriptor::ContextRegister(), LoadIC::ReceiverRegister(), LoadIC::NameRegister() }; descriptor->Initialize(MajorKey(), ARRAY_SIZE(registers), registers); } private: virtual Major MajorKey() const V8_OVERRIDE { return NoCache; } virtual int NotMissMinorKey() const V8_OVERRIDE { return 0; } virtual bool UseSpecialCache() V8_OVERRIDE { return true; } ContextualMode contextual_mode_; }; // TODO(mstarzinger): This is a temporary shim to be able to call an IC stub // which doesn't have an interface descriptor yet. It mimics a hydrogen code // stub for the underlying IC stub code. class KeyedLoadICStubShim : public HydrogenCodeStub { public: explicit KeyedLoadICStubShim(Isolate* isolate) : HydrogenCodeStub(isolate) { i::compiler::GetInterfaceDescriptor(isolate, this); } virtual Handle<Code> GenerateCode() V8_OVERRIDE { return isolate()->builtins()->KeyedLoadIC_Initialize(); } virtual void InitializeInterfaceDescriptor( CodeStubInterfaceDescriptor* descriptor) V8_OVERRIDE { Register registers[] = { InterfaceDescriptor::ContextRegister(), KeyedLoadIC::ReceiverRegister(), KeyedLoadIC::NameRegister() }; descriptor->Initialize(MajorKey(), ARRAY_SIZE(registers), registers); } private: virtual Major MajorKey() const V8_OVERRIDE { return NoCache; } virtual int NotMissMinorKey() const V8_OVERRIDE { return 0; } virtual bool UseSpecialCache() V8_OVERRIDE { return true; } }; // TODO(mstarzinger): This is a temporary shim to be able to call an IC stub // which doesn't have an interface descriptor yet. It mimics a hydrogen code // stub for the underlying IC stub code. class StoreICStubShim : public HydrogenCodeStub { public: StoreICStubShim(Isolate* isolate, StrictMode strict_mode) : HydrogenCodeStub(isolate), strict_mode_(strict_mode) { i::compiler::GetInterfaceDescriptor(isolate, this); } virtual Handle<Code> GenerateCode() V8_OVERRIDE { return StoreIC::initialize_stub(isolate(), strict_mode_); } virtual void InitializeInterfaceDescriptor( CodeStubInterfaceDescriptor* descriptor) V8_OVERRIDE { Register registers[] = { InterfaceDescriptor::ContextRegister(), StoreIC::ReceiverRegister(), StoreIC::NameRegister(), StoreIC::ValueRegister() }; descriptor->Initialize(MajorKey(), ARRAY_SIZE(registers), registers); } private: virtual Major MajorKey() const V8_OVERRIDE { return NoCache; } virtual int NotMissMinorKey() const V8_OVERRIDE { return 0; } virtual bool UseSpecialCache() V8_OVERRIDE { return true; } StrictMode strict_mode_; }; // TODO(mstarzinger): This is a temporary shim to be able to call an IC stub // which doesn't have an interface descriptor yet. It mimics a hydrogen code // stub for the underlying IC stub code. class KeyedStoreICStubShim : public HydrogenCodeStub { public: KeyedStoreICStubShim(Isolate* isolate, StrictMode strict_mode) : HydrogenCodeStub(isolate), strict_mode_(strict_mode) { i::compiler::GetInterfaceDescriptor(isolate, this); } virtual Handle<Code> GenerateCode() V8_OVERRIDE { return strict_mode_ == SLOPPY ? isolate()->builtins()->KeyedStoreIC_Initialize() : isolate()->builtins()->KeyedStoreIC_Initialize_Strict(); } virtual void InitializeInterfaceDescriptor( CodeStubInterfaceDescriptor* descriptor) V8_OVERRIDE { Register registers[] = { InterfaceDescriptor::ContextRegister(), KeyedStoreIC::ReceiverRegister(), KeyedStoreIC::NameRegister(), KeyedStoreIC::ValueRegister() }; descriptor->Initialize(MajorKey(), ARRAY_SIZE(registers), registers); } private: virtual Major MajorKey() const V8_OVERRIDE { return NoCache; } virtual int NotMissMinorKey() const V8_OVERRIDE { return 0; } virtual bool UseSpecialCache() V8_OVERRIDE { return true; } StrictMode strict_mode_; }; JSGenericLowering::JSGenericLowering(CompilationInfo* info, JSGraph* jsgraph, MachineOperatorBuilder* machine, SourcePositionTable* source_positions) : LoweringBuilder(jsgraph->graph(), source_positions), info_(info), jsgraph_(jsgraph), linkage_(new (jsgraph->zone()) Linkage(info)), machine_(machine) {} void JSGenericLowering::PatchOperator(Node* node, Operator* op) { node->set_op(op); } void JSGenericLowering::PatchInsertInput(Node* node, int index, Node* input) { node->InsertInput(zone(), index, input); } Node* JSGenericLowering::SmiConstant(int32_t immediate) { return jsgraph()->SmiConstant(immediate); } Node* JSGenericLowering::Int32Constant(int immediate) { return jsgraph()->Int32Constant(immediate); } Node* JSGenericLowering::CodeConstant(Handle<Code> code) { return jsgraph()->HeapConstant(code); } Node* JSGenericLowering::FunctionConstant(Handle<JSFunction> function) { return jsgraph()->HeapConstant(function); } Node* JSGenericLowering::ExternalConstant(ExternalReference ref) { return jsgraph()->ExternalConstant(ref); } void JSGenericLowering::Lower(Node* node) { Node* replacement = NULL; // Dispatch according to the opcode. switch (node->opcode()) { #define DECLARE_CASE(x) \ case IrOpcode::k##x: \ replacement = Lower##x(node); \ break; DECLARE_CASE(Branch) JS_OP_LIST(DECLARE_CASE) #undef DECLARE_CASE default: // Nothing to see. return; } // Nothing to do if lowering was done by patching the existing node. if (replacement == node) return; // Iterate through uses of the original node and replace uses accordingly. UNIMPLEMENTED(); } #define REPLACE_IC_STUB_CALL(op, StubDeclaration) \ Node* JSGenericLowering::Lower##op(Node* node) { \ StubDeclaration; \ ReplaceWithICStubCall(node, &stub); \ return node; \ } REPLACE_IC_STUB_CALL(JSBitwiseOr, BinaryOpICStub stub(isolate(), Token::BIT_OR)) REPLACE_IC_STUB_CALL(JSBitwiseXor, BinaryOpICStub stub(isolate(), Token::BIT_XOR)) REPLACE_IC_STUB_CALL(JSBitwiseAnd, BinaryOpICStub stub(isolate(), Token::BIT_AND)) REPLACE_IC_STUB_CALL(JSShiftLeft, BinaryOpICStub stub(isolate(), Token::SHL)) REPLACE_IC_STUB_CALL(JSShiftRight, BinaryOpICStub stub(isolate(), Token::SAR)) REPLACE_IC_STUB_CALL(JSShiftRightLogical, BinaryOpICStub stub(isolate(), Token::SHR)) REPLACE_IC_STUB_CALL(JSAdd, BinaryOpICStub stub(isolate(), Token::ADD)) REPLACE_IC_STUB_CALL(JSSubtract, BinaryOpICStub stub(isolate(), Token::SUB)) REPLACE_IC_STUB_CALL(JSMultiply, BinaryOpICStub stub(isolate(), Token::MUL)) REPLACE_IC_STUB_CALL(JSDivide, BinaryOpICStub stub(isolate(), Token::DIV)) REPLACE_IC_STUB_CALL(JSModulus, BinaryOpICStub stub(isolate(), Token::MOD)) REPLACE_IC_STUB_CALL(JSToNumber, ToNumberStub stub(isolate())) #undef REPLACE_IC_STUB_CALL #define REPLACE_COMPARE_IC_CALL(op, token, pure) \ Node* JSGenericLowering::Lower##op(Node* node) { \ ReplaceWithCompareIC(node, token, pure); \ return node; \ } REPLACE_COMPARE_IC_CALL(JSEqual, Token::EQ, false) REPLACE_COMPARE_IC_CALL(JSNotEqual, Token::NE, false) REPLACE_COMPARE_IC_CALL(JSStrictEqual, Token::EQ_STRICT, true) REPLACE_COMPARE_IC_CALL(JSStrictNotEqual, Token::NE_STRICT, true) REPLACE_COMPARE_IC_CALL(JSLessThan, Token::LT, false) REPLACE_COMPARE_IC_CALL(JSGreaterThan, Token::GT, false) REPLACE_COMPARE_IC_CALL(JSLessThanOrEqual, Token::LTE, false) REPLACE_COMPARE_IC_CALL(JSGreaterThanOrEqual, Token::GTE, false) #undef REPLACE_COMPARE_IC_CALL #define REPLACE_RUNTIME_CALL(op, fun) \ Node* JSGenericLowering::Lower##op(Node* node) { \ ReplaceWithRuntimeCall(node, fun); \ return node; \ } REPLACE_RUNTIME_CALL(JSTypeOf, Runtime::kTypeof) REPLACE_RUNTIME_CALL(JSCreate, Runtime::kAbort) REPLACE_RUNTIME_CALL(JSCreateFunctionContext, Runtime::kNewFunctionContext) REPLACE_RUNTIME_CALL(JSCreateCatchContext, Runtime::kPushCatchContext) REPLACE_RUNTIME_CALL(JSCreateWithContext, Runtime::kPushWithContext) REPLACE_RUNTIME_CALL(JSCreateBlockContext, Runtime::kPushBlockContext) REPLACE_RUNTIME_CALL(JSCreateModuleContext, Runtime::kPushModuleContext) REPLACE_RUNTIME_CALL(JSCreateGlobalContext, Runtime::kAbort) #undef REPLACE_RUNTIME #define REPLACE_UNIMPLEMENTED(op) \ Node* JSGenericLowering::Lower##op(Node* node) { \ UNIMPLEMENTED(); \ return node; \ } REPLACE_UNIMPLEMENTED(JSToString) REPLACE_UNIMPLEMENTED(JSToName) REPLACE_UNIMPLEMENTED(JSYield) REPLACE_UNIMPLEMENTED(JSDebugger) #undef REPLACE_UNIMPLEMENTED void JSGenericLowering::ReplaceWithCompareIC(Node* node, Token::Value token, bool pure) { BinaryOpICStub stub(isolate(), Token::ADD); // TODO(mstarzinger): Hack. CodeStubInterfaceDescriptor* d = stub.GetInterfaceDescriptor(); CallDescriptor* desc_compare = linkage()->GetStubCallDescriptor(d); Handle<Code> ic = CompareIC::GetUninitialized(isolate(), token); Node* compare; if (pure) { // A pure (strict) comparison doesn't have an effect or control. // But for the graph, we need to add these inputs. compare = graph()->NewNode(common()->Call(desc_compare), CodeConstant(ic), NodeProperties::GetValueInput(node, 0), NodeProperties::GetValueInput(node, 1), NodeProperties::GetContextInput(node), graph()->start(), graph()->start()); } else { compare = graph()->NewNode(common()->Call(desc_compare), CodeConstant(ic), NodeProperties::GetValueInput(node, 0), NodeProperties::GetValueInput(node, 1), NodeProperties::GetContextInput(node), NodeProperties::GetEffectInput(node), NodeProperties::GetControlInput(node)); } node->ReplaceInput(0, compare); node->ReplaceInput(1, SmiConstant(token)); ReplaceWithRuntimeCall(node, Runtime::kBooleanize); } void JSGenericLowering::ReplaceWithICStubCall(Node* node, HydrogenCodeStub* stub) { CodeStubInterfaceDescriptor* d = stub->GetInterfaceDescriptor(); CallDescriptor* desc = linkage()->GetStubCallDescriptor(d); Node* stub_code = CodeConstant(stub->GetCode()); PatchInsertInput(node, 0, stub_code); PatchOperator(node, common()->Call(desc)); } void JSGenericLowering::ReplaceWithBuiltinCall(Node* node, Builtins::JavaScript id, int nargs) { CallFunctionStub stub(isolate(), nargs - 1, NO_CALL_FUNCTION_FLAGS); CodeStubInterfaceDescriptor* d = GetInterfaceDescriptor(isolate(), &stub); CallDescriptor* desc = linkage()->GetStubCallDescriptor(d, nargs); // TODO(mstarzinger): Accessing the builtins object this way prevents sharing // of code across native contexts. Fix this by loading from given context. Handle<JSFunction> function( JSFunction::cast(info()->context()->builtins()->javascript_builtin(id))); Node* stub_code = CodeConstant(stub.GetCode()); Node* function_node = FunctionConstant(function); PatchInsertInput(node, 0, stub_code); PatchInsertInput(node, 1, function_node); PatchOperator(node, common()->Call(desc)); } void JSGenericLowering::ReplaceWithRuntimeCall(Node* node, Runtime::FunctionId f, int nargs_override) { Operator::Property props = node->op()->properties(); const Runtime::Function* fun = Runtime::FunctionForId(f); int nargs = (nargs_override < 0) ? fun->nargs : nargs_override; CallDescriptor::DeoptimizationSupport deopt = OperatorProperties::CanLazilyDeoptimize(node->op()) ? CallDescriptor::kCanDeoptimize : CallDescriptor::kCannotDeoptimize; CallDescriptor* desc = linkage()->GetRuntimeCallDescriptor(f, nargs, props, deopt); Node* ref = ExternalConstant(ExternalReference(f, isolate())); Node* arity = Int32Constant(nargs); if (!centrystub_constant_.is_set()) { centrystub_constant_.set(CodeConstant(CEntryStub(isolate(), 1).GetCode())); } PatchInsertInput(node, 0, centrystub_constant_.get()); PatchInsertInput(node, nargs + 1, ref); PatchInsertInput(node, nargs + 2, arity); PatchOperator(node, common()->Call(desc)); } Node* JSGenericLowering::LowerBranch(Node* node) { Node* test = graph()->NewNode(machine()->WordEqual(), node->InputAt(0), jsgraph()->TrueConstant()); node->ReplaceInput(0, test); return node; } Node* JSGenericLowering::LowerJSUnaryNot(Node* node) { ToBooleanStub stub(isolate(), ToBooleanStub::RESULT_AS_INVERSE_ODDBALL); ReplaceWithICStubCall(node, &stub); return node; } Node* JSGenericLowering::LowerJSToBoolean(Node* node) { ToBooleanStub stub(isolate(), ToBooleanStub::RESULT_AS_ODDBALL); ReplaceWithICStubCall(node, &stub); return node; } Node* JSGenericLowering::LowerJSToObject(Node* node) { ReplaceWithBuiltinCall(node, Builtins::TO_OBJECT, 1); return node; } Node* JSGenericLowering::LowerJSLoadProperty(Node* node) { KeyedLoadICStubShim stub(isolate()); ReplaceWithICStubCall(node, &stub); return node; } Node* JSGenericLowering::LowerJSLoadNamed(Node* node) { LoadNamedParameters p = OpParameter<LoadNamedParameters>(node); LoadICStubShim stub(isolate(), p.contextual_mode); PatchInsertInput(node, 1, jsgraph()->HeapConstant(p.name)); ReplaceWithICStubCall(node, &stub); return node; } Node* JSGenericLowering::LowerJSStoreProperty(Node* node) { // TODO(mstarzinger): The strict_mode needs to be carried along in the // operator so that graphs are fully compositional for inlining. StrictMode strict_mode = info()->strict_mode(); KeyedStoreICStubShim stub(isolate(), strict_mode); ReplaceWithICStubCall(node, &stub); return node; } Node* JSGenericLowering::LowerJSStoreNamed(Node* node) { PrintableUnique<Name> key = OpParameter<PrintableUnique<Name> >(node); // TODO(mstarzinger): The strict_mode needs to be carried along in the // operator so that graphs are fully compositional for inlining. StrictMode strict_mode = info()->strict_mode(); StoreICStubShim stub(isolate(), strict_mode); PatchInsertInput(node, 1, jsgraph()->HeapConstant(key)); ReplaceWithICStubCall(node, &stub); return node; } Node* JSGenericLowering::LowerJSDeleteProperty(Node* node) { StrictMode strict_mode = OpParameter<StrictMode>(node); PatchInsertInput(node, 2, SmiConstant(strict_mode)); ReplaceWithBuiltinCall(node, Builtins::DELETE, 3); return node; } Node* JSGenericLowering::LowerJSHasProperty(Node* node) { ReplaceWithBuiltinCall(node, Builtins::IN, 2); return node; } Node* JSGenericLowering::LowerJSInstanceOf(Node* node) { InstanceofStub::Flags flags = static_cast<InstanceofStub::Flags>( InstanceofStub::kReturnTrueFalseObject | InstanceofStub::kArgsInRegisters); InstanceofStub stub(isolate(), flags); CodeStubInterfaceDescriptor* d = GetInterfaceDescriptor(isolate(), &stub); CallDescriptor* desc = linkage()->GetStubCallDescriptor(d, 0); Node* stub_code = CodeConstant(stub.GetCode()); PatchInsertInput(node, 0, stub_code); PatchOperator(node, common()->Call(desc)); return node; } Node* JSGenericLowering::LowerJSLoadContext(Node* node) { ContextAccess access = OpParameter<ContextAccess>(node); // TODO(mstarzinger): Use simplified operators instead of machine operators // here so that load/store optimization can be applied afterwards. for (int i = 0; i < access.depth(); ++i) { node->ReplaceInput( 0, graph()->NewNode( machine()->Load(kMachineTagged), NodeProperties::GetValueInput(node, 0), Int32Constant(Context::SlotOffset(Context::PREVIOUS_INDEX)), NodeProperties::GetEffectInput(node))); } node->ReplaceInput(1, Int32Constant(Context::SlotOffset(access.index()))); PatchOperator(node, machine()->Load(kMachineTagged)); return node; } Node* JSGenericLowering::LowerJSStoreContext(Node* node) { ContextAccess access = OpParameter<ContextAccess>(node); // TODO(mstarzinger): Use simplified operators instead of machine operators // here so that load/store optimization can be applied afterwards. for (int i = 0; i < access.depth(); ++i) { node->ReplaceInput( 0, graph()->NewNode( machine()->Load(kMachineTagged), NodeProperties::GetValueInput(node, 0), Int32Constant(Context::SlotOffset(Context::PREVIOUS_INDEX)), NodeProperties::GetEffectInput(node))); } node->ReplaceInput(2, NodeProperties::GetValueInput(node, 1)); node->ReplaceInput(1, Int32Constant(Context::SlotOffset(access.index()))); PatchOperator(node, machine()->Store(kMachineTagged, kFullWriteBarrier)); return node; } Node* JSGenericLowering::LowerJSCallConstruct(Node* node) { int arity = OpParameter<int>(node); CallConstructStub stub(isolate(), NO_CALL_CONSTRUCTOR_FLAGS); CodeStubInterfaceDescriptor* d = GetInterfaceDescriptor(isolate(), &stub); CallDescriptor* desc = linkage()->GetStubCallDescriptor(d, arity); Node* stub_code = CodeConstant(stub.GetCode()); Node* construct = NodeProperties::GetValueInput(node, 0); PatchInsertInput(node, 0, stub_code); PatchInsertInput(node, 1, Int32Constant(arity - 1)); PatchInsertInput(node, 2, construct); PatchInsertInput(node, 3, jsgraph()->UndefinedConstant()); PatchOperator(node, common()->Call(desc)); return node; } Node* JSGenericLowering::LowerJSCallFunction(Node* node) { CallParameters p = OpParameter<CallParameters>(node); CallFunctionStub stub(isolate(), p.arity - 2, p.flags); CodeStubInterfaceDescriptor* d = GetInterfaceDescriptor(isolate(), &stub); CallDescriptor* desc = linkage()->GetStubCallDescriptor(d, p.arity - 1); Node* stub_code = CodeConstant(stub.GetCode()); PatchInsertInput(node, 0, stub_code); PatchOperator(node, common()->Call(desc)); return node; } Node* JSGenericLowering::LowerJSCallRuntime(Node* node) { Runtime::FunctionId function = OpParameter<Runtime::FunctionId>(node); int arity = OperatorProperties::GetValueInputCount(node->op()); ReplaceWithRuntimeCall(node, function, arity); return node; } } } } // namespace v8::internal::compiler
gpl-3.0
blueboxgroup/ansible-modules-core
cloud/docker/docker.py
74584
#!/usr/bin/python # (c) 2013, Cove Schneider # (c) 2014, Joshua Conner <[email protected]> # (c) 2014, Pavel Antonov <[email protected]> # # This file is part of Ansible, # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>. ###################################################################### DOCUMENTATION = ''' --- module: docker version_added: "1.4" short_description: manage docker containers description: - Manage the life cycle of docker containers. options: count: description: - Number of matching containers that should be in the desired state. default: 1 image: description: - Container image used to match and launch containers. required: true pull: description: - Control when container images are updated from the C(docker_url) registry. If "missing," images will be pulled only when missing from the host; if '"always," the registry will be checked for a newer version of the image' each time the task executes. default: missing choices: [ "missing", "always" ] version_added: "1.9" entrypoint: description: - Corresponds to ``--entrypoint`` option of ``docker run`` command and ``ENTRYPOINT`` directive of Dockerfile. Used to match and launch containers. default: null required: false version_added: "2.1" command: description: - Command used to match and launch containers. default: null name: description: - Name used to match and uniquely name launched containers. Explicit names are used to uniquely identify a single container or to link among containers. Mutually exclusive with a "count" other than "1". default: null version_added: "1.5" ports: description: - "List containing private to public port mapping specification. Use docker 'CLI-style syntax: C(8000), C(9000:8000), or C(0.0.0.0:9000:8000)' where 8000 is a container port, 9000 is a host port, and 0.0.0.0 is - a host interface. The container ports need to be exposed either in the Dockerfile or via the C(expose) option." default: null version_added: "1.5" expose: description: - List of additional container ports to expose for port mappings or links. If the port is already exposed using EXPOSE in a Dockerfile, you don't need to expose it again. default: null version_added: "1.5" publish_all_ports: description: - Publish all exposed ports to the host interfaces. default: false version_added: "1.5" volumes: description: - List of volumes to mount within the container - 'Use docker CLI-style syntax: C(/host:/container[:mode])' - You can specify a read mode for the mount with either C(ro) or C(rw). Starting at version 2.1, SELinux hosts can additionally use C(z) or C(Z) mount options to use a shared or private label for the volume. default: null volumes_from: description: - List of names of containers to mount volumes from. default: null links: description: - List of other containers to link within this container with an optional - 'alias. Use docker CLI-style syntax: C(redis:myredis).' default: null version_added: "1.5" devices: description: - List of host devices to expose to container default: null required: false version_added: "2.1" log_driver: description: - You can specify a different logging driver for the container than for the daemon. "json-file" Default logging driver for Docker. Writes JSON messages to file. docker logs command is available only for this logging driver. "none" disables any logging for the container. "syslog" Syslog logging driver for Docker. Writes log messages to syslog. docker logs command is not available for this logging driver. "journald" Journald logging driver for Docker. Writes log messages to "journald". "gelf" Graylog Extended Log Format (GELF) logging driver for Docker. Writes log messages to a GELF endpoint likeGraylog or Logstash. "fluentd" Fluentd logging driver for Docker. Writes log messages to "fluentd" (forward input). "awslogs" (added in 2.1) Awslogs logging driver for Docker. Writes log messages to AWS Cloudwatch Logs. If not defined explicitly, the Docker daemon's default ("json-file") will apply. Requires docker >= 1.6.0. required: false default: json-file choices: - json-file - none - syslog - journald - gelf - fluentd - awslogs version_added: "2.0" log_opt: description: - Additional options to pass to the logging driver selected above. See Docker `log-driver <https://docs.docker.com/reference/logging/overview/>` documentation for more information. Requires docker >=1.7.0. required: false default: null version_added: "2.0" memory_limit: description: - RAM allocated to the container as a number of bytes or as a human-readable string like "512MB". Leave as "0" to specify no limit. default: 0 docker_url: description: - URL of the host running the docker daemon. This will default to the env var DOCKER_HOST if unspecified. default: ${DOCKER_HOST} or unix://var/run/docker.sock use_tls: description: - Whether to use tls to connect to the docker server. "no" means not to use tls (and ignore any other tls related parameters). "encrypt" means to use tls to encrypt the connection to the server. "verify" means to also verify that the server's certificate is valid for the server (this both verifies the certificate against the CA and that the certificate was issued for that host. If this is unspecified, tls will only be used if one of the other tls options require it. choices: [ "no", "encrypt", "verify" ] version_added: "1.9" tls_client_cert: description: - Path to the PEM-encoded certificate used to authenticate docker client. If specified tls_client_key must be valid default: ${DOCKER_CERT_PATH}/cert.pem version_added: "1.9" tls_client_key: description: - Path to the PEM-encoded key used to authenticate docker client. If specified tls_client_cert must be valid default: ${DOCKER_CERT_PATH}/key.pem version_added: "1.9" tls_ca_cert: description: - Path to a PEM-encoded certificate authority to secure the Docker connection. This has no effect if use_tls is encrypt. default: ${DOCKER_CERT_PATH}/ca.pem version_added: "1.9" tls_hostname: description: - A hostname to check matches what's supplied in the docker server's certificate. If unspecified, the hostname is taken from the docker_url. default: Taken from docker_url version_added: "1.9" docker_api_version: description: - Remote API version to use. This defaults to the current default as specified by docker-py. default: docker-py default remote API version version_added: "1.8" docker_user: description: - Username or UID to use within the container required: false default: null version_added: "2.0" username: description: - Remote API username. default: null password: description: - Remote API password. default: null email: description: - Remote API email. default: null hostname: description: - Container hostname. default: null domainname: description: - Container domain name. default: null env: description: - Pass a dict of environment variables to the container. default: null env_file: version_added: "2.1" description: - Pass in a path to a file with environment variable (FOO=BAR). If a key value is present in both explicitly presented (i.e. as 'env') and in the environment file, the explicit value will override. Requires docker-py >= 1.4.0. default: null required: false dns: description: - List of custom DNS servers for the container. required: false default: null detach: description: - Enable detached mode to leave the container running in background. If disabled, fail unless the process exits cleanly. default: true signal: version_added: "2.0" description: - With the state "killed", you can alter the signal sent to the container. required: false default: KILL state: description: - Assert the container's desired state. "present" only asserts that the matching containers exist. "started" asserts that the matching containers both exist and are running, but takes no action if any configuration has changed. "reloaded" (added in Ansible 1.9) asserts that all matching containers are running and restarts any that have any images or configuration out of date. "restarted" unconditionally restarts (or starts) the matching containers. "stopped" and '"killed" stop and kill all matching containers. "absent" stops and then' removes any matching containers. required: false default: started choices: - present - started - reloaded - restarted - stopped - killed - absent privileged: description: - Whether the container should run in privileged mode or not. default: false lxc_conf: description: - LXC configuration parameters, such as C(lxc.aa_profile:unconfined). default: null stdin_open: description: - Keep stdin open after a container is launched. default: false version_added: "1.6" tty: description: - Allocate a pseudo-tty within the container. default: false version_added: "1.6" net: description: - 'Network mode for the launched container: bridge, none, container:<name|id>' - or host. Requires docker >= 0.11. default: false version_added: "1.8" pid: description: - Set the PID namespace mode for the container (currently only supports 'host'). Requires docker-py >= 1.0.0 and docker >= 1.5.0 required: false default: None aliases: [] version_added: "1.9" registry: description: - Remote registry URL to pull images from. default: DockerHub aliases: [] version_added: "1.8" read_only: description: - Mount the container's root filesystem as read only default: null aliases: [] version_added: "2.0" restart_policy: description: - Container restart policy. - The 'unless-stopped' choice is only available starting in Ansible 2.1 and for Docker 1.9 and above. choices: ["no", "on-failure", "always", "unless-stopped"] default: null version_added: "1.9" restart_policy_retry: description: - Maximum number of times to restart a container. Leave as "0" for unlimited retries. default: 0 version_added: "1.9" extra_hosts: version_added: "2.0" description: - Dict of custom host-to-IP mappings to be defined in the container insecure_registry: description: - Use insecure private registry by HTTP instead of HTTPS. Needed for docker-py >= 0.5.0. default: false version_added: "1.9" cpu_set: description: - CPUs in which to allow execution. Requires docker-py >= 0.6.0. required: false default: null version_added: "2.0" cap_add: description: - Add capabilities for the container. Requires docker-py >= 0.5.0. required: false default: false version_added: "2.0" cap_drop: description: - Drop capabilities for the container. Requires docker-py >= 0.5.0. required: false default: false aliases: [] version_added: "2.0" labels: description: - Set container labels. Requires docker >= 1.6 and docker-py >= 1.2.0. required: false default: null version_added: "2.1" stop_timeout: description: - How many seconds to wait for the container to stop before killing it. required: false default: 10 version_added: "2.0" timeout: description: - Docker daemon response timeout in seconds. required: false default: 60 version_added: "2.1" cpu_shares: description: - CPU shares (relative weight). Requires docker-py >= 0.6.0. required: false default: 0 version_added: "2.1" ulimits: description: - ulimits, list ulimits with name, soft and optionally hard limit separated by colons. e.g. nofile:1024:2048 Requires docker-py >= 1.2.0 and docker >= 1.6.0 required: false default: null version_added: "2.1" author: - "Cove Schneider (@cove)" - "Joshua Conner (@joshuaconner)" - "Pavel Antonov (@softzilla)" - "Thomas Steinbach (@ThomasSteinbach)" - "Philippe Jandot (@zfil)" - "Daan Oosterveld (@dusdanig)" requirements: - "python >= 2.6" - "docker-py >= 0.3.0" - "The docker server >= 0.10.0" ''' EXAMPLES = ''' # Containers are matched either by name (if provided) or by an exact match of # the image they were launched with and the command they're running. The module # can accept either a name to target a container uniquely, or a count to operate # on multiple containers at once when it makes sense to do so. # Ensure that a data container with the name "mydata" exists. If no container # by this name exists, it will be created, but not started. - name: data container docker: name: mydata image: busybox state: present volumes: - /data # Ensure that a Redis server is running, using the volume from the data # container. Expose the default Redis port. - name: redis container docker: name: myredis image: redis command: redis-server --appendonly yes state: started expose: - 6379 volumes_from: - mydata # Ensure that a container of your application server is running. This will: # - pull the latest version of your application image from DockerHub. # - ensure that a container is running with the specified name and exact image. # If any configuration options have changed, the existing container will be # stopped and removed, and a new one will be launched in its place. # - link this container to the existing redis container launched above with # an alias. # - grant the container read write permissions for the host's /dev/sda device # through a node named /dev/xvda # - bind TCP port 9000 within the container to port 8080 on all interfaces # on the host. # - bind UDP port 9001 within the container to port 8081 on the host, only # listening on localhost. # - specify 2 ip resolutions. # - set the environment variable SECRET_KEY to "ssssh". - name: application container docker: name: myapplication image: someuser/appimage state: reloaded pull: always links: - "myredis:aliasedredis" devices: - "/dev/sda:/dev/xvda:rwm" ports: - "8080:9000" - "127.0.0.1:8081:9001/udp" extra_hosts: host1: "192.168.0.1" host2: "192.168.0.2" env: SECRET_KEY: ssssh # Ensure that exactly five containers of another server are running with this # exact image and command. If fewer than five are running, more will be launched; # if more are running, the excess will be stopped. - name: load-balanced containers docker: state: reloaded count: 5 image: someuser/anotherappimage command: sleep 1d # Unconditionally restart a service container. This may be useful within a # handler, for example. - name: application service docker: name: myservice image: someuser/serviceimage state: restarted # Stop all containers running the specified image. - name: obsolete container docker: image: someuser/oldandbusted state: stopped # Stop and remove a container with the specified name. - name: obsolete container docker: name: ohno image: someuser/oldandbusted state: absent # Example Syslogging Output - name: myservice container docker: name: myservice image: someservice/someimage state: reloaded log_driver: syslog log_opt: syslog-address: tcp://my-syslog-server:514 syslog-facility: daemon syslog-tag: myservice ''' HAS_DOCKER_PY = True DEFAULT_DOCKER_API_VERSION = None DEFAULT_TIMEOUT_SECONDS = 60 import sys import json import os import shlex from urlparse import urlparse try: import docker.client import docker.utils import docker.errors from requests.exceptions import RequestException except ImportError: HAS_DOCKER_PY = False if HAS_DOCKER_PY: try: from docker.errors import APIError as DockerAPIError except ImportError: from docker.client import APIError as DockerAPIError try: # docker-py 1.2+ import docker.constants DEFAULT_DOCKER_API_VERSION = docker.constants.DEFAULT_DOCKER_API_VERSION DEFAULT_TIMEOUT_SECONDS = docker.constants.DEFAULT_TIMEOUT_SECONDS except (ImportError, AttributeError): # docker-py less than 1.2 DEFAULT_DOCKER_API_VERSION = docker.client.DEFAULT_DOCKER_API_VERSION DEFAULT_TIMEOUT_SECONDS = docker.client.DEFAULT_TIMEOUT_SECONDS def _human_to_bytes(number): suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'] if isinstance(number, int): return number if number[-1] == suffixes[0] and number[-2].isdigit(): return number[:-1] i = 1 for each in suffixes[1:]: if number[-len(each):] == suffixes[i]: return int(number[:-len(each)]) * (1024 ** i) i = i + 1 raise ValueError('Could not convert %s to integer' % (number,)) def _ansible_facts(container_list): return {"docker_containers": container_list} def _docker_id_quirk(inspect): # XXX: some quirk in docker if 'ID' in inspect: inspect['Id'] = inspect['ID'] del inspect['ID'] return inspect def get_split_image_tag(image): # If image contains a host or org name, omit that from our check if '/' in image: registry, resource = image.rsplit('/', 1) else: registry, resource = None, image # now we can determine if image has a tag if ':' in resource: resource, tag = resource.split(':', 1) if registry: resource = '/'.join((registry, resource)) if tag == "": tag = "latest" else: tag = "latest" resource = image return resource, tag def normalize_image(image): """ Normalize a Docker image name to include the implied :latest tag. """ return ":".join(get_split_image_tag(image)) def is_running(container): '''Return True if an inspected container is in a state we consider "running."''' return container['State']['Running'] == True and not container['State'].get('Ghost', False) def get_docker_py_versioninfo(): if hasattr(docker, '__version__'): # a '__version__' attribute was added to the module but not until # after 0.3.0 was pushed to pypi. If it's there, use it. version = [] for part in docker.__version__.split('.'): try: version.append(int(part)) except ValueError: for idx, char in enumerate(part): if not char.isdigit(): nondigit = part[idx:] digit = part[:idx] break if digit: version.append(int(digit)) if nondigit: version.append(nondigit) elif hasattr(docker.Client, '_get_raw_response_socket'): # HACK: if '__version__' isn't there, we check for the existence of # `_get_raw_response_socket` in the docker.Client class, which was # added in 0.3.0 version = (0, 3, 0) else: # This is untrue but this module does not function with a version less # than 0.3.0 so it's okay to lie here. version = (0,) return tuple(version) def check_dependencies(module): """ Ensure `docker-py` >= 0.3.0 is installed, and call module.fail_json with a helpful error message if it isn't. """ if not HAS_DOCKER_PY: module.fail_json(msg="`docker-py` doesn't seem to be installed, but is required for the Ansible Docker module.") else: versioninfo = get_docker_py_versioninfo() if versioninfo < (0, 3, 0): module.fail_json(msg="The Ansible Docker module requires `docker-py` >= 0.3.0.") class DockerManager(object): counters = dict( created=0, started=0, stopped=0, killed=0, removed=0, restarted=0, pulled=0 ) reload_reasons = [] _capabilities = set() # Map optional parameters to minimum (docker-py version, server APIVersion) # docker-py version is a tuple of ints because we have to compare them # server APIVersion is passed to a docker-py function that takes strings _cap_ver_req = { 'devices': ((0, 7, 0), '1.2'), 'dns': ((0, 3, 0), '1.10'), 'volumes_from': ((0, 3, 0), '1.10'), 'restart_policy': ((0, 5, 0), '1.14'), 'extra_hosts': ((0, 7, 0), '1.3.1'), 'pid': ((1, 0, 0), '1.17'), 'log_driver': ((1, 2, 0), '1.18'), 'log_opt': ((1, 2, 0), '1.18'), 'host_config': ((0, 7, 0), '1.15'), 'cpu_set': ((0, 6, 0), '1.14'), 'cap_add': ((0, 5, 0), '1.14'), 'cap_drop': ((0, 5, 0), '1.14'), 'read_only': ((1, 0, 0), '1.17'), 'labels': ((1, 2, 0), '1.18'), 'stop_timeout': ((0, 5, 0), '1.0'), 'ulimits': ((1, 2, 0), '1.18'), # Clientside only 'insecure_registry': ((0, 5, 0), '0.0'), 'env_file': ((1, 4, 0), '0.0') } def __init__(self, module): self.module = module self.binds = None self.volumes = None if self.module.params.get('volumes'): self.binds = {} self.volumes = [] vols = self.module.params.get('volumes') for vol in vols: parts = vol.split(":") # regular volume if len(parts) == 1: self.volumes.append(parts[0]) # host mount (e.g. /mnt:/tmp, bind mounts host's /tmp to /mnt in the container) elif 2 <= len(parts) <= 3: # default to read-write mode = 'rw' # with supplied bind mode if len(parts) == 3: if parts[2] not in ["rw", "rw,Z", "rw,z", "z,rw", "Z,rw", "Z", "z", "ro", "ro,Z", "ro,z", "z,ro", "Z,ro"]: self.module.fail_json(msg='invalid bind mode ' + parts[2]) else: mode = parts[2] self.binds[parts[0]] = {'bind': parts[1], 'mode': mode } else: self.module.fail_json(msg='volumes support 1 to 3 arguments') self.lxc_conf = None if self.module.params.get('lxc_conf'): self.lxc_conf = [] options = self.module.params.get('lxc_conf') for option in options: parts = option.split(':', 1) self.lxc_conf.append({"Key": parts[0], "Value": parts[1]}) self.exposed_ports = None if self.module.params.get('expose'): self.exposed_ports = self.get_exposed_ports(self.module.params.get('expose')) self.port_bindings = None if self.module.params.get('ports'): self.port_bindings = self.get_port_bindings(self.module.params.get('ports')) self.links = None if self.module.params.get('links'): self.links = self.get_links(self.module.params.get('links')) env = self.module.params.get('env', None) env_file = self.module.params.get('env_file', None) self.environment = self.get_environment(env, env_file) self.ulimits = None if self.module.params.get('ulimits'): self.ulimits = [] ulimits = self.module.params.get('ulimits') for ulimit in ulimits: parts = ulimit.split(":") if len(parts) == 2: self.ulimits.append({'name': parts[0], 'soft': int(parts[1]), 'hard': int(parts[1])}) elif len(parts) == 3: self.ulimits.append({'name': parts[0], 'soft': int(parts[1]), 'hard': int(parts[2])}) else: self.module.fail_json(msg='ulimits support 2 to 3 arguments') # Connect to the docker server using any configured host and TLS settings. env_host = os.getenv('DOCKER_HOST') env_docker_verify = os.getenv('DOCKER_TLS_VERIFY') env_cert_path = os.getenv('DOCKER_CERT_PATH') env_docker_hostname = os.getenv('DOCKER_TLS_HOSTNAME') docker_url = module.params.get('docker_url') if not docker_url: if env_host: docker_url = env_host else: docker_url = 'unix://var/run/docker.sock' docker_api_version = module.params.get('docker_api_version') timeout = module.params.get('timeout') tls_client_cert = module.params.get('tls_client_cert', None) if not tls_client_cert and env_cert_path: tls_client_cert = os.path.join(env_cert_path, 'cert.pem') tls_client_key = module.params.get('tls_client_key', None) if not tls_client_key and env_cert_path: tls_client_key = os.path.join(env_cert_path, 'key.pem') tls_ca_cert = module.params.get('tls_ca_cert') if not tls_ca_cert and env_cert_path: tls_ca_cert = os.path.join(env_cert_path, 'ca.pem') tls_hostname = module.params.get('tls_hostname') if tls_hostname is None: if env_docker_hostname: tls_hostname = env_docker_hostname else: parsed_url = urlparse(docker_url) if ':' in parsed_url.netloc: tls_hostname = parsed_url.netloc[:parsed_url.netloc.rindex(':')] else: tls_hostname = parsed_url if not tls_hostname: tls_hostname = True # use_tls can be one of four values: # no: Do not use tls # encrypt: Use tls. We may do client auth. We will not verify the server # verify: Use tls. We may do client auth. We will verify the server # None: Only use tls if the parameters for client auth were specified # or tls_ca_cert (which requests verifying the server with # a specific ca certificate) use_tls = module.params.get('use_tls') if use_tls is None and env_docker_verify is not None: use_tls = 'verify' tls_config = None if use_tls != 'no': params = {} # Setup client auth if tls_client_cert and tls_client_key: params['client_cert'] = (tls_client_cert, tls_client_key) # We're allowed to verify the connection to the server if use_tls == 'verify' or (use_tls is None and tls_ca_cert): if tls_ca_cert: params['ca_cert'] = tls_ca_cert params['verify'] = True params['assert_hostname'] = tls_hostname else: params['verify'] = True params['assert_hostname'] = tls_hostname elif use_tls == 'encrypt': params['verify'] = False if params: # See https://github.com/docker/docker-py/blob/d39da11/docker/utils/utils.py#L279-L296 docker_url = docker_url.replace('tcp://', 'https://') tls_config = docker.tls.TLSConfig(**params) self.client = docker.Client(base_url=docker_url, version=docker_api_version, tls=tls_config, timeout=timeout) self.docker_py_versioninfo = get_docker_py_versioninfo() def _check_capabilities(self): """ Create a list of available capabilities """ api_version = self.client.version()['ApiVersion'] for cap, req_vers in self._cap_ver_req.items(): if (self.docker_py_versioninfo >= req_vers[0] and docker.utils.compare_version(req_vers[1], api_version) >= 0): self._capabilities.add(cap) def ensure_capability(self, capability, fail=True): """ Some of the functionality this ansible module implements are only available in newer versions of docker. Ensure that the capability is available here. If fail is set to False then return True or False depending on whether we have the capability. Otherwise, simply fail and exit the module if we lack the capability. """ if not self._capabilities: self._check_capabilities() if capability in self._capabilities: return True if not fail: return False api_version = self.client.version()['ApiVersion'] self.module.fail_json(msg='Specifying the `%s` parameter requires' ' docker-py: %s, docker server apiversion %s; found' ' docker-py: %s, server: %s' % ( capability, '.'.join(map(str, self._cap_ver_req[capability][0])), self._cap_ver_req[capability][1], '.'.join(map(str, self.docker_py_versioninfo)), api_version)) def get_environment(self, env, env_file): """ If environment files are combined with explicit environment variables, the explicit environment variables will override the key from the env file. """ final_env = {} if env_file: self.ensure_capability('env_file') parsed_env_file = docker.utils.parse_env_file(env_file) for name, value in parsed_env_file.iteritems(): final_env[name] = str(value) if env: for name, value in env.iteritems(): final_env[name] = str(value) return final_env def get_links(self, links): """ Parse the links passed, if a link is specified without an alias then just create the alias of the same name as the link """ processed_links = {} for link in links: parsed_link = link.split(':', 1) if(len(parsed_link) == 2): processed_links[parsed_link[0]] = parsed_link[1] else: processed_links[parsed_link[0]] = parsed_link[0] return processed_links def get_exposed_ports(self, expose_list): """ Parse the ports and protocols (TCP/UDP) to expose in the docker-py `create_container` call from the docker CLI-style syntax. """ if expose_list: exposed = [] for port in expose_list: port = str(port).strip() if port.endswith('/tcp') or port.endswith('/udp'): port_with_proto = tuple(port.split('/')) else: # assume tcp protocol if not specified port_with_proto = (port, 'tcp') exposed.append(port_with_proto) return exposed else: return None def get_start_params(self): """ Create start params """ params = { 'lxc_conf': self.lxc_conf, 'binds': self.binds, 'port_bindings': self.port_bindings, 'publish_all_ports': self.module.params.get('publish_all_ports'), 'privileged': self.module.params.get('privileged'), 'links': self.links, 'network_mode': self.module.params.get('net'), } optionals = {} for optional_param in ('devices', 'dns', 'volumes_from', 'restart_policy', 'restart_policy_retry', 'pid', 'extra_hosts', 'log_driver', 'cap_add', 'cap_drop', 'read_only', 'log_opt'): optionals[optional_param] = self.module.params.get(optional_param) if optionals['devices'] is not None: self.ensure_capability('devices') params['devices'] = optionals['devices'] if optionals['dns'] is not None: self.ensure_capability('dns') params['dns'] = optionals['dns'] if optionals['volumes_from'] is not None: self.ensure_capability('volumes_from') params['volumes_from'] = optionals['volumes_from'] if optionals['restart_policy'] is not None: self.ensure_capability('restart_policy') params['restart_policy'] = { 'Name': optionals['restart_policy'] } if params['restart_policy']['Name'] == 'on-failure': params['restart_policy']['MaximumRetryCount'] = optionals['restart_policy_retry'] # docker_py only accepts 'host' or None if 'pid' in optionals and not optionals['pid']: optionals['pid'] = None if optionals['pid'] is not None: self.ensure_capability('pid') params['pid_mode'] = optionals['pid'] if optionals['extra_hosts'] is not None: self.ensure_capability('extra_hosts') params['extra_hosts'] = optionals['extra_hosts'] if optionals['log_driver'] is not None: self.ensure_capability('log_driver') log_config = docker.utils.LogConfig(type=docker.utils.LogConfig.types.JSON) if optionals['log_opt'] is not None: for k, v in optionals['log_opt'].iteritems(): log_config.set_config_value(k, v) log_config.type = optionals['log_driver'] params['log_config'] = log_config if optionals['cap_add'] is not None: self.ensure_capability('cap_add') params['cap_add'] = optionals['cap_add'] if optionals['cap_drop'] is not None: self.ensure_capability('cap_drop') params['cap_drop'] = optionals['cap_drop'] if optionals['read_only'] is not None: self.ensure_capability('read_only') params['read_only'] = optionals['read_only'] return params def create_host_config(self): """ Create HostConfig object """ params = self.get_start_params() return docker.utils.create_host_config(**params) def get_port_bindings(self, ports): """ Parse the `ports` string into a port bindings dict for the `start_container` call. """ binds = {} for port in ports: # ports could potentially be an array like [80, 443], so we make sure they're strings # before splitting parts = str(port).split(':') container_port = parts[-1] if '/' not in container_port: container_port = int(parts[-1]) p_len = len(parts) if p_len == 1: # Bind `container_port` of the container to a dynamically # allocated TCP port on all available interfaces of the host # machine. bind = ('0.0.0.0',) elif p_len == 2: # Bind `container_port` of the container to port `parts[0]` on # all available interfaces of the host machine. bind = ('0.0.0.0', int(parts[0])) elif p_len == 3: # Bind `container_port` of the container to port `parts[1]` on # IP `parts[0]` of the host machine. If `parts[1]` empty bind # to a dynamically allocated port of IP `parts[0]`. bind = (parts[0], int(parts[1])) if parts[1] else (parts[0],) if container_port in binds: old_bind = binds[container_port] if isinstance(old_bind, list): # append to list if it already exists old_bind.append(bind) else: # otherwise create list that contains the old and new binds binds[container_port] = [binds[container_port], bind] else: binds[container_port] = bind return binds def get_summary_message(self): ''' Generate a message that briefly describes the actions taken by this task, in English. ''' parts = [] for k, v in self.counters.iteritems(): if v == 0: continue if v == 1: plural = "" else: plural = "s" parts.append("%s %d container%s" % (k, v, plural)) if parts: return ", ".join(parts) + "." else: return "No action taken." def get_reload_reason_message(self): ''' Generate a message describing why any reloaded containers were reloaded. ''' if self.reload_reasons: return ", ".join(self.reload_reasons) else: return None def get_summary_counters_msg(self): msg = "" for k, v in self.counters.iteritems(): msg = msg + "%s %d " % (k, v) return msg def increment_counter(self, name): self.counters[name] = self.counters[name] + 1 def has_changed(self): for k, v in self.counters.iteritems(): if v > 0: return True return False def get_inspect_image(self): try: return self.client.inspect_image(self.module.params.get('image')) except DockerAPIError as e: if e.response.status_code == 404: return None else: raise e def get_image_repo_tags(self): image, tag = get_split_image_tag(self.module.params.get('image')) if tag is None: tag = 'latest' resource = '%s:%s' % (image, tag) for image in self.client.images(name=image): if resource in image.get('RepoTags', []): return image['RepoTags'] return [] def get_inspect_containers(self, containers): inspect = [] for i in containers: details = self.client.inspect_container(i['Id']) details = _docker_id_quirk(details) inspect.append(details) return inspect def get_differing_containers(self): """ Inspect all matching, running containers, and return those that were started with parameters that differ from the ones that are provided during this module run. A list containing the differing containers will be returned, and a short string describing the specific difference encountered in each container will be appended to reload_reasons. This generates the set of containers that need to be stopped and started with new parameters with state=reloaded. """ running = self.get_running_containers() current = self.get_inspect_containers(running) defaults = self.client.info() #Get API version api_version = self.client.version()['ApiVersion'] image = self.get_inspect_image() if image is None: # The image isn't present. Assume that we're about to pull a new # tag and *everything* will be restarted. # # This will give false positives if you untag an image on the host # and there's nothing more to pull. return current differing = [] for container in current: # IMAGE # Compare the image by ID rather than name, so that containers # will be restarted when new versions of an existing image are # pulled. if container['Image'] != image['Id']: self.reload_reasons.append('image ({0} => {1})'.format(container['Image'], image['Id'])) differing.append(container) continue # ENTRYPOINT expected_entrypoint = self.module.params.get('entrypoint') if expected_entrypoint: expected_entrypoint = shlex.split(expected_entrypoint) actual_entrypoint = container["Config"]["Entrypoint"] if actual_entrypoint != expected_entrypoint: self.reload_reasons.append( 'entrypoint ({0} => {1})' .format(actual_entrypoint, expected_entrypoint) ) differing.append(container) continue # COMMAND expected_command = self.module.params.get('command') if expected_command: expected_command = shlex.split(expected_command) actual_command = container["Config"]["Cmd"] if actual_command != expected_command: self.reload_reasons.append('command ({0} => {1})'.format(actual_command, expected_command)) differing.append(container) continue # EXPOSED PORTS expected_exposed_ports = set((image['ContainerConfig'].get('ExposedPorts') or {}).keys()) for p in (self.exposed_ports or []): expected_exposed_ports.add("/".join(p)) actually_exposed_ports = set((container["Config"].get("ExposedPorts") or {}).keys()) if actually_exposed_ports != expected_exposed_ports: self.reload_reasons.append('exposed_ports ({0} => {1})'.format(actually_exposed_ports, expected_exposed_ports)) differing.append(container) continue # VOLUMES expected_volume_keys = set((image['ContainerConfig']['Volumes'] or {}).keys()) if self.volumes: expected_volume_keys.update(self.volumes) actual_volume_keys = set((container['Config']['Volumes'] or {}).keys()) if actual_volume_keys != expected_volume_keys: self.reload_reasons.append('volumes ({0} => {1})'.format(actual_volume_keys, expected_volume_keys)) differing.append(container) continue # ULIMITS expected_ulimit_keys = set(map(lambda x: '%s:%s:%s' % (x['name'],x['soft'],x['hard']), self.ulimits or [])) actual_ulimit_keys = set(map(lambda x: '%s:%s:%s' % (x['Name'],x['Soft'],x['Hard']), (container['HostConfig']['Ulimits'] or []))) if actual_ulimit_keys != expected_ulimit_keys: self.reload_reasons.append('ulimits ({0} => {1})'.format(actual_ulimit_keys, expected_ulimit_keys)) differing.append(container) continue # CPU_SHARES expected_cpu_shares = self.module.params.get('cpu_shares') actual_cpu_shares = container['HostConfig']['CpuShares'] if expected_cpu_shares and actual_cpu_shares != expected_cpu_shares: self.reload_reasons.append('cpu_shares ({0} => {1})'.format(actual_cpu_shares, expected_cpu_shares)) differing.append(container) continue # MEM_LIMIT try: expected_mem = _human_to_bytes(self.module.params.get('memory_limit')) except ValueError as e: self.module.fail_json(msg=str(e)) #For v1.19 API and above use HostConfig, otherwise use Config if docker.utils.compare_version('1.19', api_version) >= 0: actual_mem = container['HostConfig']['Memory'] else: actual_mem = container['Config']['Memory'] if expected_mem and actual_mem != expected_mem: self.reload_reasons.append('memory ({0} => {1})'.format(actual_mem, expected_mem)) differing.append(container) continue # ENVIRONMENT # actual_env is likely to include environment variables injected by # the Dockerfile. expected_env = {} for image_env in image['ContainerConfig']['Env'] or []: name, value = image_env.split('=', 1) expected_env[name] = value if self.environment: for name, value in self.environment.iteritems(): expected_env[name] = str(value) actual_env = {} for container_env in container['Config']['Env'] or []: name, value = container_env.split('=', 1) actual_env[name] = value if actual_env != expected_env: # Don't include the environment difference in the output. self.reload_reasons.append('environment {0} => {1}'.format(actual_env, expected_env)) differing.append(container) continue # LABELS expected_labels = {} for name, value in self.module.params.get('labels').iteritems(): expected_labels[name] = str(value) actual_labels = {} for container_label in container['Config']['Labels'] or []: name, value = container_label.split('=', 1) actual_labels[name] = value if actual_labels != expected_labels: self.reload_reasons.append('labels {0} => {1}'.format(actual_labels, expected_labels)) differing.append(container) continue # HOSTNAME expected_hostname = self.module.params.get('hostname') actual_hostname = container['Config']['Hostname'] if expected_hostname and actual_hostname != expected_hostname: self.reload_reasons.append('hostname ({0} => {1})'.format(actual_hostname, expected_hostname)) differing.append(container) continue # DOMAINNAME expected_domainname = self.module.params.get('domainname') actual_domainname = container['Config']['Domainname'] if expected_domainname and actual_domainname != expected_domainname: self.reload_reasons.append('domainname ({0} => {1})'.format(actual_domainname, expected_domainname)) differing.append(container) continue # DETACH # We don't have to check for undetached containers. If it wasn't # detached, it would have stopped before the playbook continued! # NAME # We also don't have to check name, because this is one of the # criteria that's used to determine which container(s) match in # the first place. # STDIN_OPEN expected_stdin_open = self.module.params.get('stdin_open') actual_stdin_open = container['Config']['AttachStdin'] if actual_stdin_open != expected_stdin_open: self.reload_reasons.append('stdin_open ({0} => {1})'.format(actual_stdin_open, expected_stdin_open)) differing.append(container) continue # TTY expected_tty = self.module.params.get('tty') actual_tty = container['Config']['Tty'] if actual_tty != expected_tty: self.reload_reasons.append('tty ({0} => {1})'.format(actual_tty, expected_tty)) differing.append(container) continue # -- "start" call differences -- # LXC_CONF if self.lxc_conf: expected_lxc = set(self.lxc_conf) actual_lxc = set(container['HostConfig']['LxcConf'] or []) if actual_lxc != expected_lxc: self.reload_reasons.append('lxc_conf ({0} => {1})'.format(actual_lxc, expected_lxc)) differing.append(container) continue # BINDS expected_binds = set() if self.binds: for host_path, config in self.binds.iteritems(): if isinstance(config, dict): container_path = config['bind'] mode = config['mode'] else: container_path = config mode = 'rw' expected_binds.add("{0}:{1}:{2}".format(host_path, container_path, mode)) actual_binds = set() for bind in (container['HostConfig']['Binds'] or []): if len(bind.split(':')) == 2: actual_binds.add(bind + ":rw") else: actual_binds.add(bind) if actual_binds != expected_binds: self.reload_reasons.append('binds ({0} => {1})'.format(actual_binds, expected_binds)) differing.append(container) continue # PORT BINDINGS expected_bound_ports = {} if self.port_bindings: for container_port, config in self.port_bindings.iteritems(): if isinstance(container_port, int): container_port = "{0}/tcp".format(container_port) if len(config) == 1: expected_bound_ports[container_port] = [{'HostIp': "0.0.0.0", 'HostPort': ""}] elif isinstance(config[0], tuple): expected_bound_ports[container_port] = [] for hostip, hostport in config: expected_bound_ports[container_port].append({ 'HostIp': hostip, 'HostPort': str(hostport)}) else: expected_bound_ports[container_port] = [{'HostIp': config[0], 'HostPort': str(config[1])}] actual_bound_ports = container['HostConfig']['PortBindings'] or {} if actual_bound_ports != expected_bound_ports: self.reload_reasons.append('port bindings ({0} => {1})'.format(actual_bound_ports, expected_bound_ports)) differing.append(container) continue # PUBLISHING ALL PORTS # What we really care about is the set of ports that is actually # published. That should be caught above. # PRIVILEGED expected_privileged = self.module.params.get('privileged') actual_privileged = container['HostConfig']['Privileged'] if actual_privileged != expected_privileged: self.reload_reasons.append('privileged ({0} => {1})'.format(actual_privileged, expected_privileged)) differing.append(container) continue # LINKS expected_links = set() for link, alias in (self.links or {}).iteritems(): expected_links.add("/{0}:{1}/{2}".format(link, container["Name"], alias)) actual_links = set(container['HostConfig']['Links'] or []) if actual_links != expected_links: self.reload_reasons.append('links ({0} => {1})'.format(actual_links, expected_links)) differing.append(container) continue # NETWORK MODE expected_netmode = self.module.params.get('net') or 'bridge' actual_netmode = container['HostConfig']['NetworkMode'] or 'bridge' if actual_netmode != expected_netmode: self.reload_reasons.append('net ({0} => {1})'.format(actual_netmode, expected_netmode)) differing.append(container) continue # DEVICES expected_devices = set() for device in (self.module.params.get('devices') or []): if len(device.split(':')) == 2: expected_devices.add(device + ":rwm") else: expected_devices.add(device) actual_devices = set() for device in (container['HostConfig']['Devices'] or []): actual_devices.add("{PathOnHost}:{PathInContainer}:{CgroupPermissions}".format(**device)) if actual_devices != expected_devices: self.reload_reasons.append('devices ({0} => {1})'.format(actual_devices, expected_devices)) differing.append(container) continue # DNS expected_dns = set(self.module.params.get('dns') or []) actual_dns = set(container['HostConfig']['Dns'] or []) if actual_dns != expected_dns: self.reload_reasons.append('dns ({0} => {1})'.format(actual_dns, expected_dns)) differing.append(container) continue # VOLUMES_FROM expected_volumes_from = set(self.module.params.get('volumes_from') or []) actual_volumes_from = set(container['HostConfig']['VolumesFrom'] or []) if actual_volumes_from != expected_volumes_from: self.reload_reasons.append('volumes_from ({0} => {1})'.format(actual_volumes_from, expected_volumes_from)) differing.append(container) # LOG_DRIVER if self.ensure_capability('log_driver', False): expected_log_driver = self.module.params.get('log_driver') or defaults['LoggingDriver'] actual_log_driver = container['HostConfig']['LogConfig']['Type'] if actual_log_driver != expected_log_driver: self.reload_reasons.append('log_driver ({0} => {1})'.format(actual_log_driver, expected_log_driver)) differing.append(container) continue if self.ensure_capability('log_opt', False): expected_logging_opts = self.module.params.get('log_opt') or {} actual_log_opts = container['HostConfig']['LogConfig']['Config'] if len(set(expected_logging_opts.items()) - set(actual_log_opts.items())) != 0: log_opt_reasons = { 'added': dict(set(expected_logging_opts.items()) - set(actual_log_opts.items())), 'removed': dict(set(actual_log_opts.items()) - set(expected_logging_opts.items())) } self.reload_reasons.append('log_opt ({0})'.format(log_opt_reasons)) differing.append(container) return differing def get_deployed_containers(self): """ Return any matching containers that are already present. """ entrypoint = self.module.params.get('entrypoint') if entrypoint is not None: entrypoint = shlex.split(entrypoint) command = self.module.params.get('command') if command is not None: command = shlex.split(command) name = self.module.params.get('name') if name and not name.startswith('/'): name = '/' + name deployed = [] # "images" will be a collection of equivalent "name:tag" image names # that map to the same Docker image. inspected = self.get_inspect_image() if inspected: repo_tags = self.get_image_repo_tags() else: repo_tags = [normalize_image(self.module.params.get('image'))] for container in self.client.containers(all=True): details = None if name: name_list = container.get('Names') if name_list is None: name_list = [] matches = name in name_list else: details = self.client.inspect_container(container['Id']) details = _docker_id_quirk(details) running_image = normalize_image(details['Config']['Image']) image_matches = running_image in repo_tags if command == None: command_matches = True else: command_matches = (command == details['Config']['Cmd']) if entrypoint == None: entrypoint_matches = True else: entrypoint_matches = ( entrypoint == details['Config']['Entrypoint'] ) matches = (image_matches and command_matches and entrypoint_matches) if matches: if not details: details = self.client.inspect_container(container['Id']) details = _docker_id_quirk(details) deployed.append(details) return deployed def get_running_containers(self): return [c for c in self.get_deployed_containers() if is_running(c)] def pull_image(self): extra_params = {} if self.module.params.get('insecure_registry'): if self.ensure_capability('insecure_registry', fail=False): extra_params['insecure_registry'] = self.module.params.get('insecure_registry') resource = self.module.params.get('image') image, tag = get_split_image_tag(resource) if self.module.params.get('username'): try: self.client.login( self.module.params.get('username'), password=self.module.params.get('password'), email=self.module.params.get('email'), registry=self.module.params.get('registry') ) except Exception as e: self.module.fail_json(msg="failed to login to the remote registry, check your username/password.", error=repr(e)) try: changes = list(self.client.pull(image, tag=tag, stream=True, **extra_params)) pull_success = False for change in changes: status = json.loads(change).get('status', '') if status.startswith('Status: Image is up to date for'): # Image is already up to date. Don't increment the counter. pull_success = True break elif (status.startswith('Status: Downloaded newer image for') or status.startswith('Download complete')): # Image was updated. Increment the pull counter. self.increment_counter('pulled') pull_success = True break if not pull_success: # Unrecognized status string. self.module.fail_json(msg="Unrecognized status from pull.", status=status, changes=changes) except Exception as e: self.module.fail_json(msg="Failed to pull the specified image: %s" % resource, error=repr(e)) def create_containers(self, count=1): try: mem_limit = _human_to_bytes(self.module.params.get('memory_limit')) except ValueError as e: self.module.fail_json(msg=str(e)) api_version = self.client.version()['ApiVersion'] params = {'image': self.module.params.get('image'), 'entrypoint': self.module.params.get('entrypoint'), 'command': self.module.params.get('command'), 'ports': self.exposed_ports, 'volumes': self.volumes, 'environment': self.environment, 'labels': self.module.params.get('labels'), 'hostname': self.module.params.get('hostname'), 'domainname': self.module.params.get('domainname'), 'detach': self.module.params.get('detach'), 'name': self.module.params.get('name'), 'stdin_open': self.module.params.get('stdin_open'), 'tty': self.module.params.get('tty'), 'cpuset': self.module.params.get('cpu_set'), 'cpu_shares': self.module.params.get('cpu_shares'), 'user': self.module.params.get('docker_user'), } if self.ensure_capability('host_config', fail=False): params['host_config'] = self.create_host_config() #For v1.19 API and above use HostConfig, otherwise use Config if docker.utils.compare_version('1.19', api_version) < 0: params['mem_limit'] = mem_limit else: params['host_config']['Memory'] = mem_limit if self.ulimits is not None: self.ensure_capability('ulimits') params['host_config']['ulimits'] = self.ulimits def do_create(count, params): results = [] for _ in range(count): result = self.client.create_container(**params) self.increment_counter('created') results.append(result) return results try: containers = do_create(count, params) except docker.errors.APIError as e: if e.response.status_code != 404: raise self.pull_image() containers = do_create(count, params) return containers def start_containers(self, containers): params = {} if not self.ensure_capability('host_config', fail=False): params = self.get_start_params() for i in containers: self.client.start(i) self.increment_counter('started') if not self.module.params.get('detach'): status = self.client.wait(i['Id']) if status != 0: output = self.client.logs(i['Id'], stdout=True, stderr=True, stream=False, timestamps=False) self.module.fail_json(status=status, msg=output) def stop_containers(self, containers): for i in containers: self.client.stop(i['Id'], self.module.params.get('stop_timeout')) self.increment_counter('stopped') return [self.client.wait(i['Id']) for i in containers] def remove_containers(self, containers): for i in containers: self.client.remove_container(i['Id']) self.increment_counter('removed') def kill_containers(self, containers): for i in containers: self.client.kill(i['Id'], self.module.params.get('signal')) self.increment_counter('killed') def restart_containers(self, containers): for i in containers: self.client.restart(i['Id']) self.increment_counter('restarted') class ContainerSet: def __init__(self, manager): self.manager = manager self.running = [] self.deployed = [] self.changed = [] def refresh(self): ''' Update our view of the matching containers from the Docker daemon. ''' self.deployed = self.manager.get_deployed_containers() self.running = [c for c in self.deployed if is_running(c)] def notice_changed(self, containers): ''' Record a collection of containers as "changed". ''' self.changed.extend(containers) def present(manager, containers, count, name): '''Ensure that exactly `count` matching containers exist in any state.''' containers.refresh() delta = count - len(containers.deployed) if delta > 0: created = manager.create_containers(delta) containers.notice_changed(manager.get_inspect_containers(created)) if delta < 0: # If both running and stopped containers exist, remove # stopped containers first. containers.deployed.sort(lambda cx, cy: cmp(is_running(cx), is_running(cy))) to_stop = [] to_remove = [] for c in containers.deployed[0:-delta]: if is_running(c): to_stop.append(c) to_remove.append(c) manager.stop_containers(to_stop) containers.notice_changed(manager.get_inspect_containers(to_remove)) manager.remove_containers(to_remove) def started(manager, containers, count, name): '''Ensure that exactly `count` matching containers exist and are running.''' containers.refresh() delta = count - len(containers.running) if delta > 0: if name and containers.deployed: # A stopped container exists with the requested name. # Clean it up before attempting to start a new one. manager.remove_containers(containers.deployed) created = manager.create_containers(delta) manager.start_containers(created) containers.notice_changed(manager.get_inspect_containers(created)) if delta < 0: excess = containers.running[0:-delta] containers.notice_changed(manager.get_inspect_containers(excess)) manager.stop_containers(excess) manager.remove_containers(excess) def reloaded(manager, containers, count, name): ''' Ensure that exactly `count` matching containers exist and are running. If any associated settings have been changed (volumes, ports or so on), restart those containers. ''' containers.refresh() for container in manager.get_differing_containers(): manager.stop_containers([container]) manager.remove_containers([container]) started(manager, containers, count, name) def restarted(manager, containers, count, name): ''' Ensure that exactly `count` matching containers exist and are running. Unconditionally restart any that were already running. ''' containers.refresh() for container in manager.get_differing_containers(): manager.stop_containers([container]) manager.remove_containers([container]) containers.refresh() manager.restart_containers(containers.running) started(manager, containers, count, name) def stopped(manager, containers, count, name): '''Stop any matching containers that are running.''' containers.refresh() manager.stop_containers(containers.running) containers.notice_changed(manager.get_inspect_containers(containers.running)) def killed(manager, containers, count, name): '''Kill any matching containers that are running.''' containers.refresh() manager.kill_containers(containers.running) containers.notice_changed(manager.get_inspect_containers(containers.running)) def absent(manager, containers, count, name): '''Stop and remove any matching containers.''' containers.refresh() manager.stop_containers(containers.running) containers.notice_changed(manager.get_inspect_containers(containers.deployed)) manager.remove_containers(containers.deployed) def main(): module = AnsibleModule( argument_spec = dict( count = dict(default=1), image = dict(required=True), pull = dict(required=False, default='missing', choices=['missing', 'always']), entrypoint = dict(required=False, default=None, type='str'), command = dict(required=False, default=None), expose = dict(required=False, default=None, type='list'), ports = dict(required=False, default=None, type='list'), publish_all_ports = dict(default=False, type='bool'), volumes = dict(default=None, type='list'), volumes_from = dict(default=None), links = dict(default=None, type='list'), devices = dict(default=None, type='list'), memory_limit = dict(default=0), memory_swap = dict(default=0), cpu_shares = dict(default=0), docker_url = dict(), use_tls = dict(default=None, choices=['no', 'encrypt', 'verify']), tls_client_cert = dict(required=False, default=None, type='str'), tls_client_key = dict(required=False, default=None, type='str'), tls_ca_cert = dict(required=False, default=None, type='str'), tls_hostname = dict(required=False, type='str', default=None), docker_api_version = dict(required=False, default=DEFAULT_DOCKER_API_VERSION, type='str'), docker_user = dict(default=None), username = dict(default=None), password = dict(), email = dict(), registry = dict(), hostname = dict(default=None), domainname = dict(default=None), env = dict(type='dict'), env_file = dict(default=None), dns = dict(), detach = dict(default=True, type='bool'), state = dict(default='started', choices=['present', 'started', 'reloaded', 'restarted', 'stopped', 'killed', 'absent', 'running']), signal = dict(default=None), restart_policy = dict(default=None, choices=['always', 'on-failure', 'no', 'unless-stopped']), restart_policy_retry = dict(default=0, type='int'), extra_hosts = dict(type='dict'), debug = dict(default=False, type='bool'), privileged = dict(default=False, type='bool'), stdin_open = dict(default=False, type='bool'), tty = dict(default=False, type='bool'), lxc_conf = dict(default=None, type='list'), name = dict(default=None), net = dict(default=None), pid = dict(default=None), insecure_registry = dict(default=False, type='bool'), log_driver = dict(default=None, choices=['json-file', 'none', 'syslog', 'journald', 'gelf', 'fluentd', 'awslogs']), log_opt = dict(default=None, type='dict'), cpu_set = dict(default=None), cap_add = dict(default=None, type='list'), cap_drop = dict(default=None, type='list'), read_only = dict(default=None, type='bool'), labels = dict(default={}, type='dict'), stop_timeout = dict(default=10, type='int'), timeout = dict(required=False, default=DEFAULT_TIMEOUT_SECONDS, type='int'), ulimits = dict(default=None, type='list'), ), required_together = ( ['tls_client_cert', 'tls_client_key'], ), ) check_dependencies(module) try: manager = DockerManager(module) count = int(module.params.get('count')) name = module.params.get('name') pull = module.params.get('pull') state = module.params.get('state') if state == 'running': # Renamed running to started in 1.9 state = 'started' if count < 0: module.fail_json(msg="Count must be greater than zero") if count > 1 and name: module.fail_json(msg="Count and name must not be used together") # Explicitly pull new container images, if requested. Do this before # noticing running and deployed containers so that the image names # will differ if a newer image has been pulled. # Missing images should be pulled first to avoid downtime when old # container is stopped, but image for new one is now downloaded yet. # It also prevents removal of running container before realizing # that requested image cannot be retrieved. if pull == "always" or (state == 'reloaded' and manager.get_inspect_image() is None): manager.pull_image() containers = ContainerSet(manager) if state == 'present': present(manager, containers, count, name) elif state == 'started': started(manager, containers, count, name) elif state == 'reloaded': reloaded(manager, containers, count, name) elif state == 'restarted': restarted(manager, containers, count, name) elif state == 'stopped': stopped(manager, containers, count, name) elif state == 'killed': killed(manager, containers, count, name) elif state == 'absent': absent(manager, containers, count, name) else: module.fail_json(msg='Unrecognized state %s. Must be one of: ' 'present; started; reloaded; restarted; ' 'stopped; killed; absent.' % state) module.exit_json(changed=manager.has_changed(), msg=manager.get_summary_message(), summary=manager.counters, reload_reasons=manager.get_reload_reason_message(), ansible_facts=_ansible_facts(containers.changed)) except DockerAPIError as e: module.fail_json(changed=manager.has_changed(), msg="Docker API Error: %s" % e.explanation) except RequestException as e: module.fail_json(changed=manager.has_changed(), msg=repr(e)) # import module snippets from ansible.module_utils.basic import * if __name__ == '__main__': main()
gpl-3.0
robmyers/like-that-generally
processing-projects/neoplastic_circle_triangle_square_grow_2d_sequential/applet/neoplastic_circle_triangle_square_grow_2d_sequential.java
7514
import processing.core.*; import processing.candy.*; import processing.xml.*; import java.applet.*; import java.awt.*; import java.awt.image.*; import java.awt.event.*; import java.io.*; import java.net.*; import java.text.*; import java.util.*; import java.util.zip.*; import javax.sound.midi.*; import javax.sound.midi.spi.*; import javax.sound.sampled.*; import javax.sound.sampled.spi.*; import java.util.regex.*; import javax.xml.parsers.*; import javax.xml.transform.*; import javax.xml.transform.dom.*; import javax.xml.transform.sax.*; import javax.xml.transform.stream.*; import org.xml.sax.*; import org.xml.sax.ext.*; import org.xml.sax.helpers.*; public class neoplastic_circle_triangle_square_grow_2d_sequential extends PApplet { //////////////////////////////////////////////////////////////////////////////// // This is a data object for the various routines to use as a data store // Each strategy for the routines will declare its own version of Appearance, // Form and Animation. But they will all know how to access an Entity. //////////////////////////////////////////////////////////////////////////////// class Entity { Appearance appearance; Form form; Animation animation; Entity (Appearance app, Form fo, Animation anim) { appearance = app; form = fo; animation = anim; } public void draw (float time) { animation.apply (form, time); appearance.draw (form); } public boolean finished (float time) { return animation.finished (time); } } //////////////////////////////////////////////////////////////////////////////// // SVG Form. Subclass and set entityNames to use. //////////////////////////////////////////////////////////////////////////////// /* SVG[] entities = null; PApplet SvgParent = this; class SvgForm { String[] entityNames = null; float x; float y; float size; Svg entity; SvgEntity () { if (entities == null) { loadEntitiesSvg (); } entity = entities [int (random (entities.length))]; } void loadEntitiesSvg () { entities = new Entities [entityNames.length]; for (int i = 0; i < entityNames.length; i++) { entities.i = new SVG (SvgParent, names[i] + ".svg") entities.drawMode (CENTER); entities.ignoreStyles (); } } void draw () { entity draw (x, y, size, size); } } */ class Appearance { int colour; Appearance () { switch (PApplet.parseInt (random (3))) { case 0: colour = color (255, 0, 0, 240); break; case 1: colour = color (255, 255, 0, 200); break; case 2: colour = color (0, 0, 255, 210); break; case 3: colour = color (0, 0, 0, 245); break; } } public void draw (Form f) { fill (colour); f.draw (); } } // (:clashes "outline" "burst_3d" "cluster_3d" "grow_3d") String MODE = P3D; int KIND_COUNT = 3; class Form { float size; float x; float y; int kind; Form () { kind = PApplet.parseInt (random (KIND_COUNT)); } public void draw () { switch (kind) { case 0: ellipseMode (CENTER); ellipse (x, y, size, size); break; case 1: rectMode (CENTER); rect (x, y, size, size); break; case 2: // Triangle float halfSize = size / 2.0f; beginShape (); vertex (-halfSize, halfSize); vertex (0.0f, -halfSize); vertex (halfSize, halfSize); endShape (); break; } } } class Animation { float size; float x; float y; float start_shrinking; float stop_shrinking; float shrink_factor; float start_growing; float stop_growing; float grow_factor; Animation (float xx, float yy, float zz, float siz, float start_grow, float stop_grow, float start_shrink, float stop_shrink) { x = xx; y = yy; size = siz; start_growing = start_grow; stop_growing = stop_grow; start_shrinking = start_shrink; stop_shrinking = stop_shrink; grow_factor = 1.0f / (stop_grow - start_grow); shrink_factor = 1.0f / (stop_shrink - start_shrink); } public float scaleFactor (float t) { if (t > stop_shrinking) { return 0.0f; } else if (t > start_shrinking) { return 1.0f - (shrink_factor * (t - start_shrinking)); } else if (t > stop_growing) { return 1.0f; } else if (t > start_growing) { return grow_factor * (t - start_growing); } // So <= start_growing return 0.0f; } public void apply (Form form, float t) { form.x = x; form.y = y; float scale_factor = scaleFactor (t); if (scale_factor == 0) { return; } form.size = size * scale_factor; float side_length = size * scale_factor; if (side_length > size) { side_length = size; } } public boolean finished (float t) { return t > stop_shrinking; } } // Configuration constants int min_objects = 4; int max_objects = 24; // In pixels int canvas_width = 400; int canvas_height = 400; int min_object_x = -100; int max_object_x = 100; int min_object_y = -100; int max_object_y = 100; float min_object_start_t = 0.0f; float max_object_start_t = 0.5f; int min_object_size = 5; int max_object_size = 200; // In seconds float min_duration = 1.0f; float max_duration = 10.0f; int num_objects; Entity[] entities; float rotation; float end_of_current_sequence; public float RandomDuration () { return random (min_duration, max_duration) * 1000; } public void GenObjects () { rotation = random (PI / 2.0f); num_objects = (int)random(min_objects, max_objects); entities = new Entity[num_objects]; float start_growing = millis (); float growing_range = RandomDuration (); float stop_growing = start_growing + growing_range; float start_shrinking = stop_growing + RandomDuration (); float shrinking_range = RandomDuration (); float stop_shrinking = start_shrinking + shrinking_range; end_of_current_sequence = stop_shrinking; for (int i = 0; i < num_objects; i++) { float t_factor = random (min_object_start_t, max_object_start_t); entities[i] = new Entity ( new Appearance (), new Form (), new Animation ( random (min_object_x, max_object_x), random (min_object_y, max_object_y), 0.0f, //random (min_object_z, max_object_z), random (min_object_size, max_object_size), start_growing + (growing_range * t_factor), stop_growing, start_shrinking, start_shrinking + (shrinking_range * t_factor))); } } public void DrawObjects () { float now = millis (); if (now >= end_of_current_sequence) { GenObjects (); } for (int i = 0; i < num_objects; i++) { if (! entities[i].finished (now)) entities[i].draw (now); } } public void draw () { background(255); if (MODE != P3D) { smooth (); } if ((MODE == P3D) || MODE == (OPENGL)) { ambientLight (245, 245, 245); directionalLight (50, 50, 50, 0, 1, -1); translate (canvas_width / 2.0f, canvas_height / 2.0f, - (max (canvas_width, canvas_height) * 0.4f)); } else { translate (canvas_width / 2.0f, canvas_height / 2.0f); } noStroke (); DrawObjects (); } public void setup () { size(canvas_width, canvas_height, MODE); frameRate(30); GenObjects (); } static public void main(String args[]) { PApplet.main(new String[] { "neoplastic_circle_triangle_square_grow_2d_sequential" }); }}
gpl-3.0
manisandro/gImageReader
gtk/src/main.cc
3677
/* -*- Mode: C++; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */ /* * main.cc * Copyright (C) 2013-2022 Sandro Mani <[email protected]> * * gImageReader is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * gImageReader is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <gtkmm.h> #include <gtkspellmm.h> #include <gtksourceviewmm.h> #include <iostream> #include <cstring> #ifdef G_OS_WIN32 #include <windows.h> #endif #include "common.hh" #include "Application.hh" #include "Config.hh" #include "CrashHandler.hh" std::string pkgDir; std::string pkgExePath; static std::string get_application_dir(char* argv0) { #ifdef G_OS_WIN32 gchar* dir = g_win32_get_package_installation_directory_of_module(0); std::string pathstr = dir; g_free(dir); #else pid_t pid = getpid(); std::string exe = Glib::ustring::compose("/proc/%1/exe", pid); GError* err = nullptr; char* path = g_file_read_link(exe.c_str(), &err); std::string pathstr = Glib::build_filename(Glib::path_get_dirname(path), ".."); g_free(path); if(err) { if(Glib::path_is_absolute(argv0)) { pathstr = Glib::build_filename(Glib::path_get_dirname(argv0), ".."); } else { pathstr = Glib::build_filename(Glib::get_current_dir(), Glib::path_get_dirname(argv0), ".."); } } #endif return pathstr; } static std::string get_application_exec_path(char* argv0) { #ifdef G_OS_WIN32 char buf[MAX_PATH]; bool success = GetModuleFileName(0, buf, MAX_PATH) > 0; std::string pathstr = buf; #else pid_t pid = getpid(); std::string exe = Glib::ustring::compose("/proc/%1/exe", pid); GError* err = nullptr; char* path = g_file_read_link(exe.c_str(), &err); std::string pathstr = path; g_free(path); bool success = err == nullptr; #endif if(!success) { if(Glib::path_is_absolute(argv0)) { pathstr = Glib::path_get_dirname(argv0); } else { pathstr = Glib::build_filename(Glib::get_current_dir(), argv0); } } return pathstr; } int main (int argc, char* argv[]) { pkgDir = get_application_dir(argv[0]); pkgExePath = get_application_exec_path(argv[0]); #ifdef G_OS_WIN32 if(Glib::getenv("LANG").empty()) { gchar* locale = g_win32_getlocale(); Glib::setenv("LANG", locale); g_free(locale); } #endif std::string localeDir = Glib::build_filename(pkgDir, "share", "locale"); bindtextdomain(GETTEXT_PACKAGE, localeDir.c_str()); bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8"); textdomain(GETTEXT_PACKAGE); if(argc > 2 && std::strcmp("crashhandle", argv[1]) == 0) { // Run the crash handler CrashHandler app(argc, argv); return app.run(); } else if(argc >= 2 && std::strcmp("tessdatadir", argv[1]) == 0) { Config::openTessdataDir(); return 0; } else if(argc >= 2 && std::strcmp("spellingdir", argv[1]) == 0) { Config::openSpellingDir(); return 0; } else { // Run the normal application #ifdef G_OS_WIN32 Glib::setenv("TWAINDSM_LOG", Glib::build_filename(pkgDir, "twain.log")); std::freopen(Glib::build_filename(pkgDir, "gimagereader.log").c_str(), "w", stderr); #endif GtkSpell::init(); Gsv::init(); Application app(argc, argv, APPLICATION_ID, Gio::APPLICATION_HANDLES_OPEN); return app.run(); } }
gpl-3.0
ursfassler/rizzly
src/ast/pass/linker/SubLinker.java
2021
/** * This file is part of Rizzly. * * Rizzly is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Rizzly 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 Rizzly. If not, see <http://www.gnu.org/licenses/>. */ package ast.pass.linker; import java.util.ArrayList; import java.util.List; import ast.Designator; import ast.data.Named; import ast.data.reference.LinkedAnchor; import ast.data.reference.RefItem; import ast.data.reference.RefName; import ast.data.reference.Reference; import ast.data.reference.ReferenceOffset; import ast.data.reference.UnlinkedAnchor; import ast.repository.query.ChildByName; public class SubLinker { final private ChildByName childByName; public SubLinker(ChildByName childByName) { super(); this.childByName = childByName; } public void link(Reference ref, Named root) { if (ref.getAnchor() instanceof UnlinkedAnchor) { List<String> targetName = new ArrayList<String>(); String rootName = ((UnlinkedAnchor) ref.getAnchor()).getLinkName(); if (!rootName.equals("self")) { targetName.add(rootName); } if (ref instanceof ReferenceOffset) { ReferenceOffset referenceOffset = (ReferenceOffset) ref; for (RefItem itr : referenceOffset.getOffset()) { String name = ((RefName) itr).name; targetName.add(name); } referenceOffset.getOffset().clear(); } Named target = childByName.get(root, new Designator(targetName), ref.metadata()); ref.setAnchor(new LinkedAnchor(target)); } } }
gpl-3.0
MyCoRe-Org/mycore
mycore-wfc/src/main/java/org/mycore/wfc/actionmapping/MCRDecision.java
1865
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.wfc.actionmapping; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.mycore.parsers.bool.MCRCondition; /** * @author Thomas Scheffler (yagee) * */ @XmlRootElement(name = "when") @XmlAccessorType(XmlAccessType.NONE) public class MCRDecision { @XmlAttribute private String url; @XmlAttribute @XmlJavaTypeAdapter(MCRWorkflowRuleAdapter.class) private MCRCondition<?> condition; /** * @return the url */ public String getUrl() { return url; } /** * @param url the url to set */ public void setUrl(String url) { this.url = url; } /** * @return the condition */ public MCRCondition<?> getCondition() { return condition; } /** * @param condition the condition to set */ public void setCondition(MCRCondition<?> condition) { this.condition = condition; } }
gpl-3.0
SamuelGjk/GComic
app/src/main/java/moe/yukinoneko/gcomic/module/download/tasks/DownloadTasksActivity.java
7185
/* * Copyright (C) 2016 SamuelGjk <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.yukinoneko.gcomic.module.download.tasks; import android.content.Intent; import android.support.v7.view.ActionMode; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import com.liulishuo.filedownloader.FileDownloadConnectListener; import java.util.List; import butterknife.BindView; import moe.yukinoneko.gcomic.R; import moe.yukinoneko.gcomic.base.ToolBarActivity; import moe.yukinoneko.gcomic.data.ComicData; import moe.yukinoneko.gcomic.database.model.DownloadTaskModel; import moe.yukinoneko.gcomic.database.model.ReadHistoryModel; import moe.yukinoneko.gcomic.download.DownloadTasksManager; import moe.yukinoneko.gcomic.utils.SnackbarUtils; import moe.yukinoneko.gcomic.widget.DividerItemDecoration; /** * Created by SamuelGjk on 2016/5/13. */ public class DownloadTasksActivity extends ToolBarActivity<DownloadTasksPresenter> implements IDownloadTasksView, DownloadTasksListAdapter.OnItemLongClickListener, ActionMode.Callback { public static final String DOWMLOADED_COMIC_ID = "DOWMLOADED_COMIC_ID"; public static final String DOWMLOADED_COMIC_TITLE = "DOWMLOADED_COMIC_TITLE"; @BindView(R.id.download_task_list) RecyclerView mTaskList; private DownloadTasksListAdapter mAdapter; private int mComicId; private FileDownloadConnectListener fileDownloadConnectListener = new FileDownloadConnectListener() { @Override public void connected() { postNotifyDataChanged(); } @Override public void disconnected() { postNotifyDataChanged(); } }; public void postNotifyDataChanged() { if (mAdapter != null) { runOnUiThread(new Runnable() { @Override public void run() { if (mAdapter != null) { mAdapter.notifyDataSetChanged(); } } }); } } @Override protected int provideContentViewId() { return R.layout.activity_download_tasks; } @Override protected void initPresenter() { presenter = new DownloadTasksPresenter(this, this); presenter.init(); } @Override public void init() { mComicId = getIntent().getIntExtra(DOWMLOADED_COMIC_ID, -1); String comicTitle = getIntent().getStringExtra(DOWMLOADED_COMIC_TITLE); mToolbar.setTitle(getString(R.string.download_tasks_label, comicTitle)); mToolbar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mTaskList.smoothScrollToPosition(0); } }); LinearLayoutManager layoutManager = new LinearLayoutManager(this); mTaskList.setLayoutManager(layoutManager); mTaskList.setHasFixedSize(true); mTaskList.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST)); mAdapter = new DownloadTasksListAdapter(this); mAdapter.setOnItemLongClickListener(this); mTaskList.setAdapter(mAdapter); DownloadTasksManager.getInstance(this).addServiceConnectListener(fileDownloadConnectListener); presenter.fetchReadHistory(mComicId); presenter.fetchDownloadTasks(mComicId); presenter.fetchComicFullChapters(mComicId); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); presenter.fetchReadHistory(mComicId); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.download_tasks, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_start_all: DownloadTasksManager.getInstance(this).startAllTasks(mAdapter.getAllTasks()); mAdapter.notifyDataSetChanged(); break; case R.id.menu_pause_all: DownloadTasksManager.getInstance(this).pauseAllTasks(mAdapter.getAllTasks()); break; } return super.onOptionsItemSelected(item); } @Override protected void onDestroy() { DownloadTasksManager.getInstance(this).removeServiceConnectListener(fileDownloadConnectListener); super.onDestroy(); } @Override public void showMessageSnackbar(int resId) { SnackbarUtils.showShort(mTaskList, resId); } @Override public void updateDownloadTasksList(List<DownloadTaskModel> tasks) { mAdapter.replaceAll(tasks); } @Override public void setComicFullChapters(List<ComicData.ChaptersBean.ChapterBean> chapters) { mAdapter.setFullChapters(chapters); } @Override public void updateReadHistory(ReadHistoryModel history) { mAdapter.setReadHistory(history); mAdapter.notifyDataSetChanged(); } @Override public void onItemLongClick(View view, int position) { if (mAdapter.getActionMode() == null) { mAdapter.setActionMode(startSupportActionMode(this)); } } @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.download_tasks_action_mode, menu); return true; } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { switch (item.getItemId()) { case R.id.menu_select_all: mAdapter.selectAll(); return true; case R.id.menu_unselect_all: mAdapter.unselectAll(); return true; case R.id.menu_delete_selected: presenter.deleteTasks(mAdapter.deleteSelectedTasks()); mAdapter.getActionMode().finish(); return true; default: return false; } } @Override public void onDestroyActionMode(ActionMode mode) { mAdapter.quitMultiselectionMode(); } }
gpl-3.0
sungju/pycrashext
source/lockup.py
8689
""" Written by Daniel Sungju Kwon """ from __future__ import print_function from __future__ import division from pykdump.API import * from LinuxDump import Tasks from LinuxDump.trees import * import crashcolor import sys def getKey(rqobj): return rqobj.Timestamp def getDelayKey(taskobj): return taskobj.sched_info.run_delay def get_task_policy_str(policy): return { 0: "N", # SCHED_NORMAL 1: "F", # SCHED_FIFO 2: "R", # SCHED_RR 3: "B", # SCHED_BATCH 5: "I", # SCHED_IDLE 6: "D", # SCHED_DEADLINE }[policy] def print_task_delay(task, options): try: sched_info = task.sched_info prio = task.prio if (task.policy != 0): prio = task.rt_priority print ("%20s (0x%x)[%s:%3d] : %10.2f sec delayed in queue" % (task.comm, task, get_task_policy_str(task.policy), prio, sched_info.run_delay / 1000000000)) if (options.task_details): print ("\t\t\texec_start = %d, exec_max = %d" % (task.se.exec_start, task.se.exec_max)) except: pass def show_rt_stat_in_rq(rq): rt = rq.rt rt_period = rt.tg.rt_bandwidth.rt_period.tv64 print ("CPU %3d: rt_nr_running = %d, rt_throttled = %d\n" "\trt_time = %12d, rt_runtime = %10d, rt_period = %d" % (rq.cpu, rt.rt_nr_running, rt.rt_throttled, rt.rt_time, rt.rt_runtime, rt_period)) def show_rt_stat(options): rqlist = Tasks.getRunQueues() for rq in rqlist: show_rt_stat_in_rq(rq) def show_rq_task_list(runqueue, reverse_sort, options): """ rq->rq->active->queue[..] crash> rq.rt ffff880028376ec0 -ox struct rq { [ffff880028377048] struct rt_rq rt; } crash> rt_rq.active ffff880028377048 -ox struct rt_rq { [ffff880028377048] struct rt_prio_array active; } crash> rt_prio_array.bitmap ffff880028377048 -ox struct rt_prio_array { [ffff880028377048] unsigned long bitmap[2]; } crash> rd ffff880028377048 2 ffff880028377048: 0000000000000001 0000001000000000 ................ crash> list_head ffff880028377058 struct list_head { next = 0xffff88145f3c16e8, prev = 0xffff88145f3d4c78 } """ head_displayed = False rt_array = runqueue.rt.active for task_list in rt_array.queue: for sched_rt_entity in readSUListFromHead(task_list, "run_list", "struct sched_rt_entity"): task_offset = member_offset("struct task_struct", "rt") task_addr = sched_rt_entity - task_offset task = readSU("struct task_struct", task_addr) if (not head_displayed): print(" RT tasks:") head_displayed = True print_task_delay(task, options) def read_task_from_sched_entity(sched_entity, runqueue): if (sched_entity == runqueue.cfs.curr): return None task_offset = member_offset("struct task_struct", "se") task_addr = sched_entity - task_offset task = readSU('struct task_struct', task_addr) return task def show_cfs_task_list(runqueue, reverse_sort, options): """ """ task_list = [] task_root = None if (member_offset('struct rq', 'cfs_tasks') >= 0): for sched_entity in readSUListFromHead(runqueue.cfs_tasks, "group_node", "struct sched_entity"): task = read_task_from_sched_entity(sched_entity, runqueue) if (task != None): task_list.append(task) elif (member_offset("struct cfs_rq", "tasks_timeline") >= 0): for sched_entity in for_all_rbtree(runqueue.cfs.tasks_timeline, "struct sched_entity", "run_node"): task = read_task_from_sched_entity(sched_entity, runqueue) if (task != None): task_list.append(task) elif (member_offset("struct cfs_rq", "tasks") >= 0): for sched_entity in readSUListFromHead(runqueue.cfs.tasks, "group_node", "struct sched_entity"): task = read_task_from_sched_entity(sched_entity, runqueue) if (task != None): task_list.append(task) else: task_list = [] sorted_task_list = sorted(task_list, key=getDelayKey, reverse=not reverse_sort) if (len(sorted_task_list)): print(" CFS tasks:") for task in sorted_task_list: print_task_delay(task, options) def show_prio_array(title, prio_array, reverse_sort, options): print ("%s" % (title)) has_any_entry = 0 for idx in range(0,140): task_list = [] for task in readSUListFromHead(prio_array.queue[idx], "run_list", "struct task_struct"): task_list.insert(0, task) if (len(task_list) == 0): continue has_any_entry = 1 sorted_task_list = sorted(task_list, key=getDelayKey, reverse=not reverse_sort) print ("\t[%4d]" % (idx)) for task in sorted_task_list: print_task_delay(task, options) if (has_any_entry == 0): print("\tNo entry under this array") return def show_prio_task_list(runqueue, reverse_sort, options): show_prio_array("Active prio_array", runqueue.active, reverse_sort, options) show_prio_array("Expired prio_array", runqueue.expired, reverse_sort, options) def show_task_list(runqueue, reverse_sort, options): if (member_offset('struct rq', 'rt') >= 0): show_rq_task_list(runqueue, reverse_sort, options) if (member_offset('struct rq', 'cfs') >= 0): show_cfs_task_list(runqueue, reverse_sort, options) if (member_offset('struct rq', 'active') >= 0): show_prio_task_list(runqueue, reverse_sort, options) print("") def lockup_display(reverse_sort, show_tasks, options): rqlist = Tasks.getRunQueues() rqsorted = sorted(rqlist, key=getKey, reverse=reverse_sort) if (reverse_sort): now = rqsorted[0].Timestamp else: now = rqsorted[-1].Timestamp try: watchdog_thresh = readSymbol("watchdog_thresh") softlockup_thresh = watchdog_thresh * 2 except: try: softlockup_thresh = readSymbol("softlockup_thresh") watchdog_thresh = 10 except: watchdog_thresh = -1 for rq in rqsorted: prio = rq.curr.prio if (rq.curr.policy != 0): prio = rq.curr.rt_priority delayed_time = (now - rq.Timestamp) / 1000000000 if watchdog_thresh > 0: if delayed_time >= softlockup_thresh: crashcolor.set_color(crashcolor.RED) elif delayed_time >= watchdog_thresh: crashcolor.set_color(crashcolor.BLUE) print ("CPU %3d: %10.2f sec behind by " "0x%x, %s [%s:%3d] (%d in queue)" % (rq.cpu, delayed_time, rq.curr, rq.curr.comm, get_task_policy_str(rq.curr.policy), prio, rq.nr_running)) if (show_tasks): show_task_list(rq, reverse_sort, options) crashcolor.set_color(crashcolor.RESET) def lockup(): op = OptionParser() op.add_option("-r", "--reverse", dest="reverse_sort", default=0, action="store_true", help="show longest holder at top") op.add_option("-t", "--tasks", dest="show_tasks", default=0, action="store_true", help="show tasks in each runqueue") op.add_option("-s", "--rt", dest="rt_stat", default=0, action="store_true", help="show RT statistics") op.add_option("-d", "--details", dest="task_details", default=0, action="store_true", help="show task details") (o, args) = op.parse_args() if (o.rt_stat): show_rt_stat(o) return lockup_display(not o.reverse_sort, o.show_tasks, o) if ( __name__ == '__main__'): lockup()
gpl-3.0
btamilselvan/tamils
ndbweb/src/app/country/country.component.ts
1337
import {Component, OnInit} from '@angular/core'; import {Country} from './country'; import {CountryService} from './country.service'; import {Location} from '@angular/common'; import {FormsModule} from '@angular/forms'; import {CountryFilterPipe} from './country-filter.pipe'; import 'rxjs/add/operator/switchMap'; import 'rxjs/add/operator/debounceTime'; import 'rxjs/add/operator/distinctUntilChanged'; import {ReactiveFormsModule, FormControl} from '@angular/forms'; @Component({ selector: 'app-country', templateUrl: './country.component.html', styleUrls: ['./country.component.css'] }) export class CountryComponent implements OnInit { countries: Country[]; countries1: Country[]; searchText: string; cName: string; term = new FormControl(); constructor( private countryService: CountryService, private location: Location) { this.term.valueChanges.debounceTime(400).distinctUntilChanged().subscribe(term => this.countryService.searchCountries(term).then(countries => this.countries1 = countries)); // this.term.valueChanges.debounceTime(400).switchMap(term => this.countryService.searchCountries(term)); } ngOnInit() { this.getCountries(); } getCountries(): void { this.countryService.getCountries().then(countries => this.countries = countries); console.log('after'); } }
gpl-3.0
CCChapel/ccchapel.com
CMS/Old_App_Code/CMSModules/ContactManagement/Extenders/ContactGroupGeneralExtender.cs
6162
using System; using System.Linq; using System.Threading.Tasks; using System.Web.UI; using CMS; using CMS.Base; using CMS.ExtendedControls; using CMS.ExtendedControls.ActionsConfig; using CMS.FormControls; using CMS.Helpers; using CMS.OnlineMarketing; using CMS.UIControls; [assembly: RegisterCustomClass("ContactGroupGeneralExtender", typeof(ContactGroupGeneralExtender))] public class ContactGroupGeneralExtender : PageExtender<CMSPage> { private ContactGroupInfo ContactGroup { get { return (ContactGroupInfo)Page.EditedObject; } } private HeaderAction RebuildHeaderAction { get { var rebuiltHeaderAction = Page.HeaderActions.ActionsList.SingleOrDefault(c => c.CommandName == "recalculate"); if (rebuiltHeaderAction == null) { rebuiltHeaderAction = new HeaderAction { CommandName = "recalculate", CommandArgument = "false", ButtonStyle = ButtonStyle.Default, Tooltip = ResHelper.GetString("om.contactgroup.rebuild.tooltip") }; Page.HeaderActions.AddAction(rebuiltHeaderAction); } return rebuiltHeaderAction; } } private FormEngineUserControl StatusLabel { get { AbstractUserControl statusLabel = Page.HeaderActions.AdditionalControls.SingleOrDefault(c => c.ID == "statusLabel"); if (statusLabel == null) { statusLabel = (AbstractUserControl)Page.LoadUserControl("~/CMSFormControls/Basic/LabelControl.ascx"); statusLabel.ID = "statusLabel"; Page.HeaderActions.AdditionalControls.Add(statusLabel); Page.HeaderActions.AdditionalControlsCssClass = "header-actions-label control-group-inline"; Page.HeaderActions.ReloadAdditionalControls(); } return (FormEngineUserControl)statusLabel; } } /// <summary> /// Initializes the extender. /// </summary> public override void OnInit() { Page.Load += Page_Load; Page.PreRender += Page_PreRender; } /// <summary> /// Initializes both recalculation button and the status label. /// </summary> void Page_PreRender(object sender, EventArgs e) { if (ContactGroup != null) { UpdateRecalculationButton(); UpdateStatus(); } } /// <summary> /// Registers to the header actions events. /// </summary> private void Page_Load(object sender, EventArgs e) { // Update panel timer is located in webpart nested in the page. // Use mode always to update buttons and status with the number of contacts as well. Page.HeaderActions.UpdatePanel.UpdateMode = UpdatePanelUpdateMode.Always; ComponentEvents.RequestEvents.RegisterForEvent("recalculate", RecalculateContactGroup); } /// <summary> /// Updates status text according to the contact group status. /// </summary> private void UpdateStatus() { bool isRebuilding = ContactGroup.ContactGroupStatus == ContactGroupStatusEnum.Rebuilding; StatusLabel.Visible = !isRebuilding && !string.IsNullOrEmpty(ContactGroup.ContactGroupDynamicCondition); SetContactGroupStatus(); } /// <summary> /// Updates text and state of the button according to the contact group status. /// </summary> private void UpdateRecalculationButton() { RebuildHeaderAction.Visible = !string.IsNullOrEmpty(ContactGroup.ContactGroupDynamicCondition); bool isRebuilding = ContactGroup.ContactGroupStatus == ContactGroupStatusEnum.Rebuilding; string buttonText = isRebuilding ? ResHelper.GetString("om.contactgroup.rebuilding") : ResHelper.GetString("om.contactgroup.rebuild"); RebuildHeaderAction.Enabled = !isRebuilding; RebuildHeaderAction.Text = buttonText; } /// <summary> /// Sets status according to the current contact group status state. /// </summary> private void SetContactGroupStatus() { switch (ContactGroup.ContactGroupStatus) { case ContactGroupStatusEnum.Ready: // 'Ready' status StatusLabel.Value = "<span class=\"StatusEnabled\">" + ResHelper.GetString("om.contactgroup.rebuildnotrequired") + "</span>"; break; case ContactGroupStatusEnum.ConditionChanged: // 'Condition changed' status StatusLabel.Value = "<span class=\"StatusDisabled\">" + ResHelper.GetString("om.contactgroup.rebuildrequired") + "</span>"; break; default: // In other cases do not display any status StatusLabel.Value = ""; break; } } /// <summary> /// Performs contact group recalculation. /// Fires, when recalculate button is clicked. /// </summary> private void RecalculateContactGroup(object sender, EventArgs e) { if (ContactGroup == null || ContactGroup.ContactGroupStatus == ContactGroupStatusEnum.Rebuilding) { return; } if (ContactGroupHelper.AuthorizedModifyContactGroup(ContactGroup.ContactGroupSiteID, true)) { RebuildHeaderAction.Text = ResHelper.GetString("om.contactgroup.rebuilding"); RebuildHeaderAction.Enabled = false; StatusLabel.Visible = false; // Set status that the contact group is being rebuilt ContactGroup.ContactGroupStatus = ContactGroupStatusEnum.Rebuilding; ContactGroupInfoProvider.SetContactGroupInfo(ContactGroup); // Evaluate the membership of the contact group ContactGroupEvaluator evaluator = new ContactGroupEvaluator(); evaluator.ContactGroup = ContactGroup; Task.Factory.StartNew(CMSThread.Wrap(evaluator.Run), TaskCreationOptions.LongRunning); } } }
gpl-3.0
VertigeASBL/genrespluriels
ecrire/configuration/logos.php
2379
<?php /***************************************************************************\ * SPIP, Systeme de publication pour l'internet * * * * Copyright (c) 2001-2013 * * Arnaud Martin, Antoine Pitrou, Philippe Riviere, Emmanuel Saint-James * * * * Ce programme est un logiciel libre distribue sous licence GNU/GPL. * * Pour plus de details voir le fichier COPYING.txt ou l'aide en ligne. * \***************************************************************************/ if (!defined('_ECRIRE_INC_VERSION')) return; include_spip('inc/presentation'); include_spip('inc/config'); // // Gestion des documents joints // function configuration_logos_dist(){ global $spip_lang_left, $spip_lang_right; $activer_logos = $GLOBALS['meta']["activer_logos"]; $activer_logos_survol = $GLOBALS['meta']["activer_logos_survol"]; $res = "<table border='0' cellspacing='1' cellpadding='3' width=\"100%\">"; $res .= "<tr><td class='verdana2'>"; $res .= _T('config_info_logos').aide('logoart'); $res .= "</td></tr>"; $res .= "<tr>"; $res .= "<td align='$spip_lang_left' class='verdana2'>"; $res .= bouton_radio("activer_logos", "oui", _T('config_info_logos_utiliser'), $activer_logos == "oui", "changeVisible(this.checked, 'logos_survol_config', 'block', 'none');") . " <br /> " . bouton_radio("activer_logos", "non", _T('config_info_logos_utiliser_non'), $activer_logos == "non", "changeVisible(this.checked, 'logos_survol_config', 'none', 'block');"); if ($activer_logos != "non") $style = "display: block;"; else $style = "display: none;"; $res .= "<br /><br /><div id='logos_survol_config' style='$style'>"; $res .= afficher_choix('activer_logos_survol', $activer_logos_survol, array('oui' => _T('config_info_logos_utiliser_survol'), 'non' => _T('config_info_logos_utiliser_survol_non')), " <br /> "); $res .= "</div>"; $res .= "</td></tr>"; $res .= "</table>\n"; $res = debut_cadre_trait_couleur("image-24.gif", true, "", _T('info_logos')) . ajax_action_post('configurer', 'logos', 'configuration','',$res) . fin_cadre_trait_couleur(true); return ajax_action_greffe('configurer-logos', '', $res); } ?>
gpl-3.0
tagoonp/rmis
secretary/menu_user.php
1170
<? session_start(); if($_SESSION['id'] == ""){ header("location:../index.php"); exit(); }else if ($_SESSION['status_name'] != "Secretary"){ echo "Secretary!"; exit(); } require "config.inc.php"; $sql_ec = "SELECT * FROM officer as r inner join prefix as p on p.id_prefix =r.id_prefix WHERE id_off = '".$_SESSION['id']."'"; $result_ec = mysql_query($sql_ec); $row_ec = mysql_fetch_array($result_ec); ?> <table width="350" height="74"> <tr> <th width="17" align="left" valign="bottom" scope="col"> <img src="images/user_online.gif" alt="online" align="top" /></th> <th width="321" height="24" align="left" valign="middle" scope="col"> <b>ชื่อผู้ใช้</b>:&nbsp; <?echo $row_ec ["prefix_name"];?> <?echo $row_ec ["full_name"];?></th> </tr> <tr> <td>&nbsp;</td> <td><b>สถานะ</b>&nbsp; <?if($row_ec["id_status"]=='5'){echo"เลขา EC";}?> </td> </tr> <tr> <td height="17">&nbsp;</td> <td><a class="ot-button-green" href="user_edit.php?id_off=<?=$row_ec["id_off"];?>">แก้ไขข้อมูลส่วนตัว</a> <a class="ot-button-green" href="logout.php">ออกจากระบบ</a></td> </tr> </table>
gpl-3.0
dscafati/unicen-promoting
src/main/java/com/unicen/app/ahp/Decision.java
1181
package com.unicen.app.ahp; public class Decision implements Comparable<Decision> { private String schoolName; private String cityName; private Integer schoolId; private double probability; public Decision (Integer schoolId, String schoolName, String cityName, double probability) { this.setSchoolId(schoolId); this.setSchoolName(schoolName); this.setCityName(cityName); this.setProbability(probability); } public String getSchoolName() { return schoolName; } public void setSchoolName(String schoolName) { this.schoolName = schoolName; } public double getProbability() { return probability; } public void setProbability(double probability) { this.probability = probability; } public void setCityName(String cityName) { this.cityName = cityName; } public String getCityName() { return this.cityName; } @Override public int compareTo(Decision o) { if (this.getProbability() < o.getProbability()) return 1; if (this.getProbability() > o.getProbability()) return -1; return 0; } public Integer getSchoolId() { return schoolId; } public void setSchoolId(Integer schoolId) { this.schoolId = schoolId; } }
gpl-3.0
mborho/rem
main.go
842
// rem - A tool to remember things on the command line. // Copyright (C) 2015 Martin Borho ([email protected]) // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package main func main() { if err := run(".rem"); err != nil { exit(err) } }
gpl-3.0
Wolframe/Wolframe
src/provider/AAAAproviderImpl.hpp
5755
/************************************************************************ Copyright (C) 2011 - 2014 Project Wolframe. All rights reserved. This file is part of Project Wolframe. Commercial Usage Licensees holding valid Project Wolframe Commercial licenses may use this file in accordance with the Project Wolframe Commercial License Agreement provided with the Software or, alternatively, in accordance with the terms contained in a written agreement between the licensee and Project Wolframe. GNU General Public License Usage Alternatively, you can redistribute this file and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Wolframe 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 Wolframe. If not, see <http://www.gnu.org/licenses/>. If you have questions regarding the use of this file, please contact Project Wolframe. ************************************************************************/ // // AAAA provider implementation // #ifndef _AAAA_PROVIDER_IMPLEMENTATION_HPP_INCLUDED #define _AAAA_PROVIDER_IMPLEMENTATION_HPP_INCLUDED #include "AAAA/AAAAprovider.hpp" #include "config/configurationBase.hpp" #include "AAAA/authUnit.hpp" #include "AAAA/authorization.hpp" #include "AAAA/audit.hpp" #include "database/DBprovider.hpp" #include <string> #include <list> #include <vector> namespace _Wolframe { namespace AAAA { // Standard authentication class and authentication provider class StandardAuthenticator : public Authenticator { public: StandardAuthenticator( const std::vector<std::string>& mechs_, const std::list< AuthenticationUnit* >& units_, const net::RemoteEndpoint& client_ ); ~StandardAuthenticator(); void dispose(); /// Get the list of available mechs virtual const std::vector<std::string>& mechs() const; /// Set the authentication mech virtual bool setMech( const std::string& mech ); /// The input message virtual void messageIn( const std::string& message ); /// The output message virtual std::string messageOut(); /// The current status of the authenticator virtual Status status() const { return m_status; } /// The authenticated user or NULL if not authenticated virtual User* user(); private: const std::vector< std::string >& m_mechs; const std::list< AuthenticationUnit* >& m_authUnits; const net::RemoteEndpoint& m_client; Authenticator::Status m_status; std::vector< AuthenticatorSlice* > m_slices; int m_currentSlice; AAAA::User* m_user; }; class AuthenticationFactory { public: AuthenticationFactory( const std::list< config::NamedConfiguration* >& confs, const module::ModulesDirectory* modules ); ~AuthenticationFactory(); bool resolveDB( const db::DatabaseProvider& db ); Authenticator* authenticator( const net::RemoteEndpoint& client ); PasswordChanger* passwordChanger( const User& user, const net::RemoteEndpoint& client ); private: std::list< AuthenticationUnit* > m_authUnits; std::vector< std::string > m_mechs; }; // Standard authorization classes and authorization provider class StandardAuthorizer : public Authorizer { public: StandardAuthorizer( const std::list< AuthorizationUnit* >& units, bool dflt ); ~StandardAuthorizer(); void close(); bool allowed( const Information& authzObject ); private: const std::list< AuthorizationUnit* >& m_authorizeUnits; bool m_default; }; class AuthorizationProvider { public: AuthorizationProvider( const std::list< config::NamedConfiguration* >& confs, bool authzDefault, const module::ModulesDirectory* modules ); ~AuthorizationProvider(); bool resolveDB( const db::DatabaseProvider& db ); Authorizer* authorizer() const { return m_authorizer; } private: std::list< AuthorizationUnit* > m_authorizeUnits; StandardAuthorizer* m_authorizer; }; // Standard audit class and audit provider class StandardAudit : public Auditor { public: StandardAudit( const std::list< AuditUnit* >& units, bool mandatory ); ~StandardAudit(); void close(); bool audit( const Information& ); private: const std::list< AuditUnit* >& m_auditUnits; bool m_mandatory; }; class AuditProvider { public: AuditProvider( const std::list< config::NamedConfiguration* >& confs, const module::ModulesDirectory* modules ); ~AuditProvider(); bool resolveDB( const db::DatabaseProvider& db ); Auditor* auditor() { return m_auditor; } private: std::list< AuditUnit* > m_auditors; StandardAudit* m_auditor; }; // AAAA provider PIMPL class class AAAAprovider::AAAAprovider_Impl { public: AAAAprovider_Impl( const AAAAconfiguration* conf, const module::ModulesDirectory* modules ); ~AAAAprovider_Impl() {} bool resolveDB( const db::DatabaseProvider& db ); Authenticator* authenticator( const net::RemoteEndpoint& client ) { return m_authenticator.authenticator( client ); } PasswordChanger* passwordChanger( const User& user, const net::RemoteEndpoint& client ) { return m_authenticator.passwordChanger( user, client ); } Authorizer* authorizer() { return m_authorizer.authorizer(); } Auditor* auditor() { return m_auditor.auditor(); } private: AuthenticationFactory m_authenticator; AuthorizationProvider m_authorizer; AuditProvider m_auditor; }; }} // namespace _Wolframe::AAAA #endif // _AAAA_PROVIDER_IMPLEMENTATION_HPP_INCLUDED
gpl-3.0
qtproject/qt-labs-vstools
src/qtwizard/Wizards/ProjectWizard/Console/ConsoleWizard.cs
3819
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the Qt VS Tools. ** ** $QT_BEGIN_LICENSE:GPL-EXCEPT$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ using System; using System.Collections.Generic; using QtVsTools.Common; namespace QtVsTools.Wizards.ProjectWizard { public class ConsoleWizard : ProjectTemplateWizard { protected override Options TemplateType => Options.Application | Options.ConsoleSystem; WizardData _WizardData; protected override WizardData WizardData => _WizardData ?? (_WizardData = new WizardData { DefaultModules = new List<string> { "QtCore" } }); WizardWindow _WizardWindow; protected override WizardWindow WizardWindow => _WizardWindow ?? (_WizardWindow = new WizardWindow(title: "Qt Console Application Wizard") { new WizardIntroPage { Data = WizardData, Header = @"Welcome to the Qt Console Application Wizard", Message = @"This wizard generates a Qt console application " + @"project. The application derives from QCoreApplication " + @"and does not present a GUI." + System.Environment.NewLine + System.Environment.NewLine + "To continue, click Next.", PreviousButtonEnabled = false, NextButtonEnabled = true, FinishButtonEnabled = false, CancelButtonEnabled = true }, new ConfigPage { Data = WizardData, Header = @"Welcome to the Qt Console Application Wizard", Message = @"Setup the configurations you want to include in your project. " + @"The recommended settings for this project are selected by default.", PreviousButtonEnabled = true, NextButtonEnabled = false, FinishButtonEnabled = true, CancelButtonEnabled = true, ValidateConfigs = ValidateConfigsForConsoleApp } }); string ValidateConfigsForConsoleApp(IEnumerable<IWizardConfiguration> configs) { foreach (var config in configs) { if (config.Target.EqualTo(ProjectTargets.WindowsStore)) { return string.Format( "Console Application project not available for the '{0}' target.", config.Target); } } return string.Empty; } } }
gpl-3.0
kiwi3685/kiwitrees
library/KT/Census/CensusOfFrance1896.php
1778
<?php /** * Kiwitrees: Web based Family History software * Copyright (C) 2012 to 2022 kiwitrees.net * * Derived from webtrees (www.webtrees.net) * Copyright (C) 2010 to 2012 webtrees development team * * Derived from PhpGedView (phpgedview.sourceforge.net) * Copyright (C) 2002 to 2010 PGV Development Team * * Kiwitrees is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with Kiwitrees. If not, see <http://www.gnu.org/licenses/>. */ /** * Definitions for a census */ class KT_Census_CensusOfFrance1896 extends KT_Census_CensusOfFrance implements KT_Census_CensusInterface { /** * When did this census occur. * * @return string */ public function censusDate() { return '16 JAN 1896'; } /** * The columns of the census. * * @return CensusColumnInterface[] */ public function columns() { return array( new KT_Census_CensusColumnSurname($this, 'Noms', 'Noms de famille'), new KT_Census_CensusColumnGivenNames($this, 'Prénoms', ''), new KT_Census_CensusColumnAge($this, 'Âge', ''), new KT_Census_CensusColumnNationality($this, 'Nationalité', ''), new KT_Census_CensusColumnOccupation($this, 'Profession', ''), new KT_Census_CensusColumnRelationToHead($this, 'Position', 'Position dans le ménage'), ); } }
gpl-3.0
Alberto-Beralix/Beralix
i386-squashfs-root/usr/share/pyshared/orca/scripts/apps/notify-osd/script.py
3625
# Orca # # Copyright 2009 Eitan Isaacson # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the # Free Software Foundation, Inc., Franklin Street, Fifth Floor, # Boston MA 02110-1301 USA. """ Custom script for The notify-osd""" __id__ = "" __version__ = "" __date__ = "" __copyright__ = "Copyright (c) 2009 Eitan Isaacson" __license__ = "LGPL" import orca.scripts.default as default import orca.settings as settings import orca.speech as speech import orca.notification_messages as notification_messages from orca.orca_i18n import _ ######################################################################## # # # The notify-osd script class. # # # ######################################################################## class Script(default.Script): def getListeners(self): """Sets up the AT-SPI event listeners for this script. """ listeners = default.Script.getListeners(self) listeners["window:create"] = \ self.onWindowCreate listeners["object:property-change:accessible-value"] = \ self.onValueChange return listeners def onValueChange(self, event): try: ivalue = event.source.queryValue() value = int(ivalue.currentValue) except NotImplementedError: value = -1 if value >= 0: speech.speak(str(value), None, True) self.displayBrailleMessage("%s" % value, flashTime=settings.brailleFlashTime) def onWindowCreate(self, event): """Called whenever a window is created in the notify-osd application. Arguments: - event: the Event. """ try: ivalue = event.source.queryValue() value = ivalue.currentValue except NotImplementedError: value = -1 utterances = [] message = "" if value < 0: # Translators: This denotes a notification to the user of some sort. # utterances.append(_('Notification')) utterances.append(self.voices.get(settings.SYSTEM_VOICE)) message = '%s %s' % (event.source.name, event.source.description) utterances.append(message) utterances.append(self.voices.get(settings.DEFAULT_VOICE)) else: # A gauge notification, e.g. the Ubuntu volume notification that # appears when you press the multimedia keys. # message = '%s %d' % (event.source.name, value) utterances.append(message) utterances.append(self.voices.get(settings.SYSTEM_VOICE)) speech.speak(utterances, None, True) self.displayBrailleMessage(message, flashTime=settings.brailleFlashTime) notification_messages.saveMessage(message)
gpl-3.0
jrialland/parserjunior
old/parser/src/main/java/net/jr/parser/impl/ActionTable.java
27818
package net.jr.parser.impl; import net.jr.common.Symbol; import net.jr.lexer.Lexemes; import net.jr.marshalling.MarshallingCapable; import net.jr.marshalling.MarshallingUtil; import net.jr.parser.Grammar; import net.jr.parser.Rule; import net.jr.util.StringUtil; import net.jr.util.table.AsciiTableView; import net.jr.util.table.TableModel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.StringWriter; import java.util.*; import java.util.stream.Collectors; /** * action table is indexed by a state of the parser and a terminal (including a special terminal ᵉᵒᶠ ({@link Lexemes#eof()}) that indicates the end of the input stream) and contains three types of actions: * <ul> * <li>shift, which is written as 'sn' and indicates that the next state is n</li> * <li>reduce, which is written as 'rm' and indicates that a reduction with grammar rule m should be performed</li> * <li>accept, which is written as 'acc' and indicates that the parser accepts the string in the input stream.</li> * </ul> */ public class ActionTable implements MarshallingCapable { private static Logger Logger = LoggerFactory.getLogger(ActionTable.class); private Map<Integer, Map<Symbol, Action>> data = new TreeMap<>(); private List<Symbol> terminals; private List<Symbol> nonTerminals; private ActionTable() { } private static final Logger getLog() { return Logger; } @SuppressWarnings("unused") public static ActionTable unMarshall(DataInput dataInputStream) throws IOException { ActionTable actionTable = new ActionTable(); actionTable.terminals = MarshallingUtil.unMarshall(dataInputStream); actionTable.nonTerminals = MarshallingUtil.unMarshall(dataInputStream); actionTable.data = MarshallingUtil.unMarshall(dataInputStream); return actionTable; } private static String actionToString(Action action) { final String sParam = Integer.toString(action.getActionParameter()); switch (action.getActionType()) { case Accept: return "acc"; case Fail: return ""; case Goto: return Integer.toString(action.getActionParameter()); case Shift: return "s" + sParam; case Reduce: return "r" + sParam; default: throw new UnsupportedOperationException(); } } public static ActionTable lalr1(Grammar grammar) { return new LALR1Builder().build(grammar); } public int getStatesCount() { return data.size(); } @Override public void marshall(DataOutput dataOutputStream) throws IOException { MarshallingUtil.marshall(terminals, dataOutputStream); MarshallingUtil.marshall(nonTerminals, dataOutputStream); MarshallingUtil.marshall(data, dataOutputStream); } private void onInitialized() { Set<Symbol> allSymbols = data.values().stream().map(m -> m.keySet()).reduce(new HashSet<>(), (acc, s) -> { acc.addAll(s); return acc; }); terminals = allSymbols.stream().filter(s -> s.isTerminal()).collect(Collectors.toList()); terminals.sort(Comparator.comparing(Symbol::toString)); nonTerminals = allSymbols.stream().filter(s -> !s.isTerminal()).collect(Collectors.toList()); nonTerminals.sort(Comparator.comparing(Symbol::toString)); if (getLog().isTraceEnabled()) { getLog().trace(String.format("%d terminals, %d non-terminals", terminals.size(), nonTerminals.size())); } } private void setAction(int state, Symbol symbol, Action action, boolean allowReplace) { Map<Symbol, Action> row = data.computeIfAbsent(state, k -> new HashMap<>()); Action oldAction = row.put(symbol, action); if (!allowReplace && oldAction != null && !oldAction.equals(action)) { StringWriter sw = new StringWriter(); sw.append("Unresolved " + oldAction.getActionType() + "/" + action.getActionType() + " conflict"); sw.append(" For state : " + state); sw.append(" For symbol : " + symbol); sw.append(" Action 1 : " + oldAction.toString()); sw.append(" Action 2 : " + action.toString()); throw new IllegalStateException(sw.toString()); } } public Action getAction(int state, Symbol symbol) { return _getAction(state, symbol); } int getNextState(int currentState, Symbol symbol) { Action gotoAction = _getAction(currentState, symbol); if (gotoAction == null) { throw new IllegalStateException(String.format("No GOTO Action for state '%d', Symbol '%s'", currentState, symbol)); } return gotoAction.getActionParameter(); } private Action _getAction(int state, Symbol symbol) { Map<Symbol, Action> row = data.get(state); if (row == null) { throw new IllegalStateException(String.format("No such state (%d)", state)); } return row.get(symbol); } private Action getActionNoCheck(int state, Symbol s) { Map<Symbol, Action> row = data.get(state); return row == null ? null : row.get(s); } public Set<Symbol> getExpectedTerminals(int state) { Map<Symbol, Action> row = data.get(state); return row.keySet().stream() .filter(s -> s.isTerminal()) .collect(Collectors.toSet()); } private int getColumnFor(Symbol symbol) { if (symbol.isTerminal()) { return getTerminals().indexOf(symbol); } else { return getTerminals().size() + getNonTerminals().indexOf(symbol); } } public List<Symbol> getTerminals() { return terminals; } public List<Symbol> getNonTerminals() { return nonTerminals; } @Override public String toString() { TableModel<String> tm = new TableModel<>(); for (Map.Entry<Integer, Map<Symbol, Action>> rowEntry : data.entrySet()) { int state = rowEntry.getKey(); for (Map.Entry<Symbol, Action> e : rowEntry.getValue().entrySet()) { Symbol s = e.getKey(); Action action = e.getValue(); tm.setData(getColumnFor(s), state, actionToString(action)); } } //make room for the labels tm.moveDataBy(1, 1); //row labels for (Map.Entry<Integer, Map<Symbol, Action>> rowEntry : data.entrySet()) { int state = rowEntry.getKey(); tm.setData(0, 1 + state, Integer.toString(state)); } //column labels int col = 1; for (Symbol term : terminals) { tm.setData(col++, 0, StringUtil.ellipsis(term.toString(), 20, "\u2026")); } for (Symbol term : nonTerminals) { tm.setData(col++, 0, StringUtil.ellipsis(term.toString(), 20, "\u2026")); } return new AsciiTableView(4, 100).tableToString(tm); } static class LALR1Builder { public ActionTable build(Grammar grammar) { Set<Rule> targetRules = grammar.getRulesTargeting(grammar.getTargetSymbol()); if (targetRules.size() != 1) { throw new IllegalStateException("Illegal target rule specification (required : only one rule for the target symbol)"); } Rule startRule = targetRules.iterator().next(); getLog().trace("Building action Table for : " + grammar.toString()); getLog().trace("Starting Rule is : " + startRule); //Syntax Analysis Goal: Item Sets Set<ItemSet> allItemSets = getAllItemSets(grammar); if (getLog().isTraceEnabled()) { getLog().trace(String.format("Action table will have %d states", allItemSets.size())); } //Syntax Analysis Goal: Translation Table Map<Integer, Map<Symbol, Integer>> translationTable = getTranslationTable(grammar, allItemSets); //Syntax Analysis Goal: Action and Goto Table ActionTable actionTable = new ActionTable(); initializeShiftsAndGotos(actionTable, translationTable); initializeReductions(grammar, actionTable, startRule, allItemSets); initializeAccept(actionTable, startRule, allItemSets); actionTable.onInitialized(); return actionTable; } /** * Add all the reduce actions to the table. * * @param grammar * @param table * @param startRule * @param itemSets */ void initializeReductions(Grammar grammar, ActionTable table, Rule startRule, Set<ItemSet> itemSets) { Grammar extendedGrammar = makeExtendedGrammar(startRule, itemSets); // Syntax Analysis Goal: FOLLOW Sets Map<Symbol, Set<? extends Symbol>> followSets = getFollowSets(extendedGrammar); //build a list of rules and and follow sets List<PreMergeReduction> step1 = new ArrayList<>(); for (Rule eRule : extendedGrammar.getRules()) { Set<Symbol> followSet = followSets.get(eRule.getTarget()) .stream() .map(s -> (s instanceof ExtendedSymbol) ? ((ExtendedSymbol) s).getSymbol() : s) .collect(Collectors.toSet()); step1.add(new PreMergeReduction((ExtendedRule) eRule, followSet)); } //merging some rules Set<MergedReduction> step2 = new HashSet<>(); for (PreMergeReduction pm : step1) { List<PreMergeReduction> matching = step1.stream().filter(r -> r.matches(pm)).collect(Collectors.toList()); if (matching.size() == 1) { MergedReduction merged = new MergedReduction(pm.getBaseRule(), pm.getFinalState(), pm.getFollowSet()); step2.add(merged); } else { Set<Symbol> newFollowSet = new HashSet<>(); for (PreMergeReduction m : matching) { newFollowSet.addAll(m.getFollowSet()); } MergedReduction merged = new MergedReduction(pm.getBaseRule(), pm.getFinalState(), newFollowSet); step2.add(merged); } } //feed the action table with reductions for (MergedReduction merged : step2) { int ruleId = merged.getRule().getId(); for (Symbol s : merged.getFollowSet()) { int state = merged.getFinalState(); //add a reduce action to the table Action actionToInsert = new Action(ActionType.Reduce, ruleId); Action existingAction = table.getActionNoCheck(state, s); if (existingAction != null) { table.setAction(state, s, resolveConflict(grammar, merged.getRule(), s, existingAction, actionToInsert), true); } else { table.setAction(state, s, actionToInsert, false); } } } } /** * When the action table already has an action (accept oneOf shift) for a given state/lexeme, * try to apply precedence rules to arbitrate * * @param grammar the grammar * @param rule the rule that is reduced * @param existing a shift oneOf accept oneOf reduce * @param reduceAction a reduce action * @return */ private Action resolveConflict(Grammar grammar, Rule rule, Symbol symbol, Action existing, Action reduceAction) { switch (existing.getActionType()) { case Accept: //accept always wins return existing; case Shift: // shift/reduce conflict ! ActionType preference = grammar.getConflictResolutionHint(rule, symbol); if (preference != null) { switch (preference) { case Fail: return null; case Shift: return existing; case Reduce: return reduceAction; default: throw new IllegalArgumentException(preference.toString()); } } else { //choose the shift by default return existing; } case Reduce: return existing; default: throw new IllegalStateException(); } } /** * Step 1 - Initialize * <p> * Add a column for the end of input, labelled $. * Place an "accept" in the $ column whenever the item set * contains an item where the pointer is at the end of the starting rule (in our example "S → N •"). * </p> */ void initializeAccept(ActionTable table, Rule startingRule, Set<ItemSet> itemSets) { final Symbol eof = Lexemes.eof(); final Action accept = new Action(ActionType.Accept, 0); Item allParsed = new Item(startingRule, startingRule.getClause().length); itemSets.stream() .filter(itemSet -> itemSet.allItems().filter(item -> item.equals(allParsed)).findAny().isPresent()) .forEach(itemSet -> table.setAction(itemSet.getId(), eof, accept, true)); } /** * Step 2 - Gotos + Step 3 - Shifts * <p> * Directly copy the Translation Table's nonterminal columns as GOTOs. * </p> * * @param table * @param translationTable */ void initializeShiftsAndGotos(ActionTable table, Map<Integer, Map<Symbol, Integer>> translationTable) { for (Map.Entry<Integer, Map<Symbol, Integer>> tEntry : translationTable.entrySet()) { int state = tEntry.getKey(); for (Map.Entry<Symbol, Integer> entry : tEntry.getValue().entrySet()) { Symbol s = entry.getKey(); if (s.isTerminal()) { table.setAction(state, s, new Action(ActionType.Shift, entry.getValue()), false); } else { table.setAction(state, s, new Action(ActionType.Goto, entry.getValue()), false); } } } } /** * Compte the FOLLOW sets for all the symbols of a grammar * * @param grammar the grammar * @return the FOLLOW sets for all the symbols of a grammar */ Map<Symbol, Set<? extends Symbol>> getFollowSets(Grammar grammar) { //The follow set of a terminal is always empty Map<Symbol, FollowSet> map = grammar.getSymbols().stream() .filter(s -> s.isTerminal()) .collect(Collectors.toMap(s -> s, s -> FollowSet.emptySet(s))); //Initialize an new set for each nonterminal for (Symbol s : grammar.getNonTerminals()) { map.put(s, new FollowSet(s)); } //Place an End of Input token ($) into the starting rule's follow set. map.get(grammar.getTargetSymbol()).setResolution(new HashSet<>(Arrays.asList(Lexemes.eof()))); for (Symbol s : grammar.getNonTerminals()) { defineFollowSet(map, grammar, s); } LazySet.resolveAll(map); return map.values() .stream() .filter(f -> !f.getSubject().isTerminal()) .collect(Collectors.toMap(FollowSet::getSubject, FollowSet::getResolution)); } /** * computes FOLLOW(D). * * @param followSets map of all follow sets, * @param grammar The grammar * @param D the symbol we compute the set for */ void defineFollowSet(Map<Symbol, FollowSet> followSets, Grammar grammar, Symbol D) { FollowSet followSet = followSets.get(D); // Construct for the rule have the form R → a* D b. for (Rule rule : grammar.getRules()) { Symbol R = rule.getTarget(); List<Symbol> clause = Arrays.asList(rule.getClause()); //for each occurence of D in the clause for (int i = 0, max = clause.size() - 1; i < max; i++) { //minus 1 because if D is the last we are not interested (i.e b must exist) //if (clause.get(i).equals(D)) { if (clause.get(i).equals(D)) { Symbol b = clause.get(i + 1); //Everything in First(b) (except for ε) is added to Follow(D) Set<Symbol> first = new HashSet<>(getFirstSet(grammar, b)); boolean containedEmpty = first.remove(Lexemes.empty()); FirstSet firstSet = new FirstSet(b); firstSet.setResolution(first); followSet.add(firstSet); //If First(b) contains ε then everything in Follow(R) is put in Follow(D) if (containedEmpty) { followSet.add(followSets.get(R)); } } } //Finally, if we have a rule R → a* D, then everything in Follow(R) is placed in Follow(D). if (!clause.isEmpty() && D.equals(clause.get(clause.size() - 1))) { followSet.add(followSets.get(R)); } } } /** * computes FIRST(symbol) * * @param grammar * @param s * @return FIRST(symbol) */ Set<Symbol> getFirstSet(Grammar grammar, Symbol s) { Set<Symbol> set = new HashSet<>(); if (s.isTerminal()) { // First(terminal) = [terminal] if (s instanceof ExtendedSymbol) { set.add(((ExtendedSymbol) s).getSymbol()); } else { set.add(s); } } else { for (Rule r : grammar.getRules()) { if (r.getTarget().equals(s)) { //if the first symbol is a terminal, the set is this terminal Symbol firstTerminal; if (r.getClause().length > 0 && (firstTerminal = r.getClause()[0]).isTerminal()) { set.add(firstTerminal); continue; } //if not, we scan the symbol, boolean brk = false; for (Symbol s2 : r.getClause()) { if (!s.equals(s2)) { Set<Symbol> a = getFirstSet(grammar, s2); boolean containedEmpty = a.remove(Lexemes.empty()); set.addAll(a); //if First(x) did not contain ε, we do not need to contine scanning if (!containedEmpty) { brk = true; break; } } } //every First(x) contained ε, so we have to add it to the set if (!brk) { set.add(Lexemes.empty()); } } } } return set.stream().map(sym -> { if (sym instanceof ExtendedSymbol) { return ((ExtendedSymbol) sym).getSymbol(); } else { return sym; } }).collect(Collectors.toSet()); } /** * Constructs 'extended' grammar, ie a more precise grammar than the original one, deduced from * the item sets that have been computed in the previous step * * @param targetRule * @param allItemSets * @return */ Grammar makeExtendedGrammar(Rule targetRule, Set<ItemSet> allItemSets) { Set<ExtendedSymbol> extendedSymbols = new HashSet<>(); Grammar eGrammar = new Grammar(); int[] counter = new int[]{0}; for (ItemSet itemSet : allItemSets) { int initialState = itemSet.getId(); itemSet.allItems() .filter(item -> item.getPointer() == 0) .map(item -> item.getRule()) .forEach(rule -> { ItemSet currentItem = itemSet; List<ExtendedSymbol> eClause = new ArrayList<>(); for (Symbol s : rule.getClause()) { final int start = currentItem.getId(); currentItem = currentItem.getTransitionFor(s); final int end = currentItem.getId(); ExtendedSymbol extSym = new ExtendedSymbol(start, s, end); if (!extendedSymbols.contains(extSym)) { extendedSymbols.add(extSym); } eClause.add(extSym); } final int finalState; ItemSet transition = itemSet.getTransitionFor(rule.getTarget()); if (transition == null) { finalState = -1; } else { finalState = transition.getId(); } ExtendedSymbol eTarget = new ExtendedSymbol(initialState, rule.getTarget(), finalState); if (!extendedSymbols.contains(eTarget)) { extendedSymbols.add(eTarget); } eGrammar.addRule(new ExtendedRule(counter[0]++, rule, eTarget, eClause.toArray(new ExtendedSymbol[]{}))); }); } ExtendedRule eTargetRule = eGrammar.getRules().stream().map(r -> (ExtendedRule) r).filter(r -> ((ExtendedSymbol) r.getTarget()).getSymbol().equals(targetRule.getTarget())).findFirst().get(); eGrammar.setTargetRule(eTargetRule); if (getLog().isTraceEnabled()) { getLog().trace(String.format("Extended grammar has %d rules", eGrammar.getRules().size())); } return eGrammar; } /** * map each state to the states that can be reached for a given symbol. * * @param grammar a grammar * @param allItemSets the itemSets for this grammar * @return */ Map<Integer, Map<Symbol, Integer>> getTranslationTable(Grammar grammar, Set<ItemSet> allItemSets) { Map<Integer, Map<Symbol, Integer>> table = new TreeMap<>(); for (ItemSet itemSet : allItemSets) { int currentState = itemSet.getId(); Map<Symbol, Integer> row = new HashMap<>(); table.put(currentState, row); for (Symbol symbol : grammar.getSymbols()) { ItemSet targetItemSet = itemSet.getTransitionFor(symbol); if (targetItemSet != null) { row.put(symbol, targetItemSet.getId()); } } } return table; } /** * Once we have the item set for the starting rule of the grammar, * generate all the other sets so we can get all LR(0) transitions * * @param grammar * @return */ Set<ItemSet> getAllItemSets(Grammar grammar) { ItemSet i0 = getFirstItemSet(grammar); Set<ItemSet> set = new HashSet<>(); set.add(i0); Map<Set<Item>, ItemSet> knownKernels = new HashMap<>(); knownKernels.put(i0.getKernel(), i0); Stack<ItemSet> stack = new Stack<>(); stack.add(i0); int i = 1; while (!stack.isEmpty()) { ItemSet currentItemSet = stack.pop(); for (Symbol symbol : currentItemSet.getPossibleNextSymbols()) { Set<Item> newKernel = new HashSet<>(); for (Item item : currentItemSet.getItemsThatExpect(symbol)) { Item nextItem = item.shift(); newKernel.add(nextItem); } if (!newKernel.isEmpty()) { ItemSet newItemSet = knownKernels.get(newKernel); if (newItemSet == null) { newItemSet = new ItemSet(newKernel, extendItemSetKernel(grammar, newKernel)); knownKernels.put(newKernel, newItemSet); newItemSet.setId(i++); set.add(newItemSet); stack.push(newItemSet); } currentItemSet.addTransition(symbol, newItemSet); } } } return set; } /** * The first item set, I0 begins with the starting rule. */ ItemSet getFirstItemSet(Grammar grammar) { Rule startingRule = grammar.getRulesTargeting(grammar.getTargetSymbol()).iterator().next(); Item firstItem = new Item(startingRule, 0); Set<Item> kernel = new HashSet<>(); kernel.add(firstItem); ItemSet i0 = new ItemSet(kernel, extendItemSetKernel(grammar, kernel)); i0.setId(0); return i0; } /** * Given the kernel of an item set, derivate it in order to get the rest of the closure. * * @param grammar * @param kernel * @return */ Set<Item> extendItemSetKernel(Grammar grammar, Set<Item> kernel) { Set<Item> set = new HashSet<>(); Stack<Item> stack = new Stack<>(); stack.addAll(kernel); while (!stack.isEmpty()) { Item currentItem = stack.pop(); Symbol expected = currentItem.getExpectedSymbol(); if (expected != null) { //find all the rules starting with 'expected' grammar.getRules().stream().filter(r -> r.getTarget().equals(expected)).forEach(r -> { Item i = new Item(r, 0); if (!set.contains(i)) { set.add(i); stack.push(i); } }); } } set.removeAll(kernel); return set; } } }
gpl-3.0
boviq/boviq
database/migrations/2016_05_01_083758_create_attachments_table.php
711
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateAttachmentsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('attachments', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('type'); $table->text('content'); $table->tinyInteger('status'); $table->timestamps(); $table->softDeletes(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('attachments'); } }
gpl-3.0
arktools/ardupilotone
Tools/ArdupilotMegaPlanner/Log.cs
39678
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Reflection; using System.Text; using System.Windows.Forms; using System.IO.Ports; using System.IO; using System.Text.RegularExpressions; using KMLib; using KMLib.Feature; using KMLib.Geometry; using Core.Geometry; using ICSharpCode.SharpZipLib.Zip; using ICSharpCode.SharpZipLib.Checksums; using ICSharpCode.SharpZipLib.Core; using log4net; namespace ArdupilotMega { public partial class Log : Form { private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); ICommsSerial comPort; int logcount = 0; serialstatus status = serialstatus.Connecting; StreamWriter sw; int currentlog = 0; bool threadrun = true; string logfile = ""; int receivedbytes = 0; List<Data> flightdata = new List<Data>(); //List<Model> orientation = new List<Model>(); Model runmodel = new Model(); Object thisLock = new Object(); DateTime start = DateTime.Now; public struct Data { public Model model; public string[] ntun; public string[] ctun; public int datetime; } enum serialstatus { Connecting, Createfile, Closefile, Reading, Waiting, Done } public Log() { InitializeComponent(); } private void Log_Load(object sender, EventArgs e) { status = serialstatus.Connecting; comPort = MainV2.comPort.BaseStream; //comPort.ReceivedBytesThreshold = 50; //comPort.ReadBufferSize = 1024 * 1024; try { comPort.toggleDTR(); //comPort.Open(); } catch (Exception ex) { log.Error("Error opening comport", ex); CustomMessageBox.Show("Error opening comport"); } var t11 = new System.Threading.Thread(delegate() { var start = DateTime.Now; threadrun = true; System.Threading.Thread.Sleep(2000); try { comPort.Write("\n\n\n\n"); // more in "connecting" } catch { } while (threadrun) { try { updateDisplay(); System.Threading.Thread.Sleep(10); if (!comPort.IsOpen) break; while (comPort.BytesToRead >= 4) { comPort_DataReceived((object)null, (SerialDataReceivedEventArgs)null); } } catch (Exception ex) { log.Error("crash in comport reader " + ex); } // cant exit unless told to } log.Info("Comport thread close"); }) {Name = "comport reader"}; t11.Start(); // doesnt seem to work on mac //comPort.DataReceived += new SerialDataReceivedEventHandler(comPort_DataReceived); } void genchkcombo(int logcount) { MethodInvoker m = delegate() { //CHK_logs.Items.Clear(); //for (int a = 1; a <= logcount; a++) if (!CHK_logs.Items.Contains(logcount)) { CHK_logs.Items.Add(logcount); } }; try { BeginInvoke(m); } catch { } } void updateDisplay() { if (start.Second != DateTime.Now.Second) { this.BeginInvoke((System.Windows.Forms.MethodInvoker)delegate() { try { TXT_status.Text = status.ToString() + " " + receivedbytes + " " + comPort.BytesToRead; } catch { } }); start = DateTime.Now; } } void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { try { while (comPort.BytesToRead > 0 && threadrun) { updateDisplay(); string line = ""; comPort.ReadTimeout = 500; try { line = comPort.ReadLine(); //readline(comPort); if (!line.Contains("\n")) line = line + "\n"; } catch { line = comPort.ReadExisting(); //byte[] data = readline(comPort); //line = Encoding.ASCII.GetString(data, 0, data.Length); } receivedbytes += line.Length; //string line = Encoding.ASCII.GetString(data, 0, data.Length); switch (status) { case serialstatus.Connecting: if (line.Contains("ENTER") || line.Contains("GROUND START") || line.Contains("reset to FLY") || line.Contains("interactive setup") || line.Contains("CLI") || line.Contains("Ardu")) { try { comPort.Write("\n\n\n\n"); } catch { } comPort.Write("logs\r"); status = serialstatus.Done; } break; case serialstatus.Closefile: sw.Close(); TextReader tr = new StreamReader(logfile); MainV2.cs.firmware = MainV2.Firmwares.ArduPlane; this.Invoke((System.Windows.Forms.MethodInvoker)delegate() { TXT_seriallog.AppendText("Createing KML for " + logfile); }); while (tr.Peek() != -1) { processLine(tr.ReadLine()); } tr.Close(); try { writeKML(logfile + ".kml"); } catch { } // usualy invalid lat long error status = serialstatus.Done; break; case serialstatus.Createfile: receivedbytes = 0; Directory.CreateDirectory(Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + @"logs"); logfile = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + @"logs" + Path.DirectorySeparatorChar + DateTime.Now.ToString("yyyy-MM-dd HH-mm") + " " + currentlog + ".log"; sw = new StreamWriter(logfile); status = serialstatus.Waiting; lock (thisLock) { this.Invoke((System.Windows.Forms.MethodInvoker)delegate() { TXT_seriallog.Clear(); }); } //if (line.Contains("Dumping Log")) { status = serialstatus.Reading; } break; case serialstatus.Done: // if (line.Contains("start") && line.Contains("end")) { Regex regex2 = new Regex(@"^Log ([0-9]+),", RegexOptions.IgnoreCase); if (regex2.IsMatch(line)) { MatchCollection matchs = regex2.Matches(line); logcount = int.Parse(matchs[0].Groups[1].Value); genchkcombo(logcount); //status = serialstatus.Done; } } if (line.Contains("No logs")) { status = serialstatus.Done; } break; case serialstatus.Reading: if (line.Contains("packets read") || line.Contains("Done") || line.Contains("logs enabled")) { status = serialstatus.Closefile; break; } sw.Write(line); continue; case serialstatus.Waiting: if (line.Contains("Dumping Log") || line.Contains("GPS:") || line.Contains("NTUN:") || line.Contains("CTUN:") || line.Contains("PM:")) { status = serialstatus.Reading; } break; } lock (thisLock) { this.BeginInvoke((MethodInvoker)delegate() { Console.Write(line); TXT_seriallog.AppendText(line.Replace((char)0x0,' ')); // auto scroll if (TXT_seriallog.TextLength >= 10000) { TXT_seriallog.Text = TXT_seriallog.Text.Substring(TXT_seriallog.TextLength / 2); } TXT_seriallog.SelectionStart = TXT_seriallog.Text.Length; TXT_seriallog.ScrollToCaret(); TXT_seriallog.Refresh(); }); } } log.Info("exit while"); } catch (Exception ex) { CustomMessageBox.Show("Error reading data" + ex.ToString()); } } string lastline = ""; string[] ctunlast = new string[] { "", "", "", "", "", "", "", "", "", "", "", "", "", "" }; string[] ntunlast = new string[] { "", "", "", "", "", "", "", "", "", "", "", "", "", "" }; List<PointLatLngAlt> cmd = new List<PointLatLngAlt>(); Point3D oldlastpos = new Point3D(); Point3D lastpos = new Point3D(); private void processLine(string line) { try { Application.DoEvents(); line = line.Replace(", ", ","); line = line.Replace(": ", ":"); string[] items = line.Split(',', ':'); if (items[0].Contains("CMD")) { if (flightdata.Count == 0) { if (int.Parse(items[2]) <= (int)MAVLink.MAV_CMD.LAST) // wps { PointLatLngAlt temp = new PointLatLngAlt(double.Parse(items[5], new System.Globalization.CultureInfo("en-US")) / 10000000, double.Parse(items[6], new System.Globalization.CultureInfo("en-US")) / 10000000, double.Parse(items[4], new System.Globalization.CultureInfo("en-US")) / 100, items[1].ToString()); cmd.Add(temp); } } } if (items[0].Contains("MOD")) { positionindex++; modelist.Add(""); // i cant be bothered doing this properly modelist.Add(""); modelist[positionindex] = (items[1]); } if (items[0].Contains("GPS") && items[2] == "1" && items[4] != "0" && items[4] != "-1" && lastline != line) // check gps line and fixed status { if (position[positionindex] == null) position[positionindex] = new List<Point3D>(); double alt = double.Parse(items[6], new System.Globalization.CultureInfo("en-US")); if (items.Length == 11 && items[6] == "0.0000") alt = double.Parse(items[7], new System.Globalization.CultureInfo("en-US")); if (items.Length == 11 && items[6] == "0") alt = double.Parse(items[7], new System.Globalization.CultureInfo("en-US")); position[positionindex].Add(new Point3D(double.Parse(items[5], new System.Globalization.CultureInfo("en-US")), double.Parse(items[4], new System.Globalization.CultureInfo("en-US")), alt)); oldlastpos = lastpos; lastpos = (position[positionindex][position[positionindex].Count - 1]); lastline = line; } if (items[0].Contains("GPS") && items[4] != "0" && items[4] != "-1" && items.Length <= 9) { if (position[positionindex] == null) position[positionindex] = new List<Point3D>(); MainV2.cs.firmware = MainV2.Firmwares.ArduCopter2; double alt = double.Parse(items[5], new System.Globalization.CultureInfo("en-US")); position[positionindex].Add(new Point3D(double.Parse(items[4], new System.Globalization.CultureInfo("en-US")), double.Parse(items[3], new System.Globalization.CultureInfo("en-US")), alt)); oldlastpos = lastpos; lastpos = (position[positionindex][position[positionindex].Count - 1]); lastline = line; } if (items[0].Contains("CTUN")) { ctunlast = items; } if (items[0].Contains("NTUN")) { ntunlast = items; line = "ATT:" + double.Parse(ctunlast[3], new System.Globalization.CultureInfo("en-US")) * 100 + "," + double.Parse(ctunlast[6], new System.Globalization.CultureInfo("en-US")) * 100 + "," + double.Parse(items[1], new System.Globalization.CultureInfo("en-US")) * 100; items = line.Split(',', ':'); } if (items[0].Contains("ATT")) { try { if (lastpos.X != 0 && oldlastpos.X != lastpos.X && oldlastpos.Y != lastpos.Y) { Data dat = new Data(); try { dat.datetime = int.Parse(lastline.Split(',', ':')[1]); } catch { } runmodel = new Model(); runmodel.Location.longitude = lastpos.X; runmodel.Location.latitude = lastpos.Y; runmodel.Location.altitude = lastpos.Z; oldlastpos = lastpos; runmodel.Orientation.roll = double.Parse(items[1], new System.Globalization.CultureInfo("en-US")) / -100; runmodel.Orientation.tilt = double.Parse(items[2], new System.Globalization.CultureInfo("en-US")) / -100; runmodel.Orientation.heading = double.Parse(items[3], new System.Globalization.CultureInfo("en-US")) / 100; dat.model = runmodel; dat.ctun = ctunlast; dat.ntun = ntunlast; flightdata.Add(dat); } } catch { } } } catch (Exception) { // if items is to short or parse fails.. ignore } } List<string> modelist = new List<string>(); List<Core.Geometry.Point3D>[] position = new List<Core.Geometry.Point3D>[200]; int positionindex = 0; private void writeGPX(string filename) { System.Xml.XmlTextWriter xw = new System.Xml.XmlTextWriter(Path.GetDirectoryName(filename) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(filename) + ".gpx",Encoding.ASCII); xw.WriteStartElement("gpx"); xw.WriteStartElement("trk"); xw.WriteStartElement("trkseg"); DateTime start = new DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day,0,0,0); foreach (Data mod in flightdata) { xw.WriteStartElement("trkpt"); xw.WriteAttributeString("lat", mod.model.Location.latitude.ToString(new System.Globalization.CultureInfo("en-US"))); xw.WriteAttributeString("lon", mod.model.Location.longitude.ToString(new System.Globalization.CultureInfo("en-US"))); xw.WriteElementString("ele", mod.model.Location.altitude.ToString(new System.Globalization.CultureInfo("en-US"))); xw.WriteElementString("time", start.AddMilliseconds(mod.datetime).ToString("yyyy-MM-ddTHH:mm:sszzzzzz")); xw.WriteElementString("course", (mod.model.Orientation.heading).ToString(new System.Globalization.CultureInfo("en-US"))); xw.WriteElementString("roll", mod.model.Orientation.roll.ToString(new System.Globalization.CultureInfo("en-US"))); xw.WriteElementString("pitch", mod.model.Orientation.tilt.ToString(new System.Globalization.CultureInfo("en-US"))); //xw.WriteElementString("speed", mod.model.Orientation.); //xw.WriteElementString("fix", mod.model.Location.altitude); xw.WriteEndElement(); } xw.WriteEndElement(); xw.WriteEndElement(); xw.WriteEndElement(); xw.Close(); } private void writeKML(string filename) { try { writeGPX(filename); } catch { } Color[] colours = { Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Blue, Color.Indigo, Color.Violet, Color.Pink }; AltitudeMode altmode = AltitudeMode.absolute; if (MainV2.cs.firmware == MainV2.Firmwares.ArduCopter2) { altmode = AltitudeMode.relativeToGround; // because of sonar, this is both right and wrong. right for sonar, wrong in terms of gps as the land slopes off. } KMLRoot kml = new KMLRoot(); Folder fldr = new Folder("Log"); Style style = new Style(); style.Id = "yellowLineGreenPoly"; style.Add(new LineStyle(HexStringToColor("7f00ffff"), 4)); PolyStyle pstyle = new PolyStyle(); pstyle.Color = HexStringToColor("7f00ff00"); style.Add(pstyle); kml.Document.AddStyle(style); int stylecode = 0xff; int g = -1; foreach (List<Point3D> poslist in position) { g++; if (poslist == null) continue; LineString ls = new LineString(); ls.AltitudeMode = altmode; ls.Extrude = true; //ls.Tessellate = true; Coordinates coords = new Coordinates(); coords.AddRange(poslist); ls.coordinates = coords; Placemark pm = new Placemark(); string mode = ""; if (g < modelist.Count) mode = modelist[g]; pm.name = g + " Flight Path " + mode; pm.styleUrl = "#yellowLineGreenPoly"; pm.LineString = ls; stylecode = colours[g % (colours.Length - 1)].ToArgb(); Style style2 = new Style(); Color color = Color.FromArgb(0xff, (stylecode >> 16) & 0xff, (stylecode >> 8) & 0xff, (stylecode >> 0) & 0xff); log.Info("colour " + color.ToArgb().ToString("X") + " " + color.ToKnownColor().ToString()); style2.Add(new LineStyle(color, 4)); pm.AddStyle(style2); fldr.Add(pm); } Folder planes = new Folder(); planes.name = "Planes"; fldr.Add(planes); Folder waypoints = new Folder(); waypoints.name = "Waypoints"; fldr.Add(waypoints); LineString lswp = new LineString(); lswp.AltitudeMode = AltitudeMode.relativeToGround; lswp.Extrude = true; Coordinates coordswp = new Coordinates(); foreach (PointLatLngAlt p1 in cmd) { coordswp.Add(new Point3D(p1.Lng, p1.Lat, p1.Alt)); } lswp.coordinates = coordswp; Placemark pmwp = new Placemark(); pmwp.name = "Waypoints"; //pm.styleUrl = "#yellowLineGreenPoly"; pmwp.LineString = lswp; waypoints.Add(pmwp); int a = 0; int l = -1; Model lastmodel = null; foreach (Data mod in flightdata) { l++; if (mod.model.Location.latitude == 0) continue; if (lastmodel != null) { if (lastmodel.Location.Equals(mod.model.Location)) { continue; } } Placemark pmplane = new Placemark(); pmplane.name = "Plane " + a; pmplane.visibility = false; Model model = mod.model; model.AltitudeMode = altmode; model.Scale.x = 2; model.Scale.y = 2; model.Scale.z = 2; try { pmplane.description = @"<![CDATA[ <table> <tr><td>Roll: " + model.Orientation.roll + @" </td></tr> <tr><td>Pitch: " + model.Orientation.tilt + @" </td></tr> <tr><td>Yaw: " + model.Orientation.heading + @" </td></tr> <tr><td>WP dist " + mod.ntun[2] + @" </td></tr> <tr><td>tar bear " + mod.ntun[3] + @" </td></tr> <tr><td>nav bear " + mod.ntun[4] + @" </td></tr> <tr><td>alt error " + mod.ntun[5] + @" </td></tr> </table> ]]>"; } catch { } try { pmplane.Point = new KmlPoint((float)model.Location.longitude, (float)model.Location.latitude, (float)model.Location.altitude); pmplane.Point.AltitudeMode = altmode; Link link = new Link(); link.href = "block_plane_0.dae"; model.Link = link; pmplane.Model = model; planes.Add(pmplane); } catch { } // bad lat long value lastmodel = mod.model; a++; } kml.Document.Add(fldr); kml.Save(filename); // create kmz - aka zip file FileStream fs = File.Open(filename.Replace(".log.kml", ".kmz"), FileMode.Create); ZipOutputStream zipStream = new ZipOutputStream(fs); zipStream.SetLevel(9); //0-9, 9 being the highest level of compression zipStream.UseZip64 = UseZip64.Off; // older zipfile // entry 1 string entryName = ZipEntry.CleanName(Path.GetFileName(filename)); // Removes drive from name and fixes slash direction ZipEntry newEntry = new ZipEntry(entryName); newEntry.DateTime = DateTime.Now; zipStream.PutNextEntry(newEntry); // Zip the file in buffered chunks // the "using" will close the stream even if an exception occurs byte[] buffer = new byte[4096]; using (FileStream streamReader = File.OpenRead(filename)) { StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); File.Delete(filename); filename = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + "block_plane_0.dae"; // entry 2 entryName = ZipEntry.CleanName(Path.GetFileName(filename)); // Removes drive from name and fixes slash direction newEntry = new ZipEntry(entryName); newEntry.DateTime = DateTime.Now; zipStream.PutNextEntry(newEntry); // Zip the file in buffered chunks // the "using" will close the stream even if an exception occurs buffer = new byte[4096]; using (FileStream streamReader = File.OpenRead(filename)) { StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); zipStream.IsStreamOwner = true; // Makes the Close also Close the underlying stream zipStream.Close(); positionindex = 0; modelist.Clear(); flightdata.Clear(); position = new List<Core.Geometry.Point3D>[200]; cmd.Clear(); } private void Log_FormClosing(object sender, FormClosingEventArgs e) { threadrun = false; System.Threading.Thread.Sleep(500); if (comPort.IsOpen) { //comPort.Close(); } System.Threading.Thread.Sleep(500); } private void CHK_logs_Click(object sender, EventArgs e) { ListBox lb = sender as ListBox; } private void BUT_DLall_Click(object sender, EventArgs e) { if (status == serialstatus.Done) { System.Threading.Thread t11 = new System.Threading.Thread(delegate() { downloadthread(1, logcount); }); t11.Name = "Log Download All thread"; t11.Start(); } } private void downloadthread(int startlognum, int endlognum) { for (int a = startlognum; a <= endlognum; a++) { currentlog = a; System.Threading.Thread.Sleep(500); comPort.Write("dump "); System.Threading.Thread.Sleep(100); comPort.Write(a.ToString() + "\r"); status = serialstatus.Createfile; while (status != serialstatus.Done) { System.Threading.Thread.Sleep(100); } } } private void downloadsinglethread() { for (int i = 0; i < CHK_logs.CheckedItems.Count; ++i) { int a = (int)CHK_logs.CheckedItems[i]; { currentlog = a; System.Threading.Thread.Sleep(500); comPort.Write("dump "); System.Threading.Thread.Sleep(100); comPort.Write(a.ToString() + "\r"); status = serialstatus.Createfile; while (status != serialstatus.Done) { System.Threading.Thread.Sleep(100); } } } } private void BUT_DLthese_Click(object sender, EventArgs e) { if (status == serialstatus.Done) { System.Threading.Thread t11 = new System.Threading.Thread(delegate() { downloadsinglethread(); }); t11.Name = "Log download single thread"; t11.Start(); } } private void BUT_clearlogs_Click(object sender, EventArgs e) { System.Threading.Thread.Sleep(500); comPort.Write("erase\r"); System.Threading.Thread.Sleep(100); TXT_seriallog.AppendText("!!Allow 30-90 seconds for erase\n"); status = serialstatus.Done; CHK_logs.Items.Clear(); } private void BUT_redokml_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.Filter = "*.log|*.log"; openFileDialog1.FilterIndex = 2; openFileDialog1.RestoreDirectory = true; openFileDialog1.Multiselect = true; try { openFileDialog1.InitialDirectory = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + @"logs" + Path.DirectorySeparatorChar; } catch { } // incase dir doesnt exist if (openFileDialog1.ShowDialog() == DialogResult.OK) { foreach (string logfile in openFileDialog1.FileNames) { TXT_seriallog.AppendText("\n\nProcessing " + logfile + "\n"); this.Refresh(); TextReader tr = new StreamReader(logfile); MainV2.cs.firmware = MainV2.Firmwares.ArduPlane; while (tr.Peek() != -1) { processLine(tr.ReadLine()); } tr.Close(); writeKML(logfile + ".kml"); TXT_seriallog.AppendText("Done\n"); } } } public static Color HexStringToColor(string hexColor) { string hc = (hexColor); if (hc.Length != 8) { // you can choose whether to throw an exception //throw new ArgumentException("hexColor is not exactly 6 digits."); return Color.Empty; } string a = hc.Substring(0, 2); string r = hc.Substring(6, 2); string g = hc.Substring(4, 2); string b = hc.Substring(2, 2); Color color = Color.Empty; try { int ai = Int32.Parse(a, System.Globalization.NumberStyles.HexNumber); int ri = Int32.Parse(r, System.Globalization.NumberStyles.HexNumber); int gi = Int32.Parse(g, System.Globalization.NumberStyles.HexNumber); int bi = Int32.Parse(b, System.Globalization.NumberStyles.HexNumber); color = Color.FromArgb(ai, ri, gi, bi); } catch { // you can choose whether to throw an exception //throw new ArgumentException("Conversion failed."); return Color.Empty; } return color; } private void BUT_firstperson_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.Filter = "*.log|*.log"; openFileDialog1.FilterIndex = 2; openFileDialog1.RestoreDirectory = true; openFileDialog1.Multiselect = true; try { openFileDialog1.InitialDirectory = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + @"logs" + Path.DirectorySeparatorChar; } catch { } // incase dir doesnt exist if (openFileDialog1.ShowDialog() == DialogResult.OK) { foreach (string logfile in openFileDialog1.FileNames) { TXT_seriallog.AppendText("\n\nProcessing " + logfile + "\n"); this.Refresh(); try { TextReader tr = new StreamReader(logfile); MainV2.cs.firmware = MainV2.Firmwares.ArduPlane; while (tr.Peek() != -1) { processLine(tr.ReadLine()); } tr.Close(); } catch (Exception ex) { CustomMessageBox.Show("Error processing log. Is it still downloading? " + ex.Message); continue; } writeKMLFirstPerson(logfile + ".kml"); TXT_seriallog.AppendText("Done\n"); } } } private void writeKMLFirstPerson(string filename) { StreamWriter stream = new StreamWriter(File.Open(filename, FileMode.Create)); System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); string header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><kml xmlns=\"http://www.opengis.net/kml/2.2\" xmlns:gx=\"http://www.google.com/kml/ext/2.2\" xmlns:kml=\"http://www.opengis.net/kml/2.2\" xmlns:atom=\"http://www.w3.org/2005/Atom\">\n <Document> <name>Paths</name> <description>Path</description>\n <Style id=\"yellowLineGreenPoly\"> <LineStyle> <color>7f00ffff</color> <width>4</width> </LineStyle> <PolyStyle> <color>7f00ff00</color> </PolyStyle> </Style>\n "; stream.Write(header); StringBuilder kml = new StringBuilder(); StringBuilder data = new StringBuilder(); double lastlat = 0; double lastlong = 0; int gpspackets = 0; int lastgpspacket = 0; foreach (Data mod in flightdata) { if (mod.model.Location.latitude == 0) continue; gpspackets++; if (lastlat == mod.model.Location.latitude && lastlong == mod.model.Location.longitude) continue; // double speed 0.05 - assumeing 10hz in log file // 1 speed = 0.1 10 / 1 = 0.1 data.Append(@" <gx:FlyTo> <gx:duration>" + ((gpspackets - lastgpspacket) * 0.1) + @"</gx:duration> <gx:flyToMode>smooth</gx:flyToMode> <Camera> <longitude>" + mod.model.Location.longitude.ToString(new System.Globalization.CultureInfo("en-US")) + @"</longitude> <latitude>" + mod.model.Location.latitude.ToString(new System.Globalization.CultureInfo("en-US")) + @"</latitude> <altitude>" + mod.model.Location.altitude.ToString(new System.Globalization.CultureInfo("en-US")) + @"</altitude> <roll>" + mod.model.Orientation.roll.ToString(new System.Globalization.CultureInfo("en-US")) + @"</roll> <tilt>" + (90 - mod.model.Orientation.tilt).ToString(new System.Globalization.CultureInfo("en-US")) + @"</tilt> <heading>" + mod.model.Orientation.heading.ToString(new System.Globalization.CultureInfo("en-US")) + @"</heading> <altitudeMode>absolute</altitudeMode> </Camera> </gx:FlyTo> "); lastlat = mod.model.Location.latitude; lastlong = mod.model.Location.longitude; lastgpspacket = gpspackets; } kml.Append(@" <Folder> <name>Flight</name> <gx:Tour> <name>Flight Do</name> <gx:Playlist> " + data + @"</gx:Playlist> </gx:Tour> </Folder> </Document> </kml> "); stream.Write(kml.ToString()); stream.Close(); // create kmz - aka zip file FileStream fs = File.Open(filename.Replace(".log.kml", ".kmz"), FileMode.Create); ZipOutputStream zipStream = new ZipOutputStream(fs); zipStream.SetLevel(9); //0-9, 9 being the highest level of compression zipStream.UseZip64 = UseZip64.Off; // older zipfile // entry 1 string entryName = ZipEntry.CleanName(Path.GetFileName(filename)); // Removes drive from name and fixes slash direction ZipEntry newEntry = new ZipEntry(entryName); newEntry.DateTime = DateTime.Now; zipStream.PutNextEntry(newEntry); // Zip the file in buffered chunks // the "using" will close the stream even if an exception occurs byte[] buffer = new byte[4096]; using (FileStream streamReader = File.OpenRead(filename)) { StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); File.Delete(filename); filename = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + "block_plane_0.dae"; // entry 2 entryName = ZipEntry.CleanName(Path.GetFileName(filename)); // Removes drive from name and fixes slash direction newEntry = new ZipEntry(entryName); newEntry.DateTime = DateTime.Now; zipStream.PutNextEntry(newEntry); // Zip the file in buffered chunks // the "using" will close the stream even if an exception occurs buffer = new byte[4096]; using (FileStream streamReader = File.OpenRead(filename)) { StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); zipStream.IsStreamOwner = true; // Makes the Close also Close the underlying stream zipStream.Close(); positionindex = 0; modelist.Clear(); flightdata.Clear(); position = new List<Core.Geometry.Point3D>[200]; cmd.Clear(); } } }
gpl-3.0
gohdan/DFC
known_files/hashes/bitrix/modules/statistic/lang/ru/admin/event_dynamic_list.php
61
Bitrix 16.5 Business Demo = 2177877d6c25bfa279a0b4021b4f23b3
gpl-3.0
masterucm1617/botzzaroni
BotzzaroniDev/src/icaro/aplicaciones/informacion/gestionPizzeria/CalendarUtil.java
21074
package icaro.aplicaciones.informacion.gestionPizzeria; /* * net/balusc/util/CalendarUtil.java * * Copyright (C) 2007 BalusC * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Lesser General Public License as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this library. * If not, see <http://www.gnu.org/licenses/>. */ import java.util.Calendar; /** * Useful Calendar utilities. * * @author BalusC * @link http://balusc.blogspot.com/2007/09/calendarutil.html */ public final class CalendarUtil { // Init // --------------------------------------------------------------------------------------- private CalendarUtil() { // Utility class, hide the constructor. } // Validators // --------------------------------------------------------------------------------- /** * Checks whether the given day, month and year combination is a valid date * or not. * * @param year * The year part of the date. * @param month * The month part of the date. * @param day * The day part of the date. * @return True if the given day, month and year combination is a valid * date. */ public static boolean isValidDate(int year, int month, int day) { return isValidDate(year, month, day, 0, 0, 0); } /** * Checks whether the given hour, minute and second combination is a valid * time or not. * * @param hour * The hour part of the time. * @param minute * The minute part of the time. * @param second * The second part of the time. * @return True if the given hour, minute and second combination is a valid * time. */ public static boolean isValidTime(int hour, int minute, int second) { return isValidDate(1, 1, 1, hour, minute, second); } /** * Checks whether the given day, month, year, hour, minute and second * combination is a valid date or not. * * @param year * The year part of the date. * @param month * The month part of the date. * @param day * The day part of the date. * @param hour * The hour part of the date. * @param minute * The minute part of the date. * @param second * The second part of the date. * @return True if the given day, month, year, hour, minute and second * combination is a valid date. */ public static boolean isValidDate(int year, int month, int day, int hour, int minute, int second) { try { getValidCalendar(year, month, day, hour, minute, second); return true; } catch (IllegalArgumentException e) { return false; } } /** * Validate the actual date of the given date elements and returns a * calendar instance based on the given date elements. The time is forced to * 00:00:00. * * @param year * The year part of the date. * @param month * The month part of the date. * @param day * The day part of the date. * @return A Calendar instance prefilled with the given date elements. * @throws IllegalArgumentException * If the given date elements does not represent a valid date. */ public static Calendar getValidCalendar(int year, int month, int day) { return getValidCalendar(year, month, day, 0, 0, 0); } /** * Validate the actual date of the given date elements and returns a * calendar instance based on the given date elements. * * @param year * The year part of the date. * @param month * The month part of the date. * @param day * The day part of the date. * @param hour * The hour part of the date. * @param minute * The minute part of the date. * @param second * The second part of the date. * @return A Calendar instance prefilled with the given date elements. * @throws IllegalArgumentException * If the given date elements does not represent a valid date. */ public static Calendar getValidCalendar(int year, int month, int day, int hour, int minute, int second) { Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.setLenient(false); // Don't automatically convert invalid date. calendar.set(year, month - 1, day, hour, minute, second); calendar.getTimeInMillis(); // Lazy update, throws // IllegalArgumentException if invalid date. return calendar; } // Changers // ----------------------------------------------------------------------------------- /** * Add the given amount of years to the given calendar. The changes are * reflected in the given calendar. * * @param calendar * The calendar to add the given amount of years to. * @param years * The amount of years to be added to the given calendar. * Negative values are also allowed, it will just go back in * time. */ public static void addYears(Calendar calendar, int years) { calendar.add(Calendar.YEAR, years); } /** * Add the given amount of months to the given calendar. The changes are * reflected in the given calendar. * * @param calendar * The calendar to add the given amount of months to. * @param months * The amount of months to be added to the given calendar. * Negative values are also allowed, it will just go back in * time. */ public static void addMonths(Calendar calendar, int months) { calendar.add(Calendar.MONTH, months); } /** * Add the given amount of days to the given calendar. The changes are * reflected in the given calendar. * * @param calendar * The calendar to add the given amount of days to. * @param days * The amount of days to be added to the given calendar. Negative * values are also allowed, it will just go back in time. */ public static void addDays(Calendar calendar, int days) { calendar.add(Calendar.DATE, days); } /** * Add the given amount of hours to the given calendar. The changes are * reflected in the given calendar. * * @param calendar * The calendar to add the given amount of hours to. * @param hours * The amount of hours to be added to the given calendar. * Negative values are also allowed, it will just go back in * time. */ public static void addHours(Calendar calendar, int hours) { calendar.add(Calendar.HOUR, hours); } /** * Add the given amount of minutes to the given calendar. The changes are * reflected in the given calendar. * * @param calendar * The calendar to add the given amount of minutes to. * @param minutes * The amount of minutes to be added to the given calendar. * Negative values are also allowed, it will just go back in * time. */ public static void addMinutes(Calendar calendar, int minutes) { calendar.add(Calendar.MINUTE, minutes); } /** * Add the given amount of seconds to the given calendar. The changes are * reflected in the given calendar. * * @param calendar * The calendar to add the given amount of seconds to. * @param seconds * The amount of seconds to be added to the given calendar. * Negative values are also allowed, it will just go back in * time. */ public static void addSeconds(Calendar calendar, int seconds) { calendar.add(Calendar.SECOND, seconds); } /** * Add the given amount of millis to the given calendar. The changes are * reflected in the given calendar. * * @param calendar * The calendar to add the given amount of millis to. * @param millis * The amount of millis to be added to the given calendar. * Negative values are also allowed, it will just go back in * time. */ public static void addMillis(Calendar calendar, int millis) { calendar.add(Calendar.MILLISECOND, millis); } // Comparators // -------------------------------------------------------------------------------- /** * Returns <tt>true</tt> if the two given calendars are dated on the same * year. * * @param one * The one calendar. * @param two * The other calendar. * @return True if the two given calendars are dated on the same year. */ public static boolean sameYear(Calendar one, Calendar two) { return one.get(Calendar.YEAR) == two.get(Calendar.YEAR); } /** * Returns <tt>true</tt> if the two given calendars are dated on the same * year and month. * * @param one * The one calendar. * @param two * The other calendar. * @return True if the two given calendars are dated on the same year and * month. */ public static boolean sameMonth(Calendar one, Calendar two) { return one.get(Calendar.MONTH) == two.get(Calendar.MONTH) && sameYear(one, two); } /** * Returns <tt>true</tt> if the two given calendars are dated on the same * year, month and day. * * @param one * The one calendar. * @param two * The other calendar. * @return True if the two given calendars are dated on the same year, month * and day. */ public static boolean sameDay(Calendar one, Calendar two) { return one.get(Calendar.DATE) == two.get(Calendar.DATE) && sameMonth(one, two); } /** * Returns <tt>true</tt> if the two given calendars are dated on the same * year, month, day and hour. * * @param one * The one calendar. * @param two * The other calendar. * @return True if the two given calendars are dated on the same year, * month, day and hour. */ public static boolean sameHour(Calendar one, Calendar two) { return one.get(Calendar.HOUR_OF_DAY) == two.get(Calendar.HOUR_OF_DAY) && sameDay(one, two); } /** * Returns <tt>true</tt> if the two given calendars are dated on the same * year, month, day, hour and minute. * * @param one * The one calendar. * @param two * The other calendar. * @return True if the two given calendars are dated on the same year, * month, day, hour and minute. */ public static boolean sameMinute(Calendar one, Calendar two) { return one.get(Calendar.MINUTE) == two.get(Calendar.MINUTE) && sameHour(one, two); } /** * Returns <tt>true</tt> if the two given calendars are dated on the same * year, month, day, hour, minute and second. * * @param one * The one calendar. * @param two * The other calendar. * @return True if the two given calendars are dated on the same year, * month, day, hour, minute and second. */ public static boolean sameSecond(Calendar one, Calendar two) { return one.get(Calendar.SECOND) == two.get(Calendar.SECOND) && sameMinute(one, two); } /** * Returns <tt>true</tt> if the two given calendars are dated on the same * time. The difference from <tt>one.equals(two)</tt> is that this method * does not respect the time zone. * * @param one * The one calendar. * @param two * The other calendar. * @return True if the two given calendars are dated on the same time. */ public static boolean sameTime(Calendar one, Calendar two) { return one.getTimeInMillis() == two.getTimeInMillis(); } // Calculators // -------------------------------------------------------------------------------- /** * Retrieve the amount of elapsed years between the two given calendars. * * @param before * The first calendar with expected date before the second * calendar. * @param after * The second calendar with expected date after the first * calendar. * @return The amount of elapsed years between the two given calendars. * @throws IllegalArgumentException * If the first calendar is dated after the second calendar. */ public static int elapsedYears(Calendar before, Calendar after) { return elapsed(before, after, Calendar.YEAR); } /** * Retrieve the amount of elapsed months between the two given calendars. * * @param before * The first calendar with expected date before the second * calendar. * @param after * The second calendar with expected date after the first * calendar. * @return The amount of elapsed months between the two given calendars. * @throws IllegalArgumentException * If the first calendar is dated after the second calendar. */ public static int elapsedMonths(Calendar before, Calendar after) { return elapsed(before, after, Calendar.MONTH); } /** * Retrieve the amount of elapsed days between the two given calendars. * * @param before * The first calendar with expected date before the second * calendar. * @param after * The second calendar with expected date after the first * calendar. * @return The amount of elapsed days between the two given calendars. * @throws IllegalArgumentException * If the first calendar is dated after the second calendar. */ public static int elapsedDays(Calendar before, Calendar after) { return elapsed(before, after, Calendar.DATE); } /** * Retrieve the amount of elapsed hours between the two given calendars. * * @param before * The first calendar with expected date before the second * calendar. * @param after * The second calendar with expected date after the first * calendar. * @return The amount of elapsed hours between the two given calendars. * @throws IllegalArgumentException * If the first calendar is dated after the second calendar. */ public static int elapsedHours(Calendar before, Calendar after) { return (int) elapsedMillis(before, after, 3600000); // 1h = 60m = 3600s // = 3600000ms } /** * Retrieve the amount of elapsed minutes between the two given calendars. * * @param before * The first calendar with expected date before the second * calendar. * @param after * The second calendar with expected date after the first * calendar. * @return The amount of elapsed minutes between the two given calendars. * @throws IllegalArgumentException * If the first calendar is dated after the second calendar. */ public static int elapsedMinutes(Calendar before, Calendar after) { return (int) elapsedMillis(before, after, 60000); // 1m = 60s = 60000ms } /** * Retrieve the amount of elapsed seconds between the two given calendars. * * @param before * The first calendar with expected date before the second * calendar. * @param after * The second calendar with expected date after the first * calendar. * @return The amount of elapsed seconds between the two given calendars. * @throws IllegalArgumentException * If the first calendar is dated after the second calendar. */ public static int elapsedSeconds(Calendar before, Calendar after) { return (int) elapsedMillis(before, after, 1000); // 1sec = 1000ms. } /** * Retrieve the amount of elapsed milliseconds between the two given * calendars. * * @param before * The first calendar with expected date before the second * calendar. * @param after * The second calendar with expected date after the first * calendar. * @return The amount of elapsed milliseconds between the two given * calendars. * @throws IllegalArgumentException * If the first calendar is dated after the second calendar. */ public static long elapsedMillis(Calendar before, Calendar after) { return elapsedMillis(before, after, 1); // 1ms is apparently 1ms. } /** * Calculate the total of elapsed time from years up to seconds between the * two given calendars. It returns an int array with the elapsed years, * months, days, hours, minutes and seconds respectively. * * @param before * The first calendar with expected date before the second * calendar. * @param after * The second calendar with expected date after the first * calendar. * @return The elapsed time between the two given calendars in years, * months, days, hours, minutes and seconds. * @throws IllegalArgumentException * If the first calendar is dated after the second calendar. */ public static int[] elapsedTime(Calendar before, Calendar after) { int[] elapsedTime = new int[6]; Calendar clone = (Calendar) before.clone(); // Otherwise changes are // been reflected. elapsedTime[0] = elapsedYears(clone, after); addYears(clone, elapsedTime[0]); elapsedTime[1] = elapsedMonths(clone, after); addMonths(clone, elapsedTime[1]); elapsedTime[2] = elapsedDays(clone, after); addDays(clone, elapsedTime[2]); elapsedTime[3] = elapsedHours(clone, after); addHours(clone, elapsedTime[3]); elapsedTime[4] = elapsedMinutes(clone, after); addMinutes(clone, elapsedTime[4]); elapsedTime[5] = elapsedSeconds(clone, after); return elapsedTime; } // Helpers // ------------------------------------------------------------------------------------ /** * Retrieve the amount of elapsed time between the two given calendars based * on the given calendar field as definied in the Calendar constants, e.g. * <tt>Calendar.MONTH</tt>. * * @param before * The first calendar with expected date before the second * calendar. * @param after * The second calendar with expected date after the first * calendar. * @param field * The calendar field as definied in the Calendar constants. * @return The amount of elapsed time between the two given calendars based * on the given calendar field. * @throws IllegalArgumentException * If the first calendar is dated after the second calendar. */ private static int elapsed(Calendar before, Calendar after, int field) { checkBeforeAfter(before, after); Calendar clone = (Calendar) before.clone(); // Otherwise changes are // been reflected. int elapsed = -1; while (!clone.after(after)) { clone.add(field, 1); elapsed++; } return elapsed; } /** * Retrieve the amount of elapsed milliseconds between the two given * calendars and directly divide the outcome by the given factor. E.g.: if * the division factor is 1, then you will get the elapsed milliseconds * unchanged; if the division factor is 1000, then the elapsed milliseconds * will be divided by 1000, resulting in the amount of elapsed seconds. * * @param before * The first calendar with expected date before the second * calendar. * @param after * The second calendar with expected date after the first * calendar. * @param factor * The division factor which to divide the milliseconds with, * expected to be at least 1. * @return The amount of elapsed milliseconds between the two given * calendars, divided by the given factor. * @throws IllegalArgumentException * If the first calendar is dated after the second calendar or * if the division factor is less than 1. */ private static long elapsedMillis(Calendar before, Calendar after, int factor) { checkBeforeAfter(before, after); if (factor < 1) { throw new IllegalArgumentException("Division factor '" + factor + "' should not be less than 1."); } return (after.getTimeInMillis() - before.getTimeInMillis()) / factor; } /** * Check if the first calendar is actually dated before the second calendar. * * @param before * The first calendar with expected date before the second * calendar. * @param after * The second calendar with expected date after the first * calendar. * @throws IllegalArgumentException * If the first calendar is dated after the second calendar. */ private static void checkBeforeAfter(Calendar before, Calendar after) { if (before.after(after)) { throw new IllegalArgumentException( "The first calendar should be dated before the second calendar."); } } }
gpl-3.0
astra-toolbox/astra-toolbox
python/astra/plugins/__init__.py
1086
# ----------------------------------------------------------------------- # Copyright: 2010-2022, imec Vision Lab, University of Antwerp # 2013-2022, CWI, Amsterdam # # Contact: [email protected] # Website: http://www.astra-toolbox.com/ # # This file is part of the ASTRA Toolbox. # # # The ASTRA Toolbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # The ASTRA Toolbox 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 the ASTRA Toolbox. If not, see <http://www.gnu.org/licenses/>. # # ----------------------------------------------------------------------- from .sirt import SIRTPlugin from .cgls import CGLSPlugin
gpl-3.0
projectestac/intraweb
intranet/modules/Content/lib/Content/ContentType/PageNavigation.php
2241
<?php /** * Content prev- & next-page plugin * * @copyright (C) 2010 - 2011 Sven Strickroth * @link http://github.com/zikula-modules/Content * @version $Id$ * @license See license.txt */ class Content_ContentType_PageNavigation extends Content_AbstractContentType { function getTitle() { return $this->__('Page navigation'); } function getDescription() { return $this->__("Allows to navigate within pages on the same level."); } function isTranslatable() { return false; } function display() { $prevpage = null; $nextpage = null; $page = ModUtil::apiFunc('Content', 'Page', 'getPage', array('id' => $this->pageId)); $tables = DBUtil::getTables(); $pageTable = $tables['content_page']; $pageColumn = $tables['content_page_column']; $options = array('makeTree' => true); $options['orderBy'] = 'position'; $options['orderDir'] = 'desc'; $options['pageSize'] = 1; $options['filter']['superParentId'] = $page['parentPageId']; if ($page['position'] > 0) { $options['filter']['where'] = "$pageColumn[level] = $page[level] and $pageColumn[position] < $page[position]"; $pages = ModUtil::apiFunc('Content', 'Page', 'getPages', $options); if (count($pages) > 0) { $prevpage = $pages[0]; } } if (isset($page['position']) && $page['position'] >= 0) { $options['orderDir'] = 'asc'; $options['filter']['where'] = "$pageColumn[level] = $page[level] and $pageColumn[position] > $page[position]"; $pages = ModUtil::apiFunc('Content', 'Page', 'getPages', $options); if (count($pages) > 0) { $nextpage = $pages[0]; } } $this->view->assign('loggedin', UserUtil::isLoggedIn()); $this->view->assign('prevpage', $prevpage); $this->view->assign('nextpage', $nextpage); return $this->view->fetch($this->getTemplate()); } function displayEditing() { return "<h3>" . $this->__('Page navigation')."</h3>"; } function getSearchableText() { return; } }
gpl-3.0
ryanbaw/yetris2
src/Engine/InputManager.hpp
1628
#ifndef INPUTMANAGER_H_DEFINED #define INPUTMANAGER_H_DEFINED #include <string> #include <map> /// namespace InputManager { /// Attaches #name to #key. void bind(std::string name, int key); /// Removes all keybindings for #name. void unbind(std::string name); /// Tells if there's a #name bound to a key. bool exists(std::string name); /// Tells if #key is bound to a name. bool isBound(int key); /// Returns the key that's bound to #name. int getBind(std::string name); /// Tells if no key was actually pressed on the last frame. bool noKeyPressed(); /// Tells if #key was pressed. /// @note It's the Ncurses' internal value. bool isPressed(int key); /// Tells if #key was pressed. /// @note It's the user-defined key binding. bool isPressed(std::string key); /// Gets the input. /// /// * If negative, will wait forever for an input. /// * If 0, will return immediately, wether a key /// was pressed or not. /// * If positive, will wait for #delay_ms milliseconds. void update(int delay_ms=0); /// Returns human-readable name for internal value #key. std::string keyToString(int key); /// Returns the internal value for nameable #string key. int stringToKey(std::string string); /// The key that was pressed on the last frame. /// /// It's an Ncurses internal value, being the ASCII /// value or some special others - like KEY_LEFT, /// KEY_RIGHT and such. /// /// Avoid using it, prefer prefer #isPressed(). extern int pressedKey; /// Contains all binds from names to internal Ncurses values. extern std::map<std::string, int> binds; } #endif //INPUTMANAGER_H_DEFINED
gpl-3.0
EasterTheBunny/ourdistrict
Gruntfile.js
4357
var pkgjson = require("./package.json") var config = { pkg: pkgjson, app: 'bower_components', dist: 'src/main/webapp/static', src: 'src/main/webapp/assets' } module.exports = function(grunt) { // Configuration grunt.initConfig({ config: config, pkg: config.pkg, bower: grunt.file.readJSON("./.bowerrc"), copy: { dist: { files: [{ expand: true, cwd: '<%= config.app %>/konva', src: 'konva.min.js', dest: '<%= config.dist %>/js' },{ expand: true, cwd: '<%= config.app %>/beemuse/dist', src: 'beemuse.min.css', dest: '<%= config.dist %>/css' },{ expand: true, cwd: '<%= config.app %>/babylon-grid/dist', src: 'jquery.babylongrid.min.js', dest: '<%= config.dist %>/js' },{ expand: true, cwd: '<%= config.app %>/babylon-grid/dist/css', src: 'babylongrid-default.css', dest: '<%= config.dist %>/css' },{ expand: true, cwd: '<%= config.app %>/jquery-pagewalkthrough/dist', src: 'jquery.pagewalkthrough.min.js', dest: '<%= config.dist %>/js' },{ expand: true, cwd: '<%= config.app %>/parallax.js', src: 'parallax.min.js', dest: '<%= config.dist %>/js' },{ expand: true, cwd: '<%= config.app %>/jquery-pagewalkthrough/dist/css', src: 'jquery.pagewalkthrough.min.css', dest: '<%= config.dist %>/css' },{ expand: true, cwd: '<%= config.app %>/jquery-pagewalkthrough/dist/css/images', src: '**', dest: '<%= config.dist %>/css/images' },{ expand: true, cwd: '<%= config.app %>/jquery-pagewalkthrough/dist/css/font', src: '**', dest: '<%= config.dist %>/css/font' },{ expand: true, cwd: '<%= config.app %>/jquery-ui/', src: 'jquery-ui.min.js', dest: '<%= config.dist %>/js' },{ expand: true, cwd: '<%= config.app %>/jquery-ui/themes/base', src: 'jquery-ui.min.css', dest: '<%= config.dist %>/css' },{ expand: true, cwd: '<%= config.app %>/jquery-ui/themes/base/images', src: '**', dest: '<%= config.dist %>/css/images' },{ expand: true, cwd: '<%= config.app %>/ionicons/fonts', src: '**', dest: '<%= config.dist %>/fonts' },{ expand: true, cwd: '<%= config.app %>/ionicons/css', src: 'ionicons.min.css', dest: '<%= config.dist %>/css' }] } }, /*concat: { dist: { src: [ '<%= config.app %>/jquery-ui/ui/minified/core.js', '<%= config.app %>/jquery-ui/ui/minified/widget.js', '<%= config.app %>/jquery-ui/ui/minified/position.js', '<%= config.app %>/jquery-ui/ui/minified/data.js', '<%= config.app %>/jquery-ui/ui/minified/keycode.js', '<%= config.app %>/jquery-ui/ui/minified/scroll-parent.js', '<%= config.app %>/jquery-ui/ui/minified/unique-id.js', '<%= config.app %>/jquery-ui/ui/widgets/sortable.js', '<%= config.app %>/jquery-ui/ui/widgets/autocomplete.js', '<%= config.app %>/jquery-ui/ui/widgets/menu.js', '<%= config.app %>/jquery-ui/ui/widgets/mouse.js' ], dest: '<%= config.dist %>/js/jquery-ui.js' } },*/ uglify: { dist: { options: { mangle: false, preserveComments: function(node, comment) { return /Copyright/.test(comment.value); } }, files: [{ expand: true, cwd: '<%= config.src %>/js', src: ['*.js', '!*.min.js'], dest: '<%= config.dist %>/js', rename: function(dst, src) { // To keep the source js files and make new files as `*.min.js`: return dst + '/' + src.replace('.js', '.min.js'); // Or to override to src: //return src; } }] } }, cssmin: { dist: { files: [{ expand: true, cwd: '<%= config.src %>/css', src: ['*.css', '!*.min.css'], dest: '<%= config.dist %>/css', ext: '.min.css' }] } }, coffee: { dist: { options: { bare: true }, files: { '<%= config.dist %>/js/main.js': '<%= config.src %>/coffee/main.coffee' } } } }); grunt.loadNpmTasks('grunt-contrib-copy'); //grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.loadNpmTasks('grunt-contrib-coffee'); grunt.registerTask('build', ['copy', 'uglify', 'cssmin', 'coffee']); };
gpl-3.0
ClassicRockFan/ShockWave-Engine
src/com/ClassicRockFan/ShockWave/engine/entities/entityComponent/rendering/SmartMove.java
2084
package com.ClassicRockFan.ShockWave.engine.entities.entityComponent.rendering; import com.ClassicRockFan.ShockWave.engine.core.Input; import com.ClassicRockFan.ShockWave.engine.core.math.Vector3f; import com.ClassicRockFan.ShockWave.engine.entities.entityComponent.EntityComponent; import org.lwjgl.input.Keyboard; public class SmartMove extends EntityComponent{ private final int UP_KEY; private final int DOWN_KEY; private final int LEFT_KEY; private final int RIGHT_KEY; private float moveSpeed; public SmartMove(float moveSpeed) { this(moveSpeed, Keyboard.KEY_W, Keyboard.KEY_S, Keyboard.KEY_A, Keyboard.KEY_D); } public SmartMove(float moveSpeed, int UP_KEY, int DOWN_KEY, int LEFT_KEY, int RIGHT_KEY) { super("freeMove"); this.moveSpeed = moveSpeed; this.UP_KEY = UP_KEY; this.DOWN_KEY = DOWN_KEY; this.LEFT_KEY = LEFT_KEY; this.RIGHT_KEY = RIGHT_KEY; } @Override public void input(float delta) { float moveAmount = moveSpeed * delta; if (Input.getKey(UP_KEY)) { move(getTransform().getRot().getForward(), moveAmount); } if (Input.getKey(DOWN_KEY)) { move(getTransform().getRot().getForward(), -moveAmount); } if (Input.getKey(LEFT_KEY)) { move(getTransform().getRot().getLeft(), moveAmount); } if (Input.getKey(RIGHT_KEY)) { move(getTransform().getRot().getRight(), moveAmount); } } private void move(Vector3f dir, float amt) { getTransform().getPos().set(getTransform().getPos().add(dir.normalized().mul(amt))); } public float getMoveSpeed() { return moveSpeed; } public void setMoveSpeed(float moveSpeed) { this.moveSpeed = moveSpeed; } public int getUP_KEY() { return UP_KEY; } public int getDOWN_KEY() { return DOWN_KEY; } public int getLEFT_KEY() { return LEFT_KEY; } public int getRIGHT_KEY() { return RIGHT_KEY; } }
gpl-3.0
vsetchinfc/envman
EnvMan/EnvMan/VersionManager/FrmVersionInfo.cs
3127
//------------------------------------------------------------------------ // <copyright file="FrmVersionInfo.cs" company="SETCHIN Freelance Consulting"> // Copyright (C) 2006-2015 SETCHIN Freelance Consulting // </copyright> // <author> // Vlad Setchin // </author> //------------------------------------------------------------------------ // EnvMan - The Open-Source Environment Variables Manager // Copyright (C) 2006-2015 SETCHIN Freelance Consulting // <http://www.setchinfc.com.au> // EnvMan Development Group: <mailto:[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. namespace SFC.EnvMan.VersionManager { using System; using System.Windows.Forms; /// <summary> /// Version Information Form /// </summary> public partial class FrmVersionInfo : Form { /// <summary> /// Initializes a new instance of the <see cref="FrmVersionInfo"/> class. /// </summary> public FrmVersionInfo() { this.InitializeComponent(); this.Text = "EnvMan - New version detected"; } /// <summary> /// Sets the message. /// </summary> /// <value>The message.</value> public string Message { set { this.lblMessage.Text = value; } } #if DEBUG /// <summary> /// Gets the OK Button. /// </summary> /// <value>The OK Button.</value> public Button BtnOk { get { return this.btnOK; } } /// <summary> /// Gets the Cancel Button. /// </summary> /// <value>The Cancel Button.</value> public Button BtnCancel { get { return this.btnCancel; } } #endif /// <summary> /// BTNs the click. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> #if DEBUG public void BtnClick(object sender, EventArgs e) #else private void BtnClick(object sender, EventArgs e) #endif { if (sender.Equals(this.btnCancel)) { this.DialogResult = DialogResult.Cancel; } else if (sender.Equals(this.btnOK)) { this.DialogResult = DialogResult.OK; } this.Hide(); } } }
gpl-3.0
sonertari/PFRE
src/Model/lib/Blank.php
1129
<?php /* * Copyright (C) 2004-2021 Soner Tari * * This file is part of PFRE. * * PFRE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PFRE 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 PFRE. If not, see <http://www.gnu.org/licenses/>. */ namespace Model; class Blank extends Rule { /** * Type definition for blank lines. * * We should never have a Blank object without 'blank' key, hence 'require'. */ protected $typedef= array( 'blank' => array( 'require' => TRUE, 'regex' => RE_BLANK, ), ); function parse($str) { $this->init(); $this->rule['blank']= $str; } function generate() { return $this->rule['blank']; } } ?>
gpl-3.0
AquaCore/AquaCore
application/themes/default/partial/header.php
2081
<?php use Aqua\Core\App; if(App::user()->loggedIn()) : ?> <div class="ac-header-user"> <span><?php echo __('account', 'welcome', htmlspecialchars(App::user()->account->displayName))?></span> <ul class="ac-user-options"> <li> <a href="<?php echo ac_build_url(array('path' => array( 'account' )))?>"> <?php echo __('account', 'my-account')?> </a> </li> <li> <a href="<?php echo ac_build_url(array('path' => array( 'account' ), 'action' => 'options'))?>"> <?php echo __('profile', 'preferences')?> </a> </li> <li> <a href="<?php echo ac_build_url(array('path' => array( 'account' ), 'action' => 'logout'))?>"> <?php echo __('login', 'logout')?> </a> </li> <?php if(App::user()->role()->hasPermission('view-admin-cp')) : ?> <li> <a href="<?php echo \Aqua\URL ?>/admin"> <?php echo __('application', 'cp-title')?> </a> </li> <?php endif; ?> </ul> </div> <?php else : ?> <div class="ac-header-login"> <form method="POST" action="<?php echo ac_build_url(array( 'protocol' => \Aqua\HTTPS || App::settings()->get('ssl', 0) >= 1 ? 'https://' : 'http://', 'path' => array( 'account' ), 'action' => 'login' ))?>"> <div class="ac-login-inputs"> <input type="text" name="username" placeholder="<?php echo __('profile', 'username') ?>"> <input type="password" name="password" placeholder="<?php echo __('profile', 'password') ?>"> </div> <input type="hidden" name="return_url" value="<?php echo App::request()->uri->url() ?>"> <input type="hidden" name="account_login" value="<?php echo App::user()->setToken('account_login')?>"> <input type="submit" value="OK" class="ac-login-submit"> </form> <ul class="ac-login-options"> <li> <a href="<?php echo ac_build_url(array('path' => array( 'account' ), 'action' => 'register'))?>"> <?php echo __('registration', 'register')?> </a> </li><li> <a href="<?php echo ac_build_url(array('path' => array( 'account' ), 'action' => 'recoverpw'))?>"> <?php echo __('reset-pw', 'recover-password')?> </a> </li> </ul> </div> <?php endif; ?>
gpl-3.0
wwwouaiebe/leaflet.TravelNotes
src/coreLib/GpxFactory.js
5677
/* Copyright - 2017 2021 - wwwouaiebe - Contact: https://www.ouaie.be/ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /* Changes: - v1.2.0: - created - v2.0.0: - Issue ♯147 : Add the travel name to gpx file name - v3.0.0: - Issue ♯175 : Private and static fields and methods are coming Doc reviewed 20210901 Tests ... */ /** @------------------------------------------------------------------------------------------------------------------------------ @file GpxFactory.js @copyright Copyright - 2017 2021 - wwwouaiebe - Contact: https://www.ouaie.be/ @license GNU General Public License @private @------------------------------------------------------------------------------------------------------------------------------ */ /** @------------------------------------------------------------------------------------------------------------------------------ @module coreLib @private @------------------------------------------------------------------------------------------------------------------------------ */ import theDataSearchEngine from '../data/DataSearchEngine.js'; import theTravelNotesData from '../data/TravelNotesData.js'; import theUtilities from '../UILib/Utilities.js'; const OUR_TAB_0 = '\n'; const OUR_TAB_1 = '\n\t'; const OUR_TAB_2 = '\n\t\t'; const OUR_TAB_3 = '\n\t\t\t'; /** @-------------------------------------------------------------------------------------------------------------------------- @class @classdesc This class is used to create gpx files @hideconstructor @-------------------------------------------------------------------------------------------------------------------------- */ class GpxFactory { #myGpxString = ''; #timeStamp = ''; #route = null; /** Creates the header of the gpx file @private */ #addHeader ( ) { // header this.#myGpxString = '<?xml version="1.0"?>' + OUR_TAB_0; this.#myGpxString += '<gpx xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' + 'xmlns:xsd="http://www.w3.org/2001/XMLSchema" ' + 'xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd" ' + 'version="1.1" creator="leaflet.TravelNotes">'; } /** Add the waypoints to the gpx file @private */ #addWayPoints ( ) { let wayPointsIterator = this.#route.wayPoints.iterator; while ( ! wayPointsIterator.done ) { this.#myGpxString += OUR_TAB_1 + '<wpt lat="' + wayPointsIterator.value.lat + '" lon="' + wayPointsIterator.value.lng + '" ' + this.#timeStamp + '/>'; } } /** Add the route to the gpx file @private */ #addRoute ( ) { this.#myGpxString += OUR_TAB_1 + '<rte>'; let maneuverIterator = this.#route.itinerary.maneuvers.iterator; while ( ! maneuverIterator.done ) { let wayPoint = this.#route.itinerary.itineraryPoints.getAt ( maneuverIterator.value.itineraryPointObjId ); let instruction = maneuverIterator.value.instruction .replaceAll ( /\u0027/g, '&apos;' ) .replaceAll ( /"/g, '&quot;' ) .replaceAll ( /</g, '&lt;' ) .replaceAll ( />/g, '&gt;' ); this.#myGpxString += OUR_TAB_2 + '<rtept lat="' + wayPoint.lat + '" lon="' + wayPoint.lng + '" ' + this.#timeStamp + 'desc="' + instruction + '" />'; } this.#myGpxString += OUR_TAB_1 + '</rte>'; } /** Add the track to the gpx file @private */ #addTrack ( ) { this.#myGpxString += OUR_TAB_1 + '<trk>'; this.#myGpxString += OUR_TAB_2 + '<trkseg>'; let itineraryPointsIterator = this.#route.itinerary.itineraryPoints.iterator; while ( ! itineraryPointsIterator.done ) { this.#myGpxString += OUR_TAB_3 + '<trkpt lat="' + itineraryPointsIterator.value.lat + '" lon="' + itineraryPointsIterator.value.lng + '" ' + this.#timeStamp + ' />'; } this.#myGpxString += OUR_TAB_2 + '</trkseg>'; this.#myGpxString += OUR_TAB_1 + '</trk>'; } /** Add the footer to the gpx file @private */ #addFooter ( ) { this.#myGpxString += OUR_TAB_0 + '</gpx>'; } /** Save the gpx string to a file @private */ #saveGpxToFile ( ) { let fileName = ( '' === theTravelNotesData.travel.name ? '' : theTravelNotesData.travel.name + ' - ' ) + this.#route.computedName; if ( '' === fileName ) { fileName = 'TravelNote'; } fileName += '.gpx'; theUtilities.saveFile ( fileName, this.#myGpxString, 'application/xml' ); } /* constructor */ constructor ( ) { Object.freeze ( this ); } /** Transform a route into a gpx file @param {!number} routeObjId the objId of the route to save in a gpx file */ routeToGpx ( routeObjId ) { this.#route = theDataSearchEngine.getRoute ( routeObjId ); if ( ! this.#route ) { return; } this.#timeStamp = 'time="' + new Date ( ).toISOString ( ) + '" '; this.#addHeader ( ); this.#addWayPoints ( ); this.#addRoute ( ); this.#addTrack ( ); this.#addFooter ( ); this.#saveGpxToFile ( ); } } export default GpxFactory; /* --- End of GpxFactory.js file ------------------------------------------------------------------------------------------------- */
gpl-3.0
ntenhoeve/Introspect-Apps
FolderSynch/src/main/java/nth/foldersynch/dom/device/DeviceService.java
666
package nth.foldersynch.dom.device; import java.util.List; import nth.reflect.fw.layer5provider.reflection.behavior.parameterfactory.ParameterFactory; public class DeviceService { private DeviceRepository deviceRepository; public DeviceService(DeviceRepository deviceRepository) { this.deviceRepository = deviceRepository; } public List<Device> allDevices() { List<Device> devices = deviceRepository.getAll(); return devices; } public void modifyDevice(Device device) { deviceRepository.persist(device); } @ParameterFactory public void createDevice(Device device) { deviceRepository.persist(device); } }
gpl-3.0
barotto/IBMulator
src/hardware/devices/dma.cpp
22320
/* * Copyright (C) 2002-2014 The Bochs Project * Copyright (C) 2015-2020 Marco Bortolin * * This file is part of IBMulator. * * IBMulator is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * IBMulator 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 IBMulator. If not, see <http://www.gnu.org/licenses/>. */ #include "ibmulator.h" #include "machine.h" #include "dma.h" #include "hardware/devices.h" #include "hardware/cpu.h" #include <cstring> #define DMA_MODE_DEMAND 0 #define DMA_MODE_SINGLE 1 #define DMA_MODE_BLOCK 2 #define DMA_MODE_CASCADE 3 IODEVICE_PORTS(DMA) = { { 0x00, 0x0F, PORT_8BIT|PORT_RW }, { 0x80, 0x8F, PORT_8BIT|PORT_RW }, { 0xC0, 0xDE, PORT_8BIT|PORT_RW } }; DMA::DMA(Devices* _dev) : IODevice(_dev) { } DMA::~DMA() { } void DMA::install() { IODevice::install(); for(int i=0; i<8; i++) { m_channels[i].used = false; m_channels[i].device = ""; } m_channels[4].used = true; m_channels[4].device = "cascade"; PDEBUGF(LOG_V2, LOG_DMA, "channel 4 used by cascade\n"); } void DMA::config_changed() { //nothing to do. //no config dependent params } void DMA::reset(unsigned type) { if(type==MACHINE_POWER_ON) { memset(&m_s, 0, sizeof(m_s)); //everything is memsetted to 0, so is the following code relevant? unsigned c, i, j; for(i=0; i < 2; i++) { for(j=0; j < 4; j++) { m_s.dma[i].DRQ[j] = 0; m_s.dma[i].DACK[j] = 0; } } m_s.HLDA = false; m_s.TC = false; for(i=0; i<2; i++) { for(c=0; c<4; c++) { m_s.dma[i].chan[c].mode.mode_type = 0; // demand mode m_s.dma[i].chan[c].mode.address_decrement = 0; // address increment m_s.dma[i].chan[c].mode.autoinit_enable = 0; // autoinit disable m_s.dma[i].chan[c].mode.transfer_type = 0; // verify m_s.dma[i].chan[c].base_address = 0; m_s.dma[i].chan[c].current_address = 0; m_s.dma[i].chan[c].base_count = 0; m_s.dma[i].chan[c].current_count = 0; m_s.dma[i].chan[c].page_reg = 0; } } } //HARD reset and POWER ON reset_controller(0); reset_controller(1); } void DMA::save_state(StateBuf &_state) { PINFOF(LOG_V1, LOG_DMA, "saving state\n"); StateHeader h; h.name = name(); h.data_size = sizeof(m_s); _state.write(&m_s,h); } void DMA::restore_state(StateBuf &_state) { PINFOF(LOG_V1, LOG_DMA, "restoring state\n"); StateHeader h; h.name = name(); h.data_size = sizeof(m_s); _state.read(&m_s,h); } void DMA::reset_controller(unsigned num) { m_s.dma[num].mask[0] = 1; m_s.dma[num].mask[1] = 1; m_s.dma[num].mask[2] = 1; m_s.dma[num].mask[3] = 1; m_s.dma[num].ctrl_disabled = 0; m_s.dma[num].command_reg = 0; m_s.dma[num].status_reg = 0; m_s.dma[num].flip_flop = 0; } // index to find channel from register number (only [0],[1],[2],[6] used) uint8_t channelindex[7] = {2, 3, 1, 0, 0, 0, 0}; uint16_t DMA::read(uint16_t address, unsigned /*io_len*/) { uint8_t retval; uint8_t channel; bool ma_sl = (address >= 0xc0); switch (address) { case 0x00: /* DMA-1 current address, channel 0 */ case 0x02: /* DMA-1 current address, channel 1 */ case 0x04: /* DMA-1 current address, channel 2 */ case 0x06: /* DMA-1 current address, channel 3 */ case 0xc0: /* DMA-2 current address, channel 0 */ case 0xc4: /* DMA-2 current address, channel 1 */ case 0xc8: /* DMA-2 current address, channel 2 */ case 0xcc: /* DMA-2 current address, channel 3 */ channel = (address >> (1 + ma_sl)) & 0x03; if(m_s.dma[ma_sl].flip_flop==0) { m_s.dma[ma_sl].flip_flop = !m_s.dma[ma_sl].flip_flop; retval = (m_s.dma[ma_sl].chan[channel].current_address & 0xff); } else { m_s.dma[ma_sl].flip_flop = !m_s.dma[ma_sl].flip_flop; retval = (m_s.dma[ma_sl].chan[channel].current_address >> 8); } break; case 0x01: /* DMA-1 current count, channel 0 */ case 0x03: /* DMA-1 current count, channel 1 */ case 0x05: /* DMA-1 current count, channel 2 */ case 0x07: /* DMA-1 current count, channel 3 */ case 0xc2: /* DMA-2 current count, channel 0 */ case 0xc6: /* DMA-2 current count, channel 1 */ case 0xca: /* DMA-2 current count, channel 2 */ case 0xce: /* DMA-2 current count, channel 3 */ channel = (address >> (1 + ma_sl)) & 0x03; if(m_s.dma[ma_sl].flip_flop==0) { m_s.dma[ma_sl].flip_flop = !m_s.dma[ma_sl].flip_flop; retval = (m_s.dma[ma_sl].chan[channel].current_count & 0xff); } else { m_s.dma[ma_sl].flip_flop = !m_s.dma[ma_sl].flip_flop; retval = (m_s.dma[ma_sl].chan[channel].current_count >> 8); } break; case 0x08: // DMA-1 Status Register case 0xd0: // DMA-2 Status Register // bit 7: 1 = channel 3 request // bit 6: 1 = channel 2 request // bit 5: 1 = channel 1 request // bit 4: 1 = channel 0 request // bit 3: 1 = channel 3 has reached terminal count // bit 2: 1 = channel 2 has reached terminal count // bit 1: 1 = channel 1 has reached terminal count // bit 0: 1 = channel 0 has reached terminal count // reading this register clears lower 4 bits (hold flags) retval = m_s.dma[ma_sl].status_reg; m_s.dma[ma_sl].status_reg &= 0xf0; break; case 0x0d: // DMA-1: temporary register case 0xda: // DMA-2: temporary register // only used for memory-to-memory transfers // write to 0x0d / 0xda clears temporary register // read of temporary register always returns 0 retval = 0; break; case 0x81: // DMA-1 page register, channel 2 case 0x82: // DMA-1 page register, channel 3 case 0x83: // DMA-1 page register, channel 1 case 0x87: // DMA-1 page register, channel 0 channel = channelindex[address - 0x81]; retval = m_s.dma[0].chan[channel].page_reg; break; case 0x89: // DMA-2 page register, channel 2 case 0x8a: // DMA-2 page register, channel 3 case 0x8b: // DMA-2 page register, channel 1 case 0x8f: // DMA-2 page register, channel 0 channel = channelindex[address - 0x89]; retval = m_s.dma[1].chan[channel].page_reg; break; case 0x80: case 0x84: case 0x85: case 0x86: case 0x88: case 0x8c: case 0x8d: case 0x8e: // extra page registers, unused retval = m_s.ext_page_reg[address & 0x0f]; break; case 0x0f: // DMA-1: undocumented: read all mask bits case 0xde: // DMA-2: undocumented: read all mask bits retval = m_s.dma[ma_sl].mask[0] | (m_s.dma[ma_sl].mask[1] << 1) | (m_s.dma[ma_sl].mask[2] << 2) | (m_s.dma[ma_sl].mask[3] << 3); retval = (0xf0 | retval); break; default: PDEBUGF(LOG_V0, LOG_DMA, "unhandled read from port 0x%04X!\n", address); return ~0; } PDEBUGF(LOG_V2, LOG_DMA, "read 0x%03X -> 0x%04X\n", address, retval); return retval; } void DMA::write(uint16_t address, uint16_t value, unsigned /*io_len*/) { uint8_t set_mask_bit; uint8_t channel; PDEBUGF(LOG_V2, LOG_DMA, "write 0x%03X <- 0x%04X ", address, value); bool ma_sl = (address >= 0xc0); switch (address) { case 0x00: case 0x02: case 0x04: case 0x06: case 0xc0: case 0xc4: case 0xc8: case 0xcc: channel = (address >> (1 + ma_sl)) & 0x03; if(m_s.dma[ma_sl].flip_flop==0) { /* 1st byte */ m_s.dma[ma_sl].chan[channel].base_address = value; m_s.dma[ma_sl].chan[channel].current_address = value; PDEBUGF(LOG_V2, LOG_DMA, "DMA-%d: ch.%d addr (first byte)\n", ma_sl+1, channel); } else { /* 2nd byte */ m_s.dma[ma_sl].chan[channel].base_address |= (value << 8); m_s.dma[ma_sl].chan[channel].current_address |= (value << 8); PDEBUGF(LOG_V2, LOG_DMA, "DMA-%d: ch.%d addr base = %04x curr = %04x\n", ma_sl+1, channel, m_s.dma[ma_sl].chan[channel].base_address, m_s.dma[ma_sl].chan[channel].current_address); } m_s.dma[ma_sl].flip_flop = !m_s.dma[ma_sl].flip_flop; break; case 0x01: case 0x03: case 0x05: case 0x07: case 0xc2: case 0xc6: case 0xca: case 0xce: channel = (address >> (1 + ma_sl)) & 0x03; if(m_s.dma[ma_sl].flip_flop==0) { /* 1st byte */ m_s.dma[ma_sl].chan[channel].base_count = value; m_s.dma[ma_sl].chan[channel].current_count = value; PDEBUGF(LOG_V2, LOG_DMA, "DMA-%d: ch.%d count (first byte)\n", ma_sl+1, channel); } else { /* 2nd byte */ m_s.dma[ma_sl].chan[channel].base_count |= (value << 8); m_s.dma[ma_sl].chan[channel].current_count |= (value << 8); PDEBUGF(LOG_V2, LOG_DMA, "DMA-%d: ch.%d count base = %04x (%d bytes), curr = %04x\n", ma_sl+1, channel, m_s.dma[ma_sl].chan[channel].base_count, int(m_s.dma[ma_sl].chan[channel].base_count)+1, m_s.dma[ma_sl].chan[channel].current_count); } m_s.dma[ma_sl].flip_flop = !m_s.dma[ma_sl].flip_flop; break; case 0x08: /* DMA-1: command register */ case 0xd0: /* DMA-2: command register */ m_s.dma[ma_sl].command_reg = value; m_s.dma[ma_sl].ctrl_disabled = (value >> 2) & 0x01; control_HRQ(ma_sl); PDEBUGF(LOG_V2, LOG_DMA, " cmd\n"); if((value & 0xfb) != 0x00) { PERRF(LOG_DMA, "DMA command value 0x%02x not supported!\n", value); } break; case 0x09: // DMA-1: request register case 0xd2: // DMA-2: request register channel = value & 0x03; // note: write to 0x0d / 0xda clears this register if(value & 0x04) { // set request bit m_s.dma[ma_sl].status_reg |= (1 << (channel+4)); PDEBUGF(LOG_V2, LOG_DMA, "DMA-%d: set request bit for ch.%u\n", ma_sl+1, channel); } else { // clear request bit m_s.dma[ma_sl].status_reg &= ~(1 << (channel+4)); PDEBUGF(LOG_V2, LOG_DMA, "DMA-%d: cleared request bit for ch.%u\n", ma_sl+1, channel); } control_HRQ(ma_sl); break; case 0x0a: case 0xd4: set_mask_bit = value & 0x04; channel = value & 0x03; m_s.dma[ma_sl].mask[channel] = (set_mask_bit > 0); PDEBUGF(LOG_V2, LOG_DMA, "DMA-%d: set_mask_bit=%u, ch.=%u, mask now=%02xh\n", ma_sl+1, set_mask_bit, channel, m_s.dma[ma_sl].mask[channel]); control_HRQ(ma_sl); break; case 0x0b: /* DMA-1 mode register */ case 0xd6: /* DMA-2 mode register */ channel = value & 0x03; m_s.dma[ma_sl].chan[channel].mode.mode_type = (value >> 6) & 0x03; m_s.dma[ma_sl].chan[channel].mode.address_decrement = (value >> 5) & 0x01; m_s.dma[ma_sl].chan[channel].mode.autoinit_enable = (value >> 4) & 0x01; m_s.dma[ma_sl].chan[channel].mode.transfer_type = (value >> 2) & 0x03; PDEBUGF(LOG_V2, LOG_DMA, "DMA-%d: mode reg[%u]: mode=%u, dec=%u, autoinit=%u, txtype=%u (%s)\n", ma_sl+1, channel, m_s.dma[ma_sl].chan[channel].mode.mode_type, m_s.dma[ma_sl].chan[channel].mode.address_decrement, m_s.dma[ma_sl].chan[channel].mode.autoinit_enable, m_s.dma[ma_sl].chan[channel].mode.transfer_type, m_s.dma[ma_sl].chan[channel].mode.transfer_type==0?"verify": (m_s.dma[ma_sl].chan[channel].mode.transfer_type==1?"write": (m_s.dma[ma_sl].chan[channel].mode.transfer_type==2?"read": "undefined"))); break; case 0x0c: /* DMA-1 clear byte flip/flop */ case 0xd8: /* DMA-2 clear byte flip/flop */ PDEBUGF(LOG_V2, LOG_DMA, "DMA-%d: clear flip/flop\n", ma_sl+1); m_s.dma[ma_sl].flip_flop = 0; break; case 0x0d: // DMA-1: master clear case 0xda: // DMA-2: master clear PDEBUGF(LOG_V2, LOG_DMA, "DMA-%d: master clear\n", ma_sl+1); // writing any value to this port resets DMA controller 1 / 2 // same action as a hardware reset // mask register is set (chan 0..3 disabled) // command, status, request, temporary, and byte flip-flop are all cleared reset_controller(ma_sl); break; case 0x0e: // DMA-1: clear mask register case 0xdc: // DMA-2: clear mask register PDEBUGF(LOG_V2, LOG_DMA, "DMA-%d: clear mask reg\n", ma_sl+1); m_s.dma[ma_sl].mask[0] = 0; m_s.dma[ma_sl].mask[1] = 0; m_s.dma[ma_sl].mask[2] = 0; m_s.dma[ma_sl].mask[3] = 0; control_HRQ(ma_sl); break; case 0x0f: // DMA-1: write all mask bits case 0xde: // DMA-2: write all mask bits PDEBUGF(LOG_V2, LOG_DMA, "DMA-%d: write all mask bits\n", ma_sl+1); m_s.dma[ma_sl].mask[0] = value & 0x01; value >>= 1; m_s.dma[ma_sl].mask[1] = value & 0x01; value >>= 1; m_s.dma[ma_sl].mask[2] = value & 0x01; value >>= 1; m_s.dma[ma_sl].mask[3] = value & 0x01; control_HRQ(ma_sl); break; case 0x81: /* DMA-1 page register, channel 2 */ case 0x82: /* DMA-1 page register, channel 3 */ case 0x83: /* DMA-1 page register, channel 1 */ case 0x87: /* DMA-1 page register, channel 0 */ /* address bits A16-A23 for DMA channel */ channel = channelindex[address - 0x81]; m_s.dma[0].chan[channel].page_reg = value; PDEBUGF(LOG_V2, LOG_DMA, "DMA-1: page reg %d = %02x\n", channel, value); break; case 0x89: /* DMA-2 page register, channel 2 */ case 0x8a: /* DMA-2 page register, channel 3 */ case 0x8b: /* DMA-2 page register, channel 1 */ case 0x8f: /* DMA-2 page register, channel 0 */ /* address bits A16-A23 for DMA channel */ channel = channelindex[address - 0x89]; m_s.dma[1].chan[channel].page_reg = value; PDEBUGF(LOG_V2, LOG_DMA, "DMA-2: page reg %d = %02x\n", channel + 4, value); break; case 0x80: case 0x84: case 0x85: case 0x86: case 0x88: case 0x8c: case 0x8d: case 0x8e: PDEBUGF(LOG_V2, LOG_DMA, "extra page reg (unused)\n"); m_s.ext_page_reg[address & 0x0f] = value; break; default: PDEBUGF(LOG_V0, LOG_DMA, "unhandled write to port 0x%04X!\n", address); break; } } void DMA::set_DRQ(unsigned channel, bool val) { uint32_t dma_base, dma_roof; uint8_t ma_sl = (channel > 3) ? 1 : 0; PDEBUGF(LOG_V2, LOG_DMA, "DMA-%d: DRQ ch.=%d %s\n", ma_sl+1, channel, val?"on":"off"); if(channel > 7) { PERRF(LOG_DMA, "set_DRQ() channel > 7\n"); return; } m_s.dma[ma_sl].DRQ[channel & 0x03] = val; if(!m_channels[channel].used) { PERRF(LOG_DMA, "set_DRQ(): channel %d not connected to device\n", channel); return; } channel &= 0x03; if(!val) { // clear bit in status reg m_s.dma[ma_sl].status_reg &= ~(1 << (channel+4)); control_HRQ(ma_sl); return; } m_s.dma[ma_sl].status_reg |= (1 << (channel+4)); if((m_s.dma[ma_sl].chan[channel].mode.mode_type != DMA_MODE_SINGLE) && (m_s.dma[ma_sl].chan[channel].mode.mode_type != DMA_MODE_DEMAND) && (m_s.dma[ma_sl].chan[channel].mode.mode_type != DMA_MODE_CASCADE)) { PERRF(LOG_DMA, "set_DRQ: mode_type(%02x) not handled\n", m_s.dma[ma_sl].chan[channel].mode.mode_type); return; } dma_base = (m_s.dma[ma_sl].chan[channel].page_reg << 16) | (m_s.dma[ma_sl].chan[channel].base_address << ma_sl); if(m_s.dma[ma_sl].chan[channel].mode.address_decrement) { dma_roof = dma_base - (m_s.dma[ma_sl].chan[channel].base_count << ma_sl); } else { dma_roof = dma_base + (m_s.dma[ma_sl].chan[channel].base_count << ma_sl); } if(channel!=0 && ((dma_base & (0x7fff0000 << ma_sl)) != (dma_roof & (0x7fff0000 << ma_sl)))) { PERRF(LOG_DMA, "dma_base = 0x%08x\n", dma_base); PERRF(LOG_DMA, "dma_base_count = 0x%08x\n", m_s.dma[ma_sl].chan[channel].base_count); PERRF(LOG_DMA, "dma_roof = 0x%08x\n", dma_roof); PERRF(LOG_DMA, "request outside %dk boundary\n", 64 << ma_sl); return; } control_HRQ(ma_sl); } bool DMA::get_DRQ(uint channel) { uint8_t ma_sl = (channel > 3)?1:0; return m_s.dma[ma_sl].DRQ[channel & 0x03]; } void DMA::control_HRQ(uint8_t ma_sl) { unsigned channel; // do nothing if controller is disabled if(m_s.dma[ma_sl].ctrl_disabled) return; // deassert HRQ if no DRQ is pending if((m_s.dma[ma_sl].status_reg & 0xf0) == 0) { if(ma_sl) { g_cpu.set_HRQ(false); } else { set_DRQ(4, 0); } return; } // find highest priority channel for(channel=0; channel<4; channel++) { if((m_s.dma[ma_sl].status_reg & (1 << (channel+4))) && (m_s.dma[ma_sl].mask[channel]==0)) { if(ma_sl) { // assert Hold ReQuest line to CPU g_cpu.set_HRQ(true); } else { // send DRQ to cascade channel of the master set_DRQ(4, 1); } break; } } } void DMA::raise_HLDA(void) { unsigned channel; uint32_t phy_addr; uint8_t ma_sl = 0; uint32_t maxlen; uint16_t len = 1; uint8_t buffer[DMA_BUFFER_SIZE]; m_s.HLDA = true; // find highest priority channel for(channel=0; channel<4; channel++) { if((m_s.dma[1].status_reg & (1 << (channel+4))) && (m_s.dma[1].mask[channel]==0)) { ma_sl = 1; break; } } if(channel == 0) { // master cascade channel m_s.dma[1].DACK[0] = 1; for(channel=0; channel<4; channel++) { if((m_s.dma[0].status_reg & (1 << (channel+4))) && (m_s.dma[0].mask[channel]==0)) { ma_sl = 0; break; } } } if(channel >= 4) { // wait till they're unmasked return; } phy_addr = (m_s.dma[ma_sl].chan[channel].page_reg << 16) | (m_s.dma[ma_sl].chan[channel].current_address << ma_sl); if(!m_s.dma[ma_sl].chan[channel].mode.address_decrement) { maxlen = (uint32_t(m_s.dma[ma_sl].chan[channel].current_count) + 1) << ma_sl; m_s.TC = (maxlen <= DMA_BUFFER_SIZE); if(maxlen > DMA_BUFFER_SIZE) { maxlen = DMA_BUFFER_SIZE; } } else { // address decrement mode, 1 byte at a time m_s.TC = (m_s.dma[ma_sl].chan[channel].current_count == 0); maxlen = 1 << ma_sl; } if(m_s.dma[ma_sl].chan[channel].mode.transfer_type == 1) { // write // DMA controlled xfer of bytes from I/O to Memory PDEBUGF(LOG_V2, LOG_DMA, "DMA-%d: writing to memory at %08x max %d bytes fomr ch.%d (count=%04x)\n", ma_sl+1, phy_addr, maxlen, channel, m_s.dma[ma_sl].chan[channel].current_count); if(!ma_sl) { if(m_h[channel].dmaWrite8) { len = m_h[channel].dmaWrite8(buffer, maxlen); } else { PERRF(LOG_DMA, "no dmaWrite handler for channel %u\n", channel); } g_memory.DMA_write(phy_addr, len, buffer); } else { if(m_h[channel].dmaWrite16) { len = m_h[channel].dmaWrite16((uint16_t*)buffer, maxlen / 2); } else { PERRF(LOG_DMA, "no dmaWrite handler for channel %u\n", channel); } g_memory.DMA_write(phy_addr, len, buffer); } } else if(m_s.dma[ma_sl].chan[channel].mode.transfer_type == 2) { // read // DMA controlled xfer of bytes from Memory to I/O PDEBUGF(LOG_V2, LOG_DMA, "DMA-%d: reading from memory at %08x max. %d bytes to ch.%d (count=%04x)\n", ma_sl+1, phy_addr, maxlen, channel, m_s.dma[ma_sl].chan[channel].current_count); if(!ma_sl) { g_memory.DMA_read(phy_addr, maxlen, buffer); if(m_h[channel].dmaRead8) { len = m_h[channel].dmaRead8(buffer, maxlen); } } else { g_memory.DMA_read(phy_addr, maxlen, buffer); if(m_h[channel].dmaRead16){ len = m_h[channel].dmaRead16((uint16_t*)buffer, maxlen / 2); } } } else if(m_s.dma[ma_sl].chan[channel].mode.transfer_type == 0) { // verify PDEBUGF(LOG_V2, LOG_DMA, "DMA-%d: verify max. %d bytes, ch.%d\n", ma_sl+1, maxlen, channel); if(!ma_sl) { if(m_h[channel].dmaWrite8) { len = m_h[channel].dmaWrite8(buffer, 1); } else { PERRF(LOG_DMA, "no dmaWrite handler for channel %u\n", channel); } } else { if(m_h[channel].dmaWrite16) { len = m_h[channel].dmaWrite16((uint16_t*)buffer, 1); } else { PERRF(LOG_DMA, "no dmaWrite handler for channel %u\n", channel); } } } else { PERRF(LOG_DMA, "hlda: transfer_type 3 is undefined\n"); } m_s.dma[ma_sl].DACK[channel] = 1; // check for expiration of count, so we can signal TC and DACK(n) // at the same time. if(!m_s.dma[ma_sl].chan[channel].mode.address_decrement) { m_s.dma[ma_sl].chan[channel].current_address += len; } else { // address decrement mode m_s.dma[ma_sl].chan[channel].current_address--; } m_s.dma[ma_sl].chan[channel].current_count -= len; if(m_s.dma[ma_sl].chan[channel].current_count == 0xffff) { // count expired, done with transfer // assert TC, deassert HRQ & DACK(n) lines m_s.dma[ma_sl].status_reg |= (1 << channel); // hold TC in status reg if(m_s.dma[ma_sl].chan[channel].mode.autoinit_enable == 0) { // set mask bit if not in autoinit mode m_s.dma[ma_sl].mask[channel] = 1; } else { // count expired, but in autoinit mode // reload count and base address m_s.dma[ma_sl].chan[channel].current_address = m_s.dma[ma_sl].chan[channel].base_address; m_s.dma[ma_sl].chan[channel].current_count = m_s.dma[ma_sl].chan[channel].base_count; } m_s.TC = false; // clear TC, adapter card already notified m_s.HLDA = false; g_cpu.set_HRQ(false); // clear HRQ to CPU m_s.dma[ma_sl].DACK[channel] = 0; // clear DACK to adapter card if(!ma_sl) { set_DRQ(4, 0); // clear DRQ to cascade m_s.dma[1].DACK[0] = 0; // clear DACK to cascade } } } void DMA::register_8bit_channel(unsigned channel, dma8_fun_t dmaRead, dma8_fun_t dmaWrite, const char *name) { if(channel > 3) { PERRF(LOG_DMA, "register_8bit_channel: invalid channel number(%u)\n", channel); return; } if(m_channels[channel].used) { PERRF(LOG_DMA, "register_8bit_channel: channel(%u) already in use\n", channel); return; } PDEBUGF(LOG_V1, LOG_DMA, "channel %u used by '%s'\n", channel, name); m_h[channel].dmaRead8 = dmaRead; m_h[channel].dmaWrite8 = dmaWrite; m_channels[channel].used = true; m_channels[channel].device = name; } void DMA::register_16bit_channel(unsigned channel, dma16_fun_t dmaRead, dma16_fun_t dmaWrite, const char *name) { if((channel < 4) || (channel > 7)) { PERRF(LOG_DMA, "register_16bit_channel: invalid channel number(%u)\n", channel); return; } if(m_channels[channel].used) { PERRF(LOG_DMA, "register_16bit_channel: channel(%u) already in use\n", channel); return; } PDEBUGF(LOG_V1, LOG_DMA, "channel %u used by %s", channel, name); m_h[channel&0x03].dmaRead16 = dmaRead; m_h[channel&0x03].dmaWrite16 = dmaWrite; m_channels[channel].used = true; m_channels[channel].device = name; } void DMA::unregister_channel(unsigned channel) { assert(channel < 8); m_channels[channel].used = false; m_channels[channel].device = ""; PDEBUGF(LOG_V1, LOG_DMA, "channel %u no longer used\n", channel); } std::string DMA::get_device_name(unsigned _channel) { assert(_channel < 8); return m_channels[_channel].device; }
gpl-3.0
mchaffotte/geo-application
buildSrc/src/main/java/fr/chaffotm/data/io/validation/AlreadyUsed.java
639
package fr.chaffotm.data.io.validation; import javax.validation.Constraint; import javax.validation.Payload; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.RetentionPolicy.RUNTIME; @Constraint(validatedBy = AlreadyUsedValidator.class) @Target({ FIELD, METHOD }) @Retention(RUNTIME) @Documented public @interface AlreadyUsed { String message() default "already used by another one"; Class<?>[] groups() default { }; Class<? extends Payload>[] payload() default { }; }
gpl-3.0
TeamLocker/Server
TeamLocker_Server/protobufs/Libsodium_pb2.py
3197
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: protobufs/Libsodium.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor.FileDescriptor( name='protobufs/Libsodium.proto', package='', syntax='proto3', serialized_pb=_b('\n\x19protobufs/Libsodium.proto\"R\n\rLibsodiumItem\x12\x0c\n\x04\x64\x61ta\x18\x01 \x01(\x0c\x12\r\n\x05nonce\x18\x02 \x01(\x0c\x12\x11\n\tops_limit\x18\x03 \x01(\x03\x12\x11\n\tmem_limit\x18\x04 \x01(\x03\x42,\n*me.camerongray.teamlocker.client.protobufsb\x06proto3') ) _LIBSODIUMITEM = _descriptor.Descriptor( name='LibsodiumItem', full_name='LibsodiumItem', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='data', full_name='LibsodiumItem.data', index=0, number=1, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='nonce', full_name='LibsodiumItem.nonce', index=1, number=2, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='ops_limit', full_name='LibsodiumItem.ops_limit', index=2, number=3, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='mem_limit', full_name='LibsodiumItem.mem_limit', index=3, number=4, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=29, serialized_end=111, ) DESCRIPTOR.message_types_by_name['LibsodiumItem'] = _LIBSODIUMITEM _sym_db.RegisterFileDescriptor(DESCRIPTOR) LibsodiumItem = _reflection.GeneratedProtocolMessageType('LibsodiumItem', (_message.Message,), dict( DESCRIPTOR = _LIBSODIUMITEM, __module__ = 'protobufs.Libsodium_pb2' # @@protoc_insertion_point(class_scope:LibsodiumItem) )) _sym_db.RegisterMessage(LibsodiumItem) DESCRIPTOR.has_options = True DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n*me.camerongray.teamlocker.client.protobufs')) # @@protoc_insertion_point(module_scope)
gpl-3.0
marxoft/cutetube2
app/src/maemo5/dailymotion/dailymotioncommentdialog.cpp
2910
/* * Copyright (C) 2016 Stuart Howarth <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * 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, see <http://www.gnu.org/licenses/>. */ #include "dailymotioncommentdialog.h" #include <QTextEdit> #include <QLabel> #include <QDialogButtonBox> #include <QPushButton> #include <QGridLayout> #include <QMessageBox> DailymotionCommentDialog::DailymotionCommentDialog(const QString &videoId, QWidget *parent) : Dialog(parent), m_comment(0), m_id(videoId), m_edit(new QTextEdit(this)), m_buttonBox(new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Vertical, this)), m_layout(new QGridLayout(this)) { setWindowTitle(tr("Add comment")); setMinimumHeight(360); m_buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); m_layout->addWidget(new QLabel(tr("Comment"), this), 0, 0); m_layout->addWidget(m_edit, 1, 0); m_layout->addWidget(m_buttonBox, 1, 1, 2, 1); m_layout->setRowStretch(1, 1); connect(m_edit, SIGNAL(textChanged()), this, SLOT(onCommentChanged())); connect(m_buttonBox, SIGNAL(accepted()), this, SLOT(addComment())); connect(m_buttonBox, SIGNAL(rejected()), this, SLOT(reject())); } void DailymotionCommentDialog::addComment() { if (isBusy()) { return; } if (!m_comment) { m_comment = new DailymotionComment(this); connect(m_comment, SIGNAL(statusChanged(QDailymotion::ResourcesRequest::Status)), this, SLOT(onCommentStatusChanged(QDailymotion::ResourcesRequest::Status))); } QVariantMap comment; comment["video.id"] = m_id; comment["message"] = m_edit->toPlainText(); m_comment->loadComment(comment); m_comment->addComment(); } void DailymotionCommentDialog::onCommentChanged() { m_buttonBox->button(QDialogButtonBox::Ok)->setEnabled(!m_edit->toPlainText().isEmpty()); } void DailymotionCommentDialog::onCommentStatusChanged(QDailymotion::ResourcesRequest::Status status) { switch (status) { case QDailymotion::ResourcesRequest::Loading: showProgressIndicator(); return; case QDailymotion::ResourcesRequest::Ready: accept(); return; case QDailymotion::ResourcesRequest::Failed: QMessageBox::critical(this, tr("Error"), m_comment->errorString()); break; default: break; } hideProgressIndicator(); }
gpl-3.0
sosilent/euca
clc/modules/msgs/src/main/java/com/eucalyptus/bootstrap/Provides.java
3915
/******************************************************************************* *Copyright (c) 2009 Eucalyptus Systems, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, only version 3 of the License. * * * This file is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * * Please contact Eucalyptus Systems, Inc., 130 Castilian * Dr., Goleta, CA 93101 USA or visit <http://www.eucalyptus.com/licenses/> * if you need additional information or have any questions. * * This file may incorporate work covered under the following copyright and * permission notice: * * Software License Agreement (BSD License) * * Copyright (c) 2008, Regents of the University of California * All rights reserved. * * Redistribution and use of this software in source and binary forms, with * or without modification, are permitted provided that the following * conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. USERS OF * THIS SOFTWARE ACKNOWLEDGE THE POSSIBLE PRESENCE OF OTHER OPEN SOURCE * LICENSED MATERIAL, COPYRIGHTED MATERIAL OR PATENTED MATERIAL IN THIS * SOFTWARE, AND IF ANY SUCH MATERIAL IS DISCOVERED THE PARTY DISCOVERING * IT MAY INFORM DR. RICH WOLSKI AT THE UNIVERSITY OF CALIFORNIA, SANTA * BARBARA WHO WILL THEN ASCERTAIN THE MOST APPROPRIATE REMEDY, WHICH IN * THE REGENTS' DISCRETION MAY INCLUDE, WITHOUT LIMITATION, REPLACEMENT * OF THE CODE SO IDENTIFIED, LICENSING OF THE CODE SO IDENTIFIED, OR * WITHDRAWAL OF THE CODE CAPABILITY TO THE EXTENT NEEDED TO COMPLY WITH * ANY SUCH LICENSES OR RIGHTS. ******************************************************************************* * @author chris grzegorczyk <[email protected]> */ package com.eucalyptus.bootstrap; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.eucalyptus.component.ComponentId; /** * Only used for logging at the moment. Will be replaced with something more useful forthwith. * deprecated cause it sucks. */ @Target({ ElementType.TYPE, ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) //@Deprecated public @interface Provides { Class value( ) default ComponentId.class; }
gpl-3.0
SoapboxRaceWorld/soapbox-race-core
src/main/java/com/soapboxrace/jaxb/http/UserSettings.java
7531
/* * This file is part of the Soapbox Race World core source code. * If you use any of this code for third-party purposes, please provide attribution. * Copyright (c) 2020. */ package com.soapboxrace.jaxb.http; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for User_Settings complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="User_Settings"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="CarCacheAgeLimit" type="{http://www.w3.org/2001/XMLSchema}int"/> * &lt;element name="IsRaceNowEnabled" type="{http://www.w3.org/2001/XMLSchema}boolean"/> * &lt;element name="MaxCarCacheSize" type="{http://www.w3.org/2001/XMLSchema}int"/> * &lt;element name="MinRaceNowLevel" type="{http://www.w3.org/2001/XMLSchema}int"/> * &lt;element name="VoipAvailable" type="{http://www.w3.org/2001/XMLSchema}boolean"/> * &lt;element name="activatedHolidaySceneryGroups" type="{}ArrayOfString" minOccurs="0"/> * &lt;element name="activeHolidayIds" type="{}ArrayOfLong" minOccurs="0"/> * &lt;element name="disactivatedHolidaySceneryGroups" type="{}ArrayOfString" minOccurs="0"/> * &lt;element name="firstTimeLogin" type="{http://www.w3.org/2001/XMLSchema}boolean"/> * &lt;element name="maxLevel" type="{http://www.w3.org/2001/XMLSchema}int"/> * &lt;element name="starterPackApplied" type="{http://www.w3.org/2001/XMLSchema}boolean"/> * &lt;element name="userId" type="{http://www.w3.org/2001/XMLSchema}long"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "User_Settings", propOrder = { "carCacheAgeLimit", "isRaceNowEnabled", "maxCarCacheSize", "minRaceNowLevel", "voipAvailable", "activatedHolidaySceneryGroups", "activeHolidayIds", "disactivatedHolidaySceneryGroups", "firstTimeLogin", "maxLevel", "starterPackApplied", "userId" }) public class UserSettings { @XmlElement(name = "CarCacheAgeLimit") protected int carCacheAgeLimit; @XmlElement(name = "IsRaceNowEnabled") protected boolean isRaceNowEnabled; @XmlElement(name = "MaxCarCacheSize") protected int maxCarCacheSize; @XmlElement(name = "MinRaceNowLevel") protected int minRaceNowLevel; @XmlElement(name = "VoipAvailable") protected boolean voipAvailable; protected ArrayOfString activatedHolidaySceneryGroups; protected ArrayOfLong activeHolidayIds; protected ArrayOfString disactivatedHolidaySceneryGroups; protected boolean firstTimeLogin; protected int maxLevel; protected boolean starterPackApplied; protected long userId; /** * Gets the value of the carCacheAgeLimit property. */ public int getCarCacheAgeLimit() { return carCacheAgeLimit; } /** * Sets the value of the carCacheAgeLimit property. */ public void setCarCacheAgeLimit(int value) { this.carCacheAgeLimit = value; } /** * Gets the value of the isRaceNowEnabled property. */ public boolean isIsRaceNowEnabled() { return isRaceNowEnabled; } /** * Sets the value of the isRaceNowEnabled property. */ public void setIsRaceNowEnabled(boolean value) { this.isRaceNowEnabled = value; } /** * Gets the value of the maxCarCacheSize property. */ public int getMaxCarCacheSize() { return maxCarCacheSize; } /** * Sets the value of the maxCarCacheSize property. */ public void setMaxCarCacheSize(int value) { this.maxCarCacheSize = value; } /** * Gets the value of the minRaceNowLevel property. */ public int getMinRaceNowLevel() { return minRaceNowLevel; } /** * Sets the value of the minRaceNowLevel property. */ public void setMinRaceNowLevel(int value) { this.minRaceNowLevel = value; } /** * Gets the value of the voipAvailable property. */ public boolean isVoipAvailable() { return voipAvailable; } /** * Sets the value of the voipAvailable property. */ public void setVoipAvailable(boolean value) { this.voipAvailable = value; } /** * Gets the value of the activatedHolidaySceneryGroups property. * * @return possible object is * {@link ArrayOfString } */ public ArrayOfString getActivatedHolidaySceneryGroups() { return activatedHolidaySceneryGroups; } /** * Sets the value of the activatedHolidaySceneryGroups property. * * @param value allowed object is * {@link ArrayOfString } */ public void setActivatedHolidaySceneryGroups(ArrayOfString value) { this.activatedHolidaySceneryGroups = value; } /** * Gets the value of the activeHolidayIds property. * * @return possible object is * {@link ArrayOfLong } */ public ArrayOfLong getActiveHolidayIds() { return activeHolidayIds; } /** * Sets the value of the activeHolidayIds property. * * @param value allowed object is * {@link ArrayOfLong } */ public void setActiveHolidayIds(ArrayOfLong value) { this.activeHolidayIds = value; } /** * Gets the value of the disactivatedHolidaySceneryGroups property. * * @return possible object is * {@link ArrayOfString } */ public ArrayOfString getDisactivatedHolidaySceneryGroups() { return disactivatedHolidaySceneryGroups; } /** * Sets the value of the disactivatedHolidaySceneryGroups property. * * @param value allowed object is * {@link ArrayOfString } */ public void setDisactivatedHolidaySceneryGroups(ArrayOfString value) { this.disactivatedHolidaySceneryGroups = value; } /** * Gets the value of the firstTimeLogin property. */ public boolean isFirstTimeLogin() { return firstTimeLogin; } /** * Sets the value of the firstTimeLogin property. */ public void setFirstTimeLogin(boolean value) { this.firstTimeLogin = value; } /** * Gets the value of the maxLevel property. */ public int getMaxLevel() { return maxLevel; } /** * Sets the value of the maxLevel property. */ public void setMaxLevel(int value) { this.maxLevel = value; } /** * Gets the value of the starterPackApplied property. */ public boolean isStarterPackApplied() { return starterPackApplied; } /** * Sets the value of the starterPackApplied property. */ public void setStarterPackApplied(boolean value) { this.starterPackApplied = value; } /** * Gets the value of the userId property. */ public long getUserId() { return userId; } /** * Sets the value of the userId property. */ public void setUserId(long value) { this.userId = value; } }
gpl-3.0
luisgustavossdd/TBD
framework/PodSixNet/Server.py
3815
#!/usr/bin/python # -*- coding: utf-8 -*- import socket import sys from async import poll, asyncore from Channel import Channel class Server(asyncore.dispatcher): channelClass = Channel def __init__(self, channelClass=None, localaddr=("127.0.0.1", 31425), listeners=15): if channelClass: self.channelClass = channelClass self._map = {} self.channels = [] asyncore.dispatcher.__init__(self, map=self._map) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) self.set_reuse_addr() self.bind(localaddr) self.listen(listeners) def handle_accept(self): try: (conn, addr) = self.accept() except socket.error: print 'warning: server accept() threw an exception' return except TypeError: print 'warning: server accept() threw EWOULDBLOCK' return self.channels.append(self.channelClass(conn, addr, self, self._map)) (self.channels)[-1].Send({"action": "connected"}) if hasattr(self, "Connected"): self.Connected((self.channels)[-1], addr) def Pump(self): [c.Pump() for c in self.channels] poll(map=self._map) if __name__ == "__main__": import unittest class ServerTestCase(unittest.TestCase): testdata = {"action": "hello", "data": {"a": 321, "b": [2, 3, 4], "c": ["afw", "wafF", "aa", "weEEW", "w234r"], "d": ["x"] * \ 256}} def setUp(self): print "ServerTestCase" print "--------------" class ServerChannel(Channel): def Network_hello(self, data): print "*Server* ran test method for 'hello' action" print "*Server* received:", data self._server.received = data class EndPointChannel(Channel): connected = False def Connected(self): print "*EndPoint* Connected()" def Network_connected(self, data): self.connected = True print "*EndPoint* Network_connected(", data, ")" print "*EndPoint* initiating send" self.Send(ServerTestCase.testdata) class TestServer(Server): connected = False received = None def Connected(self, channel, addr): self.connected = True print "*Server* Connected() ", channel, \ "connected on", addr self.server = TestServer(channelClass=ServerChannel) sender = asyncore.dispatcher(map=self.server._map) sender.create_socket(socket.AF_INET, socket.SOCK_STREAM) sender.connect(("localhost", 31425)) self.outgoing = EndPointChannel(sender, map=self.server._map) def runTest(self): from time import sleep print "*** polling for half a second" for x in range(250): self.server.Pump() self.outgoing.Pump() if self.server.received: self.failUnless(self.server.received == self.testdata) self.server.received = None sleep(0.001) self.failUnless(self.server.connected == True, "Server is not connected") self.failUnless(self.outgoing.connected == True, "Outgoing socket is not connected") def tearDown(self): pass del self.server del self.outgoing unittest.main()
gpl-3.0
robottitto/lab
js/jsdoc/js/main.js
674
'use strict'; /** Class representing a point. */ class Point { /** * Create a point. * @param {number} x - The x value. * @param {number} y - The y value. */ constructor (x, y) { this.x = x; this.y = y; } /** * Get the x value. * @return {number} The x value. */ getX () { // ... } /** * Get the y value. * @return {number} The y value. */ getY () { // ... } /** * Convert a string containing two comma-separated numbers into a point. * @param {string} str - The string containing two comma-separated numbers. * @return {Point} A Point object. */ static fromString (str) { // ... } }
gpl-3.0
randomize/VimConfig
tags/unity5/UnityEditor/GizmoType.cs
512
namespace UnityEditor { using System; public enum GizmoType { Active = 8, InSelectionHierarchy = 0x10, NonSelected = 0x20, NotInSelectionHierarchy = 2, [Obsolete("Use NotInSelectionHierarchy instead (UnityUpgradable) -> NotInSelectionHierarchy")] NotSelected = -127, Pickable = 1, Selected = 4, [Obsolete("Use InSelectionHierarchy instead (UnityUpgradable) -> InSelectionHierarchy")] SelectedOrChild = -127 } }
gpl-3.0
ojengwa/ThinkUp
webapp/plugins/facebook/model/class.FacebookPlugin.php
14729
<?php /** * * ThinkUp/webapp/plugins/facebook/model/class.FacebookPlugin.php * * Copyright (c) 2009-2013 Gina Trapani, Mark Wilkie * * LICENSE: * * This file is part of ThinkUp (http://thinkup.com). * * ThinkUp is free software: you can redistribute it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any * later version. * * ThinkUp 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 ThinkUp. If not, see * <http://www.gnu.org/licenses/>. * * * @author Gina Trapani <ginatrapani[at]gmail[dot]com> * @author Mark Wilkie <mark[at]bitterpill[dot]org> * @license http://www.gnu.org/licenses/gpl.html * @copyright 2009-2013 Gina Trapani, Mark Wilkie */ class FacebookPlugin extends Plugin implements CrawlerPlugin, DashboardPlugin, PostDetailPlugin { public function __construct($vals=null) { parent::__construct($vals); $this->folder_name = 'facebook'; $this->addRequiredSetting('facebook_app_id'); $this->addRequiredSetting('facebook_api_secret'); } public function activate() { } public function deactivate() { //Pause all active Facebook user profile and page instances $instance_dao = DAOFactory::getDAO('InstanceDAO'); $facebook_instances = $instance_dao->getAllInstances("DESC", true, "facebook"); foreach ($facebook_instances as $ti) { $instance_dao->setActive($ti->id, false); } $facebook_instances = $instance_dao->getAllInstances("DESC", true, "facebook page"); foreach ($facebook_instances as $ti) { $instance_dao->setActive($ti->id, false); } } public function crawl() { $logger = Logger::getInstance(); $config = Config::getInstance(); $instance_dao = DAOFactory::getDAO('InstanceDAO'); $owner_instance_dao = DAOFactory::getDAO('OwnerInstanceDAO'); $owner_dao = DAOFactory::getDAO('OwnerDAO'); $plugin_option_dao = DAOFactory::GetDAO('PluginOptionDAO'); $options = $plugin_option_dao->getOptionsHash('facebook', true); //get cached $max_crawl_time = isset($options['max_crawl_time']) ? $options['max_crawl_time']->option_value : 20; //convert to seconds $max_crawl_time = $max_crawl_time * 60; $current_owner = $owner_dao->getByEmail(Session::getLoggedInUser()); //crawl Facebook user profiles and pages $profiles = $instance_dao->getActiveInstancesStalestFirstForOwnerByNetworkNoAuthError($current_owner, 'facebook'); $pages = $instance_dao->getActiveInstancesStalestFirstForOwnerByNetworkNoAuthError($current_owner, 'facebook page'); $instances = array_merge($profiles, $pages); foreach ($instances as $instance) { $logger->setUsername(ucwords($instance->network) . ' | '.$instance->network_username ); $logger->logUserSuccess("Starting to collect data for ".$instance->network_username."'s ". ucwords($instance->network), __METHOD__.','.__LINE__); $tokens = $owner_instance_dao->getOAuthTokens($instance->id); $access_token = $tokens['oauth_access_token']; $instance_dao->updateLastRun($instance->id); $facebook_crawler = new FacebookCrawler($instance, $access_token, $max_crawl_time); $dashboard_module_cacher = new DashboardModuleCacher($instance); try { $facebook_crawler->fetchPostsAndReplies(); } catch (APIOAuthException $e) { $logger->logUserError(get_class($e).": ".$e->getMessage(), __METHOD__.','.__LINE__); //Don't send reauth email if it's app-level API rate limting //https://developers.facebook.com/docs/reference/ads-api/api-rate-limiting/#applimit if ( strpos($e->getMessage(), 'Application request limit reached') === false //Don't send reauth email if Facebook is saying the app should try again later && strpos($e->getMessage(), 'Please retry your request later.') === false) { //The access token is invalid, save in owner_instances table $owner_instance_dao->setAuthErrorByTokens($instance->id, $access_token, '', $e->getMessage()); //Send email alert //Get owner by auth tokens first, then send to that person $owner_email_to_notify = $owner_instance_dao->getOwnerEmailByInstanceTokens($instance->id, $access_token, ''); $email_attempt = $this->sendInvalidOAuthEmailAlert($owner_email_to_notify, $instance->network_username); if ($email_attempt) { $logger->logUserInfo('Sent reauth email to '.$owner_email_to_notify, __METHOD__.','.__LINE__); } else { $logger->logInfo('Didn\'t send reauth email to '.$owner_email_to_notify, __METHOD__.','.__LINE__); } } else { $logger->logInfo('Facebook API returned an error: '.$e->getMessage(). ' Do nothing now and try again later', __METHOD__.','.__LINE__); } } catch (Exception $e) { $logger->logUserError(get_class($e).": ".$e->getMessage(), __METHOD__.','.__LINE__); } $dashboard_module_cacher->cacheDashboardModules(); $instance_dao->save($facebook_crawler->instance, 0, $logger); Reporter::reportVersion($instance); $logger->logUserSuccess("Finished collecting data for ".$instance->network_username."'s ". ucwords($instance->network), __METHOD__.','.__LINE__); } } /** * Send user email alert about invalid OAuth tokens, at most one message per week. * In test mode, this will only write the message body to a file in the application data directory. * @param str $email * @param str $username * @return bool Whether or not email was sent */ private function sendInvalidOAuthEmailAlert($email, $username) { //Determine whether or not an email about invalid tokens was sent in the past 7 days $should_send_email = true; $option_dao = DAOFactory::getDAO('OptionDAO'); $plugin_dao = DAOFactory::getDAO('PluginDAO'); $plugin_id = $plugin_dao->getPluginId('facebook'); $last_email_timestamp = $option_dao->getOptionByName(OptionDAO::PLUGIN_OPTIONS.'-'.$plugin_id, 'invalid_oauth_email_sent_timestamp'); if (isset($last_email_timestamp)) { //option exists, a message was sent //a message was sent in the past week if ($last_email_timestamp->option_value > strtotime('-1 week') ) { $should_send_email = false; } else { $option_dao->updateOption($last_email_timestamp->option_id, time()); } } else { $option_dao->insertOption(OptionDAO::PLUGIN_OPTIONS.'-'.$plugin_id, 'invalid_oauth_email_sent_timestamp', time()); } if ($should_send_email) { $mailer_view_mgr = new ViewManager(); $mailer_view_mgr->caching=false; $mailer_view_mgr->assign('thinkup_site_url', Utils::getApplicationURL()); $mailer_view_mgr->assign('email', $email ); $mailer_view_mgr->assign('faceboook_user_name', $username); $message = $mailer_view_mgr->fetch(Utils::getPluginViewDirectory('facebook').'_email.invalidtoken.tpl'); Mailer::mail($email, "Please re-authorize ThinkUp to access ". $username. " on Facebook", $message); return true; } else { return false; } } public function renderConfiguration($owner) { $controller = new FacebookPluginConfigurationController($owner); return $controller->go(); } public function renderInstanceConfiguration($owner, $instance_username, $instance_network) { return ''; } public function getDashboardMenuItems($instance) { $menus = array(); $posts_data_tpl = Utils::getPluginViewDirectory('facebook').'posts.tpl'; $posts_menu_item = new MenuItem("Posts", "Post insights", $posts_data_tpl); $posts_menu_ds_1 = new Dataset("all_posts", 'PostDAO', "getAllPosts", array($instance->network_user_id, $instance->network, 5, "#page_number#"), 'getAllPostsIterator', array($instance->network_user_id, $instance->network, GridController::getMaxRows()), false ); $posts_menu_item->addDataset($posts_menu_ds_1); $posts_menu_ds_2 = new Dataset("most_replied_to", 'PostDAO', "getMostRepliedToPosts", array($instance->network_user_id, $instance->network, 5, '#page_number#')); $posts_menu_item->addDataset($posts_menu_ds_2); $posts_menu_ds_3 = new Dataset("most_liked", 'PostDAO', "getMostFavedPosts", array($instance->network_user_id, $instance->network, 5, '#page_number#')); $posts_menu_item->addDataset($posts_menu_ds_3); $posts_menu_ds_4 = new Dataset("inquiries", 'PostDAO', "getAllQuestionPosts", array($instance->network_user_id, $instance->network, 5, "#page_number#")); $posts_menu_item->addDataset($posts_menu_ds_4); $posts_menu_ds_5 = new Dataset("wallposts", 'PostDAO', "getPostsToUser", array($instance->network_user_id, $instance->network, 5, '#page_number#', !Session::isLoggedIn()), 'getPostsToUserIterator', array($instance->network_user_id, $instance->network, GridController::getMaxRows())); $posts_menu_item->addDataset($posts_menu_ds_5); $menus['posts'] = $posts_menu_item; $friends_data_tpl = Utils::getPluginViewDirectory('facebook').'friends.tpl'; $friend_fan_menu_title = $instance->network == 'facebook page'?'Fans':'Friends'; $friends_menu_item = new MenuItem($friend_fan_menu_title, "Friends insights", $friends_data_tpl); $friends_menu_ds_2 = new Dataset("follower_count_history_by_day", 'CountHistoryDAO', 'getHistory', array($instance->network_user_id, $instance->network, 'DAY', 15)); $friends_menu_item->addDataset($friends_menu_ds_2); $friends_menu_ds_3 = new Dataset("follower_count_history_by_week", 'CountHistoryDAO', 'getHistory', array($instance->network_user_id, $instance->network, 'WEEK', 15)); $friends_menu_item->addDataset($friends_menu_ds_3); $friends_menu_ds_4 = new Dataset("follower_count_history_by_month", 'CountHistoryDAO', 'getHistory', array($instance->network_user_id, $instance->network, 'MONTH', 11)); $friends_menu_item->addDataset($friends_menu_ds_4); $menus['friends'] = $friends_menu_item; $fb_data_tpl = Utils::getPluginViewDirectory('facebook').'facebook.inline.view.tpl'; //All tab $alltab = new MenuItem("All posts", 'All your status updates', $fb_data_tpl, 'posts' ); $alltabds = new Dataset("all_facebook_posts", 'PostDAO', "getAllPosts", array($instance->network_user_id, $instance->network, 15, "#page_number#"), 'getAllPostsIterator', array($instance->network_user_id, $instance->network, GridController::getMaxRows()), false); $alltabds->addHelp('userguide/listings/facebook/dashboard_all_facebook_posts'); $alltab->addDataset($alltabds); $menus["posts-all"] = $alltab; // Most replied-to tab $mrttab = new MenuItem("Most replied-to", "Posts with most replies", $fb_data_tpl, 'posts' ); $mrttabds = new Dataset("most_replied_to_posts", 'PostDAO', "getMostRepliedToPosts", array($instance->network_user_id, $instance->network, 15, '#page_number#')); $mrttabds->addHelp('userguide/listings/facebook/dashboard_mostreplies'); $mrttab->addDataset($mrttabds); $menus["posts-mostreplies"] = $mrttab; // Most liked posts $mltab = new MenuItem("Most liked", "Posts with most likes", $fb_data_tpl, 'posts' ); $mltabds = new Dataset("most_replied_to_posts", 'PostDAO', "getMostFavedPosts", array($instance->network_user_id, $instance->network, 15, '#page_number#')); $mltabds->addHelp('userguide/listings/facebook/dashboard_mostlikes'); $mltab->addDataset($mltabds); $menus["posts-mostlikes"] = $mltab; //Questions tab $qtab = new MenuItem("Inquiries", "Inquiries, or posts with a question mark in them", $fb_data_tpl, 'posts' ); $qtabds = new Dataset("all_facebook_posts", 'PostDAO', "getAllQuestionPosts", array($instance->network_user_id, $instance->network, 15, "#page_number#")); $qtabds->addHelp('userguide/listings/facebook/dashboard_questions'); $qtab->addDataset($qtabds); $menus["posts-questions"] = $qtab; // Wall Posts $messagestab = new MenuItem("Posts On Your Wall", "Posts to your wall by other users", $fb_data_tpl, 'posts' ); $messagestabds = new Dataset("messages_to_you", 'PostDAO', "getPostsToUser", array($instance->network_user_id, $instance->network, 15, '#page_number#', !Session::isLoggedIn()), 'getPostsToUserIterator', array($instance->network_user_id, $instance->network, GridController::getMaxRows())); $messagestabds->addHelp('userguide/listings/facebook/dashboard-wallposts'); $messagestab->addDataset($messagestabds); $menus["posts-toyou"] = $messagestab; return $menus; } public function getPostDetailMenuItems($post) { $facebook_data_tpl = Utils::getPluginViewDirectory('facebook').'facebook.post.likes.tpl'; $menus = array(); if ($post->network == 'facebook' || $post->network == 'facebook page') { $likes_menu_item = new MenuItem("Likes", "Those who liked this post", $facebook_data_tpl); //if not logged in, show only public fav'd info $liked_dataset = new Dataset("likes", 'FavoritePostDAO', "getUsersWhoFavedPost", array($post->post_id, $post->network, !Session::isLoggedIn()) ); $likes_menu_item->addDataset($liked_dataset); $menus['likes'] = $likes_menu_item; } return $menus; } }
gpl-3.0
Archerpe/aries
src/main/java/com/andy/design_patterns/command/remote/CeilingFanOffCommand.java
297
package com.andy.design_patterns.command.remote; public class CeilingFanOffCommand implements Command { CeilingFan ceilingFan; public CeilingFanOffCommand(CeilingFan ceilingFan) { this.ceilingFan = ceilingFan; } public void execute() { ceilingFan.off(); } }
gpl-3.0
EXEM-OSS/Flamingo2
flamingo2-web/src/main/webapp/resources/app/view/designer/canvas/events/onCanvasRender.js
8007
/* * Copyright (C) 2011 Flamingo Project (http://www.cloudine.io). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ Ext.define('Flamingo2.view.designer.canvas.events.onCanvasRender', { extend: 'Ext.app.ViewController', /** * 캔버스 패널 Render 핸들러 : * - 내부 SVG 그래프 캔버스 인스턴스를 생성한다. * - 노드의 DropZone 을 설정하고 Drop 되었을때 노드가 드로잉 되도록 한다. * - 노드를 더블클릭 하였을때 프라퍼티 설정창이 팝업되도록 한다. * * @param {Ext.Component} component * @param {Object} eOpts The options object passed to Ext.util.Observable.addListener. */ onCanvasRender: function (component, eOpts) { var canvas = query('canvas') var getPropertyWindow = Ext.create('Flamingo2.view.designer.canvas.events.onCanvasActionController')._getPropertyWindow; // 내부 SVG 그래프 캔버스 인스턴스를 생성 canvas.graph = new OG.Canvas(canvas.body.dom, [1024, 768], 'white'); // OpenGraph 디폴트 스타일 설정 //canvas.graph._CONFIG.DEFAULT_STYLE.EDGE = { // 'stroke': 'blue', // 'stroke-width': 1, // 'stroke-opacity': 1, // 'edge-type': 'straight', // FIXME : 선의 유형 // 'edge-direction': 'c c', // 'arrow-start': 'none', // 'arrow-end': 'classic-wide-long', // 'stroke-dasharray': '', // 'label-position': 'center' //}; // OpenGraph 기능 활성화 여부 canvas.graph._CONFIG.MOVABLE_.EDGE = false; canvas.graph._CONFIG.SELF_CONNECTABLE = false; canvas.graph._CONFIG.CONNECT_CLONEABLE = false; canvas.graph._CONFIG.RESIZABLE = false; canvas.graph._CONFIG.LABEL_EDITABLE_.GEOM = false; canvas.graph._CONFIG.LABEL_EDITABLE_.TEXT = false; canvas.graph._CONFIG.LABEL_EDITABLE_.HTML = false; canvas.graph._CONFIG.LABEL_EDITABLE_.IMAGE = false; canvas.graph._CONFIG.LABEL_EDITABLE_.EDGE = true; canvas.graph._CONFIG.LABEL_EDITABLE_.GROUP = false; canvas.graph._CONFIG.ENABLE_HOTKEY_DELETE = true; canvas.graph._CONFIG.ENABLE_HOTKEY_CTRL_A = false; canvas.graph._CONFIG.ENABLE_HOTKEY_CTRL_C = false; canvas.graph._CONFIG.ENABLE_HOTKEY_CTRL_V = false; canvas.graph._CONFIG.ENABLE_HOTKEY_CTRL_G = false; canvas.graph._CONFIG.ENABLE_HOTKEY_CTRL_U = false; canvas.graph._CONFIG.ENABLE_HOTKEY_ARROW = true; canvas.graph._CONFIG.ENABLE_HOTKEY_SHIFT_ARROW = true; // 디폴트 시작, 끝 노드 드로잉 Ext.create('Flamingo2.view.designer.canvas.events._drawDefaultNodeController').run(); // 노드의 DropZone 설정 canvas.dropZone = Ext.create('Ext.dd.DropZone', canvas.getEl(), { dropAllowed: 'canvas_contents', notifyOver: function (dragSource, event, data) { return Ext.dd.DropTarget.prototype.dropAllowed; }, notifyDrop: function (dragSource, event, data) { var nodeMeta = Ext.clone(data.nodeMeta); var shapeElement; var properties = Ext.clone(nodeMeta.defaultProperties) || {}; var identifier = nodeMeta.identifier; var isValidated = false; if (nodeMeta.type == 'ROLE') { identifier = 'SHELL_ROLE' } else if (nodeMeta.type == 'NODE') { identifier = 'SHELL_NODE'; properties.node_display = nodeMeta.name; properties.node_from = 'node'; nodeMeta.name = 'CHEF NODE : ' + nodeMeta.name; isValidated = true; } var shape = Ext.create('Flamingo2.' + identifier, nodeMeta.icon, nodeMeta.name); shapeElement = canvas.graph.drawShape([event.browserEvent.layerX, event.browserEvent.layerY], shape, [60, 60]); canvas.graph.getRenderer().drawLabel(shapeElement, nodeMeta.name); canvas.graph.setCustomData(shapeElement, { metadata: nodeMeta, properties: properties, isValidated: isValidated }); canvas.setwireEvent(shapeElement); return true; } }); // onDrawShape Listener canvas.graph.onDrawShape(function (event, element) { // 노드를 더블클릭 하였을때 프라퍼티 설정창 팝업 Ext.get(element.id).on('dblclick', function () { var propertyWindow = getPropertyWindow(element); if (propertyWindow) { propertyWindow.show(); } }); }); // onBeforeConnectShape -> fireEvent canvas.nodeBeforeConnect canvas.graph.onBeforeConnectShape(function (event, edgeElement, fromElement, toElement) { return canvas.fireEvent('nodeBeforeConnect', canvas, event, edgeElement, fromElement, toElement); }); // onBeforeRemoveShape -> fireEvent canvas.nodeBeforeRemove canvas.graph.onBeforeRemoveShape(function (event, element) { return canvas.fireEvent('nodeBeforeRemove', canvas, event, element); }); // onConnectShape -> fireEvent canvas.nodeConnect canvas.graph.onConnectShape(function (event, edgeElement, fromElement, toElement) { canvas.fireEvent('nodeConnect', canvas, event, edgeElement, fromElement, toElement); }); // onDisconnectShape -> fireEvent canvas.nodeDisconnected canvas.graph.onDisconnectShape(function (event, edgeElement, fromElement, toElement) { canvas.fireEvent('nodeDisconnected', canvas, event, edgeElement, fromElement, toElement); }); // onBeforeLabelChange -> fireEvent canvas.beforeLabelChange canvas.graph.onBeforeLabelChange(function (event, element, afterText, beforeText) { return canvas.fireEvent('beforeLabelChange', canvas, event, element, afterText, beforeText); }); // onLabelChanged -> fireEvent canvas.labelChanged canvas.graph.onLabelChanged(function (event, element, afterText, beforeText) { canvas.fireEvent('labelChanged', canvas, event, element, afterText, beforeText); }); }, /** * 캔버스 패널 Resize 핸들러 : 내부 SVG 그래프 캔버스 사이즈를 조정한다. * * @param {Ext.Component} component * @param {Number} width * @param {Number} height * @param {Number} oldWidth * @param {Number} oldHeight * @param {Object} eOpts The options object passed to Ext.util.Observable.addListener. */ onCanvasResize: function (component, width, height, oldWidth, oldHeight, eOpts) { var graphBBox = component.graph.getRootBBox(); // 내부 SVG 그래프 캔버스 사이즈가 외부 캔버스 패널 사이즈보다 작을 경우 if (graphBBox.width < width || graphBBox.height < height) { component.graph.setCanvasSize([ graphBBox.width < width ? width : graphBBox.width, graphBBox.height < height ? width : graphBBox.height ]); } } });
gpl-3.0
tuttarealstep/MyCMS
src/App/Content/Theme/simple/languages/en_US.php
5461
<?php /* *\ | MyCMS | \* */ //LINGUA : ENGLISH $language = [ 'Lorem ipsum' => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.', //NEW HOME 'comment' => 'Comment', 'comments' => 'Comments', 'read_more' => 'Read More...', 'show_more' => 'Show more post', 'blog_post_last_comments' => 'All comments:', //PAGE NAME '404_error_page_name' => 'Error 404', 'maintenance_page_name' => 'Maintenance Break!', //Page ELEMENT //Error 'error_email_password' => "The email or password are incorrect", 'error_name' => "Name is too short or too long", 'error_surname' => "Surname too short, or too long", 'error_email' => "Invalid Email", 'error_password' => "Password too short", 'error_email_in_use' => "This email address is already registered to another user", //header 'header_login/registration_button' => 'Login/Register', 'header_logout_a' => 'Logout', 'header_admin_a' => 'Admin Panel', //footer 'footer_powered' => 'Site based on', //404 '404_title' => 'Error Page Not Found!', '404_description' => 'The page you are looking for could not be more helpful!', //maintenance 'maintenance_title' => 'We are in maintenance', 'maintenance_title_description' => 'The site will be back soon!', //HOME -MYCMS 'home_title' => 'Home', 'my_cms_welcome_h1' => 'Thank you for using MyCMS!', 'my_cms_welcome_description' => 'Thank you for downloading MyCMS, this is your website, you can edit quickly and at your leisure thanks to bootstrap and functions of MyCMS.', //blog 'blog_page_name' => 'Blog', 'blog_archive_page_name' => 'Articles Archive', 'blog_title_archive' => 'Here are all the articles:', 'blog_a_no_posts' => 'There are no articles', 'blog_created_by' => 'Created by:', 'blog_category' => 'Category:', 'blog_posted' => 'Posted on', 'blog_post_title_comment' => 'Leave a Comment (Max 250):', 'blog_post_comment_button_send' => 'Send', 'blog_post_last_25_comments' => 'The last 25 comments:', 'blog_post_0_comments' => 'No comment', 'blog_all_posts_in_category' => 'All articles posted in the category:', 'blog_you_search' => 'You looked:', 'blog_all_posts_by_author' => 'All articles posted by:', //blog-bar 'blog-bar_search' => 'Search in the Blog', 'blog-bar_popular_categories' => 'Popular categories', //login 'login_page_title' => 'Login', 'login_h2_register_title' => 'New User?', 'login_register_description' => 'Register on our site, completely free, you can comment and access are private site.', 'login_button_register' => 'Sign In', 'login_h2_login_title' => 'Registered User', 'login_login_description' => 'Already registered? Login!', 'login_login_email' => 'Email Address *', 'login_login_password' => 'Password *', 'login_login_button' => 'Login', 'login_login_remember' => 'Remember', //registration 'registration_page_title' => 'Registration', 'registration_obbligatory' => 'Required Fields', 'registration_name' => 'Name', 'registration_surname' => 'Surname', 'registration_email' => 'Email', 'registration_password' => 'Password', 'registration_info' => ' ', 'registration_info_description' => ' ', 'registration_insert' => 'Insert', 'registration_button_register' => 'Register', //PRIVACY & INFO 'site_privacy_info' => ' ', //EU COOKIES POLICY 'eu_cookie_policy_message' => "In this Cookies are used to allow for the safe and efficient website. By using this site you agree to the use of cookies.", 'eu_cookie_policy_close_message' => 'Close', 'eu_cookie_policy_learn_more_message' => 'Read More', 'customizer_theme_colors' => 'Colors', 'posts' => 'Posts', 'customizer_theme_settings' => 'Theme Settings', 'customizer_theme_reset_settings' => 'Reset Settings', 'customizer_theme_select_header_img_settings' => 'Select header image', 'customizer_theme_home_page_select' => 'Select page for the home', 'customizer_theme_home_page_select_simple_articles' => 'Blog(SimpleThemeHomePage)' ];
gpl-3.0
RomanaBW/BwPostman
src/administrator/components/com_bwpostman/src/View/Mailinglist/HtmlView.php
6681
<?php /** * BwPostman Newsletter Component * * BwPostman single mailinglists view for backend. * * @version %%version_number%% * @package BwPostman-Admin * @author Romana Boldt * @copyright (C) %%copyright_year%% Boldt Webservice <[email protected]> * @support https://www.boldt-webservice.de/en/forum-en/forum/bwpostman.html * @license GNU/GPL, see LICENSE.txt * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ namespace BoldtWebservice\Component\BwPostman\Administrator\View\Mailinglist; // Check to ensure this file is included in Joomla! defined('_JEXEC') or die('Restricted access'); use Exception; use Joomla\CMS\Factory; use Joomla\CMS\Uri\Uri; use Joomla\CMS\Toolbar\Toolbar; use Joomla\CMS\Toolbar\ToolbarHelper; use Joomla\CMS\Language\Text; use Joomla\CMS\Environment\Browser; use BoldtWebservice\Component\BwPostman\Administrator\Helper\BwPostmanHelper; use BoldtWebservice\Component\BwPostman\Administrator\Helper\BwPostmanHTMLHelper; use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView; /** * BwPostman Mailinglist View * * @package BwPostman-Admin * * @subpackage Mailinglists * * @since 0.9.1 */ class HtmlView extends BaseHtmlView { /** * property to hold form data * * @var array $form * * @since 0.9.1 */ protected $form; /** * property to hold selected item * * @var object $item * * @since 0.9.1 */ protected $item; /** * property to hold state * * @var array|object $state * * @since 0.9.1 */ protected $state; /** * property to hold queue entries property * * @var boolean $queueEntries * * @since 0.9.1 */ public $queueEntries; /** * property to hold request url * * @var object $request_url * * @since 0.9.1 */ protected $request_url; /** * property to hold template * * @var object $template * * @since 0.9.1 */ public $template; /** * property to hold permissions as array * * @var array $permissions * * @since 2.0.0 */ public $permissions; /** * Execute and display a template script. * * @param string $tpl The name of the template file to parse; automatically searches through the template paths. * * @return HtmlView A string if successful, otherwise a JError object. * * @throws Exception * * @since 0.9.1 */ public function display($tpl = null): HtmlView { $app = Factory::getApplication(); $template = $app->getTemplate(); $uri = Uri::getInstance(); $uri_string = str_replace('&', '&amp;', $uri->toString()); $this->permissions = $app->getUserState('com_bwpm.permissions'); if (!$this->permissions['view']['mailinglist']) { $app->enqueueMessage(Text::sprintf('COM_BWPOSTMAN_VIEW_NOT_ALLOWED', Text::_('COM_BWPOSTMAN_MLS')), 'error'); $app->redirect('index.php?option=com_bwpostman'); } $app->setUserState('com_bwpostman.edit.mailinglist.id', $app->input->getInt('id', 0)); //check for queue entries $this->queueEntries = BwPostmanHelper::checkQueueEntries(); $this->form = $this->get('Form'); $this->item = $this->get('Item'); $this->state = $this->get('State'); // Save a reference into view $this->request_url = $uri_string; $this->template = $template; $this->addToolbar(); // Call parent display parent::display($tpl); return $this; } /** * Add the page title, styles and toolbar. * * @throws Exception * * @since 0.9.1 */ protected function addToolbar() { $app = Factory::getApplication(); $app->input->set('hidemainmenu', true); $uri = Uri::getInstance(); $userId = $app->getIdentity()->get('id'); // Get the toolbar object instance $toolbar = Toolbar::getInstance(); $this->document->getWebAssetManager()->useScript('com_bwpostman.admin-bwpm_mailinglist'); // Set toolbar title depending on the state of the item: Is it a new item? --> Create; Is it an existing record? --> Edit $isNew = ($this->item->id < 1); // Set toolbar title and items $checkedOut = !($this->item->checked_out == 0 || $this->item->checked_out == $userId); // For new records, check the create permission. if ($isNew && BwPostmanHelper::canAdd('mailinglist')) { ToolbarHelper::title(Text::_('COM_BWPOSTMAN_ML_DETAILS') . ': <small>[ ' . Text::_('NEW') . ' ]</small>', 'plus'); $toolbar->apply('mailinglist.apply'); $saveGroup = $toolbar->dropdownButton('save-group'); $saveGroup->configure( function (Toolbar $childBar) { $childBar->save('mailinglist.save'); $childBar->save2new('mailinglist.save2new'); } ); $toolbar->cancel('mailinglist.cancel', 'JTOOLBAR_CANCEL'); } else { // Can't save the record if it's checked out. if (!$checkedOut) { // Since it's an existing record, check the edit permission, or fall back to edit own if the owner. if (BwPostmanHelper::canEdit('mailinglist')) { ToolbarHelper::title(Text::_('COM_BWPOSTMAN_ML_DETAILS') . ': <small>[ ' . Text::_('EDIT') . ' ]</small>', 'edit'); $toolbar->apply('mailinglist.apply'); $saveGroup = $toolbar->dropdownButton('save-group'); $saveGroup->configure( function (Toolbar $childBar) { $childBar->save('mailinglist.save'); $childBar->save2new('mailinglist.save2new'); $childBar->save2copy('mailinglist.save2copy'); } ); $toolbar->cancel('mailinglist.cancel'); } } } $backlink = ''; if (key_exists('HTTP_REFERER', $_SERVER)) { $backlink = $app->input->server->get('HTTP_REFERER', '', ''); } $siteURL = $uri->base() . 'index.php?option=com_bwpostman&view=bwpostman'; // If we came from the cover page we will show a back-button if ($backlink == $siteURL) { $toolbar->back(); } $toolbar->addButtonPath(JPATH_COMPONENT_ADMINISTRATOR . '/libraries/toolbar'); $manualButton = BwPostmanHTMLHelper::getManualButton('mailinglist'); $forumButton = BwPostmanHTMLHelper::getForumButton(); $toolbar->appendButton($manualButton); $toolbar->appendButton($forumButton); } }
gpl-3.0
dtu-dsp/Robochameleon
doc/user manual/html/search/variables_4.js
1299
var searchData= [ ['e',['E',['../classsignal__interface.html#a6a513c589314f0508d9264b8830b477a',1,'signal_interface']]], ['edfagain',['EDFAGain',['../class_nonlinear_channel__v1.html#a7eb0c971c743a0546551abef0b20d007',1,'NonlinearChannel_v1']]], ['edfanf',['EDFANF',['../class_nonlinear_channel__v1.html#a9f4114dabab04b38b7b5a40876df4651',1,'NonlinearChannel_v1']]], ['enable',['enable',['../class_d_s_o__v1.html#a6688f56cb12cb1312ecc1ecd8249dabc',1,'DSO_v1']]], ['enablecounter',['EnableCounter',['../class_b_e_r_t__v1.html#ac2023443312134dbd068badef7a52329',1,'BERT_v1']]], ['enablemetrics',['EnableMetrics',['../class_b_e_r_t__v1.html#a1972a2dc4ef79fcf780fa6ce610f514a',1,'BERT_v1']]], ['equalizer_5fconv',['equalizer_conv',['../class_adaptive_equalizer___m_m_a___r_d_e__v1.html#a121dcc9801474a6e6c373c1516a7e4d7',1,'AdaptiveEqualizer_MMA_RDE_v1']]], ['er',['ER',['../class_p_b_c___nx1__v1.html#afe98796521092aa2b77bc64172211971',1,'PBC_Nx1_v1::ER()'],['../class_p_b_s__1x_n__v1.html#a4555ad09d1a7ffbc45d274b908774765',1,'PBS_1xN_v1::ER()'],['../class_polarizer__v1.html#a87f500343f6e50fb7b8b7ac3c639082b',1,'Polarizer_v1::ER()']]], ['extinctionratio',['extinctionRatio',['../class_intensity_modulator__v1.html#af4fa2b07f6d3ee86b789a1e2c48376d4',1,'IntensityModulator_v1']]] ];
gpl-3.0
Reaktoro/Reaktoro
Reaktoro/Thermodynamics/Models/ThermoModel.cpp
2803
// Reaktoro is a unified framework for modeling chemically reactive systems. // // Copyright (C) 2014-2018 Allan Leal // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this library. If not, see <http://www.gnu.org/licenses/>. #include "ThermoModel.hpp" namespace Reaktoro { ThermoModelResult::ThermoModelResult() {} ThermoModelResult::ThermoModelResult(Index nphases, Index nspecies) : standard_partial_molar_gibbs_energies(nspecies), standard_partial_molar_enthalpies(nspecies), standard_partial_molar_volumes(nspecies), standard_partial_molar_heat_capacities_cp(nspecies), standard_partial_molar_heat_capacities_cv(nspecies), ln_activity_constants(nspecies) {} auto ThermoModelResult::resize(Index nphases, Index nspecies) -> void { standard_partial_molar_gibbs_energies.resize(nspecies); standard_partial_molar_enthalpies.resize(nspecies); standard_partial_molar_volumes.resize(nspecies); standard_partial_molar_heat_capacities_cp.resize(nspecies); standard_partial_molar_heat_capacities_cv.resize(nspecies); ln_activity_constants.resize(nspecies); } auto ThermoModelResult::phaseProperties(Index iphase, Index ispecies, Index nspecies) -> PhaseThermoModelResult { return { rows(standard_partial_molar_gibbs_energies, ispecies, nspecies), rows(standard_partial_molar_enthalpies, ispecies, nspecies), rows(standard_partial_molar_volumes, ispecies, nspecies), rows(standard_partial_molar_heat_capacities_cp, ispecies, nspecies), rows(standard_partial_molar_heat_capacities_cv, ispecies, nspecies), rows(ln_activity_constants, ispecies, nspecies), }; } auto ThermoModelResult::phaseProperties(Index iphase, Index ispecies, Index nspecies) const -> PhaseThermoModelResultConst { return { rows(standard_partial_molar_gibbs_energies, ispecies, nspecies), rows(standard_partial_molar_enthalpies, ispecies, nspecies), rows(standard_partial_molar_volumes, ispecies, nspecies), rows(standard_partial_molar_heat_capacities_cp, ispecies, nspecies), rows(standard_partial_molar_heat_capacities_cv, ispecies, nspecies), rows(ln_activity_constants, ispecies, nspecies), }; } } // namespace Reaktoro
gpl-3.0
lingcarzy/v5cart
catalog/controller/affiliate/register.php
7325
<?php class ControllerAffiliateRegister extends Controller { public function index() { if ($this->affiliate->isLogged()) { $this->redirect(U('affiliate/account', '', 'SSL')); } $this->language->load('affiliate/register'); $this->document->setTitle(L('heading_title')); M('affiliate/affiliate'); if ($this->request->isPost() && $this->validate()) { $this->model_affiliate_affiliate->addAffiliate($this->request->post); $this->affiliate->login($this->request->post['email'], $this->request->post['password']); $this->redirect(U('affiliate/success')); } $this->data['breadcrumbs'] = array(); $this->data['breadcrumbs'][] = array( 'text' => L('text_home'), 'href' => HTTP_SERVER, 'separator' => false ); $this->data['breadcrumbs'][] = array( 'text' => L('text_account'), 'href' => U('affiliate/account', '', 'SSL'), 'separator' => L('text_separator') ); $this->data['breadcrumbs'][] = array( 'text' => L('text_register'), 'href' => U('affiliate/register', '', 'SSL'), 'separator' => L('text_separator') ); $this->document->addScript('catalog/view/javascript/jquery/jquery.validate.js'); $this->data['heading_title'] = L('heading_title'); $this->data['text_select'] = L('text_select'); $this->data['text_none'] = L('text_none'); $this->data['text_account_already'] = sprintf(L('text_account_already'), U('affiliate/login', '', 'SSL')); $this->data['text_signup'] = L('text_signup'); $this->data['text_your_details'] = L('text_your_details'); $this->data['text_your_address'] = L('text_your_address'); $this->data['text_payment'] = L('text_payment'); $this->data['text_your_password'] = L('text_your_password'); $this->data['text_cheque'] = L('text_cheque'); $this->data['text_paypal'] = L('text_paypal'); $this->data['text_bank'] = L('text_bank'); $this->data['entry_firstname'] = L('entry_firstname'); $this->data['entry_lastname'] = L('entry_lastname'); $this->data['entry_email'] = L('entry_email'); $this->data['entry_telephone'] = L('entry_telephone'); $this->data['entry_fax'] = L('entry_fax'); $this->data['entry_company'] = L('entry_company'); $this->data['entry_website'] = L('entry_website'); $this->data['entry_address_1'] = L('entry_address_1'); $this->data['entry_address_2'] = L('entry_address_2'); $this->data['entry_postcode'] = L('entry_postcode'); $this->data['entry_city'] = L('entry_city'); $this->data['entry_country'] = L('entry_country'); $this->data['entry_zone'] = L('entry_zone'); $this->data['entry_tax'] = L('entry_tax'); $this->data['entry_payment'] = L('entry_payment'); $this->data['entry_cheque'] = L('entry_cheque'); $this->data['entry_paypal'] = L('entry_paypal'); $this->data['entry_bank_name'] = L('entry_bank_name'); $this->data['entry_bank_branch_number'] = L('entry_bank_branch_number'); $this->data['entry_bank_swift_code'] = L('entry_bank_swift_code'); $this->data['entry_bank_account_name'] = L('entry_bank_account_name'); $this->data['entry_bank_account_number'] = L('entry_bank_account_number'); $this->data['entry_password'] = L('entry_password'); $this->data['entry_confirm'] = L('entry_confirm'); $this->data['button_continue'] = L('button_continue'); $this->data['action'] = U('affiliate/register', '', 'SSL'); $this->data['firstname'] = P('firstname'); $this->data['lastname'] = P('lastname'); $this->data['email'] = P('email'); $this->data['telephone'] = P('telephone'); $this->data['fax'] = P('fax'); $this->data['company'] = P('company'); $this->data['website'] = P('website'); $this->data['address_1'] = P('address_1'); $this->data['address_2'] = P('address_2'); $this->data['postcode'] = P('postcode'); $this->data['city'] = P('city'); $this->data['country_id'] = P('country_id'); $this->data['zone_id'] = P('zone_id'); $this->data['tax'] = P('tax'); $this->data['payment'] = P('payment', 'cheque'); $this->data['cheque'] = P('cheque'); $this->data['paypal'] = P('paypal'); $this->data['bank_name'] = P('bank_name'); $this->data['bank_branch_number'] = P('bank_branch_number'); $this->data['bank_swift_code'] = P('bank_swift_code'); $this->data['bank_account_name'] = P('bank_account_name'); $this->data['bank_account_number'] = P('bank_account_number'); $this->data['password'] = P('password'); $this->data['confirm'] = P('confirm'); $this->data['countries'] = cache_read('country.php'); if (C('config_affiliate_id')) { M('catalog/page'); $page_info = $this->model_catalog_page->getPage(C('config_affiliate_id')); if ($page_info) { $this->data['text_agree'] = sprintf(L('text_agree'), U('page/index/info', 'page_id=' . C('config_affiliate_id'), 'SSL'), $page_info['title'], $page_info['title']); } else { $this->data['text_agree'] = ''; } } else { $this->data['text_agree'] = ''; } $this->data['agree'] = P('agree', false); $this->children = array( 'common/column_left', 'common/column_right', 'common/content_top', 'common/content_bottom', 'common/footer', 'common/header' ); $this->display('affiliate/register.tpl'); } protected function validate() { if ($this->model_affiliate_affiliate->getTotalAffiliatesByEmail($this->request->post['email'])) { $this->setMessage('error_warning', L('error_exists')); return false; } if (C('config_affiliate_id')) { M('catalog/page'); $page_info = $this->model_catalog_page->getPage(C('config_affiliate_id')); if ($page_info && !isset($this->request->post['agree'])) { $this->setMessage('error_warning', sprintf(L('error_agree'), $page_info['title'])); return false; } } $this->load->library('form_validation', true); $this->form_validation->set_rules('firstname', '', 'required|range_length[1,32]', L('error_firstname')); $this->form_validation->set_rules('lastname', '', 'required|range_length[1,32]', L('error_lastname')); $this->form_validation->set_rules('email', '', 'required|range_length[5,96]|email', L('error_email')); $this->form_validation->set_rules('telephone', '', 'required|range_length[3,32]', L('error_telephone')); $this->form_validation->set_rules('address_1', '', 'required|range_length[3,128]', L('error_address_1')); $this->form_validation->set_rules('city', '', 'required|range_length[2,128]', L('error_city')); M('localisation/country'); $country_info = $this->model_localisation_country->getCountry($this->request->post['country_id']); if ($country_info && $country_info['postcode_required']) { $this->form_validation->set_rules('postcode', '', 'required|range_length[2,10]', L('error_postcode')); } $this->form_validation->set_rules('country_id', '', 'required', L('error_country')); $this->form_validation->set_rules('zone_id', '', 'required', L('error_zone')); $this->form_validation->set_rules('password', '', 'required|range_length[4,20]', L('error_password')); $this->form_validation->set_rules('confirm', '', 'required|matches[password]', L('error_confirm')); return $this->form_validation->run(); } } ?>
gpl-3.0
CapsAdmin/goluwa
game/lua/libraries/gmod/sv_exported.lua
134254
return { enums = { SCHED_MOVE_AWAY = 68, ACT_RUN_SCARED = 111, ACT_VM_IDLE_DEPLOYED_5 = 538, TYPE_NIL = 0, ACT_MP_PRIMARY_GRENADE1_IDLE = 1278, ACT_DOD_SPRINT_IDLE_PSCHRECK = 793, ACT_MP_RELOAD_SWIM = 1031, ACT_TURN_RIGHT = 44, KEY_APP = 87, ACT_HL2MP_SWIM_AR2 = 1816, ACT_SLAM_DETONATOR_STICKWALL_DRAW = 265, COLLISION_GROUP_VEHICLE_CLIP = 12, ACT_MP_ATTACK_CROUCH_PRIMARY = 1061, ACT_STARTDYING = 428, ACT_DOD_SPRINT_AIM_KNIFE = 759, ACT_HL2MP_SIT_CROSSBOW = 2012, ACT_MP_GESTURE_VC_THUMBSUP_BUILDING = 1416, ACT_VM_LOWERED_TO_IDLE = 205, BLEND_DST_COLOR = 2, FL_ONTRAIN = 16, ACT_RUN_RIFLE = 362, MOUSE_WHEEL_DOWN = 113, ACT_DOD_RUN_AIM_BAZOOKA = 773, ACT_MP_RELOAD_CROUCH_LOOP = 1029, IN_ATTACK2 = 2048, ACT_DOD_CROUCHWALK_IDLE = 601, CAP_USE = 256, KEY_CAPSLOCKTOGGLE = 104, FL_ONFIRE = 268435456, CAP_SQUAD = 67108864, TYPE_SOUND = 30, ACT_MP_GESTURE_VC_NODYES_SECONDARY = 1393, SCHED_DIE = 53, ACT_WALK_SUITCASE = 329, SOLID_BSP = 1, ACT_DOD_CROUCH_AIM_GREN_STICK = 746, KEY_BACKSLASH = 61, ACT_VM_PRIMARYATTACK_DEPLOYED_1 = 579, ACT_RANGE_ATTACK_HMG1 = 282, ACT_DEPLOY = 470, SCHED_COMBAT_PATROL = 75, SCHED_SCENE_GENERIC = 62, SF_NPC_DROP_HEALTHKIT = 8, DMG_CRUSH = 1, ACT_HL2MP_SWIM_SHOTGUN = 1826, IN_CANCEL = 64, FCVAR_REPLICATED = 8192, ACT_VM_DRYFIRE_SILENCED = 495, KEY_PAD_MULTIPLY = 48, ACT_DOD_WALK_IDLE_MG = 720, ACT_IDLE_ANGRY = 76, KEY_HOME = 74, TYPE_FUNCTION = 6, ACT_BUSY_SIT_CHAIR_EXIT = 397, ACT_DOD_SPRINT_IDLE_TNT = 985, ACT_VM_RELEASE = 210, SOLID_VPHYSICS = 6, DMG_DIRECT = 268435456, KEY_F = 16, ACT_DOD_CROUCH_AIM = 600, ACT_GMOD_TAUNT_CHEER = 1620, ACT_RUN_CROUCH_AIM = 13, ACT_CROSSBOW_IDLE_UNLOADED = 487, ACT_MP_RELOAD_CROUCH_SECONDARY_END = 1129, ACT_VM_UNUSABLE_TO_USABLE = 1429, BLEND_ONE = 1, TEAM_CONNECTING = 0, ACT_ARM = 70, ACT_HL2MP_GESTURE_RANGE_ATTACK_SCARED = 1698, ACT_OBJ_DETERIORATING = 468, ACT_DOD_PRIMARYATTACK_GREN_FRAG = 874, ACT_MP_GESTURE_VC_HANDMOUTH_PDA = 1419, ACT_DIE_BACKSIDE = 409, KEY_LSHIFT = 79, ACT_FLINCH_RIGHTLEG = 123, ACT_VM_RECOIL3 = 208, ACT_MP_ATTACK_STAND_SECONDARYFIRE = 1013, ACT_SLAM_STICKWALL_DETONATOR_HOLSTER = 236, ACT_HL2MP_WALK_REVOLVER = 1664, BONE_ALWAYS_PROCEDURAL = 4, ACT_VM_IDLE_3 = 531, ACT_DOD_RUN_IDLE_PSCHRECK = 792, CAP_TURN_HEAD = 4096, ACT_VM_FIREMODE = 1930, ACT_DROP_WEAPON = 72, SCHED_HIDE_AND_RELOAD = 50, ACT_DOD_SECONDARYATTACK_CROUCH = 955, ACT_MP_STAND_SECONDARY = 1109, ACT_VM_SWINGMISS = 201, KEY_X = 34, KEY_EQUAL = 63, ACT_DOD_PRONE_DEPLOY_MG = 838, ACT_MP_AIRWALK_SECONDARY = 1113, ACT_DOD_CROUCHWALK_IDLE_PISTOL = 615, MAT_SNOW = 74, ACT_FLINCH_HEAD = 117, ACT_DOD_CROUCH_ZOOM_RIFLE = 809, ACT_MP_RUN_MELEE = 1173, ACT_CLIMB_DOWN = 35, ACT_VM_DEPLOY_3 = 559, ACT_MP_JUMP_START_MELEE = 1178, ACT_DOD_STAND_AIM_MP44 = 685, ACT_DOD_SPRINT_IDLE_BOLT = 657, TYPE_IMESH = 28, ACT_VM_UNLOAD = 1957, TEXT_ALIGN_BOTTOM = 4, ACT_MP_WALK_PRIMARY = 1047, KEY_PAD_8 = 45, CAP_WEAPON_RANGE_ATTACK2 = 16384, ACT_STEP_FORE = 136, ACT_SLAM_TRIPMINE_DRAW = 256, SOLID_BBOX = 2, ACT_MP_ATTACK_STAND_POSTFIRE = 1038, ACT_OVERLAY_SHIELD_UP_IDLE = 446, ACT_VICTORY_DANCE = 112, ACT_DOD_RELOAD_PRONE_BOLT = 926, ACT_FLINCH_STOMACH = 119, ACT_RUN = 10, EFL_DIRTY_ABSTRANSFORM = 2048, HUD_PRINTCONSOLE = 2, ACT_HL2MP_GESTURE_RANGE_ATTACK_AR2 = 1812, ACT_HL2MP_IDLE_PISTOL = 1787, ACT_GESTURE_RANGE_ATTACK_SNIPER_RIFLE = 317, ACT_DOD_CROUCH_AIM_MP40 = 673, ACT_BUSY_LEAN_LEFT = 386, ACT_IDLE_SMG1 = 320, MOUSE_LAST = 113, ACT_MP_JUMP_FLOAT_PRIMARY = 1052, ACT_SLAM_STICKWALL_ND_DRAW = 238, ACT_IDLE_AGITATED = 79, ACT_SMG2_RELOAD2 = 273, SCHED_SHOOT_ENEMY_COVER = 39, ACT_HL2MP_GESTURE_RELOAD_DUEL = 1853, ACT_HL2MP_IDLE_CAMERA = 1673, PLAYER_WALK = 1, ACT_DOD_PRIMARYATTACK_TOMMY = 850, TYPE_SOUNDHANDLE = 38, ACT_RUN_RIFLE_STIMULATED = 335, ACT_VM_SECONDARYATTACK = 182, ACT_DOD_RELOAD_PRONE_MP44 = 929, ACT_RUN_AIM_PISTOL = 372, ACT_IDLE_SMG1_STIMULATED = 331, TYPE_BOOL = 1, KEY_XBUTTON_UP = 146, ACT_GESTURE_RANGE_ATTACK2_LOW = 142, ACT_GMOD_GESTURE_RANGE_FRENZY = 1645, ACT_DOD_CROUCHWALK_AIM_30CAL = 726, RENDERMODE_TRANSCOLOR = 1, ACT_IDLE = 1, PLAYER_ATTACK1 = 5, ACT_DOD_CROUCHWALK_AIM_MG = 713, ACT_DOD_CROUCH_AIM_SPADE = 762, ACT_HL2MP_WALK_ZOMBIE_02 = 1629, ACT_RUN_CROUCH = 12, ACT_WALK_AIM_PISTOL = 371, ACT_DOD_PRIMARYATTACK_PRONE = 593, ACT_VM_UNDEPLOY = 543, SF_NPC_START_EFFICIENT = 16, KEY_APOSTROPHE = 56, ACT_FIRE_START = 435, ACT_TURN = 461, ACT_MP_SECONDARY_GRENADE2_DRAW = 1286, ACT_RANGE_ATTACK_PISTOL = 289, SCHED_ALERT_FACE_BESTSOUND = 6, BLEND_ONE_MINUS_DST_COLOR = 3, KEY_XBUTTON_LTRIGGER = 154, KEY_F1 = 92, MAT_COMPUTER = 80, ACT_SLAM_STICKWALL_ATTACH2 = 232, MASK_OPAQUE_AND_NPCS = 33570945, ACT_MP_CROUCH_DEPLOYED = 993, SCHED_PRE_FAIL_ESTABLISH_LINE_OF_FIRE = 37, ACT_MP_GESTURE_VC_FISTPUMP_BUILDING = 1415, ACT_HANDGRENADE_THROW1 = 475, ACT_DOD_DEPLOY_TOMMY = 833, ACT_HL2MP_IDLE_PHYSGUN = 1857, ACT_DOD_WALK_AIM_MG = 714, ACT_HL2MP_GESTURE_RELOAD_KNIFE = 1981, ACT_READINESS_PISTOL_RELAXED_TO_STIMULATED = 422, ACT_DOD_DEFUSE_TNT = 988, PLAYERANIMEVENT_FLINCH_HEAD = 10, FCVAR_CLIENTCMD_CAN_EXECUTE = 1073741824, ACT_DOD_PRONE_DEPLOYED = 582, PLAYERANIMEVENT_FLINCH_RIGHTLEG = 14, ACT_DOD_SPRINT_AIM_GREN_STICK = 751, PLAYERANIMEVENT_CUSTOM_GESTURE = 20, ACT_CROUCHIDLE_AGITATED = 104, RENDERGROUP_STATIC_HUGE = 0, ACT_STEP_BACK = 135, ACT_MP_RELOAD_STAND = 1025, ACT_HL2MP_SWIM_IDLE_SMG1 = 1805, ACT_DOD_RELOAD_TOMMY = 895, MASK_SHOT = 1174421507, KEY_XBUTTON_A = 114, ACT_MP_SPRINT = 1000, FSOLID_FORCE_WORLD_ALIGNED = 64, ACT_MP_ATTACK_STAND_GRENADE_SECONDARY = 1140, ACT_WALK_AIM_RIFLE_STIMULATED = 337, ACT_DI_ALYX_ZOMBIE_SHOTGUN26 = 417, CONTENTS_CURRENT_270 = 2097152, KEY_RBRACKET = 54, MASK_SOLID = 33570827, KEY_XBUTTON_LEFT = 149, MAT_WARPSHIELD = 90, ACT_VM_DEPLOYED_IDLE = 1913, ACT_MP_ATTACK_STAND_PDA = 1356, ACT_HL2MP_WALK_CROUCH_SMG1 = 1801, IN_SCORE = 65536, CHAN_STATIC = 6, ACT_DOD_IDLE_ZOOMED = 583, MAT_SAND = 78, ACT_DOD_PRIMARYATTACK_PRONE_DEPLOYED_MG = 868, ACT_DOD_DEPLOY_30CAL = 835, SCHED_CHASE_ENEMY = 17, EF_FOLLOWBONE = 1024, ACT_MP_GESTURE_VC_HANDMOUTH_BUILDING = 1413, ACT_RPG_IDLE_UNLOADED = 484, ACT_MP_GESTURE_VC_HANDMOUTH_MELEE = 1395, ACT_HL2MP_IDLE_CROUCH_AR2 = 1810, ACT_HL2MP_SIT_SHOTGUN = 2006, KEY_XSTICK2_UP = 159, ACT_RUN_AIM = 11, COLLISION_GROUP_WORLD = 20, ACT_IDLE_SMG1_RELAXED = 330, KEY_PAD_9 = 46, ACT_HL2MP_IDLE_ZOMBIE = 1703, ACT_MP_ATTACK_AIRWALK_PRIMARYFIRE = 1022, ACT_HL2MP_GESTURE_RELOAD_MELEE2 = 2001, ACT_HL2MP_SWIM_IDLE_RPG = 1835, ACT_VM_DRAWFULL_M203 = 1938, ACT_DRIVE_JEEP = 1973, PLAYER_JUMP = 2, ACT_MP_ATTACK_SWIM_PRIMARY = 1063, ACT_HL2MP_WALK_PISTOL = 1788, ACT_OBJ_RUNNING = 465, ACT_DYINGLOOP = 429, FL_INWATER = 1024, PATTACH_ABSORIGIN_FOLLOW = 1, KEY_LCONTROL = 83, ACT_PLAYER_CROUCH_WALK_FIRE = 502, KEY_RSHIFT = 80, ACT_VM_PRIMARYATTACK_EMPTY = 522, ACT_DOD_CROUCHWALK_IDLE_MP44 = 693, ACT_BARNACLE_CHOMP = 169, ACT_VM_DETACH_SILENCER = 212, ACT_DOD_PRONE_AIM_GREN_FRAG = 742, SCHED_SCRIPTED_FACE = 61, ACT_DOD_STAND_AIM_TOMMY = 659, KEY_F4 = 95, ACT_DOD_CROUCH_IDLE_PISTOL = 614, FL_CONVEYOR = 8192, TYPE_NAVAREA = 37, ACT_VM_RELOAD_END = 1952, CONTENTS_DETAIL = 134217728, SCHED_ESTABLISH_LINE_OF_FIRE_FALLBACK = 36, ACT_VM_PRIMARYATTACK_5 = 566, SF_FLOOR_TURRET_CITIZEN = 512, ACT_DOD_ZOOMLOAD_PRONE_PSCHRECK = 940, ACT_DOD_PRIMARYATTACK_PRONE_GREASE = 861, ACT_RANGE_ATTACK_RPG = 295, ACT_SHOTGUN_PUMP = 269, ACT_SLAM_STICKWALL_ND_ATTACH2 = 234, KEY_0 = 1, ACT_HL2MP_JUMP_PHYSGUN = 1864, ACT_DOD_WALK_IDLE_PISTOL = 616, ACT_MP_GESTURE_VC_THUMBSUP_PDA = 1422, ACT_RPG_DRAW_UNLOADED = 482, ACT_VM_IDLE_DEPLOYED_EMPTY = 525, TYPE_INVALID = -1, ACT_MP_JUMP = 1001, TRANSMIT_NEVER = 1, SCHED_MELEE_ATTACK1 = 41, ACT_MP_GESTURE_VC_FISTPUMP_PRIMARY = 1385, ACT_HL2MP_WALK_ZOMBIE_03 = 1630, ACT_VM_DEPLOY_2 = 560, ACT_DOD_PRONE_ZOOM_FORWARD_RIFLE = 946, ACT_GESTURE_TURN_RIGHT90 = 162, ACT_MP_ATTACK_STAND_PRIMARYFIRE = 1011, CLASS_STALKER = 17, MASK_OPAQUE = 16513, ACT_DOD_PRIMARYATTACK_MG = 866, ACT_GESTURE_RANGE_ATTACK_SMG1 = 308, ACT_RESET = 0, ACT_MP_GRENADE1_DRAW = 1271, SF_CITIZEN_RANDOM_HEAD_FEMALE = 8388608, ACT_DOD_SPRINT_IDLE_MP40 = 683, ACT_COVER_LOW = 5, ACT_GESTURE_FLINCH_LEFTLEG = 155, ACT_MP_GESTURE_FLINCH_CHEST = 1265, MOVETYPE_PUSH = 7, ACT_DOD_SECONDARYATTACK_PRONE_BOLT = 849, ACT_DOD_PRIMARYATTACK_30CAL = 870, ACT_DOD_WALK_AIM_PISTOL = 610, ACT_WALK_RIFLE_RELAXED = 332, ACT_CROUCHING_SHIELD_ATTACK = 457, CONTENTS_IGNORE_NODRAW_OPAQUE = 8192, FCVAR_NOTIFY = 256, ACT_VM_UNDEPLOY_7 = 545, ACT_GESTURE_RANGE_ATTACK_HMG1 = 306, SCHED_DUCK_DODGE = 84, ACT_LOOKBACK_RIGHT = 59, RENDERGROUP_STATIC = 6, ACT_MP_ATTACK_STAND_MELEE = 1182, KEY_DELETE = 73, KEY_SLASH = 60, ACT_MP_ATTACK_CROUCH_SECONDARY = 1121, ACT_MP_RELOAD_AIRWALK = 1034, ACT_DOD_RELOAD_GREASEGUN = 896, ACT_DOD_PRONEWALK_IDLE_TOMMY = 671, ACT_HL2MP_SIT_PISTOL = 2005, ACT_HL2MP_SWIM = 1786, ACT_PLAYER_WALK_FIRE = 503, ACT_MP_SWIM_BUILDING = 1317, PLAYERANIMEVENT_ATTACK_GRENADE = 2, KEY_XBUTTON_B = 115, COLLISION_GROUP_PROJECTILE = 13, SF_NPC_WAIT_FOR_SCRIPT = 128, SND_IGNORE_PHONEMES = 256, SCHED_COWER = 40, ACT_SHIELD_UP_IDLE = 451, ACT_RANGE_AIM_SMG1_LOW = 298, SCHED_ARM_WEAPON = 48, ACT_DOD_PRIMARYATTACK_BAR = 886, ACT_VM_PRIMARYATTACK_SILENCED = 493, ACT_VM_HOLSTER = 173, ACT_DOD_PRONE_ZOOM_FORWARD_BAZOOKA = 948, FL_KILLME = 134217728, ACT_VM_IDLE_EMPTY = 524, ACT_HL2MP_GESTURE_RANGE_ATTACK = 1782, CAP_INNATE_RANGE_ATTACK2 = 262144, ACT_VM_RELOAD_INSERT_EMPTY = 1954, ACT_DOD_CROUCHWALK_AIM_SPADE = 763, ACT_DOD_RUN_AIM_KNIFE = 757, ACT_MP_ATTACK_SWIM_BUILDING = 1320, SF_CITIZEN_USE_RENDER_BOUNDS = 16777216, ACT_RELOAD_SMG1 = 378, ACT_HL2MP_JUMP_GRENADE = 1844, ACT_VM_PICKUP = 209, TYPE_EFFECTDATA = 16, COLLISION_GROUP_VEHICLE = 7, ACT_DOD_PRONEWALK_IDLE_MP44 = 697, DMG_BULLET = 2, ACT_MP_CROUCHWALK_BUILDING = 1312, IN_WEAPON2 = 2097152, ACT_DOD_STAND_IDLE_MP44 = 691, ACT_DOD_CROUCH_AIM_BAR = 796, KEY_J = 20, SURF_TRIGGER = 64, KEY_END = 75, ACT_DOD_RELOAD_CROUCH_C96 = 913, ACT_DOD_RELOAD_DEPLOYED_30CAL = 919, HULL_MEDIUM_TALL = 9, ACT_DOD_STAND_IDLE_GREASE = 704, FSOLID_TRIGGER = 8, CLIENT = false, KEY_XBUTTON_LEFT_SHOULDER = 118, ACT_DOD_CROUCH_AIM_BAZOOKA = 770, KEY_F7 = 98, ACT_WALK_AIM_RIFLE = 359, ACT_MP_JUMP_START_BUILDING = 1314, ACT_SMG2_FIRE2 = 271, CONTENTS_BLOCKLOS = 64, ACT_DOD_HS_IDLE_K98 = 969, KEY_Z = 36, CONTENTS_GRATE = 8, ACT_BUSY_LEAN_BACK = 389, ACT_MP_ATTACK_AIRWALK_GRENADE_BUILDING = 1325, BOX_TOP = 4, NUM_HULLS = 10, ACT_VM_FIRE_TO_EMPTY = 1956, PLAYER_RELOAD = 7, ACT_HL2MP_WALK_PHYSGUN = 1858, HULL_TINY_CENTERED = 6, NAV_MESH_OBSTACLE_TOP = 16384, ACT_VM_PRIMARYATTACK_DEPLOYED_2 = 578, FVPHYSICS_NO_SELF_COLLISIONS = 32768, ACT_MP_GESTURE_VC_NODYES_PDA = 1423, ACT_VM_MISSCENTER = 197, ACT_VM_SPRINT_LEAVE = 434, PATTACH_WORLDORIGIN = 5, PLAYERANIMEVENT_FLINCH_RIGHTARM = 12, ACT_DOD_SECONDARYATTACK_PRONE_TOMMY = 853, ACT_DOD_PRONEWALK_IDLE_TNT = 986, ACT_MP_ATTACK_AIRWALK_SECONDARY = 1123, ACT_MP_RELOAD_AIRWALK_LOOP = 1035, PLAYERANIMEVENT_RELOAD_END = 5, ACT_DOD_CROUCHWALK_IDLE_C96 = 628, SCHED_NEW_WEAPON_CHEAT = 64, ACT_CROUCHING_SHIELD_KNOCKBACK = 458, TYPE_MOVEDATA = 17, SCHED_FALL_TO_GROUND = 78, SF_NPC_ALWAYSTHINK = 1024, DONT_BLEED = -1, ACT_DOD_PRIMARYATTACK_PRONE_BAZOOKA = 883, SF_CITIZEN_RANDOM_HEAD = 262144, TYPE_NONE = -1, SCHED_DISARM_WEAPON = 49, ACT_MP_GESTURE_FLINCH_RIGHTARM = 1268, ACT_VM_UNDEPLOY_6 = 546, KEY_NUMLOCK = 69, BLOOD_COLOR_ZOMBIE = 5, ACT_MP_GESTURE_FLINCH_LEFTLEG = 1269, MOVETYPE_OBSERVER = 10, ACT_HL2MP_IDLE_MELEE2 = 1995, KEY_F12 = 103, ACT_GMOD_IN_CHAT = 2019, DMG_CLUB = 128, ACT_MP_RELOAD_CROUCH_PRIMARY_LOOP = 1069, ACT_DOD_SECONDARYATTACK_BOLT = 847, ACT_HL2MP_SWIM_MELEE2 = 2004, CAP_SKIP_NAV_GROUND_CHECK = 128, SCHED_SCRIPTED_WALK = 57, ACT_DOD_WALK_AIM_MP44 = 688, ACT_MELEE_ATTACK_SWING = 296, ACT_DOD_PRIMARYATTACK_PRONE_MP40 = 855, ACT_DOD_STAND_AIM_KNIFE = 753, SIMPLE_USE = 3, ACT_TRIPMINE_GROUND = 491, ACT_MP_ATTACK_STAND_GRENADE_MELEE = 1188, SURF_NOCHOP = 16384, ACT_MP_RELOAD_CROUCH = 1028, ACT_RANGE_ATTACK_ML = 283, ACT_SHIELD_KNOCKBACK = 453, DMG_BLAST_SURFACE = 134217728, ACT_RANGE_ATTACK_PISTOL_LOW = 290, kRenderFxFadeFast = 6, ACT_DOD_CROUCH_AIM_MP44 = 686, ACT_DOD_RUN_AIM = 606, ACT_CROSSBOW_DRAW_UNLOADED = 486, ACT_HL2MP_WALK_ZOMBIE_06 = 1647, ACT_MP_CROUCH_BUILDING = 1308, ACT_HL2MP_SWIM_IDLE_SUITCASE = 1721, ACT_IDLE_MELEE = 346, ACT_VM_HOLSTER_EMPTY = 1899, ACT_SHIPLADDER_UP = 37, ACT_MP_JUMP_PRIMARY = 1050, ACT_WALK_RPG_RELAXED = 356, TYPE_VECTOR = 10, FVPHYSICS_PENETRATING = 64, ACT_MP_GESTURE_FLINCH_MELEE = 1261, ACT_IDLE_AIM_RIFLE_STIMULATED = 336, ACT_DOD_STAND_AIM_MG = 711, ACT_MP_RELOAD_SWIM_SECONDARY = 1130, NUM_AI_CLASSES = 26, IN_RUN = 4096, ACT_GAUSS_SPINUP = 489, ACT_DIESIMPLE = 20, ACT_MP_CROUCH_IDLE = 991, ACT_HL2MP_SIT_FIST = 2015, ACT_HL2MP_IDLE_SHOTGUN = 1817, ACT_HL2MP_RUN_MELEE = 1879, ACT_VM_IDLE_DEPLOYED_8 = 535, ACT_VM_MISSLEFT = 193, NAV_MESH_STAND = 1024, kRenderFxPulseFastWider = 24, ACT_DOD_PRIMARYATTACK_PRONE_RIFLE = 842, ACT_HL2MP_WALK_CROUCH_PASSIVE = 1989, ACT_HL2MP_WALK_CROUCH_GRENADE = 1841, ACT_DOD_SPRINT_IDLE_PISTOL = 618, ACT_VM_UNDEPLOY_EMPTY = 552, TYPE_LOCOMOTION = 35, ACT_DOD_PRONE_AIM_TOMMY = 664, ACT_DI_ALYX_ZOMBIE_MELEE = 412, ACT_FLINCH_RIGHTARM = 121, KEY_F2 = 93, ACT_DOD_PRONEWALK_AIM_KNIFE = 760, GLOBAL_OFF = 0, SCHED_NPC_FREEZE = 73, ACT_VM_DEPLOYED_IRON_OUT = 1923, ACT_GESTURE_FLINCH_HEAD = 150, ACT_HL2MP_WALK_CROUCH_ZOMBIE = 1707, ACT_GESTURE_MELEE_ATTACK2 = 140, ACT_VM_DEPLOY_8 = 554, ACT_DOD_STAND_AIM_RIFLE = 633, ACT_DOD_PRONE_AIM_RIFLE = 638, ACT_HL2MP_JUMP_REVOLVER = 1670, KEY_F10 = 101, IN_WEAPON1 = 1048576, ACT_HL2MP_GESTURE_RANGE_ATTACK_GRENADE = 1842, ACT_VM_DEPLOY = 553, LAST_SHARED_SCHEDULE = 88, ACT_HL2MP_SWIM_IDLE_MAGIC = 1661, ACT_SLAM_DETONATOR_IDLE = 261, KEY_M = 23, ACT_HL2MP_RUN_PHYSGUN = 1859, ACT_DOD_STAND_IDLE_RIFLE = 639, ACT_MP_ATTACK_CROUCH_PREFIRE = 1040, KEY_XBUTTON_RIGHT = 147, ACT_HL2MP_GESTURE_RANGE_ATTACK_MELEE = 1882, ACT_DOD_RELOAD_CROUCH = 595, TYPE_STRING = 4, ACT_MP_WALK = 997, ACT_HL2MP_IDLE_CROUCH_ZOMBIE_01 = 1638, SND_CHANGE_PITCH = 2, kRenderFxSpotlight = 22, ACT_VM_IDLE = 174, KEY_MINUS = 62, ACT_DOD_RELOAD_CROUCH_TOMMY = 908, ACT_IDLE_RPG = 349, ACT_HL2MP_RUN_SUITCASE = 1715, ACT_RUNTOIDLE = 506, GESTURE_SLOT_CUSTOM = 6, ACT_DOD_CROUCH_AIM_MG = 712, ACT_DOD_CROUCH_AIM_C96 = 621, ACT_DOD_STAND_IDLE_TNT = 980, ACT_OBJ_ASSEMBLING = 462, ACT_HL2MP_GESTURE_RELOAD_MELEE = 1883, SCHED_GET_HEALTHKIT = 66, ACT_VM_DEPLOYED_RELOAD = 1916, EFL_NO_PHYSCANNON_INTERACTION = 1073741824, ACT_SLAM_THROW_DETONATE = 252, ACT_SIGNAL_HALT = 55, D_NU = 4, ACT_DOD_PRIMARYATTACK_CROUCH_GREN_FRAG = 953, ACT_HL2MP_SWIM_KNIFE = 1984, ACT_IDLE_HURT = 81, ACT_RUN_AIM_SHOTGUN = 368, ACT_HL2MP_IDLE_CROUCH_SMG1 = 1800, ACT_DOD_PRIMARYATTACK_DEPLOYED = 589, ACT_IDLE_AIM_STEALTH = 93, ACT_VM_THROW = 179, ACT_DOD_SECONDARYATTACK_PRONE_RIFLE = 843, ACT_DOD_PRONE_ZOOM_FORWARD_PSCHRECK = 949, ACT_GESTURE_TURN_RIGHT90_FLAT = 166, PLAYERANIMEVENT_CUSTOM_GESTURE_SEQUENCE = 22, ACT_MP_GESTURE_VC_FINGERPOINT_MELEE = 1396, KEY_SCROLLLOCK = 71, ACT_VM_FIZZLE = 989, ACT_HL2MP_JUMP_SHOTGUN = 1824, ACT_VM_UNDEPLOY_5 = 547, ACT_MP_RELOAD_STAND_END = 1027, NPC_STATE_INVALID = -1, ACT_GESTURE_FLINCH_RIGHTLEG = 156, MAT_GLASS = 89, ACT_RUN_AIM_STIMULATED = 99, ACT_VM_DIFIREMODE = 1934, ACT_VM_IIDLE_EMPTY = 1907, ACT_MP_ATTACK_STAND_GRENADE = 1014, ACT_SLAM_TRIPMINE_TO_STICKWALL_ND = 259, ACT_STRAFE_RIGHT = 40, ACT_MP_SWIM_DEPLOYED = 1008, ACT_GESTURE_RANGE_ATTACK_THROW = 316, KEY_2 = 3, MOVECOLLIDE_FLY_BOUNCE = 1, ACT_HL2MP_RUN_MELEE2 = 1997, ACT_MP_ATTACK_CROUCH_PRIMARYFIRE = 1015, CAP_SIMPLE_RADIUS_DAMAGE = 2147483648, ACT_HL2MP_IDLE_CROUCH_MELEE2 = 1998, ACT_WALK_HURT = 105, FSOLID_ROOT_PARENT_ALIGNED = 256, ACT_VM_DEPLOY_EMPTY = 562, ACT_MP_ATTACK_AIRWALK_MELEE = 1187, ACT_DOD_CROUCHWALK_IDLE_BAZOOKA = 777, ACT_DOD_CROUCHWALK_ZOOM_RIFLE = 810, ACT_DOD_PRIMARYATTACK_DEPLOYED_RIFLE = 845, ACT_MP_RELOAD_AIRWALK_SECONDARY_LOOP = 1134, ACT_DOD_RUN_AIM_PSCHRECK = 786, ACT_STAND = 47, ACT_MP_CROUCHWALK_PDA = 1350, PLAYERANIMEVENT_DIE = 8, SCHED_RELOAD = 51, ACT_DOD_SECONDARYATTACK_PRONE_MP40 = 857, ACT_HL2MP_WALK_CROUCH_MAGIC = 1657, ACT_HL2MP_IDLE_CROUCH_PHYSGUN = 1860, CAP_MOVE_JUMP = 2, ACT_DOD_STAND_AIM_GREASE = 698, ACT_WALK_ON_FIRE = 126, CAP_INNATE_MELEE_ATTACK1 = 524288, ACT_DOD_CROUCHWALK_AIM_GREN_FRAG = 739, CAP_USE_SHOT_REGULATOR = 16777216, ACT_HL2MP_WALK_CROUCH_AR2 = 1811, IN_ZOOM = 524288, NAV_MESH_WALK = 64, ACT_MP_STAND_MELEE = 1171, FVPHYSICS_NO_IMPACT_DMG = 1024, ACT_DOD_RELOAD_CROUCH_BAZOOKA = 909, ACT_DOD_STAND_AIM_MP40 = 672, ACT_VM_DEPLOYED_IRON_DRYFIRE = 1922, ACT_DOD_HS_CROUCH_KNIFE = 973, ACT_GESTURE_RANGE_ATTACK2 = 138, DIRECTIONAL_USE = 2, DMG_AIRBOAT = 33554432, ACT_MP_JUMP_FLOAT_BUILDING = 1315, ACT_VM_ISHOOT = 1903, CONTENTS_CURRENT_0 = 262144, HULL_TINY = 3, ACT_VM_DOWN_M203 = 1948, ACT_HL2MP_GESTURE_RANGE_ATTACK_REVOLVER = 1668, ACT_DOD_RUN_ZOOM_BAZOOKA = 824, KEY_L = 22, ACT_COVER_SMG1_LOW = 302, CAP_ANIMATEDFACE = 8388608, CLASS_ANTLION = 4, NPC_STATE_COMBAT = 3, ACT_HL2MP_WALK_MAGIC = 1654, ACT_HL2MP_GESTURE_RELOAD_SLAM = 1893, KEY_F5 = 96, ACT_HL2MP_IDLE_SLAM = 1887, ACT_BUSY_SIT_GROUND_EXIT = 394, ACT_VM_IFIREMODE = 1932, CAP_MOVE_CLIMB = 8, KEY_FIRST = 0, D_HT = 1, CLASS_FLARE = 22, MOVETYPE_NOCLIP = 8, SF_CITIZEN_IGNORE_SEMAPHORE = 2097152, ACT_VM_PRIMARYATTACK_DEPLOYED_EMPTY = 580, CONTENTS_AREAPORTAL = 32768, ACT_VM_PULLBACK_LOW = 178, MAT_ANTLION = 65, ACT_DOD_STAND_IDLE_PSCHRECK = 788, KEY_5 = 6, ACT_HL2MP_RUN_FAST = 1621, NAV_MESH_CROUCH = 1, CHAN_BODY = 4, RENDERMODE_TRANSALPHADD = 8, FL_PARTIALGROUND = 262144, FVPHYSICS_MULTIOBJECT_ENTITY = 16, ACT_MP_GESTURE_VC_NODYES_MELEE = 1399, CAP_MOVE_GROUND = 1, TYPE_USERDATA = 7, ACT_DOD_SECONDARYATTACK_PRONE = 594, ACT_HL2MP_ZOMBIE_SLUMP_RISE = 1627, ACT_RANGE_ATTACK_SMG1 = 284, DMG_BURN = 8, ACT_VM_READY = 1902, ACT_SIGNAL_RIGHT = 57, ACT_HL2MP_SWIM_IDLE_KNIFE = 1983, OBS_MODE_FREEZECAM = 2, ACT_HL2MP_WALK_CROUCH_ANGRY = 1687, ACT_VM_IOUT = 1908, ACT_RELOAD = 66, NPC_STATE_PRONE = 6, KEY_O = 25, ACT_MP_GESTURE_FLINCH_SECONDARY = 1260, HUD_PRINTTALK = 3, JOYSTICK_LAST_BUTTON = 145, ACT_GAUSS_SPINCYCLE = 490, ACT_HL2MP_SWIM_SCARED = 1702, KEY_LALT = 81, ACT_HL2MP_WALK_CROUCH_ZOMBIE_02 = 1634, ACT_PHYSCANNON_ANIMATE_POST = 406, CLASS_PROTOSNIPER = 20, ACT_TURN_LEFT = 43, ACT_DOD_PRIMARYATTACK_MP40 = 854, ACT_PICKUP_RACK = 75, HULL_WIDE_SHORT = 4, ACT_HL2MP_RUN_CROSSBOW = 1869, ACT_MP_RELOAD_STAND_SECONDARY = 1124, ACT_MP_JUMP_FLOAT = 1003, ACT_DOD_CROUCHWALK_AIM_PISTOL = 609, HULL_HUMAN = 0, ACT_HL2MP_GESTURE_RELOAD_SMG1 = 1803, ACT_DOD_PRONEWALK_IDLE_MP40 = 684, EFL_NO_MEGAPHYSCANNON_RAGDOLL = 268435456, GLOBAL_ON = 1, ACT_DOD_PRIMARYATTACK_C96 = 864, ACT_MP_WALK_SECONDARY = 1112, ACT_MP_ATTACK_AIRWALK_GRENADE = 1024, ACT_DISARM = 71, CLASS_EARTH_FAUNA = 23, ACT_MP_MELEE_GRENADE1_IDLE = 1290, ACT_SLAM_THROW_ND_DRAW = 249, ACT_DOD_SECONDARYATTACK_RIFLE = 841, ACT_DOD_RELOAD_PRONE_TOMMY = 932, BLOOD_COLOR_GREEN = 2, SND_NOFLAGS = 0, KEY_RALT = 82, EFL_SETTING_UP_BONES = 8, KEY_PAD_0 = 37, CHAN_VOICE2 = 7, ACT_HL2MP_WALK_CROUCH_SHOTGUN = 1821, HUD_PRINTNOTIFY = 1, ACT_DOD_RELOAD_PRONE_PSCHRECK = 939, ACT_HL2MP_WALK_CAMERA = 1674, ACT_HL2MP_SWIM_FIST = 1969, ACT_VM_IDLE_LOWERED = 204, kRenderFxClampMinScale = 19, SF_NPC_TEMPLATE = 2048, ACT_HL2MP_RUN_KNIFE = 1977, ACT_TURNLEFT45 = 460, NAV_MESH_HAS_ELEVATOR = 1073741824, ACT_MP_ATTACK_SWIM_GRENADE_SECONDARY = 1142, ACT_VM_CRAWL_M203 = 1947, ACT_DOD_RELOAD_BAZOOKA = 914, DMG_RADIATION = 262144, ACT_MP_ATTACK_SWIM_GRENADE_MELEE = 1190, ACT_OPEN_DOOR = 411, ACT_DOD_SPRINT_IDLE_GREASE = 709, ACT_DOD_RUN_AIM_30CAL = 728, ACT_HL2MP_JUMP = 1784, MAT_BLOODYFLESH = 66, KEY_PAD_MINUS = 49, ACT_MP_GESTURE_VC_NODYES = 1381, CAP_INNATE_MELEE_ATTACK2 = 1048576, SND_DO_NOT_OVERWRITE_EXISTING_ON_CHANNEL = 1024, CAP_INNATE_RANGE_ATTACK1 = 131072, SF_CITIZEN_FOLLOW = 65536, ACT_GESTURE_RANGE_ATTACK_AR2_GRENADE = 305, ACT_DOD_RELOAD_PSCHRECK = 916, MAT_FLESH = 70, ACT_HL2MP_SWIM_IDLE_CAMERA = 1681, SCHED_AISCRIPT = 56, kRenderFxSolidSlow = 7, ACT_CROUCH = 45, NAV_MESH_JUMP = 2, SND_STOP = 4, ACT_IDLE_STIMULATED = 78, SCREENFADE = { OUT = 2, IN = 1, MODULATE = 4, PURGE = 16, STAYOUT = 8, }, ACT_ZOMBIE_LEAPING = 1649, ACT_GESTURE_RANGE_ATTACK_SHOTGUN = 311, CLASS_PLAYER_ALLY = 2, ACT_DOD_PRIMARYATTACK_DEPLOYED_MG = 869, CONTENTS_DEBRIS = 67108864, MOUSE_FIRST = 107, ACT_VM_DEPLOYED_RELOAD_EMPTY = 1917, ACT_MP_RUN_PDA = 1347, ACT_DOD_RELOAD_CROUCH_PISTOL = 911, ACT_DOD_SPRINT_IDLE_MP44 = 696, ACT_HL2MP_RUN_GRENADE = 1839, SURF_NOLIGHT = 1024, KEY_XSTICK1_RIGHT = 150, ACT_WALK_AIM_RELAXED = 94, ACT_MP_WALK_PDA = 1348, GESTURE_SLOT_GRENADE = 1, ACT_MP_WALK_BUILDING = 1310, ACT_DOD_RUN_IDLE_TNT = 984, KEY_4 = 5, TYPE_LIGHTUSERDATA = 2, ACT_SHOTGUN_RELOAD_START = 267, CONTENTS_MONSTERCLIP = 131072, ACT_SPECIAL_ATTACK1 = 107, ACT_DOD_RELOAD_PRONE_DEPLOYED = 592, CAP_DUCK = 134217728, ACT_IDLE_RELAXED = 77, COLLISION_GROUP_WEAPON = 11, SF_CITIZEN_RANDOM_HEAD_MALE = 4194304, ACT_VM_RELOAD_INSERT_PULL = 1951, BUTTON_CODE_LAST = 171, ACT_RANGE_ATTACK2_LOW = 19, ACT_SLAM_STICKWALL_ND_ATTACH = 233, ACT_RUN_AIM_RIFLE_STIMULATED = 338, ACT_DOD_HS_CROUCH_STICKGRENADE = 976, WEAPON_PROFICIENCY_POOR = 0, kRenderFxDistort = 15, ACT_MP_CROUCHWALK_PRIMARY = 1049, ACT_HL2MP_RUN_CHARGING = 1622, ACT_DOD_PRIMARYATTACK_PRONE_KNIFE = 879, ACT_OVERLAY_SHIELD_UP = 444, ACT_VM_IDLE_DEPLOYED_3 = 540, KEY_N = 24, ACT_DOD_WALK_IDLE_MP40 = 681, ACT_MP_CROUCH_DEPLOYED_IDLE = 992, ACT_HL2MP_RUN_FIST = 1962, ACT_DOD_PRONE_DEPLOY_30CAL = 839, ACT_DOD_ZOOMLOAD_PSCHRECK = 917, ACT_IDLE_ANGRY_SHOTGUN = 324, ACT_MP_GESTURE_VC_HANDMOUTH = 1377, IN_LEFT = 128, MOVETYPE_ISOMETRIC = 1, ACT_DOD_HS_CROUCH_MP44 = 978, PATTACH_ABSORIGIN = 0, SCHED_SPECIAL_ATTACK1 = 45, ACT_DOD_PRONE_AIM_MP44 = 690, ACT_DOD_PRIMARYATTACK_PRONE_30CAL = 871, ACT_WALK_RELAXED = 82, ACT_DOD_RELOAD_CROUCH_RIFLEGRENADE = 904, ACT_SLAM_DETONATOR_THROW_DRAW = 266, KEY_PAGEDOWN = 77, ACT_DOD_WALK_ZOOM_BAZOOKA = 823, ACT_VM_PULLBACK_HIGH = 177, CONTENTS_SLIME = 16, ACT_DOD_RELOAD_RIFLEGRENADE = 900, ACT_MP_SWIM_IDLE = 1010, ACT_GESTURE_RANGE_ATTACK_SLAM = 314, PLAYERANIMEVENT_SWIM = 7, ACT_HL2MP_IDLE_MAGIC = 1653, ACT_HL2MP_GESTURE_RANGE_ATTACK_DUEL = 1852, ACT_DOD_HS_IDLE = 958, EFL_NOTIFY = 64, DMG_PLASMA = 16777216, ACT_MELEE_ATTACK1 = 64, ACT_MP_GRENADE1_IDLE = 1272, ACT_DEPLOY_IDLE = 471, TYPE_CONVAR = 27, ACT_SLAM_THROW_THROW_ND = 246, EF_NORECEIVESHADOW = 64, ACT_DOD_PRONEWALK_IDLE_BAR = 807, ACT_DOD_CROUCHWALK_AIM_RIFLE = 635, ACT_DOD_RELOAD_DEPLOYED_MG34 = 921, ACT_RUN_AGITATED = 88, RENDERGROUP_VIEWMODEL = 10, TYPE_DLIGHT = 32, NAV_MESH_NAV_BLOCKER = 2147483648, ACT_HL2MP_IDLE_CROUCH_SHOTGUN = 1820, ACT_HL2MP_GESTURE_RELOAD_SCARED = 1699, PLAYERANIMEVENT_CUSTOM = 19, ACT_OBJ_STARTUP = 464, ACT_GESTURE_RELOAD_PISTOL = 383, ACT_PHYSCANNON_DETACH = 403, ACT_OVERLAY_PRIMARYATTACK = 443, ACT_HL2MP_GESTURE_RELOAD_PISTOL = 1793, FL_GODMODE = 32768, ACT_GMOD_GESTURE_MELEE_SHOVE_1HAND = 2025, ACT_GMOD_TAUNT_DANCE = 1642, ACT_DOD_WALK_AIM_GREASE = 701, ACT_IDLE_ANGRY_MELEE = 347, ACT_HL2MP_SWIM_ZOMBIE = 1712, ACT_FLY = 25, NAV_MESH_STOP = 16, ACT_MP_GESTURE_VC_FINGERPOINT_PDA = 1420, ACT_DOD_CROUCH_IDLE_PSCHRECK = 789, ACT_GMOD_GESTURE_DISAGREE = 1613, MASK_PLAYERSOLID_BRUSHONLY = 81931, ACT_180_LEFT = 129, color_transparent = { r = 255, b = 255, a = 0, g = 255, }, FL_AIMTARGET = 131072, SCHED_FEAR_FACE = 14, ACT_HL2MP_IDLE_CROUCH_SUITCASE = 1716, SND_IGNORE_NAME = 512, IN_ALT2 = 32768, ACT_DOD_STAND_AIM_SPADE = 761, SURF_SKY = 4, ACT_HL2MP_RUN_PROTECTED = 1624, ACT_HL2MP_WALK_CROUCH_DUEL = 1851, CLASS_MANHACK = 13, ACT_DOD_RELOAD_BOLT = 893, ACT_HL2MP_IDLE_CROUCH = 1780, ACT_DOD_STAND_IDLE_MP40 = 678, SND_STOP_LOOPING = 32, ACT_SHIPLADDER_DOWN = 38, ACT_HL2MP_SWIM_CAMERA = 1682, ACT_HL2MP_IDLE_CROUCH_GRENADE = 1840, ACT_HL2MP_IDLE_REVOLVER = 1663, CONTENTS_MONSTER = 33554432, HULL_LARGE_CENTERED = 8, ACT_MP_RELOAD_STAND_PRIMARY_LOOP = 1066, SCHED_ALERT_REACT_TO_COMBAT_SOUND = 7, ACT_SMG2_IDLE2 = 270, ACT_DOD_PRIMARYATTACK_PRONE_GREN_FRAG = 875, FCVAR_ARCHIVE = 128, ACT_DOD_WALK_AIM_GREN_FRAG = 740, CLASS_METROPOLICE = 14, ACT_HL2MP_RUN_SCARED = 1695, ACT_HL2MP_GESTURE_RELOAD_CAMERA = 1679, IN_FORWARD = 8, MOVECOLLIDE_FLY_SLIDE = 3, ACT_MP_JUMP_PDA = 1351, ACT_DOD_PLANT_TNT = 987, CONTENTS_WINDOW = 2, KEY_F8 = 99, ACT_BUSY_LEAN_LEFT_ENTRY = 387, kRenderFxStrobeSlow = 9, RENDERMODE_TRANSADD = 5, WEAPON_PROFICIENCY_AVERAGE = 1, ACT_GET_UP_CROUCH = 511, RENDERGROUP_OTHER = 13, ACT_HL2MP_WALK_SCARED = 1694, ACT_HL2MP_IDLE_CROUCH_ANGRY = 1686, ACT_MP_ATTACK_STAND_PRIMARYFIRE_DEPLOYED = 1012, SOLID_OBB = 3, CLASS_VORTIGAUNT = 18, ACT_DOD_DEPLOY_MG = 834, ACT_DOD_HS_CROUCH_PISTOL = 975, ACT_SLAM_DETONATOR_DRAW = 262, ACT_GESTURE_TURN_RIGHT = 158, RENDERMODE_TRANSTEXTURE = 2, ACT_DOD_CROUCHWALK_AIM_PSCHRECK = 784, ACT_SLAM_THROW_TO_STICKWALL = 250, MAT_DEFAULT = 88, ACT_VM_UNDEPLOY_3 = 549, ACT_RUN_RPG = 353, ACT_ROLL_RIGHT = 42, KEY_PAD_2 = 39, TEXT_ALIGN_RIGHT = 2, EFL_DORMANT = 2, FVPHYSICS_PART_OF_RAGDOLL = 8, SCHED_RUN_FROM_ENEMY_FALLBACK = 33, BLOOD_COLOR_MECH = 3, ACT_DOD_PRONE_AIM_30CAL = 729, ACT_GET_DOWN_STAND = 508, ACT_VM_DEPLOY_5 = 557, KEY_PAD_PLUS = 50, BUTTON_CODE_NONE = 0, ACT_MP_CROUCHWALK_MELEE = 1176, KEY_Q = 27, DMG_BUCKSHOT = 536870912, ACT_MELEE_ATTACK2 = 65, ACT_DOD_PRONE_ZOOM_PSCHRECK = 831, ACT_DOD_RUN_AIM_GREN_STICK = 749, PLAYERANIMEVENT_CUSTOM_SEQUENCE = 21, BOX_RIGHT = 2, CONTENTS_LADDER = 536870912, COLLISION_GROUP_PUSHAWAY = 17, ACT_SWIM = 28, ACT_HL2MP_WALK_CROUCH_KNIFE = 1979, MAT_EGGSHELL = 69, JOYSTICK_FIRST = 114, ACT_MP_AIRWALK = 998, ACT_HL2MP_JUMP_SCARED = 1700, TRACER_BEAM = 3, ACT_DOD_CROUCH_IDLE_MP44 = 692, EFL_NO_ROTORWASH_PUSH = 2097152, ACT_GRENADE_ROLL = 473, FSOLID_NOT_SOLID = 4, ACT_MP_STAND_PDA = 1345, ACT_HL2MP_WALK_GRENADE = 1838, ACT_DOD_RELOAD_GARAND = 888, ACT_RANGE_ATTACK_SHOTGUN = 287, BOX_FRONT = 0, SCHED_ALERT_STAND = 9, ACT_IDLE_ON_FIRE = 125, PLAYERANIMEVENT_FLINCH_LEFTLEG = 13, ACT_MP_ATTACK_CROUCH_GRENADE_PRIMARY = 1106, KEY_XBUTTON_RIGHT_SHOULDER = 119, ACT_DOD_RUN_IDLE_BOLT = 656, ACT_HL2MP_FIST_BLOCK = 1971, ACT_DOD_RUN_IDLE_GREASE = 708, SIM_GLOBAL_ACCELERATION = 3, MAT_CONCRETE = 67, ACT_DOD_WALK_AIM_30CAL = 727, KEY_LWIN = 85, ACT_DEEPIDLE3 = 516, SCHED_WAIT_FOR_SPEAK_FINISH = 67, ACT_MP_GESTURE_FLINCH_RIGHTLEG = 1270, ACT_TRIPMINE_WORLD = 492, ACT_ZOMBIE_CLIMB_END = 1652, ACT_HL2MP_WALK_CROUCH_SUITCASE = 1717, ACT_DOD_RELOAD_MP40 = 891, CHAN_WEAPON = 1, ACT_VM_DEPLOYED_IN = 1912, ACT_DOD_HS_IDLE_30CAL = 960, ACT_DOD_CROUCHWALK_IDLE_MG = 719, EFL_DIRTY_ABSANGVELOCITY = 8192, ACT_DOD_RELOAD_DEPLOYED_BAR = 922, ACT_LAND = 33, ACT_WALK_AIM_STEALTH = 97, KEY_ESCAPE = 70, IN_SPEED = 131072, ACT_HL2MP_JUMP_ANGRY = 1690, SCHED_INTERACTION_MOVE_TO_PARTNER = 85, SURF_HINT = 256, ACT_VM_READY_M203 = 1939, ACT_WALK_CROUCH_RPG = 354, MASK_SHOT_HULL = 100679691, OBS_MODE_NONE = 0, IN_DUCK = 4, DMG_POISON = 131072, MAT_TILE = 84, ACT_VM_IDLE_TO_LOWERED = 203, ACT_VM_IDLE_8 = 526, CAP_FRIENDLY_DMG_IMMUNE = 33554432, ACT_DOD_CROUCHWALK_AIM_BAR = 797, TYPE_USERCMD = 19, ACT_MP_GESTURE_FLINCH_STOMACH = 1266, ACT_HL2MP_GESTURE_RELOAD_MAGIC = 1659, ACT_HL2MP_IDLE_FIST = 1960, FL_CLIENT = 256, ACT_DOD_WALK_IDLE_PSCHRECK = 791, ACT_HL2MP_IDLE_CROUCH_RPG = 1830, ACT_DOD_RELOAD_PRONE_DEPLOYED_MG34 = 945, ACT_RELOAD_PISTOL_LOW = 377, ACT_DOD_PRIMARYATTACK_PRONE_SPADE = 881, ACT_VM_RELOAD_END_EMPTY = 1953, ACT_DIE_RIGHTSIDE = 408, EF_NODRAW = 32, FL_DISSOLVING = 536870912, ACT_GMOD_TAUNT_ROBOT = 1643, ACT_VM_RELOAD_EMPTY = 523, ACT_HL2MP_JUMP_CAMERA = 1680, ACT_DOD_RELOAD_PRONE_PISTOL = 923, EFL_DIRTY_ABSVELOCITY = 4096, ACT_SMG2_TOAUTO = 275, ACT_VM_PRIMARYATTACK_3 = 568, ACT_GESTURE_RANGE_ATTACK_PISTOL_LOW = 313, ACT_MP_VCD = 1009, CT_DEFAULT = 0, ACT_HL2MP_JUMP_ZOMBIE = 1710, ACT_RUN_RIFLE_RELAXED = 333, kRenderFxEnvRain = 20, RENDERGROUP_OPAQUE = 7, ACT_DOD_SPRINT_IDLE_RIFLE = 644, ACT_HL2MP_WALK_ZOMBIE_01 = 1628, SIM_LOCAL_FORCE = 2, BONE_USED_MASK = 524032, ACT_MP_ATTACK_CROUCH_GRENADE = 1018, TYPE_SAVE = 13, ACT_SLAM_TRIPMINE_TO_THROW_ND = 260, GAME_DLL = true, ACT_RANGE_AIM_AR2_LOW = 300, KEY_P = 26, SCHED_MOVE_TO_WEAPON_RANGE = 34, ACT_SLAM_TRIPMINE_IDLE = 255, ACT_VM_DEPLOY_4 = 558, KEY_DOWN = 90, CAP_MOVE_SWIM = 16, ACT_HL2MP_WALK_CROUCH_SCARED = 1697, KEY_6 = 7, ACT_HL2MP_WALK_CROUCH_ZOMBIE_03 = 1635, ACT_DOD_CROUCH_IDLE_TNT = 981, SCHED_CHASE_ENEMY_FAILED = 18, ACT_DOD_RUN_IDLE_C96 = 630, ACT_DOD_RELOAD_DEPLOYED_FG42 = 918, KEY_UP = 88, KEY_XBUTTON_Y = 117, ACT_VM_DEPLOYED_IRON_IN = 1919, ACT_HL2MP_IDLE_MELEE_ANGRY = 1625, ACT_MP_RUN_SECONDARY = 1111, KEY_NONE = 0, ACT_DO_NOT_DISTURB = 171, SCHED_NEW_WEAPON = 63, ACT_DOD_PRONE_AIM_MG = 716, ACT_MP_ATTACK_SWIM_SECONDARYFIRE = 1020, IN_MOVELEFT = 512, ACT_TURNRIGHT45 = 459, ACT_DOD_WALK_AIM_RIFLE = 636, ACT_VM_RELOADEMPTY = 1927, KEY_PAD_3 = 40, BUTTON_CODE_COUNT = 172, ACT_VM_IIDLE_M203 = 1945, ACT_DOD_RUN_IDLE_30CAL = 734, ACT_VM_DFIREMODE = 1933, ACT_MP_JUMP_LAND_SECONDARY = 1118, ACT_HL2MP_WALK_CROUCH_FIST = 1964, DMG_NEVERGIB = 4096, ACT_DOD_PRONEWALK_IDLE_BOLT = 658, EFL_DONTWALKON = 67108864, ACT_SIGNAL2 = 50, ACT_DOD_RELOAD_PISTOL = 897, ACT_HL2MP_IDLE_DUEL = 1847, ACT_DOD_PRIMARYATTACK_KNIFE = 878, ACT_DOD_RELOAD_PRONE = 596, MASK_ALL = 4294967295, ACT_HL2MP_SWIM_IDLE_SLAM = 1895, IN_ALT1 = 16384, ACT_MP_ATTACK_SWIM_SECONDARY = 1122, ACT_DIE_HEADSHOT = 113, SURF_LIGHT = 1, DMG_DISSOLVE = 67108864, ACT_DEEPIDLE4 = 517, ACT_HL2MP_WALK_SUITCASE = 1714, ACT_DOD_CROUCH_ZOOM_BAZOOKA = 821, ACT_BUSY_STAND = 398, KEY_TAB = 67, ACT_WALK_CARRY = 427, CLASS_COMBINE_GUNSHIP = 10, CLASS_HACKED_ROLLERMINE = 24, ACT_GESTURE_FLINCH_LEFTARM = 153, ACT_CROSSBOW_FIDGET_UNLOADED = 488, ACT_DOD_PRONEWALK_IDLE_PISTOL = 619, ACT_DOD_RELOAD_PRONE_C96 = 936, ACT_HL2MP_SIT_MELEE = 2013, ACT_DOD_RELOAD_CROUCH_BOLT = 905, TYPE_MATRIX = 29, FL_NPC = 16384, BONE_SCREEN_ALIGN_SPHERE = 8, CLASS_CITIZEN_PASSIVE = 7, ACT_DOD_RELOAD_M1CARBINE = 894, KEY_PAD_DECIMAL = 52, FSOLID_CUSTOMBOXTEST = 2, EFL_NO_WATER_VELOCITY_CHANGE = 536870912, ACT_DOD_WALK_IDLE_BOLT = 655, CONTENTS_CURRENT_180 = 1048576, ACT_DOD_CROUCHWALK_IDLE_PSCHRECK = 790, ACT_DOD_PRONE_ZOOM_BOLT = 819, ACT_HL2MP_SWIM_IDLE_AR2 = 1815, ACT_MP_RELOAD_SWIM_PRIMARY_END = 1073, SCHED_SWITCH_TO_PENDING_WEAPON = 65, ACT_WALK_RPG = 352, ACT_DOD_RUN_IDLE_BAZOOKA = 779, ACT_RAPPEL_LOOP = 128, ACT_DOD_RELOAD_RIFLE = 899, ACT_SPECIAL_ATTACK2 = 108, ACT_HL2MP_RUN_SHOTGUN = 1819, ACT_SLAM_STICKWALL_ND_IDLE = 230, COLLISION_GROUP_NPC = 9, FCVAR_LUA_CLIENT = 262144, ALL_VISIBLE_CONTENTS = 255, BLOOD_COLOR_RED = 0, ACT_OBJ_PLACING = 467, ACT_GESTURE_RANGE_ATTACK_AR2 = 304, EFL_IN_SKYBOX = 131072, FCVAR_USERINFO = 512, ACT_MP_JUMP_LAND_PDA = 1354, HULL_LARGE = 7, ACT_HL2MP_JUMP_MAGIC = 1660, BOX_LEFT = 3, ACT_IDLE_SHOTGUN_AGITATED = 341, ACT_GESTURE_TURN_LEFT45 = 159, ACT_VM_CRAWL_EMPTY = 1898, TYPE_COLOR = 255, CONTENTS_TRANSLUCENT = 268435456, ACT_RUN_RELAXED = 86, MAT_CLIP = 73, RENDERMODE_NORMAL = 0, ACT_HL2MP_SIT = 1970, KEY_A = 11, CLASS_SCANNER = 16, TRANSMIT_ALWAYS = 0, ACT_SIGNAL_ADVANCE = 52, MASK_VISIBLE = 24705, ACT_HL2MP_SWIM_IDLE_REVOLVER = 1671, CAP_AUTO_DOORS = 1024, PLAYERANIMEVENT_FLINCH_LEFTARM = 11, ACT_DOD_CROUCH_AIM_TOMMY = 660, ACT_MP_ATTACK_SWIM_GRENADE_BUILDING = 1324, ACT_HL2MP_WALK_SLAM = 1888, ACT_VM_SHOOTLAST = 1935, ACT_DOD_CROUCHWALK_AIM = 602, TYPE_PANEL = 22, BONE_USED_BY_VERTEX_LOD6 = 65536, ACT_DOD_PRONEWALK_IDLE_GREASE = 710, SF_NPC_WAIT_TILL_SEEN = 1, ACT_VM_UNDEPLOY_8 = 544, ACT_DOD_HS_IDLE_BAZOOKA = 961, COLLISION_GROUP_NPC_SCRIPTED = 19, ACT_DOD_SPRINT_IDLE_MG = 722, ACT_GESTURE_RANGE_ATTACK1 = 137, ACT_USE = 48, EFL_IS_BEING_LIFTED_BY_BARNACLE = 1048576, KEY_9 = 10, KEY_SCROLLLOCKTOGGLE = 106, COLLISION_GROUP_INTERACTIVE_DEBRIS = 3, ACT_MP_ATTACK_SWIM_PRIMARYFIRE = 1019, ACT_DIEFORWARD = 22, ACT_DOD_HS_CROUCH_30CAL = 970, ACT_RANGE_ATTACK_AR2 = 279, SCHED_RANGE_ATTACK1 = 43, ACT_SIGNAL1 = 49, ACT_MP_GESTURE_VC_FINGERPOINT_SECONDARY = 1390, MOVECOLLIDE_DEFAULT = 0, CONTENTS_CURRENT_UP = 4194304, kRenderFxStrobeFast = 10, ACT_DOD_RELOAD_CROUCH_RIFLE = 903, EFL_DIRTY_SPATIAL_PARTITION = 32768, PATTACH_CUSTOMORIGIN = 2, MOUSE_5 = 111, CAP_USE_WEAPONS = 2097152, BONE_SCREEN_ALIGN_CYLINDER = 16, ACT_HL2MP_IDLE_CROUCH_FIST = 1963, ACT_HL2MP_IDLE_PASSIVE = 1985, CAP_WEAPON_MELEE_ATTACK2 = 65536, ACT_MP_SWIM_PRIMARY = 1054, MASK_NPCWORLDSTATIC = 131083, BUILD_LUACHECK = true, ACT_HL2MP_JUMP_DUEL = 1854, ACT_BUSY_SIT_CHAIR = 395, KEY_S = 29, ACT_HL2MP_GESTURE_RANGE_ATTACK_MELEE2 = 2000, ACT_HL2MP_JUMP_KNIFE = 1982, SCHED_TAKE_COVER_FROM_ORIGIN = 30, ACT_DOD_PRIMARYATTACK_MP44 = 858, ACT_VM_RELOAD_SILENCED = 494, ACT_VM_CRAWL = 1897, ACT_VM_DRAW_SILENCED = 497, SCHED_DIE_RAGDOLL = 54, ACT_DOD_RUN_AIM_MP44 = 689, ACT_DOD_RUN_AIM_BOLT = 650, TYPE_DAMAGEINFO = 15, MOVETYPE_FLYGRAVITY = 5, BLEND_SRC_ALPHA_SATURATE = 8, ACT_DIE_FRONTSIDE = 407, ACT_DOD_CROUCH_AIM_GREASE = 699, ACT_MELEE_ATTACK_SWING_GESTURE = 143, ACT_GRENADE_TOSS = 474, CONTINUOUS_USE = 0, ACT_HL2MP_RUN_MAGIC = 1655, SND_SHOULDPAUSE = 128, ACT_GESTURE_BIG_FLINCH = 145, ACT_READINESS_AGITATED_TO_STIMULATED = 420, ACT_HL2MP_SWIM_IDLE_ZOMBIE = 1711, ACT_MP_DEPLOYED_PRIMARY = 1055, ACT_HL2MP_SWIM_IDLE_PHYSGUN = 1865, SCHED_FAIL = 81, CONTENTS_TEAM2 = 4096, ACT_HL2MP_IDLE_ANGRY = 1683, SCHED_RANGE_ATTACK2 = 44, SF_NPC_GAG = 2, TYPE_PARTICLESYSTEM = 40, MASK_DEADSOLID = 65547, NAV_MESH_NO_HOSTAGES = 2048, DMG_ACID = 1048576, ACT_DOD_PRIMARYATTACK_PSCHRECK = 884, ACT_VM_DEPLOYED_IRON_FIRE = 1921, ACT_MP_RUN = 996, ACT_HL2MP_SIT_AR2 = 2008, KEY_F9 = 100, ACT_WALK_AIM_SHOTGUN = 367, ACT_DOD_CROUCH_IDLE_MG = 718, MOVETYPE_FLY = 4, NPC_STATE_IDLE = 1, ACT_DOD_RELOAD_C96 = 901, ACT_DOD_PRIMARYATTACK_CROUCH_KNIFE = 952, EF_BRIGHTLIGHT = 2, ACT_WALK_CROUCH_AIM_RIFLE = 361, ACT_DOD_PRONE_ZOOM_BAZOOKA = 825, ACT_HL2MP_GESTURE_RANGE_ATTACK_PASSIVE = 1990, ACT_GLOCK_SHOOT_RELOAD = 481, ACT_MP_RELOAD_AIRWALK_SECONDARY = 1133, ACT_VM_IDLE_DEPLOYED_7 = 536, ACT_HL2MP_JUMP_FIST = 1967, ACT_VM_DRAW_M203 = 1937, ACT_MP_ATTACK_CROUCH_GRENADE_BUILDING = 1323, ACT_HL2MP_IDLE_RPG = 1827, ACT_DOD_RUN_AIM_GREN_FRAG = 741, ACT_MP_AIRWALK_BUILDING = 1311, ACT_GESTURE_FLINCH_BLAST_DAMAGED_SHOTGUN = 149, ACT_VM_IDLE_6 = 528, ACT_HL2MP_GESTURE_RELOAD_ZOMBIE = 1709, MASK_SPLITAREAPORTAL = 48, MOUSE_LEFT = 107, ACT_HANDGRENADE_THROW2 = 476, RENDERMODE_GLOW = 3, ACT_MP_DOUBLEJUMP = 1005, ACT_HL2MP_RUN_ZOMBIE = 1705, ACT_DOD_WALK_IDLE_BAZOOKA = 778, KEY_XSTICK1_LEFT = 151, ACT_IDLE_SHOTGUN_STIMULATED = 340, kRenderFxPulseSlow = 1, ACT_BUSY_SIT_CHAIR_ENTRY = 396, ACT_MP_RELOAD_CROUCH_PRIMARY_END = 1070, ACT_RANGE_ATTACK_SHOTGUN_LOW = 288, ACT_GMOD_GESTURE_BECON = 1611, ACT_RIDE_MANNED_GUN = 431, ACT_SLAM_TRIPMINE_ATTACH2 = 258, CLASS_MILITARY = 15, MASK_CURRENT = 16515072, ACT_GESTURE_SMALL_FLINCH = 144, ACT_DOD_WALK_IDLE = 603, ACT_MP_RELOAD_SWIM_END = 1033, ACT_VM_PRIMARYATTACK = 181, ACT_HL2MP_SWIM_SMG1 = 1806, ACT_CROSSBOW_HOLSTER_UNLOADED = 1955, ACT_MP_RELOAD_AIRWALK_PRIMARY_END = 1076, ACT_HL2MP_GESTURE_RANGE_ATTACK_PISTOL = 1792, ACT_DOD_WALK_IDLE_MP44 = 694, ACT_HL2MP_WALK_CROUCH_ZOMBIE_01 = 1633, KEY_XBUTTON_STICK2 = 123, EFL_KEEP_ON_RECREATE_ENTITIES = 16, FCVAR_SERVER_CAN_EXECUTE = 268435456, KEY_8 = 9, CLASS_BARNACLE = 5, ACT_SMALL_FLINCH = 62, MAT_FOLIAGE = 79, MASK_BLOCKLOS_AND_NPCS = 33570881, ACT_DOD_PRONE_ZOOMED = 587, ACT_VM_RECOIL1 = 206, STEPSOUNDTIME_WATER_FOOT = 3, ACT_MP_JUMP_LAND_BUILDING = 1316, COLLISION_GROUP_DEBRIS_TRIGGER = 2, ACT_DOD_PRIMARYATTACK_PRONE_DEPLOYED_30CAL = 873, ACT_MP_JUMP_FLOAT_SECONDARY = 1117, color_white = { r = 255, b = 255, a = 255, g = 255, }, ACT_POLICE_HARASS1 = 343, ACT_GESTURE_RELOAD = 382, ACT_MP_AIRWALK_PRIMARY = 1048, ACT_VM_DEPLOYED_LIFTED_IDLE = 1925, CT_REBEL = 3, ACT_MP_GESTURE_VC_NODNO_MELEE = 1400, ACT_FLINCH_LEFTLEG = 122, IN_JUMP = 2, ACT_GESTURE_TURN_LEFT90 = 161, SCHED_MOVE_AWAY_END = 70, HULL_MEDIUM = 5, DMG_SLASH = 4, ACT_DOD_CROUCH_AIM_RIFLE = 634, KEY_INSERT = 72, BONE_USED_BY_HITBOX = 256, ACT_VM_DEPLOY_1 = 561, OBS_MODE_DEATHCAM = 1, CAP_WEAPON_MELEE_ATTACK1 = 32768, MOVETYPE_STEP = 3, ACT_SLAM_THROW_THROW2 = 245, CLASS_ZOMBIE = 19, KEY_PAD_5 = 42, ACT_VM_DEPLOYED_OUT = 1918, ACT_HL2MP_WALK_CROUCH_PISTOL = 1791, EF_PARENT_ANIMATES = 512, ACT_MP_GESTURE_FLINCH_HEAD = 1264, NAV_MESH_NO_MERGE = 8192, CONTENTS_TESTFOGVOLUME = 256, ACT_HL2MP_GESTURE_RELOAD_PHYSGUN = 1863, ACT_HL2MP_SIT_PHYSGUN = 2009, ACT_SLAM_DETONATOR_DETONATE = 263, ACT_MP_GESTURE_VC_THUMBSUP = 1380, ACT_DOD_RUN_AIM_SPADE = 765, HITGROUP_GEAR = 10, ACT_MP_ATTACK_STAND_STARTFIRE = 1039, ACT_DOD_PRIMARYATTACK_GREASE = 860, ACT_DOD_CROUCHWALK_AIM_KNIFE = 755, MOUSE_MIDDLE = 109, ACT_READINESS_RELAXED_TO_STIMULATED = 418, ACT_BUSY_SIT_GROUND = 392, SF_ROLLERMINE_FRIENDLY = 65536, PLAYER_SUPERJUMP = 3, ACT_GESTURE_FLINCH_BLAST = 146, CONTENTS_TEAM1 = 2048, ACT_SLAM_STICKWALL_DRAW = 237, SCHED_FLEE_FROM_BEST_SOUND = 29, ACT_MP_ATTACK_SWIM_PDA = 1357, ACT_HL2MP_GESTURE_RELOAD = 1783, SF_NPC_NO_WEAPON_DROP = 8192, ACT_WALK_STEALTH_PISTOL = 373, kRenderFxNoDissipation = 14, TYPE_PIXELVISHANDLE = 31, ACT_HL2MP_SWIM_IDLE_MELEE2 = 2003, ACT_OBJ_IDLE = 466, ACT_MP_CROUCH_SECONDARY = 1110, kRenderFxFlickerFast = 13, MOVETYPE_WALK = 2, ACT_HL2MP_SWIM_IDLE = 2026, FCVAR_SERVER_CANNOT_QUERY = 536870912, ACT_MP_ATTACK_STAND_PREFIRE = 1037, CLASS_COMBINE_HUNTER = 25, TYPE_TEXTURE = 25, ACT_WALK_AIM = 7, EF_BONEMERGE_FASTCULL = 128, ACT_GMOD_GESTURE_MELEE_SHOVE_2HAND = 2024, ACT_DOD_SECONDARYATTACK_TOMMY = 852, IN_ATTACK = 1, ACT_MP_GESTURE_VC_NODYES_BUILDING = 1417, ACT_DOD_WALK_AIM_GREN_STICK = 748, ACT_MP_GESTURE_VC_FISTPUMP_MELEE = 1397, ACT_HL2MP_SWIM_IDLE_MELEE = 1885, ACT_DRIVE_AIRBOAT = 1972, SCHED_TAKE_COVER_FROM_BEST_SOUND = 28, KEY_H = 18, TYPE_VIDEO = 33, MOUSE_COUNT = 7, ACT_DOD_WALK_AIM_C96 = 623, ACT_HL2MP_SWIM_PISTOL = 1796, TYPE_TABLE = 5, ACT_MP_ATTACK_STAND_BUILDING = 1318, TYPE_PATH = 36, ACT_DOD_CROUCH_ZOOM_PSCHRECK = 827, ACT_RELOAD_START = 67, ACT_GLIDE = 27, TYPE_NAVLADDER = 39, ACT_HL2MP_WALK_ZOMBIE = 1704, ACT_HL2MP_WALK_PASSIVE = 1986, ACT_GMOD_GESTURE_RANGE_ZOMBIE = 1640, ACT_DOD_WALK_AIM_MP40 = 675, ACT_STEP_LEFT = 133, SCHED_COMBAT_FACE = 12, FCVAR_NEVER_AS_STRING = 4096, ACT_MP_JUMP_FLOAT_MELEE = 1179, ACT_IDLE_ANGRY_RPG = 350, JOYSTICK_LAST = 161, ACT_MP_SECONDARY_GRENADE1_IDLE = 1284, BONE_USED_BY_VERTEX_LOD1 = 2048, ACT_HL2MP_SWIM_IDLE_FIST = 1968, MASK_NPCSOLID = 33701899, ACT_MP_PRIMARY_GRENADE2_DRAW = 1280, ACT_HANDGRENADE_THROW3 = 477, ACT_VM_IIN = 1904, ACT_SWIM_IDLE = 29, ACT_HL2MP_JUMP_PASSIVE = 1992, ACT_MP_GRENADE2_IDLE = 1275, ACT_DOD_CROUCH_IDLE_30CAL = 731, CAP_NO_HIT_PLAYER = 268435456, ACT_MP_GRENADE1_ATTACK = 1273, ACT_DOD_PRIMARYATTACK_DEPLOYED_30CAL = 872, ACT_DOD_RELOAD_CROUCH_MP44 = 906, ACT_HL2MP_JUMP_RPG = 1834, ACT_VM_IDLE_1 = 533, ACT_DOD_RELOAD_PRONE_DEPLOYED_MG = 944, FVPHYSICS_NO_NPC_IMPACT_DMG = 2048, ACT_CROUCHING_GRENADEIDLE = 438, ACT_DOD_HS_IDLE_PISTOL = 965, ACT_DOD_WALK_AIM_KNIFE = 756, STEPSOUNDTIME_NORMAL = 0, ACT_HL2MP_GESTURE_RANGE_ATTACK_SMG1 = 1802, ACT_HL2MP_GESTURE_RANGE_ATTACK_PHYSGUN = 1862, ACT_HL2MP_WALK_CROSSBOW = 1868, ACT_MP_JUMP_MELEE = 1177, ACT_MP_CROUCH_MELEE = 1172, ACT_DOD_CROUCH_IDLE_RIFLE = 640, ACT_DOD_PRIMARYATTACK_BAZOOKA = 882, ACT_WALK_ANGRY = 342, FCVAR_NONE = 0, ACT_DOD_PRIMARYATTACK_PRONE_TOMMY = 851, ACT_HL2MP_GESTURE_RELOAD_FIST = 1966, ACT_VM_RECOIL2 = 207, ACT_DOD_RUN_IDLE_MP44 = 695, ACT_HL2MP_WALK_CROUCH_PHYSGUN = 1861, KEY_XBUTTON_RTRIGGER = 155, ACT_DOD_CROUCH_AIM_PSCHRECK = 783, ACT_HL2MP_GESTURE_RANGE_ATTACK_CAMERA = 1678, ACT_SLAM_STICKWALL_ATTACH = 231, ACT_RUN_PISTOL = 370, BLEND_SRC_COLOR = 9, ACT_MP_RELOAD_CROUCH_SECONDARY_LOOP = 1128, MOVETYPE_NONE = 0, ACT_MP_GESTURE_VC_FISTPUMP_PDA = 1421, FCVAR_ARCHIVE_XBOX = 16777216, ACT_MP_JUMP_START_SECONDARY = 1116, MASK_PLAYERSOLID = 33636363, ACT_90_LEFT = 131, ACT_HL2MP_WALK_SHOTGUN = 1818, ACT_VM_SPRINT_ENTER = 432, ACT_90_RIGHT = 132, ACT_MP_RELOAD_AIRWALK_PRIMARY_LOOP = 1075, ACT_GESTURE_FLINCH_RIGHTARM = 154, ACT_MP_RELOAD_SWIM_PRIMARY = 1071, ACT_MP_RELOAD_STAND_PRIMARY_END = 1067, ACT_HL2MP_WALK_CROUCH_REVOLVER = 1667, ACT_DOD_RUN_AIM_C96 = 624, ACT_DOD_WALK_ZOOMED = 584, ACT_MP_RELOAD_STAND_PRIMARY = 1065, ACT_PRONE_FORWARD = 512, BLEND_ONE_MINUS_SRC_COLOR = 10, ACT_MP_ATTACK_STAND_PRIMARY = 1059, ACT_DOD_STAND_IDLE_30CAL = 730, ACT_DOD_STAND_AIM_PISTOL = 607, ACT_VM_HOLSTERFULL_M203 = 1943, ACT_GMOD_GESTURE_AGREE = 1610, CONTENTS_WATER = 32, ACT_DOD_RUN_AIM_TOMMY = 663, OBS_MODE_IN_EYE = 4, IN_GRENADE2 = 16777216, ACT_BUSY_LEAN_BACK_EXIT = 391, DMG_DROWN = 16384, ACT_DOD_PRONEWALK_IDLE_PSCHRECK = 794, ACT_VM_PRIMARYATTACK_2 = 569, ACT_GMOD_GESTURE_BOW = 1612, KEY_B = 12, ACT_HL2MP_WALK_CROUCH_ZOMBIE_04 = 1636, ACT_RELOAD_FINISH = 68, ACT_HL2MP_WALK_FIST = 1961, ACT_MP_RELOAD_AIRWALK_END = 1036, ACT_MP_ATTACK_AIRWALK_SECONDARYFIRE = 1023, ACT_HL2MP_SWIM_GRENADE = 1846, ACT_VM_HITLEFT2 = 188, BONE_USED_BY_ANYTHING = 524032, ACT_VM_IRECOIL1 = 1928, HITGROUP_GENERIC = 0, ACT_MP_ATTACK_CROUCH_MELEE = 1184, ACT_MP_CROUCHWALK = 999, SOLID_CUSTOM = 5, EF_NOINTERP = 8, ACT_DOD_PRONE_AIM_GREASE = 703, ACT_RUN_AIM_AGITATED = 100, MAT_GRATE = 71, ACT_HL2MP_WALK_CROUCH_CAMERA = 1677, ACT_GESTURE_MELEE_ATTACK_SWING = 318, SCHED_MOVE_AWAY_FROM_ENEMY = 25, KEY_C = 13, ACT_DOD_SPRINT_IDLE_BAZOOKA = 780, ACT_VM_HITKILL = 1911, KEY_SPACE = 65, BONE_USED_BY_VERTEX_LOD4 = 16384, FCVAR_UNLOGGED = 2048, ACT_DOD_HS_IDLE_TOMMY = 967, FCVAR_PROTECTED = 32, ACT_HL2MP_GESTURE_RELOAD_CROSSBOW = 1873, KEY_I = 19, ACT_DOD_CROUCHWALK_IDLE_30CAL = 732, ACT_ZOMBIE_LEAP_START = 1648, ACT_VM_IIN_EMPTY = 1905, ACT_HL2MP_IDLE_CROSSBOW = 1867, SCHED_SCRIPTED_RUN = 58, ACT_HL2MP_GESTURE_RELOAD_GRENADE = 1843, ACT_DOD_RELOAD_PRONE_BAR = 930, ACT_VM_PULLBACK = 176, ACT_MP_RELOAD_SWIM_LOOP = 1032, ACT_HOVER = 26, SURF_NODRAW = 128, ACT_DOD_HS_IDLE_KNIFE = 963, ACT_HL2MP_WALK_CROUCH_RPG = 1831, CONTENTS_AUX = 4, KEY_XBUTTON_DOWN = 148, DMG_REMOVENORAGDOLL = 4194304, SF_CITIZEN_MEDIC = 131072, CONTENTS_PLAYERCLIP = 65536, ACT_OBJ_UPGRADING = 469, ACT_DOD_STAND_AIM_PSCHRECK = 782, ACT_MP_DEPLOYED = 1007, NPC_STATE_PLAYDEAD = 5, ACT_DI_ALYX_HEADCRAB_MELEE = 414, ACT_DOD_WALK_ZOOM_BOLT = 817, ACT_MP_SECONDARY_GRENADE1_DRAW = 1283, ACT_OVERLAY_SHIELD_DOWN = 445, FL_WORLDBRUSH = 33554432, ACT_DOD_RELOAD_CROUCH_MP40 = 907, ACT_HL2MP_SWIM_SUITCASE = 1722, ACT_GESTURE_TURN_RIGHT45 = 160, ACT_MP_ATTACK_STAND_SECONDARY = 1120, ACT_GMOD_TAUNT_LAUGH = 1618, USE_OFF = 0, FSOLID_TRIGGER_TOUCH_DEBRIS = 512, ACT_DOD_HS_CROUCH_TOMMY = 977, MOVETYPE_CUSTOM = 11, SCHED_NONE = 0, ACT_MP_RELOAD_SWIM_SECONDARY_LOOP = 1131, ACT_MP_ATTACK_STAND_GRENADE_BUILDING = 1322, ACT_MP_RELOAD_AIRWALK_SECONDARY_END = 1135, SURF_HITBOX = 32768, ACT_DIE_GUTSHOT = 115, ACT_MP_GESTURE_VC_THUMBSUP_MELEE = 1398, FL_GRAPHED = 1048576, ACT_HL2MP_WALK_RPG = 1828, ACT_GESTURE_RANGE_ATTACK_ML = 307, ACT_HL2MP_WALK_CROUCH_SLAM = 1891, ACT_COMBAT_IDLE = 109, ACT_VM_IOUT_EMPTY = 1909, ACT_RANGE_ATTACK_SLAM = 291, ACT_SLAM_DETONATOR_HOLSTER = 264, ACT_WALK_AIM_AGITATED = 96, ACT_HL2MP_GESTURE_RANGE_ATTACK_RPG = 1832, ACT_DOD_RELOAD_PRONE_DEPLOYED_BAR = 941, SCHED_COMBAT_WALK = 16, TYPE_COUNT = 42, ACT_HL2MP_IDLE_CROUCH_CROSSBOW = 1870, HITGROUP_STOMACH = 3, ACT_POLICE_HARASS2 = 344, FCVAR_NOT_CONNECTED = 4194304, SCHED_FORCED_GO = 71, ACT_VM_MISSCENTER2 = 198, ACT_HL2MP_JUMP_MELEE2 = 2002, COLLISION_GROUP_NPC_ACTOR = 18, ACT_DOD_HS_CROUCH_K98 = 979, ACT_SLAM_STICKWALL_TO_THROW = 239, TYPE_RECIPIENTFILTER = 18, ACT_RUN_RPG_RELAXED = 357, ACT_IDLE_SUITCASE = 328, ACT_DOD_CROUCH_ZOOM_BOLT = 815, FCVAR_DONTRECORD = 131072, ACT_RUN_STIMULATED = 87, FCVAR_PRINTABLEONLY = 1024, MOUSE_WHEEL_UP = 112, KEY_COMMA = 58, ACT_GMOD_TAUNT_SALUTE = 1614, ACT_HL2MP_SWIM_IDLE_SHOTGUN = 1825, ACT_DOD_PRIMARYATTACK_CROUCH = 950, ACT_DOD_HS_IDLE_MG42 = 964, ACT_DOD_PRIMARYATTACK_PRONE_BOLT = 848, BLEND_ONE_MINUS_SRC_ALPHA = 5, WEAPON_PROFICIENCY_VERY_GOOD = 3, ACT_MP_SECONDARY_GRENADE2_IDLE = 1287, EFL_SERVER_ONLY = 512, ACT_DOD_SECONDARYATTACK_MP40 = 856, ACT_DOD_SECONDARYATTACK_CROUCH_TOMMY = 956, ACT_DOD_PRIMARYATTACK_CROUCH_GREN_STICK = 954, ACT_DOD_PRONE_AIM_MP40 = 677, ACT_SCRIPT_CUSTOM_MOVE = 15, TYPE_PHYSOBJ = 12, ACT_DOD_RELOAD_PRONE_DEPLOYED_30CAL = 943, kRenderFxFadeSlow = 5, SCHED_PATROL_RUN = 76, ACT_DOD_PRIMARYATTACK_PRONE_DEPLOYED_RIFLE = 844, DMG_FALL = 32, DMG_PARALYZE = 32768, ACT_DOD_STAND_ZOOM_BOLT = 814, ACT_DOD_RELOAD_DEPLOYED_MG = 920, ACT_VM_PRIMARYATTACK_6 = 565, ACT_DOD_RUN_IDLE_PISTOL = 617, ACT_DOD_SPRINT_AIM_SPADE = 767, ACT_READINESS_PISTOL_AGITATED_TO_STIMULATED = 424, ACT_DOD_STAND_AIM = 598, ACT_DOD_WALK_ZOOM_PSCHRECK = 829, ACT_DOD_DEPLOY_RIFLE = 832, ACT_RANGE_ATTACK1 = 16, ACT_HL2MP_SWIM_IDLE_CROSSBOW = 1875, ACT_VM_IDLE_DEPLOYED_1 = 542, g_SBoxObjects = { }, KEY_LAST = 106, ACT_MP_GESTURE_VC_THUMBSUP_SECONDARY = 1392, ACT_DIERAGDOLL = 24, ACT_DOD_RUN_AIM_BAR = 799, ACT_MP_GESTURE_VC_FISTPUMP = 1379, ACT_FIRE_END = 437, ACT_DIEBACKWARD = 21, KEY_PAGEUP = 76, ACT_DOD_PRIMARYATTACK_PRONE_PSCHRECK = 885, DMG_SONIC = 512, ACT_DOD_RELOAD_MP44 = 892, D_LI = 3, ACT_SHOTGUN_RELOAD_FINISH = 268, ACT_VM_DRYFIRE_LEFT = 499, MASK_WATER = 16432, BOX_BACK = 1, ACT_VM_RELOAD2 = 1958, ACT_VM_IDLE_5 = 529, SCHED_SPECIAL_ATTACK2 = 46, EFL_DIRTY_SURROUNDING_COLLISION_BOUNDS = 16384, COLLISION_GROUP_PLAYER = 5, ACT_RELOAD_LOW = 69, ACT_VM_PRIMARYATTACK_8 = 563, KEY_RCONTROL = 84, ACT_DOD_CROUCHWALK_ZOOMED = 586, MASK_SOLID_BRUSHONLY = 16395, SOLID_NONE = 0, ACT_DOD_ZOOMLOAD_BAZOOKA = 915, EF_NOSHADOW = 16, SCHED_FLINCH_PHYSICS = 80, MOVETYPE_VPHYSICS = 6, ACT_COVER_PISTOL_LOW = 301, ACT_HL2MP_RUN_AR2 = 1809, NPC_STATE_NONE = 0, ACT_DOD_PRONE_AIM_BOLT = 651, ACT_GESTURE_TURN_LEFT = 157, KEY_PAD_7 = 44, CONTENTS_ORIGIN = 16777216, ACT_ROLL_LEFT = 41, ACT_DOD_RELOAD_PRONE_FG42 = 933, ACT_MP_GESTURE_VC_NODNO_PRIMARY = 1388, ACT_WALK_PACKAGE = 327, ACT_MP_JUMP_FLOAT_PDA = 1353, ACT_SIGNAL_GROUP = 54, PATTACH_POINT_FOLLOW = 4, ACT_SIGNAL_LEFT = 56, ACT_OBJ_DISMANTLING = 463, HUD_PRINTCENTER = 4, ACT_IDLE_AIM_AGITATED = 92, ACT_DIE_LEFTSIDE = 410, ACT_RELOAD_SMG1_LOW = 379, ACT_MP_MELEE_GRENADE2_IDLE = 1293, IN_MOVERIGHT = 1024, ACT_MP_RELOAD_SWIM_PRIMARY_LOOP = 1072, ACT_VM_UNDEPLOY_4 = 548, ACT_VM_DEPLOYED_FIRE = 1914, ACT_MP_PRIMARY_GRENADE2_ATTACK = 1282, KEY_E = 15, ACT_OVERLAY_GRENADEIDLE = 441, ACT_MP_RELOAD_STAND_SECONDARY_LOOP = 1125, ACT_RANGE_ATTACK_SMG2 = 286, ACT_VM_HITRIGHT = 189, ACT_VM_IDLE_4 = 530, ACT_HL2MP_IDLE_CROUCH_DUEL = 1850, ACT_DOD_CROUCHWALK_ZOOM_BOLT = 816, OBS_MODE_ROAMING = 6, BONE_PHYSICS_PROCEDURAL = 2, ACT_MP_GESTURE_VC_THUMBSUP_PRIMARY = 1386, ACT_HL2MP_WALK_AR2 = 1808, ACT_DOD_PRONE_ZOOM_RIFLE = 813, ACT_DOD_RUN_ZOOM_RIFLE = 812, ACT_DOD_STAND_ZOOM_RIFLE = 808, SCHED_WAKE_ANGRY = 4, ACT_DOD_WALK_AIM_PSCHRECK = 785, ACT_DOD_WALK_IDLE_BAR = 804, ACT_DOD_CROUCHWALK_IDLE_BAR = 803, ACT_COVER_LOW_RPG = 351, ACT_HL2MP_WALK_ZOMBIE_04 = 1631, kRenderFxStrobeFaster = 11, ACT_HL2MP_IDLE = 1777, ACT_DOD_RELOAD_PRONE_GREASEGUN = 931, ACT_DOD_STAND_AIM_GREN_FRAG = 737, DMG_DROWNRECOVER = 524288, ACT_VM_UNUSABLE = 1428, ACT_DOD_STAND_AIM_BAZOOKA = 769, ACT_DOD_WALK_AIM_BAR = 798, ACT_WALK_AIM_STEALTH_PISTOL = 374, ACT_HL2MP_WALK_MELEE = 1878, SOLID_OBB_YAW = 4, ACT_VM_IDLE_SILENCED = 496, ACT_DOD_STAND_IDLE_BAZOOKA = 775, ACT_DOD_PRONE_AIM_BAZOOKA = 774, ACT_DOD_WALK_AIM_BAZOOKA = 772, CT_DOWNTRODDEN = 1, ACT_OVERLAY_GRENADEREADY = 442, TYPE_MATERIAL = 21, ACT_DOD_CROUCHWALK_AIM_BAZOOKA = 771, ACT_DOD_CROUCHWALK_AIM_BOLT = 648, ACT_HL2MP_IDLE_GRENADE = 1837, ACT_RUN_STEALTH_PISTOL = 366, MAT_SLOSH = 83, ACT_MP_SWIM_SECONDARY = 1119, MAT_VENT = 86, EFL_KILLME = 1, EFL_HAS_PLAYER_CHILD = 16, ACT_MP_ATTACK_SWIM_MELEE = 1186, ACT_BIG_FLINCH = 63, EFL_FORCE_CHECK_TRANSMIT = 128, COLLISION_GROUP_PASSABLE_DOOR = 15, ACT_READINESS_RELAXED_TO_STIMULATED_WALK = 419, ACT_SHIELD_ATTACK = 452, ACT_WALK_RIFLE = 358, ACT_HL2MP_SIT_SMG1 = 2007, ACT_HL2MP_GESTURE_RANGE_ATTACK_ANGRY = 1688, EFL_NO_DISSOLVE = 134217728, ACT_DOD_STAND_IDLE_TOMMY = 665, ACT_DOD_SPRINT_AIM_GREN_FRAG = 743, EFL_USE_PARTITION_WHEN_NOT_SOLID = 262144, ACT_DOD_CROUCH_AIM_GREN_FRAG = 738, ACT_HL2MP_RUN_CAMERA = 1675, COLLISION_GROUP_DISSOLVING = 16, EF_BONEMERGE = 1, ACT_DOD_PRONEWALK_IDLE_30CAL = 736, EFL_NO_GAME_PHYSICS_SIMULATION = 8388608, ACT_DOD_SPRINT_IDLE_30CAL = 735, ACT_MP_MELEE_GRENADE2_ATTACK = 1294, ACT_MP_JUMP_START = 1002, GESTURE_SLOT_VCD = 5, ACT_HL2MP_WALK_MELEE2 = 1996, ACT_DOD_STAND_ZOOM_PSCHRECK = 826, ACT_RANGE_AIM_LOW = 297, ACT_MP_SWIM = 1006, ACT_DOD_SPRINT_IDLE_C96 = 631, FL_DUCKING = 2, ACT_VM_PRIMARYATTACK_DEPLOYED = 571, ACT_MP_ATTACK_CROUCH_PRIMARY_DEPLOYED = 1062, ACT_MP_SWIM_PDA = 1355, FL_WATERJUMP = 8, ACT_SMG2_DRAW2 = 272, BONE_USED_BY_VERTEX_LOD5 = 32768, ACT_DIE_BARNACLE_SWALLOW = 401, ACT_DOD_PRONEWALK_IDLE_MG = 723, ACT_CROUCHIDLE_AIM_STIMULATED = 103, ACT_SLAM_STICKWALL_TO_TRIPMINE_ND = 241, IN_RIGHT = 256, FL_SWIM = 4096, TYPE_SCRIPTEDVEHICLE = 20, KEY_PERIOD = 59, ACT_HL2MP_GESTURE_RELOAD_ANGRY = 1689, ACT_TRANSITION = 2, ACT_GMOD_GESTURE_ITEM_THROW = 2023, ACT_IDLE_ANGRY_PISTOL = 323, ACT_HL2MP_WALK_ZOMBIE_05 = 1632, ACT_HL2MP_RUN = 1779, KEY_SEMICOLON = 55, ACT_DOD_CROUCHWALK_IDLE_BOLT = 654, SF_PHYSPROP_MOTIONDISABLED = 8, ACT_HL2MP_IDLE_SMG1 = 1797, ACT_DOD_PRIMARYATTACK_PRONE_GREN_STICK = 877, ACT_DOD_PRIMARYATTACK_PRONE_BAR = 887, ACT_HL2MP_SWIM_SLAM = 1896, ACT_RUN_AIM_RIFLE = 363, FCVAR_UNREGISTERED = 1, ACT_MP_JUMP_BUILDING = 1313, ACT_IDLE_ANGRY_SMG1 = 321, ACT_HL2MP_IDLE_CROUCH_PISTOL = 1790, ACT_FLINCH_LEFTARM = 120, ACT_DOD_WALK_IDLE_GREASE = 707, COLLISION_GROUP_DOOR_BLOCKER = 14, ACT_MP_GESTURE_VC_HANDMOUTH_PRIMARY = 1383, ACT_HL2MP_WALK_KNIFE = 1976, ACT_SLAM_THROW_DETONATOR_HOLSTER = 253, ACT_HL2MP_WALK = 1778, ACT_RANGE_ATTACK_AR2_GRENADE = 281, KEY_F11 = 102, ACT_DOD_CROUCH_IDLE_GREASE = 705, ACT_DOD_RUN_AIM_GREASE = 702, SIM_NOTHING = 0, ACT_LOOKBACK_LEFT = 60, ACT_DOD_CROUCHWALK_IDLE_MP40 = 680, KEY_T = 30, SND_SPAWNING = 8, RENDERMODE_TRANSADDFRAMEBLEND = 7, ACT_DOD_CROUCHWALK_AIM_C96 = 622, ACT_DOD_RUN_IDLE_MP40 = 682, RENDERMODE_NONE = 10, KEY_COUNT = 107, ACT_MP_GESTURE_VC_FINGERPOINT = 1378, ACT_READINESS_STIMULATED_TO_RELAXED = 421, ACT_WALK_CROUCH_RIFLE = 360, ACT_DOD_CROUCH_IDLE_MP40 = 679, ACT_DUCK_DODGE = 400, FVPHYSICS_HEAVY_OBJECT = 32, ACT_DOD_CROUCHWALK_AIM_MP40 = 674, ACT_DOD_SPRINT_IDLE_TOMMY = 670, ACT_DOD_RELOAD_PRONE_BAZOOKA = 937, ACT_DEEPIDLE2 = 515, ACT_DI_ALYX_ANTLION = 415, ACT_DOD_WALK_AIM_TOMMY = 662, KEY_W = 33, ACT_HL2MP_JUMP_PISTOL = 1794, ACT_DOD_STAND_IDLE_BOLT = 652, CLASS_HEADCRAB = 12, LAST_SHARED_ACTIVITY = 2027, ACT_DOD_HS_CROUCH_PSCHRECK = 972, ACT_GMOD_GESTURE_ITEM_GIVE = 2020, ACT_RUN_AIM_STEALTH_PISTOL = 375, MAT_GRASS = 85, SF_NPC_FALL_TO_GROUND = 4, ACT_DOD_WALK_AIM_BOLT = 649, ACT_VM_IOUT_M203 = 1946, ACT_GMOD_TAUNT_MUSCLE = 1617, ACT_GESTURE_MELEE_ATTACK1 = 139, TEXT_ALIGN_CENTER = 1, ACT_GMOD_TAUNT_PERSISTENCE = 1616, ACT_RANGE_ATTACK_AR1 = 278, MASK_VISIBLE_AND_NPCS = 33579137, ACT_MP_SECONDARY_GRENADE2_ATTACK = 1288, ACT_HL2MP_RUN_PASSIVE = 1987, ACT_SLAM_THROW_DRAW = 248, ACT_DOD_WALK_IDLE_RIFLE = 642, CLASS_CONSCRIPT = 11, CLASS_MISSILE = 21, ACT_DOD_HS_CROUCH_BAZOOKA = 971, ACT_VM_IDLE_DEPLOYED_4 = 539, ACT_DOD_CROUCHWALK_IDLE_RIFLE = 641, ACT_DIEVIOLENT = 23, ACT_HL2MP_JUMP_CROSSBOW = 1874, ACT_MP_DEPLOYED_IDLE = 995, CHAN_AUTO = 0, ACT_HL2MP_GESTURE_RELOAD_SHOTGUN = 1823, CONTENTS_TEAM3 = 1024, CHAN_STREAM = 5, ACT_DOD_STAND_AIM_C96 = 620, ACT_HL2MP_RUN_PANICKED = 1623, ACT_DOD_RELOAD_FG42 = 898, ACT_VM_FIDGET = 175, SCHED_STANDOFF = 47, ACT_HL2MP_RUN_DUEL = 1849, TRACER_NONE = 0, ACT_DOD_STAND_IDLE_PISTOL = 613, TRACER_LINE_AND_WHIZ = 4, CT_UNIQUE = 4, ACT_DOD_CROUCH_IDLE = 599, ACT_DOD_STAND_IDLE = 597, KEY_RWIN = 86, ACT_VM_HAULBACK = 199, ACT_DOD_PRONEWALK_IDLE_C96 = 632, ACT_SLAM_THROW_THROW = 244, VERSION = 170525, SND_DELAY = 16, ACT_DOD_DEPLOYED = 581, ACT_WALK_CROUCH_AIM = 9, ACT_VM_PRIMARYATTACK_DEPLOYED_5 = 575, ACT_DOD_PRIMARYATTACK_PRONE_PISTOL = 863, ACT_MP_GESTURE_VC_NODNO_PDA = 1424, ACT_VM_PRIMARYATTACK_7 = 564, NAV_MESH_INVALID = 0, NAV_MESH_PRECISE = 4, ACT_VM_HITCENTER2 = 192, NAV_MESH_RUN = 32, HITGROUP_RIGHTLEG = 7, OBS_MODE_FIXED = 3, NAV_MESH_AVOID = 128, ACT_VM_IDLE_DEPLOYED_6 = 537, ACT_VM_IDLE_2 = 532, ACT_HL2MP_SWIM_ANGRY = 1692, ACT_VM_DRAW = 172, ACT_VM_DRAW_DEPLOYED = 520, ACT_HL2MP_SWIM_PHYSGUN = 1866, SF_NPC_FADE_CORPSE = 512, NAV_MESH_CLIFF = 32768, ACT_VM_HITLEFT = 187, ACT_RANGE_ATTACK2 = 17, ACT_RUN_AIM_STEALTH = 101, ACT_IDLE_AIM_RELAXED = 90, ACT_RANGE_ATTACK1_LOW = 18, ACT_SIGNAL3 = 51, ACT_VM_PRIMARYATTACK_4 = 567, ACT_SLAM_THROW_THROW_ND2 = 247, ACT_DOD_RUN_IDLE_TOMMY = 669, ACT_MP_STAND_PRIMARY = 1044, ACT_MP_STAND_IDLE = 990, ACT_DOD_RELOAD_CROUCH_M1CARBINE = 912, ACT_MP_AIRWALK_MELEE = 1175, ACT_DOD_CROUCH_IDLE_BOLT = 653, ACT_DOD_RELOAD_PRONE_GARAND = 924, TYPE_RESTORE = 14, MASK_NPCSOLID_BRUSHONLY = 147467, ACT_GESTURE_RANGE_ATTACK_TRIPWIRE = 315, ACT_IDLETORUN = 505, D_FR = 2, ACT_VM_IDLE_7 = 527, ACT_DOD_CROUCHWALK_IDLE_TOMMY = 667, ACT_VM_PRIMARYATTACK_DEPLOYED_4 = 576, ACT_READINESS_PISTOL_STIMULATED_TO_RELAXED = 425, ACT_MP_GESTURE_VC_NODNO_BUILDING = 1418, ACT_LEAP = 32, DMG_NERVEGAS = 65536, ACT_VM_IDLE_EMPTY_LEFT = 498, EFL_DIRTY_SHADOWUPDATE = 32, ACT_RPG_HOLSTER_UNLOADED = 483, ACT_MP_RELOAD_AIRWALK_PRIMARY = 1074, ACT_SHOTGUN_IDLE4 = 479, SCHED_SCRIPTED_WAIT = 60, DMG_PREVENT_PHYSICS_FORCE = 2048, ACT_UNDEPLOY = 472, KEY_XSTICK2_RIGHT = 156, SCHED_INVESTIGATE_SOUND = 11, ACT_OVERLAY_SHIELD_KNOCKBACK = 448, ACT_CROUCHING_SHIELD_DOWN = 455, SURF_WARP = 8, ACT_DOD_CROUCHWALK_AIM_GREASE = 700, FVPHYSICS_NO_PLAYER_PICKUP = 128, ACT_DOD_STAND_ZOOM_BAZOOKA = 820, ACT_DOD_CROUCHWALK_ZOOM_PSCHRECK = 828, ACT_HL2MP_GESTURE_RANGE_ATTACK_ZOMBIE = 1708, ACT_DOD_RELOAD_PRONE_RIFLE = 934, ACT_MP_JUMP_LAND_PRIMARY = 1053, ACT_IDLE_RIFLE = 319, BONE_USED_BY_ATTACHMENT = 512, SCHED_FORCED_GO_RUN = 72, D_ER = 0, kRenderFxPulseSlowWide = 3, ACT_PICKUP_GROUND = 74, ACT_HL2MP_GESTURE_RANGE_ATTACK_FIST = 1965, TYPE_THREAD = 8, ACT_DOD_PRIMARYATTACK_PRONE_DEPLOYED = 590, ACT_MP_ATTACK_SWIM_POSTFIRE = 1043, USE_TOGGLE = 3, SURF_NOSHADOWS = 4096, FSOLID_VOLUME_CONTENTS = 32, ACT_HL2MP_GESTURE_RANGE_ATTACK_CROSSBOW = 1872, ACT_VM_DEPLOYED_IRON_IDLE = 1920, ACT_MP_ATTACK_CROUCH_PRIMARYFIRE_DEPLOYED = 1016, ACT_COWER = 61, ACT_MP_ATTACK_AIRWALK_PRIMARY = 1064, ACT_VM_SWINGHARD = 200, CLASS_PLAYER_ALLY_VITAL = 3, ACT_HL2MP_WALK_CROUCH_MELEE = 1881, ACT_DOD_CROUCH_AIM_BOLT = 647, EF_DIMLIGHT = 4, ACT_BARNACLE_CHEW = 170, ACT_VM_DEPLOY_7 = 555, ACT_RPG_FIDGET_UNLOADED = 485, ACT_HL2MP_JUMP_AR2 = 1814, ACT_DYINGTODEAD = 430, CHAN_USER_BASE = 136, ACT_VM_MISSLEFT2 = 194, MOVETYPE_LADDER = 9, ACT_DOD_WALK_IDLE_C96 = 629, ACT_DOD_CROUCH_IDLE_BAZOOKA = 776, IN_BACK = 16, ACT_MP_ATTACK_SWIM_GRENADE_PRIMARY = 1107, ACT_IDLE_RPG_RELAXED = 348, ACT_DOD_RUN_AIM_RIFLE = 637, ACT_DOD_STAND_AIM_30CAL = 724, ACT_WALK_PISTOL = 369, ACT_VM_SPRINT_IDLE = 433, KEY_PAD_6 = 43, ACT_DOD_RELOAD_PRONE_MP40 = 928, ACT_DOD_PRONE_AIM_PSCHRECK = 787, CONTENTS_MOVEABLE = 16384, KEY_XSTICK1_UP = 153, ACT_SHIELD_DOWN = 450, ACT_GESTURE_TURN_LEFT90_FLAT = 165, SCHED_FAIL_ESTABLISH_LINE_OF_FIRE = 38, KEY_7 = 8, ACT_DROP_WEAPON_SHOTGUN = 73, BONE_USED_BY_VERTEX_LOD2 = 4096, ACT_CROUCHING_SHIELD_UP_IDLE = 456, ACT_PLAYER_CROUCH_FIRE = 501, ACT_MP_RELOAD_CROUCH_PRIMARY = 1068, ACT_VM_DRAW_EMPTY = 521, FORCE_NUMBER = 2, FORCE_STRING = 1, ACT_RANGE_AIM_PISTOL_LOW = 299, ACT_GESTURE_FLINCH_CHEST = 151, ACT_MP_RELOAD_CROUCH_END = 1030, ACT_HL2MP_WALK_CROUCH_ZOMBIE_05 = 1637, ACT_DOD_PRIMARYATTACK_PRONE_C96 = 865, ACT_HL2MP_GESTURE_RANGE_ATTACK_KNIFE = 1980, ACT_VM_RELOAD_INSERT = 1950, ACT_HL2MP_SWIM_MELEE = 1886, FL_ANIMDUCKING = 4, ACT_VM_ISHOOT_M203 = 1949, ACT_SPRINT = 507, TYPE_NUMBER = 3, ACT_SLAM_THROW_TO_STICKWALL_ND = 251, SURF_SKIP = 512, ACT_HL2MP_IDLE_CROUCH_PASSIVE = 1988, JOYSTICK_FIRST_POV_BUTTON = 146, FCVAR_CLIENTDLL = 8, COLLISION_GROUP_INTERACTIVE = 4, ACT_HL2MP_SWIM_DUEL = 1856, KEY_U = 31, ACT_RANGE_ATTACK_AR2_LOW = 280, SF_PHYSBOX_MOTIONDISABLED = 32768, ACT_INVALID = -1, RENDERGROUP_TRANSLUCENT = 8, CONTENTS_SOLID = 1, KEY_PAD_1 = 38, ACT_HL2MP_RUN_PISTOL = 1789, ACT_MP_PRIMARY_GRENADE1_DRAW = 1277, ACT_VM_UNDEPLOY_2 = 550, ACT_VM_IDLE_DEPLOYED_2 = 541, ACT_HL2MP_IDLE_CROUCH_KNIFE = 1978, ACT_MP_ATTACK_AIRWALK_GRENADE_MELEE = 1191, ACT_HL2MP_IDLE_CROUCH_SCARED = 1696, FCVAR_CHEAT = 16384, ACT_SLAM_THROW_ND_IDLE = 243, ACT_MP_MELEE_GRENADE2_DRAW = 1292, CONTENTS_HITBOX = 1073741824, ACT_MP_ATTACK_STAND_MELEE_SECONDARY = 1183, NAV_MESH_DONT_HIDE = 512, ACT_HL2MP_IDLE_MELEE = 1877, FVPHYSICS_WAS_THROWN = 256, ACT_VM_PULLPIN = 180, COLLISION_GROUP_BREAKABLE_GLASS = 6, IN_GRENADE1 = 8388608, ACT_IDLE_MANNEDGUN = 345, SF_PHYSPROP_PREVENT_PICKUP = 512, ACT_GMOD_GESTURE_TAUNT_ZOMBIE = 1641, ONOFF_USE = 1, ACT_VM_IIDLE = 1906, ACT_DOD_PRIMARYATTACK_PRONE_MP44 = 859, ACT_HL2MP_GESTURE_RANGE_ATTACK_SLAM = 1892, ACT_HL2MP_SWIM_IDLE_SCARED = 1701, ACT_MP_CROUCH_PRIMARY = 1045, ACT_DOD_CROUCHWALK_IDLE_TNT = 982, ACT_180_RIGHT = 130, HULL_SMALL_CENTERED = 1, ACT_MP_GESTURE_FLINCH_LEFTARM = 1267, ACT_HL2MP_JUMP_SUITCASE = 1720, KEY_XSTICK1_DOWN = 152, FCVAR_DEMO = 65536, ACT_MP_ATTACK_AIRWALK_BUILDING = 1321, ACT_DOD_PRIMARYATTACK_RIFLE = 840, ACT_VM_RELOAD = 183, ACT_MP_GESTURE_FLINCH_PRIMARY = 1259, FSOLID_USE_TRIGGER_BOUNDS = 128, PLAYERANIMEVENT_ATTACK_PRIMARY = 0, TYPE_ENTITY = 9, JOYSTICK_LAST_POV_BUTTON = 149, TYPE_USERMSG = 26, ACT_DOD_CROUCHWALK_ZOOM_BAZOOKA = 822, KEY_1 = 2, FL_TRANSRAGDOLL = 1073741824, TEAM_UNASSIGNED = 1001, ACT_PHYSCANNON_ANIMATE_PRE = 405, KEY_K = 21, MASK_SHOT_PORTAL = 33570819, TYPE_ANGLE = 11, ACT_RUN_CROUCH_RPG = 355, ACT_DOD_STAND_IDLE_C96 = 626, CAP_WEAPON_RANGE_ATTACK1 = 8192, GLOBAL_DEAD = 2, ACT_DOD_HS_IDLE_MP44 = 968, ACT_DOD_PRONEWALK_AIM_SPADE = 768, COLLISION_GROUP_PLAYER_MOVEMENT = 8, HITGROUP_LEFTLEG = 6, ACT_DOD_RELOAD_CROUCH_PSCHRECK = 910, ACT_HL2MP_GESTURE_RELOAD_RPG = 1833, ACT_DOD_PRONE_AIM_KNIFE = 758, KEY_ENTER = 64, SURF_NOPORTAL = 32, SIM_LOCAL_ACCELERATION = 1, ACT_DOD_PRONEWALK_AIM_GREN_STICK = 752, FL_OBJECT = 67108864, ACT_MP_ATTACK_CROUCH_POSTFIRE = 1041, ACT_WALK_SCARED = 110, SCHED_RUN_FROM_ENEMY_MOB = 83, ACT_HL2MP_SWIM_PASSIVE = 1993, ACT_MP_GESTURE_VC_NODYES_PRIMARY = 1387, kRenderFxPulseFast = 2, WEAPON_PROFICIENCY_PERFECT = 4, ACT_GESTURE_RANGE_ATTACK1_LOW = 141, ACT_SLAM_STICKWALL_DETONATE = 235, ACT_DOD_STAND_AIM_BOLT = 646, ACT_RUN_CROUCH_RIFLE = 364, ACT_DOD_WALK_IDLE_30CAL = 733, PLAYER_IN_VEHICLE = 6, ACT_DOD_PRONE_FORWARD_ZOOMED = 588, TEXT_ALIGN_LEFT = 0, ACT_DOD_CROUCH_AIM_30CAL = 725, ACT_MP_ATTACK_AIRWALK_GRENADE_SECONDARY = 1143, PLAYERANIMEVENT_ATTACK_SECONDARY = 1, DMG_ALWAYSGIB = 8192, ACT_GESTURE_FLINCH_STOMACH = 152, ACT_DOD_PRIMARYATTACK_PRONE_MG = 867, ACT_DOD_RELOAD_PRONE_RIFLEGRENADE = 935, GESTURE_SLOT_JUMP = 2, CLASS_PLAYER = 1, ACT_MP_JUMP_LAND = 1004, BONE_USED_BY_VERTEX_MASK = 261120, MOVECOLLIDE_FLY_CUSTOM = 2, ACT_BUSY_LEAN_LEFT_EXIT = 388, ACT_MP_MELEE_GRENADE1_DRAW = 1289, ACT_CROUCHING_GRENADEREADY = 439, ACT_HL2MP_WALK_CROUCH = 1781, ACT_CROUCHIDLE = 46, ACT_HL2MP_GESTURE_RANGE_ATTACK_MAGIC = 1658, ACT_DOD_STAND_IDLE_MG = 717, KEY_BACKQUOTE = 57, KEY_RIGHT = 91, SCHED_TARGET_CHASE = 21, SF_NPC_ALTCOLLISION = 4096, JOYSTICK_FIRST_BUTTON = 114, ACT_HL2MP_IDLE_CROUCH_MELEE = 1880, ACT_VM_PRIMARYATTACK_DEPLOYED_3 = 577, ACT_MP_RELOAD_CROUCH_SECONDARY = 1127, FCVAR_LUA_SERVER = 524288, ACT_SLAM_THROW_IDLE = 242, CONTENTS_CURRENT_DOWN = 8388608, ACT_DOD_CROUCHWALK_AIM_MP44 = 687, ACT_RUN_CROUCH_AIM_RIFLE = 365, ACT_HL2MP_GESTURE_RANGE_ATTACK_SHOTGUN = 1822, KEY_3 = 4, ACT_VM_HITRIGHT2 = 190, ACT_HL2MP_JUMP_SMG1 = 1804, STEPSOUNDTIME_ON_LADDER = 1, ACT_MP_GESTURE_VC_FINGERPOINT_PRIMARY = 1384, RENDERMODE_TRANSALPHA = 4, EF_ITEM_BLINK = 256, ACT_DOD_PRONE_DEPLOY_TOMMY = 837, ACT_DOD_HS_IDLE_STICKGRENADE = 966, ACT_MP_RELOAD_STAND_LOOP = 1026, ACT_MP_ATTACK_AIRWALK_GRENADE_PRIMARY = 1108, ACT_OVERLAY_SHIELD_ATTACK = 447, ACT_VM_MISSRIGHT2 = 196, ACT_STEP_RIGHT = 134, ACT_GESTURE_FLINCH_BLAST_SHOTGUN = 147, ACT_RELOAD_PISTOL = 376, ACT_HL2MP_IDLE_CROUCH_ZOMBIE_02 = 1639, ACT_MP_CROUCHWALK_SECONDARY = 1114, SURF_NODECALS = 8192, ACT_DOD_WALK_ZOOM_RIFLE = 811, ACT_HL2MP_RUN_ZOMBIE_FAST = 1646, ACT_GMOD_GESTURE_ITEM_PLACE = 2022, ACT_ZOMBIE_CLIMB_START = 1651, ACT_MP_JUMP_START_PRIMARY = 1051, ACT_DI_ALYX_ZOMBIE_TORSO_MELEE = 413, ACT_DOD_PRIMARYATTACK_GREN_STICK = 876, ACT_DOD_PRIMARYATTACK_BOLT = 846, ACT_DOD_STAND_AIM_BAR = 795, KEY_XSTICK2_DOWN = 158, DMG_SHOCK = 256, KEY_XBUTTON_X = 116, ACT_MP_SECONDARY_GRENADE1_ATTACK = 1285, IN_RELOAD = 8192, ACT_DOD_RUN_IDLE = 605, ACT_MP_JUMP_SECONDARY = 1115, ACT_DOD_STAND_AIM_GREN_STICK = 745, IN_USE = 32, ACT_DOD_PRONE_AIM_BAR = 800, ACT_PLAYER_IDLE_FIRE = 500, ACT_DOD_PRONE_DEPLOY_RIFLE = 836, GESTURE_SLOT_SWIM = 3, ACT_DOD_PRONE_AIM_GREN_STICK = 750, ACT_DOD_RELOAD_DEPLOYED = 591, ACT_DOD_PRIMARYATTACK_CROUCH_SPADE = 951, ACT_DOD_RELOAD_PRONE_DEPLOYED_FG42 = 942, ACT_IDLE_PACKAGE = 326, ACT_HL2MP_SWIM_CROSSBOW = 1876, ACT_VM_PRIMARYATTACK_1 = 570, CLASS_CITIZEN_REBEL = 8, ACT_VM_HITCENTER = 191, ACT_GESTURE_FLINCH_BLAST_DAMAGED = 148, ACT_RUN_STEALTH = 89, ACT_HL2MP_GESTURE_RELOAD_REVOLVER = 1669, SCHED_IDLE_WALK = 2, ACT_HL2MP_JUMP_MELEE = 1884, CONTENTS_CURRENT_90 = 524288, ACT_MP_ATTACK_CROUCH_GRENADE_SECONDARY = 1141, TRACER_LINE = 1, ACT_FIRE_LOOP = 436, ACT_DOD_RUN_ZOOM_BOLT = 818, ACT_DOD_PRONEWALK_IDLE_RIFLE = 645, ACT_PRONE_IDLE = 513, FL_GRENADE = 2097152, BONE_USED_BY_VERTEX_LOD0 = 1024, KEY_F6 = 97, ACT_MP_CROUCH_PDA = 1346, ACT_HOP = 31, ACT_DOD_RUN_AIM_PISTOL = 611, HITGROUP_RIGHTARM = 5, ACT_DOD_RUN_AIM_MG = 715, FVPHYSICS_DMG_DISSOLVE = 512, ACT_CROUCHING_SHIELD_UP = 454, kRenderFxGlowShell = 18, ACT_HL2MP_SWIM_RPG = 1836, FSOLID_CUSTOMRAYTEST = 1, ACT_GET_DOWN_CROUCH = 510, PLAYERANIMEVENT_CANCEL = 16, ACT_DOD_CROUCHWALK_AIM_TOMMY = 661, ACT_VM_MISSRIGHT = 195, ACT_DOD_PRIMARYATTACK_SPADE = 880, ACT_GESTURE_TURN_LEFT45_FLAT = 163, ACT_WALK = 6, ACT_DOD_CROUCH_AIM_PISTOL = 608, IN_BULLRUSH = 4194304, ACT_MP_GESTURE_VC_NODNO_SECONDARY = 1394, SCHED_AMBUSH = 52, ACT_GMOD_GESTURE_WAVE = 1615, PLAYERANIMEVENT_DOUBLEJUMP = 15, ACT_VM_DEPLOY_6 = 556, ACT_HL2MP_IDLE_CROUCH_REVOLVER = 1666, ACT_MP_ATTACK_SWIM_GRENADE = 1021, TYPE_PARTICLE = 23, ACT_VM_DEPLOYED_DRYFIRE = 1915, ACT_PHYSCANNON_UPGRADE = 277, ACT_HL2MP_SIT_GRENADE = 2010, IN_WALK = 262144, KEY_BREAK = 78, ACT_GET_UP_STAND = 509, BLOOD_COLOR_YELLOW = 1, SCHED_INTERACTION_WAIT_FOR_PARTNER = 86, ACT_HL2MP_IDLE_SCARED = 1693, CAP_AIM_GUN = 536870912, ACT_JUMP = 30, STEPSOUNDTIME_WATER_KNEE = 2, ACT_BARNACLE_HIT = 167, EFL_NO_AUTO_EDICT_ATTACH = 1024, ACT_HL2MP_JUMP_SLAM = 1894, ACT_GLOCK_SHOOTEMPTY = 480, KEY_PAD_4 = 41, ACT_BUSY_QUEUE = 399, CLASS_BULLSEYE = 6, FVPHYSICS_PLAYER_HELD = 4, JOYSTICK_LAST_AXIS_BUTTON = 161, ACT_ZOMBIE_CLIMB_UP = 1650, ACT_COVER_MED = 4, ACT_VM_PRIMARYATTACK_DEPLOYED_6 = 574, ACT_MP_GESTURE_VC_FISTPUMP_SECONDARY = 1391, HITGROUP_HEAD = 1, ACT_HL2MP_WALK_CROUCH_MELEE2 = 1999, SCHED_DROPSHIP_DUSTOFF = 79, ACT_IDLE_PISTOL = 322, ACT_MP_AIRWALK_PDA = 1349, BONE_USED_BY_VERTEX_LOD3 = 8192, DMG_SLOWBURN = 2097152, ACT_HL2MP_SWIM_IDLE_PASSIVE = 1994, ACT_DOD_RELOAD_CROUCH_BAR = 902, ACT_HL2MP_SIT_RPG = 2011, ACT_BUSY_LEAN_BACK_ENTRY = 390, EFL_BOT_FROZEN = 256, FORCE_BOOL = 3, SF_NPC_NO_PLAYER_PUSHAWAY = 16384, KEY_V = 32, CONTENTS_OPAQUE = 128, ACT_SHIELD_UP = 449, ACT_MP_GESTURE_VC_NODNO = 1382, ACT_READINESS_PISTOL_RELAXED_TO_STIMULATED_WALK = 423, ACT_MP_ATTACK_STAND_PRIMARY_DEPLOYED = 1060, KEY_NUMLOCKTOGGLE = 105, ACT_MP_RELOAD_SWIM_SECONDARY_END = 1132, SERVER = true, ACT_HL2MP_IDLE_AR2 = 1807, DMG_ENERGYBEAM = 1024, KEY_D = 14, SCHED_TARGET_FACE = 20, ACT_VM_DEPLOYED_LIFTED_IN = 1924, ACT_VM_HOLSTER_M203 = 1942, PATTACH_POINT = 3, NAV_MESH_STAIRS = 4096, HULL_WIDE_HUMAN = 2, ACT_VM_PRIMARYATTACK_DEPLOYED_8 = 572, NAV_MESH_TRANSIENT = 256, ACT_GESTURE_RANGE_ATTACK_SMG2 = 310, ACT_VM_DEPLOYED_LIFTED_OUT = 1926, FL_BASEVELOCITY = 16777216, ACT_WALK_AIM_STIMULATED = 95, ACT_GMOD_SIT_ROLLERCOASTER = 1974, SCHED_IDLE_STAND = 1, FSOLID_MAX_BITS = 10, ACT_GESTURE_BARNACLE_STRANGLE = 402, ACT_SMG2_DRYFIRE2 = 274, ACT_RANGE_ATTACK_SMG1_LOW = 285, FSOLID_NOT_STANDABLE = 16, ACT_HL2MP_IDLE_SUITCASE = 1713, FCVAR_GAMEDLL = 4, LAST_VISIBLE_CONTENTS = 128, SENSORBONE = { SHOULDER_RIGHT = 8, SHOULDER_LEFT = 4, HIP = 0, ELBOW_RIGHT = 9, KNEE_RIGHT = 17, WRIST_RIGHT = 10, ANKLE_LEFT = 14, FOOT_LEFT = 15, WRIST_LEFT = 6, FOOT_RIGHT = 19, HAND_RIGHT = 11, SHOULDER = 2, HIP_LEFT = 12, HIP_RIGHT = 16, HAND_LEFT = 7, ANKLE_RIGHT = 18, SPINE = 1, ELBOW_LEFT = 5, KNEE_LEFT = 13, HEAD = 3, }, ACT_VM_SWINGHIT = 202, EFL_NOCLIP_ACTIVE = 4, TRACER_RAIL = 2, HITGROUP_CHEST = 2, ACT_GMOD_NOCLIP_LAYER = 1959, ACT_DOD_PRONE_ZOOM_FORWARD_BOLT = 947, ACT_HL2MP_SIT_SLAM = 2014, CHAN_VOICE_BASE = 8, ACT_HL2MP_RUN_SMG1 = 1799, ACT_DOD_SECONDARYATTACK_CROUCH_MP40 = 957, CHAN_REPLACE = -1, ACT_SMG2_TOBURST = 276, TEAM_SPECTATOR = 1002, ACT_HL2MP_RUN_RPG = 1829, TEXT_ALIGN_TOP = 3, ACT_GESTURE_RELOAD_SMG1 = 384, ACT_MP_RELOAD_STAND_SECONDARY_END = 1126, PLAYERANIMEVENT_RELOAD_LOOP = 4, ACT_MP_SWIM_DEPLOYED_PRIMARY = 1056, TRANSMIT_PVS = 2, PLAYER_LEAVE_AIMING = 9, KEY_F3 = 94, KEY_R = 28, USE_ON = 1, BONE_USED_BY_BONE_MERGE = 262144, BONE_USED_BY_VERTEX_LOD7 = 131072, ACT_GESTURE_RANGE_ATTACK_PISTOL = 312, BONE_CALCULATE_MASK = 31, BOX_BOTTOM = 5, SURF_BUMPLIGHT = 2048, ACT_HL2MP_IDLE_CROUCH_SLAM = 1890, NAV_MESH_FUNC_COST = 536870912, ACT_DOD_RELOAD_K43 = 889, DMG_VEHICLE = 16, ACT_IDLE_STEALTH_PISTOL = 325, SF_CITIZEN_AMMORESUPPLIER = 524288, ACT_DOD_WALK_IDLE_TOMMY = 668, FL_STEPMOVEMENT = 4194304, BLOOD_COLOR_ANTLION_WORKER = 6, RENDERMODE_ENVIROMENTAL = 6, ACT_CLIMB_DISMOUNT = 36, RENDERGROUP_OPAQUE_BRUSH = 12, RENDERGROUP_VIEWMODEL_TRANSLUCENT = 11, PLAYER_IDLE = 0, ACT_DIE_CHESTSHOT = 114, RENDERGROUP_OPAQUE_HUGE = 1, ACT_DOD_RUN_IDLE_BAR = 805, ACT_DOD_CROUCHWALK_IDLE_GREASE = 706, color_black = { r = 0, b = 0, a = 255, g = 0, }, ACT_VM_UNDEPLOY_1 = 551, FL_DONTTOUCH = 8388608, FL_STATICPROP = 524288, FL_NOTARGET = 65536, ACT_VM_PRIMARYATTACK_DEPLOYED_7 = 573, SCHED_RUN_RANDOM = 77, SF_CITIZEN_NOT_COMMANDABLE = 1048576, MASK_BLOCKLOS = 16449, MOVECOLLIDE_COUNT = 4, CONTENTS_TEAM4 = 512, FL_FROZEN = 64, BLEND_SRC_ALPHA = 4, ACT_VM_DOWN_EMPTY = 1901, ACT_DOD_CROUCH_AIM_KNIFE = 754, EFL_NO_DAMAGE_FORCES = -2147483648, PLAYERANIMEVENT_SNAP_YAW = 18, ACT_HL2MP_WALK_CROUCH_CROSSBOW = 1871, ACT_DOD_ZOOMLOAD_PRONE_BAZOOKA = 938, ACT_MP_MELEE_GRENADE1_ATTACK = 1291, ACT_DOD_CROUCH_IDLE_C96 = 627, EFL_CHECK_UNTOUCH = 16777216, DMG_BLAST = 64, EFL_NO_THINK_FUNCTION = 4194304, ACT_VM_ATTACH_SILENCER = 211, EFL_TOUCHING_FLUID = 524288, CHAN_ITEM = 3, ACT_MP_WALK_MELEE = 1174, ACT_MP_ATTACK_CROUCH_BUILDING = 1319, ACT_MP_GESTURE_VC_FINGERPOINT_BUILDING = 1414, CAP_MOVE_SHOOT = 64, COLLISION_GROUP_NONE = 0, ACT_IDLE_STEALTH = 80, ACT_DOD_WALK_AIM = 604, ACT_HL2MP_IDLE_KNIFE = 1975, MAT_WOOD = 87, ACT_VM_ISHOOTDRY = 1936, ACT_PHYSCANNON_ANIMATE = 404, FL_ATCONTROLS = 128, MAT_METAL = 77, MAT_PLASTIC = 76, MAT_ALIENFLESH = 72, MAT_DIRT = 68, kRenderFxRagdoll = 23, ACT_MP_ATTACK_SWIM_PREFIRE = 1042, kRenderFxEnvSnow = 21, ACT_VM_DOWN = 1900, kRenderFxHologram = 16, ACT_HL2MP_WALK_SMG1 = 1798, KEY_PAD_DIVIDE = 47, CLASS_COMBINE = 9, ACT_PLAYER_RUN_FIRE = 504, ACT_CROUCHIDLE_STIMULATED = 102, ACT_HL2MP_RUN_ANGRY = 1685, SCHED_BIG_FLINCH = 23, ACT_MP_GESTURE_VC_HANDMOUTH_SECONDARY = 1389, GESTURE_SLOT_ATTACK_AND_RELOAD = 0, USE_SET = 2, PLAYERANIMEVENT_SPAWN = 17, ACT_VM_IDLE_M203 = 1940, ACT_DOD_PRONE_AIM_C96 = 625, FL_UNBLOCKABLE_BY_PLAYER = -2147483648, PLAYERANIMEVENT_JUMP = 6, KEY_LBRACKET = 53, ACT_WALK_STIMULATED = 83, kRenderFxFlickerSlow = 12, BONE_PHYSICALLY_SIMULATED = 1, PLAYERANIMEVENT_RELOAD = 3, ACT_MP_PRIMARY_GRENADE1_ATTACK = 1279, SCHED_COMBAT_SWEEP = 13, KEY_BACKSPACE = 66, ACT_FLINCH_PHYSICS = 124, ACT_MP_PRIMARY_GRENADE2_IDLE = 1281, ACT_HL2MP_SWIM_IDLE_GRENADE = 1845, ACT_CLIMB_UP = 34, RENDERGROUP_BOTH = 9, ACT_MP_JUMP_START_PDA = 1352, ACT_RUN_ON_FIRE = 127, ACT_RUN_PROTECTED = 14, EFL_DONTBLOCKLOS = 33554432, ACT_MP_STAND_BUILDING = 1307, ACT_HL2MP_SWIM_MAGIC = 1662, ACT_DOD_RUN_AIM_MP40 = 676, JOYSTICK_FIRST_AXIS_BUTTON = 150, ACT_IDLE_CARRY = 426, SF_NPC_LONG_RANGE = 256, ACT_DOD_WALK_IDLE_TNT = 983, kRenderFxPulseFastWide = 4, ACT_DOD_PRONEWALK_IDLE_BAZOOKA = 781, LAST_SHARED_COLLISION_GROUP = 21, CT_REFUGEE = 2, KEY_XBUTTON_BACK = 120, ACT_HL2MP_RUN_SLAM = 1889, ACT_CROUCHING_PRIMARYATTACK = 440, ACT_GESTURE_RELOAD_SHOTGUN = 385, SCHED_WAIT_FOR_SCRIPT = 55, SCHED_SMALL_FLINCH = 22, ACT_HL2MP_SWIM_IDLE_PISTOL = 1795, TYPE_PARTICLEEMITTER = 24, ACT_GMOD_GESTURE_RANGE_ZOMBIE_SPECIAL = 1644, ACT_DOD_STAND_IDLE_BAR = 801, KEY_XSTICK2_LEFT = 157, NPC_STATE_SCRIPT = 4, ACT_IDLE_AIM_STIMULATED = 91, ACT_DOD_RUN_IDLE_RIFLE = 643, ACT_WALK_AGITATED = 84, ACT_DOD_RUN_IDLE_MG = 721, ACT_MP_GRENADE2_ATTACK = 1276, ACT_MP_ATTACK_STAND_GRENADE_PRIMARY = 1105, ACT_DOD_CROUCHWALK_AIM_GREN_STICK = 747, CAP_NO_HIT_SQUADMATES = 1073741824, ACT_WALK_CROUCH = 8, SCHED_RUN_FROM_ENEMY = 32, WEAPON_PROFICIENCY_GOOD = 2, BLEND_ONE_MINUS_DST_ALPHA = 7, CAP_OPEN_DOORS = 2048, CAP_MOVE_CRAWL = 32, PLAYER_START_AIMING = 8, ACT_DOD_CROUCH_IDLE_BAR = 802, SCHED_SLEEP = 87, FL_FLY = 2048, ACT_WALK_STEALTH = 85, SCHED_FAIL_NOSTOP = 82, ACT_DOD_PRONEWALK_AIM_GREN_FRAG = 744, SCHED_PATROL_WALK = 74, SCHED_MOVE_AWAY_FAIL = 69, ACT_HL2MP_ZOMBIE_SLUMP_IDLE = 1626, SCHED_SCRIPTED_CUSTOM_MOVE = 59, BUTTON_CODE_INVALID = -1, MOUSE_RIGHT = 108, ACT_DOD_CROUCH_IDLE_TOMMY = 666, SCHED_FAIL_TAKE_COVER = 31, ACT_MP_RUN_BUILDING = 1309, SCHED_BACK_AWAY_FROM_SAVE_POSITION = 26, ACT_HL2MP_SWIM_IDLE_DUEL = 1855, CLASS_NONE = 0, ACT_RELOAD_SHOTGUN = 380, ACT_RUN_HURT = 106, SCHED_VICTORY_DANCE = 19, ACT_DOD_RUN_ZOOM_PSCHRECK = 830, SCHED_COMBAT_STAND = 15, ACT_GESTURE_RANGE_ATTACK_SMG1_LOW = 309, ACT_MP_ATTACK_CROUCH_GRENADE_MELEE = 1189, SCHED_ALERT_FACE = 5, COLLISION_GROUP_DEBRIS = 1, SCHED_ALERT_SCAN = 8, ACT_MP_RUN_PRIMARY = 1046, ACT_IDLE_SHOTGUN_RELAXED = 339, ACT_GESTURE_RANGE_ATTACK_AR1 = 303, CAP_MOVE_FLY = 4, KEY_G = 17, NPC_STATE_ALERT = 2, CHAN_VOICE = 2, kRenderFxExplode = 17, SIM_GLOBAL_FORCE = 4, ACT_GMOD_GESTURE_ITEM_DROP = 2021, ACT_GESTURE_TURN_RIGHT45_FLAT = 164, FVPHYSICS_CONSTRAINT_STATIC = 2, ACT_DOD_CROUCH_ZOOMED = 585, FVPHYSICS_DMG_SLICE = 1, TEXFILTER = { NONE = 0, ANISOTROPIC = 3, POINT = 1, LINEAR = 2, }, GMOD_MAXDTVARS = 32, KEY_XBUTTON_START = 121, FL_ONGROUND = 1, BLEND_ZERO = 0, kRenderFxNone = 0, PLAYERANIMEVENT_FLINCH_CHEST = 9, ACT_VM_IIN_M203 = 1944, ACT_VM_RELOAD_DEPLOYED = 518, ACT_VM_RELOAD_M203 = 1941, ACT_HL2MP_IDLE_CROUCH_CAMERA = 1676, ACT_VM_USABLE_TO_UNUSABLE = 1430, KEY_XBUTTON_STICK1 = 122, ACT_STRAFE_LEFT = 39, ACT_MP_JUMP_LAND_MELEE = 1180, ACT_DOD_RELOAD_PRONE_K43 = 927, ACT_HL2MP_GESTURE_RELOAD_PASSIVE = 1991, HITGROUP_LEFTARM = 4, ACT_RELOAD_SHOTGUN_LOW = 381, ACT_DEEPIDLE1 = 514, ACT_VM_IRECOIL2 = 1929, GESTURE_SLOT_FLINCH = 4, ACT_RANGE_ATTACK_THROW = 293, KEY_CAPSLOCK = 68, RENDERMODE_WORLDGLOW = 9, NAV_MESH_NO_JUMP = 8, ACT_WALK_RIFLE_STIMULATED = 334, ACT_SHOTGUN_IDLE_DEEP = 478, FCVAR_SPONLY = 64, ACT_DOD_PRONE_AIM_PISTOL = 612, ACT_SLAM_THROW_TO_TRIPMINE_ND = 254, SCHED_IDLE_WANDER = 3, ACT_SIGNAL_FORWARD = 53, ACT_HL2MP_IDLE_CROUCH_ZOMBIE = 1706, ACT_DOD_HS_CROUCH_MG42 = 974, SCHED_BACK_AWAY_FROM_ENEMY = 24, SCHED_TAKE_COVER_FROM_ENEMY = 27, ACT_HL2MP_WALK_DUEL = 1848, ACT_HL2MP_GESTURE_RELOAD_SUITCASE = 1719, ACT_HL2MP_GESTURE_RANGE_ATTACK_SUITCASE = 1718, ACT_MP_ATTACK_CROUCH_MELEE_SECONDARY = 1185, SCHED_MELEE_ATTACK2 = 42, NPC_STATE_DEAD = 7, KEY_Y = 35, ACT_COVER = 3, ACT_MP_ATTACK_CROUCH_SECONDARYFIRE = 1017, MOUSE_4 = 110, ACT_DOD_HS_IDLE_PSCHRECK = 962, ACT_DIE_BACKSHOT = 116, PLAYER_DIE = 4, BLEND_DST_ALPHA = 6, FL_FAKECLIENT = 512, ACT_DOD_WALK_AIM_SPADE = 764, ACT_SLAM_STICKWALL_TO_THROW_ND = 240, ACT_DOD_RELOAD_BAR = 890, ACT_SIGNAL_TAKECOVER = 58, ACT_HL2MP_SWIM_IDLE_ANGRY = 1691, KEY_LEFT = 89, ACT_HL2MP_WALK_ANGRY = 1684, ACT_HL2MP_SWIM_REVOLVER = 1672, SCHED_ESTABLISH_LINE_OF_FIRE = 35, ACT_HL2MP_RUN_REVOLVER = 1665, SCHED_ALERT_WALK = 10, BLOOD_COLOR_ANTLION = 4, ACT_HL2MP_GESTURE_RELOAD_AR2 = 1813, ACT_FLINCH_CHEST = 118, ACT_DOD_PRIMARYATTACK_PISTOL = 862, ACT_HL2MP_IDLE_CROUCH_MAGIC = 1656, ACT_SLAM_STICKWALL_IDLE = 229, SURF_TRANS = 16, ACT_RUN_AIM_RELAXED = 98, COLLISION_GROUP_IN_VEHICLE = 10, SND_CHANGE_VOL = 1, OBS_MODE_CHASE = 5, ACT_DOD_HS_CROUCH = 959, TYPE_FILE = 34, kRenderFxSolidFast = 8, DMG_PHYSGUN = 8388608, KEY_PAD_ENTER = 51, DMG_GENERIC = 0, ACT_BARNACLE_PULL = 168, ACT_GMOD_GESTURE_POINT = 1619, ACT_RANGE_ATTACK_SNIPER_RIFLE = 294, ACT_MP_GRENADE2_DRAW = 1274, ACT_MP_SWIM_MELEE = 1181, ACT_DI_ALYX_ZOMBIE_SHOTGUN64 = 416, ACT_VM_DRYFIRE = 186, ACT_DOD_RELOAD_PRONE_M1CARBINE = 925, CONTENTS_EMPTY = 0, ACT_RANGE_ATTACK_TRIPWIRE = 292, ACT_DOD_PRONE_AIM_SPADE = 766, SF_PHYSBOX_NEVER_PICK_UP = 2097152, ACT_VM_RELOAD_IDLE = 519, ACT_DOD_SPRINT_IDLE_BAR = 806, FL_INRAIN = 32, ACT_SLAM_TRIPMINE_ATTACH = 257, ACT_VM_ISHOOT_LAST = 1931, ACT_BUSY_SIT_GROUND_ENTRY = 393, ACT_VM_IDLE_DEPLOYED = 534, ACT_MP_GESTURE_FLINCH = 1258, ACT_VM_PULLBACK_HIGH_BAKE = 1910, }, meta = { NextBot = { GetRangeTo = "C", GetSolidMask = "C", GetActivity = "C", __newindex = "C", __tostring = "C", BodyMoveXY = "C", SetSolidMask = "C", GetRangeSquaredTo = "C", BecomeRagdoll = "C", StartActivity = "C", }, NPC = { LostEnemySound = "C", Give = "C", SetSchedule = "C", IsNPC = "C", AlertSound = "C", ClearSchedule = "C", IdleSound = "C", GetAimVector = "C", CapabilitiesRemove = "C", ConditionName = "C", SetMovementActivity = "C", CapabilitiesAdd = "C", SetArrivalSpeed = "C", ClearEnemyMemory = "C", SetTarget = "C", SetHullSizeNormal = "C", GetActiveWeapon = "C", NavSetRandomGoal = "C", SetArrivalDirection = "C", SetMaxRouteRebuildTime = "C", NavSetGoal = "C", RunEngineTask = "C", FoundEnemySound = "C", UseNoBehavior = "C", MoveOrder = "C", AddEntityRelationship = "C", UseAssaultBehavior = "C", FearSound = "C", GetArrivalSequence = "C", SetArrivalSequence = "C", UpdateEnemyMemory = "C", TaskComplete = "C", SetCurrentWeaponProficiency = "C", SetEnemy = "C", SetLastPosition = "C", GetActivity = "C", SetMovementSequence = "C", SetArrivalDistance = "C", GetMovementSequence = "C", GetPathDistanceToGoal = "C", GetPathTimeToGoal = "C", GetHullType = "C", NavSetGoalTarget = "C", ClearCondition = "C", GetEnemy = "C", CapabilitiesClear = "C", Classify = "C", __newindex = "C", UseActBusyBehavior = "C", GetExpression = "C", RemoveMemory = "C", ExitScriptedSequence = "C", GetCurrentWeaponProficiency = "C", GetMovementActivity = "C", UseLeadBehavior = "C", GetTarget = "C", AddRelationship = "C", ClearExpression = "C", TaskFail = "C", SetArrivalActivity = "C", GetNPCState = "C", IsUnreachable = "C", CapabilitiesGet = "C", MarkEnemyAsEluded = "C", SetCondition = "C", HasCondition = "C", MaintainActivity = "C", StartEngineTask = "C", TargetOrder = "C", GetArrivalActivity = "C", SetNPCState = "C", SetHullType = "C", NavSetWanderGoal = "C", StopMoving = "C", Disposition = "C", GetBlockingEntity = "C", SetExpression = "C", IsMoving = "C", UseFollowBehavior = "C", PlaySentence = "C", UseFuncTankBehavior = "C", __tostring = "C", IsRunningBehavior = "C", GetShootPos = "C", SentenceStop = "C", ClearGoal = "C", IsCurrentSchedule = "C", }, Player = { StopWalking = "C", GiveAmmo = "C", IsNPC = "C", AllowImmediateDecalPainting = "C", Frags = "C", SetTeam = "C", SetNoCollideWithTeammates = "C", IsTimingOut = "C", GetAimVector = "C", Kill = "C", GetViewModel = "C", EquipSuit = "C", KeyReleased = "C", KeyPressed = "C", SetHoveredWidget = "C", AddDeaths = "C", SetNoTarget = "C", Armor = "C", GetActiveWeapon = "C", GetPreferredCarryAngles = "C", AnimSetGestureWeight = "C", LagCompensation = "C", GetShootPos = "C", Team = "C", StripAmmo = "C", RemoveAmmo = "C", Alive = "C", SimulateGravGunPickup = "C", SetStepSize = "C", SetEyeAngles = "C", SetFOV = "C", IsWorldClicking = "C", SetUnDuckSpeed = "C", RemoveAllItems = "C", SetViewEntity = "C", LastHitGroup = "C", PacketLoss = "C", PhysgunUnfreeze = "L", SetDeaths = "C", SetActiveWeapon = "C", DebugInfo = "L", ViewPunch = "C", ViewPunchReset = "C", GetCurrentCommand = "C", GetPunchAngle = "C", Freeze = "L", GetStepSize = "C", SetArmor = "C", UniqueIDTable = "L", SetHands = "C", GetNoCollideWithTeammates = "C", Ban = "C", GetViewOffsetDucked = "C", Flashlight = "C", InVehicle = "C", SetAllowFullRotation = "C", KeyDown = "C", KillSilent = "C", GetLaggedMovementValue = "C", GetAllowFullRotation = "C", SetAvoidPlayers = "C", GetUnDuckSpeed = "C", IsFrozen = "L", GetObserverMode = "C", SetMaxSpeed = "C", GodEnable = "L", TimeConnected = "C", SprintDisable = "C", GetMaxSpeed = "C", GetHands = "C", TraceHullAttack = "C", EnterVehicle = "C", DrawWorldModel = "C", GetTool = "L", MotionSensorPos = "C", IsWeapon = "C", GetFOV = "C", StripWeapons = "C", SetLaggedMovementValue = "C", TranslateWeaponActivity = "C", AnimRestartGesture = "C", Kick = "C", SetDSP = "C", Spectate = "C", StripWeapon = "C", DropObject = "C", Lock = "C", IsConnected = "C", FlashlightIsOn = "C", CheckLimit = "L", PlayStepSound = "C", SetSuppressPickupNotices = "C", KeyDownLast = "C", GetWeapons = "C", ResetHull = "C", GetObserverTarget = "C", Ping = "C", AddFrags = "C", SetDuckSpeed = "C", GetWeaponColor = "C", SelectWeapon = "C", SetCrouchedWalkSpeed = "C", GetInfo = "C", __tostring = "C", UnSpectate = "C", SetViewPunchAngles = "C", GetInfoNum = "C", GetAllowWeaponsInVehicle = "C", IsListenServerHost = "C", IsPlayingTaunt = "C", SendHint = "L", UniqueID = "C", Give = "C", SetRunSpeed = "C", GetClassID = "C", AddCleanup = "L", SetViewOffset = "C", GetCrouchedWalkSpeed = "C", SetAmmo = "C", AccountID = "C", GodDisable = "L", ShouldDropWeapon = "C", GetTimeoutSeconds = "C", DoSecondaryAttack = "C", RemoveAllAmmo = "C", GetEyeTrace = "L", RemovePData = "L", SetAllowWeaponsInVehicle = "C", Crouching = "C", IPAddress = "C", SetObserverMode = "C", SuppressHint = "L", GetViewOffset = "C", DropNamedWeapon = "C", SetPressedWidget = "C", SetWeaponColor = "C", DoCustomAnimEvent = "C", CrosshairEnable = "C", GetRagdollEntity = "C", AnimSetGestureSequence = "C", AnimRestartMainSequence = "C", SteamID64 = "C", GetPlayerColor = "C", SetCanWalk = "C", GetCanWalk = "C", HasWeapon = "C", ExitVehicle = "C", GetHull = "C", SetHullDuck = "C", IsTyping = "C", UnLock = "C", SprayDecal = "C", ChatPrint = "C", LimitHit = "L", GetWalkSpeed = "C", SetJumpPower = "C", GetCanZoom = "C", IsVehicle = "C", AddFrozenPhysicsObject = "L", AddCount = "L", GetHullDuck = "C", UserID = "C", GetVehicle = "C", GetEyeTraceNoCursor = "L", GetRunSpeed = "C", SetUserGroup = "L", SprintEnable = "C", DoAttackEvent = "C", GetDuckSpeed = "C", HasGodMode = "L", GetViewPunchAngles = "C", StartSprinting = "C", StopZooming = "C", StartWalking = "C", GetViewEntity = "C", SetHull = "C", GetPressedWidget = "C", PickupObject = "C", DetonateTripmines = "C", GetHoveredWidget = "C", SetFrags = "C", SetRenderAngles = "C", IsBot = "C", SetPlayerColor = "C", DrawViewModel = "C", StopSprinting = "C", GetDrivingMode = "C", SetClassID = "C", SteamID = "C", GetWeapon = "C", AnimResetGestureSlot = "C", UnfreezePhysicsObjects = "L", SimulateGravGunDrop = "C", AddVCDSequenceToGestureSlot = "C", RemoveSuit = "C", Name = "C", IsSuitEquipped = "C", Say = "C", GetName = "C", SpectateEntity = "C", SetViewOffsetDucked = "C", DoAnimationEvent = "C", IsDrivingEntity = "C", IsPlayer = "C", PrintMessage = "C", SetDrivingEntity = "C", GetJumpPower = "C", GetAvoidPlayers = "C", DropWeapon = "C", ScreenFade = "C", SendLua = "C", SetWalkSpeed = "C", GetCount = "L", GetRenderAngles = "C", GetAmmoCount = "C", IsAdmin = "L", GetCurrentViewOffset = "C", SetupHands = "L", CanUseFlashlight = "L", CreateRagdoll = "C", DoReloadEvent = "C", IsFullyAuthenticated = "C", GetUserGroup = "L", SwitchToDefaultWeapon = "L", Nick = "C", GetDrivingEntity = "C", __newindex = "C", SetPData = "L", SetCurrentViewOffset = "C", GetPData = "L", AllowFlashlight = "L", IsUserGroup = "L", SetCanZoom = "C", IsSuperAdmin = "L", ConCommand = "C", CrosshairDisable = "C", Deaths = "C", }, PathFollower = { GetAllSegments = "C", Invalidate = "C", FirstSegment = "C", GetCursorPosition = "C", Compute = "C", MoveCursorToStart = "C", GetClosestPosition = "C", GetStart = "C", SetGoalTolerance = "C", MoveCursorToEnd = "C", Update = "C", SetMinLookAheadDistance = "C", ResetAge = "C", MoveCursorTo = "C", Draw = "C", GetCursorData = "C", GetLength = "C", GetEnd = "C", GetPositionOnPath = "C", GetCurrentGoal = "C", GetHindrance = "C", MoveCursor = "C", __tostring = "C", MoveCursorToClosestPosition = "C", LastSegment = "C", Chase = "C", GetAge = "C", IsValid = "C", }, CLuaLocomotion = { SetJumpHeight = "C", ClearStuck = "C", GetStepHeight = "C", SetDesiredSpeed = "C", Jump = "C", GetDeceleration = "C", IsStuck = "C", GetDeathDropHeight = "C", SetDeceleration = "C", IsOnGround = "C", GetCurrentAcceleration = "C", GetJumpHeight = "C", GetAcceleration = "C", SetDeathDropHeight = "C", Approach = "C", FaceTowards = "C", SetAcceleration = "C", IsUsingLadder = "C", IsClimbingOrJumping = "C", IsAttemptingToMove = "C", GetVelocity = "C", GetGroundMotionVector = "C", IsAreaTraversable = "C", GetMaxJumpHeight = "C", __tostring = "C", GetMaxYawRate = "C", JumpAcrossGap = "C", SetMaxYawRate = "C", SetStepHeight = "C", SetVelocity = "C", }, CUserCmd = { ClearMovement = "C", SetMouseWheel = "C", SetMouseX = "C", SetViewAngles = "C", GetUpMove = "C", KeyDown = "C", GetMouseX = "C", SelectWeapon = "C", SetImpulse = "C", SetUpMove = "C", SetSideMove = "C", GetViewAngles = "C", SetMouseY = "C", SetForwardMove = "C", SetButtons = "C", GetMouseWheel = "C", ClearButtons = "C", GetMouseY = "C", IsForced = "C", GetImpulse = "C", CommandNumber = "C", GetSideMove = "C", GetButtons = "C", GetForwardMove = "C", TickCount = "C", RemoveKey = "C", }, IRestore = { ReadVector = "C", ReadAngle = "C", StartBlock = "C", ReadInt = "C", EndBlock = "C", ReadString = "C", ReadEntity = "C", ReadFloat = "C", ReadBool = "C", }, CMoveData = { GetOldAngles = "C", GetButtons = "C", GetAbsMoveAngles = "C", SetSideSpeed = "C", GetOrigin = "C", KeyDown = "C", SetImpulseCommand = "C", SetUpSpeed = "C", KeyWasDown = "C", GetSideSpeed = "C", KeyPressed = "C", SetButtons = "C", SetAbsMoveAngles = "C", GetMaxSpeed = "C", SetForwardSpeed = "C", GetMaxClientSpeed = "C", GetOldButtons = "C", SetVelocity = "C", GetAngles = "C", SetMaxClientSpeed = "C", SetOldButtons = "C", GetUpSpeed = "C", SetOldAngles = "C", SetOrigin = "C", GetConstraintRadius = "C", SetMoveAngles = "C", GetVelocity = "C", SetConstraintRadius = "C", AddKey = "C", GetImpulseCommand = "C", GetForwardSpeed = "C", SetMaxSpeed = "C", SetAngles = "C", KeyReleased = "C", GetMoveAngles = "C", }, PhysObj = { GetVolume = "C", WorldToLocalVector = "C", SetBuoyancyRatio = "C", GetPos = "C", IsMoveable = "C", SetVelocityInstantaneous = "C", SetPos = "C", IsGravityEnabled = "C", GetEntity = "C", GetAngleVelocity = "C", __eq = "C", GetRotDamping = "C", SetDragCoefficient = "C", SetMass = "C", RotateAroundAxis = "C", EnableMotion = "C", IsDragEnabled = "C", Wake = "C", IsCollisionEnabled = "C", GetVelocity = "C", GetAABB = "C", UpdateShadow = "C", GetStress = "C", AddGameFlag = "C", OutputDebugInfo = "C", ApplyForceOffset = "C", SetMaterial = "C", LocalToWorldVector = "C", AddVelocity = "C", ApplyForceCenter = "C", ClearGameFlag = "C", SetInertia = "C", SetAngles = "C", GetDamping = "C", GetMaterial = "C", EnableDrag = "C", GetInvInertia = "C", GetMeshConvexes = "C", LocalToWorld = "C", SetDamping = "C", GetEnergy = "C", HasGameFlag = "C", GetSpeedDamping = "C", AlignAngles = "C", GetMassCenter = "C", IsValid = "C", GetInertia = "C", GetMesh = "C", CalculateVelocityOffset = "C", SetVelocity = "C", IsAsleep = "C", EnableCollisions = "C", ComputeShadowControl = "C", RecheckCollisionFilter = "C", SetAngleDragCoefficient = "C", GetInvMass = "C", GetSurfaceArea = "C", IsMotionEnabled = "C", GetMass = "C", GetAngles = "C", AddAngleVelocity = "C", WorldToLocal = "C", __tostring = "C", IsPenetrating = "C", Sleep = "C", EnableGravity = "C", GetName = "C", CalculateForceOffset = "C", }, ISave = { WriteEntity = "C", WriteBool = "C", StartBlock = "C", WriteAngle = "C", WriteFloat = "C", WriteVector = "C", EndBlock = "C", WriteInt = "C", WriteString = "C", }, Weapon = { GetWeight = "C", GetActivity = "C", GetHoldType = "C", GetSlotPos = "C", GetSlot = "C", GetWeaponViewModel = "C", GetNextSecondaryFire = "C", LastShootTime = "C", Clip2 = "C", HasAmmo = "C", IsWeaponVisible = "C", __newindex = "C", SetHoldType = "C", SetNextPrimaryFire = "C", SetNextSecondaryFire = "C", IsWeapon = "C", GetPrimaryAmmoType = "C", AllowsAutoSwitchFrom = "C", IsScripted = "C", GetSecondaryAmmoType = "C", AllowsAutoSwitchTo = "C", IsVehicle = "C", GetPrintName = "C", IsNPC = "C", CallOnClient = "C", GetWeaponWorldModel = "C", DefaultReload = "C", GetNextPrimaryFire = "C", GetMaxClip2 = "C", SendWeaponAnim = "C", IsPlayer = "C", __tostring = "C", Clip1 = "C", SetClip1 = "C", GetMaxClip1 = "C", SetClip2 = "C", SetLastShootTime = "C", }, Vector = { GetNormalized = "C", DotProduct = "C", Normalize = "C", IsEqualTol = "C", Distance = "C", Length = "C", Cross = "C", __mul = "C", __newindex = "C", IsZero = "C", __tostring = "C", Sub = "C", __sub = "C", Add = "C", LengthSqr = "C", DistToSqr = "C", __div = "C", Length2D = "C", __unm = "C", Dot = "C", WithinAABox = "C", AngleEx = "C", Set = "C", ToColor = "L", GetNormal = "C", Mul = "C", __add = "C", __eq = "C", Rotate = "C", Length2DSqr = "C", Zero = "C", Angle = "C", }, CSoundPatch = { GetVolume = "C", Stop = "C", SetSoundLevel = "C", GetDSP = "C", Play = "C", ChangePitch = "C", GetPitch = "C", PlayEx = "C", ChangeVolume = "C", GetSoundLevel = "C", __tostring = "C", IsPlaying = "C", SetDSP = "C", FadeOut = "C", }, CRecipientFilter = { GetPlayers = "C", AddAllPlayers = "C", AddPAS = "C", GetCount = "C", AddPlayer = "C", __tostring = "C", AddRecipientsByTeam = "C", RemoveAllPlayers = "C", RemovePAS = "C", AddPVS = "C", RemoveRecipientsByTeam = "C", RemovePVS = "C", RemovePlayer = "C", RemoveRecipientsNotOnTeam = "C", }, ITexture = { GetMappingWidth = "C", Download = "C", GetColor = "C", IsError = "C", Width = "C", GetMappingHeight = "C", GetName = "C", Height = "C", __tostring = "C", }, Entity = { SetPreventTransmit = "C", GetSpawnFlags = "C", IsWidget = "L", DropToFloor = "C", SetNotSolid = "C", SetShouldServerRagdoll = "C", SetPos = "C", SetTransmitWithParent = "C", SetNetworkedNumber = "C", GetNW2VarTable = "C", IsLagCompensated = "C", EnableConstraints = "C", GetVar = "L", GetManipulateBonePosition = "C", SetAnimation = "C", CallOnRemove = "L", SetCollisionBoundsWS = "C", HasBoneManipulations = "C", SetTable = "C", PhysicsInitSphere = "C", GetHitBoxBounds = "C", Spawn = "C", GetNumPoseParameters = "C", SetDTInt = "C", SetBoneController = "C", WorldSpaceAABB = "C", AddLayeredSequence = "C", GibBreakClient = "C", GetClass = "C", PointAtEntity = "C", GetLocalAngularVelocity = "C", GetRight = "C", ClearPoseParameters = "C", SetNetworkedEntity = "C", SetCustomCollisionCheck = "C", GetLocalAngles = "C", CollisionRulesChanged = "C", GetModelBounds = "C", SetSkin = "C", AddCallback = "C", GetFlexBounds = "C", ManipulateBoneJiggle = "C", SetPhysicsAttacker = "C", SetSaveValue = "C", AddFlags = "C", GetCustomCollisionCheck = "C", ResetSequenceInfo = "C", GetPlaybackRate = "C", GibBreakServer = "C", OBBMins = "C", FireBullets = "C", GetBoneController = "C", PassesFilter = "C", TakeDamageInfo = "C", GetAngles = "C", SetLayerCycle = "C", GetDTString = "C", TranslatePhysBoneToBone = "C", SetLayerPlaybackRate = "C", GetFlexScale = "C", GetDTEntity = "C", SetEntity = "C", SetLocalAngularVelocity = "C", SetNetworked2Entity = "C", GetWorkshopID = "C", GetConstrainedPhysObjects = "C", SelectWeightedSequenceSeeded = "C", GetNWBool = "C", __tostring = "C", SetVar = "L", GetNW2Entity = "C", SetBloodColor = "C", GetModelScale = "C", SetNetworked2Float = "C", GetLayerCycle = "C", SetNetworkOrigin = "C", SetPersistent = "C", DispatchTraceAttack = "C", GetManipulateBoneScale = "C", FindBodygroupByName = "C", GetPersistent = "C", GetBoneParent = "C", IsValidLayer = "C", MapCreationID = "C", SetModelScale = "C", PhysicsInitConvex = "C", FindTransitionSequence = "C", IsWorld = "C", GetCreationID = "C", GetSolidFlags = "C", WaterLevel = "C", SetLocalAngles = "C", SetLayerWeight = "C", SetLocalVelocity = "C", EmitSound = "C", GetDTBool = "C", Fire = "C", HasFlexManipulatior = "C", RagdollStopControlling = "C", SetPoseParameter = "C", GetAbsVelocity = "C", GetEFlags = "C", GetNetworked2VarTable = "C", SetPlaybackRate = "C", SetAttachment = "C", SetMoveParent = "C", SetVelocity = "C", IsPlayerHolding = "C", GetAttachment = "C", Input = "C", SetSubMaterial = "C", GetNetworkedString = "C", GetForward = "C", GetFlexNum = "C", SetKeyValue = "C", PhysicsFromMesh = "C", SetMoveCollide = "C", SetSolidFlags = "C", GetFlags = "C", IsVehicle = "C", SetAbsVelocity = "C", GetSequenceList = "C", GetChildBones = "L", GetBodygroup = "C", RemoveAllDecals = "C", GetRotatedAABB = "C", GetNWEntity = "C", RemoveEffects = "C", IsOnGround = "C", GetBoneMatrix = "C", GetSequenceActivityName = "C", SetNetworkedInt = "C", Weapon_TranslateActivity = "C", GetNW2String = "C", GetPoseParameter = "C", GetCollisionBounds = "C", GetLayerWeight = "C", GetCollisionGroup = "C", SetWeaponModel = "C", WorldToLocal = "C", NearestPoint = "C", SetBoneMatrix = "C", CreatedByMap = "C", SetDTString = "C", SetHealth = "C", SetSequence = "C", GetBrushPlane = "C", TakePhysicsDamage = "C", IsConstrained = "L", Activate = "C", GetInternalVariable = "C", GetMoveParent = "C", SetNW2Int = "C", GetMoveCollide = "C", IsValid = "C", GetSubMaterial = "C", GetName = "C", SetCollisionBounds = "C", SequenceDuration = "C", SetNW2Entity = "C", SetNetworked2Bool = "C", FollowBone = "C", GetNW2Bool = "C", GetSpawnEffect = "C", GetNoDraw = "C", IsPlayer = "C", ForcePlayerDrop = "C", GetNumBodyGroups = "C", GetMaterial = "C", RemoveFlags = "C", GetUp = "C", GetDTVector = "C", SetNetworkedBool = "C", SetModelName = "C", ManipulateBoneAngles = "C", IsWeapon = "C", SetParent = "C", SetNetworkedVector = "C", SetLayerBlendIn = "C", EyePos = "C", IsRagdoll = "C", LookupBone = "C", GetBoneName = "C", IsEffectActive = "C", LocalToWorldAngles = "C", GetSequenceActivity = "C", GetManipulateBoneAngles = "C", IsPlayingGesture = "C", SetEyeTarget = "C", SetNetworked2Vector = "C", SetNoDraw = "C", GetGroundEntity = "C", GetPoseParameterName = "C", GetFlexWeight = "C", GetTable = "C", SetNetworkedVar = "C", SetLagCompensated = "C", SetDTFloat = "C", SetBodygroup = "C", SetLayerBlendOut = "C", GetNetworkedAngle = "C", GetChildren = "C", GetFlexName = "C", Blocked = "C", EntIndex = "C", SetFlexWeight = "C", GetModel = "C", SetRenderMode = "C", GetColor = "C", SetDTEntity = "C", GetBonePosition = "C", SetRagdollBuildFunction = "C", SetMaxHealth = "C", Health = "C", SetOwner = "C", IsNPC = "C", RemoveGesture = "C", GetNetworked2Vector = "C", GetNetworked2Int = "C", IsLineOfSightClear = "C", SetRagdollPos = "C", GetBrushPlaneCount = "C", SetNetworked2Int = "C", BoneHasFlag = "C", SetNetworked2String = "C", GetDTAngle = "C", GetCycle = "C", GetRenderMode = "C", GetRenderFX = "C", GetBodygroupCount = "C", StartMotionController = "C", LookupAttachment = "C", SetRenderFX = "C", GetPos = "C", GetOwner = "C", GetPoseParameterRange = "C", GetHitboxSetCount = "C", PrecacheGibs = "C", GetSequence = "C", RemoveCallOnRemove = "L", GetNWAngle = "C", SetNW2Var = "C", GetNetworkedFloat = "C", SetNetworkedString = "C", NextThink = "C", GetMomentaryRotButtonPos = "C", GetSkin = "C", SetSpawnEffect = "C", OnGround = "C", GetAnimInfo = "C", SetMoveType = "C", StopLoopingSound = "C", GetParentPhysNum = "C", SetNetworkedVarProxy = "L", GetMoveType = "C", HeadTarget = "C", GetHitboxSet = "C", SetModel = "C", GetGravity = "C", SetUnFreezable = "L", GetSolid = "C", GetNW2Var = "C", RemoveEFlags = "C", BodyTarget = "C", GetConstrainedEntities = "C", GetSequenceName = "C", SetDTBool = "C", SetNetworked2Var = "C", SetNWAngle = "C", GetHitBoxCount = "C", GetDTInt = "C", GetVelocity = "C", GetCreator = "L", TakeDamage = "C", SetMaterial = "C", GetNetworked2String = "C", ObjectCaps = "C", AddToMotionController = "C", PhysicsInitShadow = "C", GetUnFreezable = "L", TranslateBoneToPhysBone = "C", AddEffects = "C", GetPhysicsObjectNum = "C", SetLayerLooping = "C", GetElasticity = "C", SetPhysConstraintObjects = "C", Respawn = "C", __newindex = "C", SetNWString = "C", WorldToLocalAngles = "C", OBBMaxs = "C", Visible = "C", SetHitboxSet = "C", GetNW2Float = "C", UseTriggerBounds = "C", GetDTFloat = "C", GetNetworkedBool = "C", OBBCenter = "C", SetLocalPos = "C", GetFlexIDByName = "C", GetSequenceGroundSpeed = "C", SetDTAngle = "C", DrawShadow = "C", PhysicsInit = "C", SetSolid = "C", GetHitboxBone = "C", GetKeyValues = "C", GetCreationTime = "C", AddEFlags = "C", GetEffects = "C", BoundingRadius = "C", AlignAngles = "C", MakePhysicsObjectAShadow = "C", SetFriction = "C", GetSequenceCount = "C", GetMaterialType = "C", GetTouchTrace = "C", SetShouldPlayPickupSound = "L", StopSound = "C", RemoveFromMotionController = "C", IsDormant = "C", GetShouldPlayPickupSound = "L", ManipulateBonePosition = "C", GetFriction = "C", Remove = "C", IsConstraint = "C", SetNetworkedFloat = "C", StopMotionController = "C", GetNetworked2Float = "C", PhysicsDestroy = "C", IsSolid = "C", GetBodygroupName = "C", SetCreator = "L", ViewModelIndex = "C", SetNetworked2Angle = "C", GetAttachments = "C", ResetSequence = "C", SetNW2Float = "C", SetCollisionGroup = "C", GetSubModels = "C", FrameAdvance = "C", GetNetworkedVector = "C", SetAngles = "C", WorldSpaceCenter = "C", SetBodyGroups = "C", GetGroundSpeedVelocity = "C", DontDeleteOnRemove = "C", RemoveSolidFlags = "C", IsInWorld = "C", SetNWInt = "C", SkinCount = "C", PlayScene = "C", GetMaterials = "C", TestPVS = "C", __eq = "C", GetParent = "C", GetNW2Angle = "C", GetBodyGroups = "C", SetUseType = "C", SetElasticity = "C", GetNW2Int = "C", GetSequenceMoveDist = "C", EnableCustomCollisions = "C", SetName = "C", GetLayerDuration = "C", GetManipulateBoneJiggle = "C", GetPhysicsObject = "C", SetDTVector = "C", SetGroundEntity = "C", AddGesture = "C", SetCycle = "C", ManipulateBoneScale = "C", SetLayerPriority = "C", __concat = "C", StopParticles = "C", IsEFlagSet = "C", GetBloodColor = "C", SetColor = "C", SetNWVector = "C", GetParentAttachment = "C", GetNWFloat = "C", IsFlagSet = "C", BoneLength = "C", Use = "C", SetParentPhysNum = "C", VisibleVec = "C", Weapon_SetActivity = "C", IsOnFire = "C", SetNetworkedAngle = "C", SetTrigger = "C", GetNetworked2Entity = "C", InstallDataTable = "L", GetRagdollOwner = "C", GetBaseVelocity = "C", LookupSequence = "C", RagdollUpdatePhysics = "C", SetNWBool = "C", GetPhysicsObjectCount = "C", Extinguish = "C", RagdollSolve = "C", SetNW2Angle = "C", GetSaveTable = "C", GetHitBoxGroupCount = "C", GetModelRenderBounds = "C", GetNetworkedEntity = "C", RestartGesture = "C", PhysicsInitMultiConvex = "C", HasSpawnFlags = "C", SetNWFloat = "C", GetSequenceInfo = "C", GetNWVarProxy = "L", StartLoopingSound = "C", GetLocalPos = "C", AddSolidFlags = "C", GetNetworkedVarProxy = "L", GetMaxHealth = "C", DeleteOnRemove = "C", GetNWInt = "C", PhysicsInitBox = "C", GetTransmitWithParent = "C", GetNetworked2Bool = "C", EyeAngles = "C", LocalToWorld = "C", GetHitBoxBone = "C", GetSequenceMoveYaw = "C", GetNetworkedInt = "C", GetNW2Vector = "C", SetNW2Bool = "C", SetNWEntity = "C", SetNW2Vector = "C", SetNW2String = "C", Ignite = "C", PassesDamageFilter = "C", GetNetworked2Angle = "C", GetPhysicsAttacker = "C", GetNWString = "C", GetShouldServerRagdoll = "C", SendViewModelMatchingSequence = "C", SetGravity = "C", GetNetworkOrigin = "C", GetBoneCount = "C", GetNWVector = "C", UseClientSideAnimation = "C", MuzzleFlash = "C", GetModelRadius = "C", AddGestureSequence = "C", SetLayerDuration = "C", PhysWake = "L", GetNetworkedVar = "C", SetFlexScale = "C", RemoveAllGestures = "C", SetRagdollAng = "C", SetNWVarProxy = "L", GetNetworked2Var = "C", SelectWeightedSequence = "C", }, Vehicle = { GetWheelContactPoint = "C", GetWheelTotalHeight = "C", GetPassenger = "C", SetWheelFriction = "C", IsEngineStarted = "C", HasBrakePedal = "C", BoostTimeLeft = "C", GetDriver = "C", IsEngineEnabled = "C", IsValidVehicle = "C", SetPos = "C", CheckExitPoint = "C", SetSteering = "C", GetWheel = "C", GetThirdPersonMode = "L", SetBoost = "C", SetCameraDistance = "L", GetMaxSpeed = "C", __newindex = "C", SetThrottle = "C", GetWheelCount = "C", SetVehicleEntryAnim = "C", SetVehicleParams = "C", GetVehicleViewPosition = "C", GetSteering = "C", GetHLSpeed = "C", GetPassengerSeatPoint = "C", GetWheelBaseHeight = "C", GetVehicleParams = "C", IsVehicleBodyInWater = "C", SetSteeringDegrees = "C", SetHasBrakePedal = "C", GetSteeringDegrees = "C", StartEngine = "C", EnableEngine = "C", HasBoost = "C", SetVehicleClass = "L", IsVehicle = "C", GetSpeed = "C", IsBoosting = "C", GetRPM = "C", GetThrottle = "C", SetMaxThrottle = "C", SetMaxReverseThrottle = "C", SetHandbrake = "C", GetCameraDistance = "L", __tostring = "C", ReleaseHandbrake = "C", SetSpringLength = "C", GetVehicleClass = "L", GetOperatingParams = "C", SetThirdPersonMode = "L", }, _LOADLIB = { }, Angle = { Set = "C", __sub = "C", __unm = "C", SnapTo = "L", __add = "C", Right = "C", Up = "C", __mul = "C", __newindex = "C", RotateAroundAxis = "C", __tostring = "C", IsZero = "C", Forward = "C", __eq = "C", Zero = "C", Normalize = "C", }, File = { ReadShort = "C", WriteByte = "C", WriteFloat = "C", WriteLong = "C", WriteDouble = "C", Close = "C", ReadLine = "C", ReadBool = "C", Seek = "C", Write = "C", Flush = "C", ReadByte = "C", Tell = "C", __tostring = "C", ReadLong = "C", ReadDouble = "C", Size = "C", Read = "C", WriteShort = "C", Skip = "C", WriteBool = "C", ReadFloat = "C", }, CEffectData = { GetStart = "C", SetAttachment = "C", SetRadius = "C", GetRadius = "C", SetScale = "C", GetAttachment = "C", GetColor = "C", GetFlags = "C", GetOrigin = "C", SetNormal = "C", GetSurfaceProp = "C", SetMaterialIndex = "C", SetStart = "C", SetOrigin = "C", GetAngles = "C", GetMaterialIndex = "C", SetMagnitude = "C", SetEntIndex = "C", SetAngles = "C", GetDamageType = "C", GetEntIndex = "C", SetEntity = "C", GetHitBox = "C", SetDamageType = "C", GetNormal = "C", GetEntity = "C", SetColor = "C", SetFlags = "C", GetMagnitude = "C", GetScale = "C", SetSurfaceProp = "C", SetHitBox = "C", }, ConVar = { GetDefault = "C", GetString = "C", SetString = "C", GetInt = "C", GetHelpText = "C", GetName = "C", __tostring = "C", SetInt = "C", SetFloat = "C", GetBool = "C", SetBool = "C", GetFloat = "C", }, CNavLadder = { IsConnectedAtSide = "C", GetTopRightArea = "C", GetPosAtHeight = "C", SetTopForwardArea = "C", SetTopRightArea = "C", GetTopForwardArea = "C", GetID = "C", GetBottomArea = "C", GetTopLeftArea = "C", GetTopBehindArea = "C", GetNormal = "C", SetTopBehindArea = "C", __tostring = "C", SetTopLeftArea = "C", GetLength = "C", ConnectTo = "C", SetBottomArea = "C", IsValid = "C", }, CTakeDamageInfo = { IsExplosionDamage = "C", SetDamageBonus = "C", IsDamageType = "C", IsBulletDamage = "C", SetDamageCustom = "C", SetDamageForce = "C", IsFallDamage = "C", GetDamageCustom = "C", GetDamageType = "C", GetReportedPosition = "C", SetReportedPosition = "C", SetMaxDamage = "C", GetAmmoType = "C", SetInflictor = "C", SubtractDamage = "C", GetDamageForce = "C", SetDamage = "C", GetInflictor = "C", GetBaseDamage = "C", SetAttacker = "C", GetDamageBonus = "C", SetDamageType = "C", AddDamage = "C", GetDamagePosition = "C", SetAmmoType = "C", ScaleDamage = "C", GetDamage = "C", SetDamagePosition = "C", GetMaxDamage = "C", GetAttacker = "C", }, VMatrix = { GetUp = "C", SetRight = "C", Invert = "C", GetInverse = "C", SetScale = "C", SetForward = "C", GetAngles = "C", __mul = "C", GetScale = "C", GetForward = "C", GetRight = "C", SetAngles = "C", __sub = "C", SetUp = "C", __tostring = "C", Set = "C", Identity = "C", IsRotationMatrix = "C", IsIdentity = "C", GetTranslation = "C", Translate = "C", GetField = "C", SetTranslation = "C", Scale = "C", InvertTR = "C", GetInverseTR = "C", __add = "C", __eq = "C", Rotate = "C", ToTable = "C", SetField = "C", ScaleTranslation = "C", }, CNavArea = { IsConnected = "C", Draw = "C", AddToClosedList = "C", IsVisible = "C", IsBlocked = "C", IsOpen = "C", GetExposedSpots = "C", RemoveFromClosedList = "C", SetAttributes = "C", GetRandomAdjacentAreaAtSide = "C", GetSizeX = "C", IsClosed = "C", Contains = "C", IsCoplanar = "C", GetAdjacentCount = "C", GetParent = "C", IsOverlapping = "C", SetTotalCost = "C", GetSizeY = "C", GetAdjacentCountAtSide = "C", GetZ = "C", __tostring = "C", __eq = "C", UpdateOnOpenList = "C", IsValid = "C", GetCenter = "C", GetRandomPoint = "C", IsFlat = "C", DrawSpots = "C", SetParent = "C", AddToOpenList = "C", HasAttributes = "C", GetAdjacentAreas = "C", IsRoughlySquare = "C", GetCorner = "C", GetLaddersAtSide = "C", IsConnectedAtSide = "C", GetLadders = "C", GetID = "C", ComputeGroundHeightChange = "C", GetClosestPointOnArea = "C", GetAdjacentAreasAtSide = "C", IsOverlappingArea = "C", GetAttributes = "C", PopOpenList = "C", ComputeAdjacentConnectionHeightChange = "C", ComputeDirection = "C", GetCostSoFar = "C", ClearSearchLists = "C", GetHidingSpots = "C", IsUnderwater = "C", GetIncomingConnections = "C", GetExtentInfo = "C", IsOpenListEmpty = "C", GetTotalCost = "C", GetIncomingConnectionsAtSide = "C", GetParentHow = "C", }, IMaterial = { GetFloat = "C", Recompute = "C", GetMatrix = "C", SetTexture = "C", SetInt = "C", GetString = "C", SetFloat = "C", GetShader = "C", GetTexture = "C", GetInt = "C", Width = "C", SetShader = "C", GetVectorLinear = "C", GetKeyValues = "C", SetString = "C", GetName = "C", SetVector = "C", IsError = "C", __tostring = "C", SetUndefined = "C", GetVector = "C", GetColor = "C", Height = "C", SetMatrix = "C", }, }, functions = { list = { Contains = "L", Set = "L", Add = "L", GetForEdit = "L", Get = "L", }, utf8 = { codepoint = "L", offset = "L", force = "L", char = "L", len = "L", codes = "L", }, hook = { Run = "L", Call = "L", Remove = "L", GetTable = "L", Add = "L", }, usermessage = { Hook = "L", GetTable = "L", IncomingMessage = "L", }, timer = { Exists = "C", UnPause = "C", Toggle = "C", Adjust = "C", Create = "C", Destroy = "C", Stop = "C", Start = "C", Remove = "C", Pause = "C", RepsLeft = "C", TimeLeft = "C", Simple = "C", Check = "C", }, team = { GetPlayers = "L", GetScore = "L", SetClass = "L", GetSpawnPoints = "L", Joinable = "L", GetAllTeams = "L", Valid = "L", TotalFrags = "L", SetColor = "L", GetColor = "L", GetSpawnPoint = "L", AddScore = "L", TotalDeaths = "L", GetName = "L", GetClass = "L", NumPlayers = "L", SetUp = "L", SetScore = "L", SetSpawnPoint = "L", BestAutoJoinTeam = "L", }, http = { Post = "L", Fetch = "L", }, system = { BatteryPower = "C", AppTime = "C", IsWindows = "C", IsOSX = "C", GetCountry = "C", IsLinux = "C", UpTime = "C", SteamTime = "C", HasFocus = "C", }, cleanup = { GetList = "L", GetTable = "L", Add = "L", Register = "L", CC_AdminCleanup = "L", ReplaceEntity = "L", CC_Cleanup = "L", }, undo = { AddEntity = "L", Finish = "L", SetPlayer = "L", Create = "L", AddFunction = "L", Do_Undo = "L", GetTable = "L", ReplaceEntity = "L", SetCustomUndoText = "L", }, engine = { LightStyle = "C", ActiveGamemode = "C", CloseServer = "C", GetGames = "C", GetAddons = "C", GetGamemodes = "C", TickInterval = "C", }, ents = { FindInCone = "C", FindInBox = "C", FindByModel = "C", FireTargets = "C", Create = "C", FindByName = "C", FindInSphere = "C", FindInPVS = "C", FindByClass = "C", GetByIndex = "C", GetAll = "C", GetMapCreatedEntity = "C", FindByClassAndParent = "L", GetCount = "C", }, scripted_ents = { GetSpawnable = "L", IsBasedOn = "L", Alias = "L", GetList = "L", GetType = "L", GetStored = "L", OnLoaded = "L", Get = "L", Register = "L", GetMember = "L", }, gameevent = { Listen = "C", }, file = { Exists = "C", Write = "L", Append = "L", Time = "C", Delete = "C", Size = "C", Read = "L", Open = "C", CreateDir = "C", Find = "C", IsDir = "C", }, constraint = { NoCollide = "L", Slider = "L", Weld = "L", CreateStaticAnchorPoint = "L", Rope = "L", GetAllConstrainedEntities = "L", Hydraulic = "L", AddConstraintTable = "L", Keepupright = "L", Motor = "L", GetTable = "L", RemoveConstraints = "L", FindConstraints = "L", AddConstraintTableNoDelete = "L", HasConstraints = "L", CreateKeyframeRope = "L", RemoveAll = "L", Axis = "L", Ballsocket = "L", Find = "L", AdvBallsocket = "L", ForgetConstraints = "L", CanConstrain = "L", FindConstraint = "L", Pulley = "L", Muscle = "L", FindConstraintEntity = "L", Winch = "L", Elastic = "L", }, gmsave = { PlayerLoad = "L", SaveMap = "L", LoadMap = "L", PlayerSave = "L", ShouldSaveEntity = "L", }, game = { MountGMA = "C", IsDedicated = "C", SetTimeScale = "C", ConsoleCommand = "C", BuildAmmoTypes = "L", AddParticles = "C", StartSpot = "C", GetMapNext = "C", KickID = "C", GetAmmoName = "C", CleanUpMap = "C", MapLoadType = "C", GetWorld = "C", GetAmmoMax = "C", GetTimeScale = "C", GetMap = "C", GetMapVersion = "C", GetGlobalState = "C", GetSkillLevel = "C", SetGlobalCounter = "C", SinglePlayer = "C", MaxPlayers = "C", SetSkillLevel = "C", GetGlobalCounter = "C", LoadNextMap = "C", SetGlobalState = "C", AddAmmoType = "L", GetAmmoID = "C", RemoveRagdolls = "C", GetIPAddress = "C", AddDecal = "C", }, gamemode = { Register = "L", Call = "L", Get = "L", }, resource = { AddFile = "C", AddWorkshop = "C", AddSingleFile = "C", }, motionsensor = { ChooseBuilderFromEntity = "L", ProcessAnglesTable = "L", ProcessPositionTable = "L", ProcessAngle = "L", BuildSkeleton = "L", }, hammer = { SendCommand = "C", }, numpad = { OnUp = "L", Remove = "L", Toggle = "L", OnDown = "L", Register = "L", Deactivate = "L", Activate = "L", FromButton = "L", }, gmod = { GetGamemode = "C", }, duplicator = { DoFlex = "L", FindEntityClass = "L", ClearEntityModifier = "L", CreateConstraintFromTable = "L", CopyEntTable = "L", GetAllConstrainedEntitiesAndConstraints = "L", ApplyBoneModifiers = "L", Copy = "L", ApplyEntityModifiers = "L", RegisterEntityModifier = "L", RegisterBoneModifier = "L", DoBoneManipulator = "L", RemoveMapCreatedEntities = "L", CopyEnts = "L", GenericDuplicatorFunction = "L", Paste = "L", WorkoutSize = "L", StoreBoneModifier = "L", RegisterEntityClass = "L", Allow = "L", SetLocalPos = "L", IsAllowed = "L", DoGeneric = "L", DoGenericPhysics = "L", StoreEntityModifier = "L", CreateEntityFromTable = "L", RegisterConstraint = "L", SetLocalAng = "L", }, navmesh = { ClearWalkableSeeds = "C", SetMarkedArea = "C", GetNavLadderByID = "C", IsLoaded = "C", IsGenerating = "C", GetEditCursorPosition = "C", Save = "C", GetNavAreaCount = "C", Load = "C", BeginGeneration = "C", GetMarkedLadder = "C", GetPlayerSpawnName = "C", SetMarkedLadder = "C", Reset = "C", GetNavAreaByID = "C", SetPlayerSpawnName = "C", Find = "C", GetNavArea = "C", AddWalkableSeed = "C", GetNearestNavArea = "C", GetMarkedArea = "C", GetAllNavAreas = "C", }, table = { Empty = "L", HasValue = "L", foreach = "C", Sanitise = "L", CopyFromTo = "L", getn = "C", GetFirstKey = "L", GetWinningKey = "L", ForEach = "L", Reverse = "L", GetFirstValue = "L", DeSanitise = "L", SortByKey = "L", KeyFromValue = "L", maxn = "C", CollapseKeyValue = "L", IsSequential = "L", Count = "L", Inherit = "L", Add = "L", Copy = "L", GetKeys = "L", LowerKeyNames = "L", ToString = "L", insert = "C", sort = "C", SortByMember = "L", foreachi = "C", ClearKeys = "L", ForceInsert = "L", FindNext = "L", Random = "L", GetLastValue = "L", KeysFromValue = "L", Merge = "L", remove = "C", SortDesc = "L", FindPrev = "L", RemoveByValue = "L", concat = "C", GetLastKey = "L", }, sound = { AddSoundOverrides = "C", GetProperties = "C", Add = "C", Play = "C", GetTable = "C", }, net = { Broadcast = "C", Receive = "L", WriteInt = "C", ReadInt = "C", WriteFloat = "C", ReadEntity = "L", ReadType = "L", BytesWritten = "C", WriteBool = "C", SendPVS = "C", SendPAS = "C", WriteBit = "C", ReadHeader = "C", WriteType = "L", ReadVector = "C", WriteNormal = "C", WriteUInt = "C", Start = "C", ReadString = "C", ReadMatrix = "C", ReadFloat = "C", WriteColor = "L", WriteDouble = "C", ReadBit = "C", WriteString = "C", ReadBool = "L", SendOmit = "C", WriteVector = "C", WriteData = "C", Send = "C", ReadUInt = "C", ReadData = "C", WriteTable = "L", WriteMatrix = "C", WriteAngle = "C", ReadDouble = "C", WriteEntity = "L", ReadAngle = "C", Incoming = "L", ReadNormal = "C", ReadTable = "L", ReadColor = "L", }, ai_task = { New = "L", }, ai_schedule = { New = "L", }, baseclass = { Get = "L", Set = "L", }, util = { SharedRandom = "C", IsModelLoaded = "C", tobool = "L", GetModelInfo = "C", SpriteTrail = "C", AddNetworkString = "C", TraceEntityHull = "C", SetPData = "L", BlastDamage = "C", JSONToTable = "C", Decal = "C", GetSurfaceIndex = "C", SteamIDFrom64 = "C", RemovePData = "L", PointContents = "C", DateStamp = "L", TimerCycle = "C", KeyValuesToTable = "C", KeyValuesToTablePreserveOrder = "C", ParticleTracer = "C", NetworkIDToString = "C", DecalMaterial = "C", IsInWorld = "C", DistanceToLine = "C", TraceHull = "C", ScreenShake = "C", NiceFloat = "L", LocalToWorld = "L", TypeToString = "L", IsValidModel = "C", Decompress = "C", QuickTrace = "L", IntersectRayWithOBB = "C", TableToKeyValues = "C", PrecacheModel = "C", PrecacheSound = "C", StringToType = "L", ParticleTracerEx = "C", RelativePathToFull = "C", TableToJSON = "C", Base64Encode = "C", AimVector = "C", Effect = "C", Timer = "L", GetSurfacePropName = "C", BlastDamageInfo = "C", SteamIDTo64 = "C", TraceLine = "C", IsValidProp = "C", IsValidPhysicsObject = "L", TraceEntity = "C", GetPlayerTrace = "L", IntersectRayWithPlane = "C", Compress = "C", GetUserGroups = "L", Stack = "L", GetPData = "L", IsValidRagdoll = "C", NetworkStringToID = "C", CRC = "C", }, properties = { OnScreenClick = "L", Add = "L", OpenEntityMenu = "L", GetHovered = "L", }, player = { GetCount = "C", GetByUniqueID = "L", GetHumans = "C", GetBySteamID64 = "L", CreateNextBot = "C", GetBySteamID = "L", GetAll = "C", GetByID = "C", GetBots = "C", }, coroutine = { create = "C", resume = "C", yield = "C", wrap = "C", wait = "L", running = "C", status = "C", }, widgets = { RenderMe = "L", PlayerTick = "L", }, saverestore = { WritableKeysInTable = "L", SaveEntity = "L", AddSaveHook = "L", WriteTable = "L", ReadTable = "L", LoadEntity = "L", AddRestoreHook = "L", ReadVar = "L", WriteVar = "L", PreRestore = "L", LoadGlobal = "L", SaveGlobal = "L", PreSave = "L", }, package = { seeall = "C", }, umsg = { PoolString = "C", Char = "C", Long = "C", Bool = "C", Vector = "C", Entity = "C", Start = "C", Float = "C", String = "C", Short = "C", VectorNormal = "C", End = "C", Angle = "C", }, jit = { off = "C", flush = "C", status = "C", attach = "C", on = "C", }, physenv = { SetAirDensity = "C", SetPerformanceSettings = "C", GetGravity = "C", GetAirDensity = "C", GetPerformanceSettings = "C", SetGravity = "C", AddSurfaceData = "C", }, GAMEMODE = { Move = "L", PlayerEnteredVehicle = "L", PlayerAuthed = "L", PlayerSpawnedNPC = "L", Saved = "L", PlayerSpawnNPC = "L", KeyRelease = "L", PhysgunPickup = "L", CanPlayerUnfreeze = "L", PlayerRequestTeam = "L", PreGamemodeLoaded = "L", PlayerSetHandsModel = "L", PlayerPostThink = "L", UpdateAnimation = "L", PlayerDriveAnimate = "L", PlayerSwitchWeapon = "L", PlayerJoinTeam = "L", Tick = "L", PlayerSpawn = "L", PlayerSpawnedProp = "L", PlayerButtonUp = "L", ShouldCollide = "L", StartEntityDriving = "L", GrabEarAnimation = "L", OnReloaded = "L", PlayerShouldTakeDamage = "L", PlayerSpawnRagdoll = "L", IsSpawnpointSuitable = "L", PlayerSpawnProp = "L", GravGunPickupAllowed = "L", PlayerStartTaunt = "L", PlayerDeathThink = "L", SetPlayerSpeed = "L", PlayerDeathSound = "L", PlayerSpawnedVehicle = "L", PlayerLeaveVehicle = "L", PlayerSpawnEffect = "L", HandlePlayerSwimming = "L", PlayerTick = "L", PlayerSay = "L", PlayerStepSoundTime = "L", CanProperty = "L", EntityKeyValue = "L", EndEntityDriving = "L", PlayerCanPickupWeapon = "L", PostGamemodeLoaded = "L", OnNPCKilled = "L", CanEditVariable = "L", HandlePlayerDucking = "L", PlayerTraceAttack = "L", CheckPassword = "L", CreateTeams = "L", PlayerSetModel = "L", OnGamemodeLoaded = "L", PlayerDisconnected = "L", PlayerCanPickupItem = "L", PlayerSpawnAsSpectator = "L", PlayerSpawnSWEP = "L", CalcMainActivity = "L", EntityRemoved = "L", FinishMove = "L", PlayerSelectTeamSpawn = "L", PlayerLoadout = "L", PlayerGiveSWEP = "L", PlayerCanHearPlayersVoice = "L", CanTool = "L", GetFallDamage = "L", PlayerFrozeObject = "L", PlayerHurt = "L", OnViewModelChanged = "L", OnPhysgunFreeze = "L", OnDamagedByExplosion = "L", SetupPlayerVisibility = "L", PlayerDeath = "L", OnPhysgunReload = "L", PlayerSpawnedRagdoll = "L", GravGunPunt = "L", CanExitVehicle = "L", GravGunOnPickedUp = "L", ShutDown = "L", PlayerNoClip = "L", InitPostEntity = "L", PlayerCanSeePlayersChat = "L", CanPlayerEnterVehicle = "L", PlayerSilentDeath = "L", OnEntityCreated = "L", PlayerFootstep = "L", PlayerShouldTaunt = "L", PlayerSpawnedEffect = "L", ShowHelp = "L", PlayerSpawnedSWEP = "L", PlayerSpray = "L", KeyPress = "L", AllowPlayerPickup = "L", PropBreak = "L", PlayerSpawnSENT = "L", Restored = "L", Think = "L", TranslateActivity = "L", PlayerConnect = "L", GravGunOnDropped = "L", GetGameDescription = "L", CanPlayerSuicide = "L", PlayerButtonDown = "L", PlayerSpawnedSENT = "L", CanDrive = "L", HandlePlayerNoClipping = "L", PlayerSelectSpawn = "L", PlayerSwitchFlashlight = "L", EntityTakeDamage = "L", PlayerUnfrozeObject = "L", Initialize = "L", ShowTeam = "L", HandlePlayerDriving = "L", PlayerCanJoinTeam = "L", HandlePlayerLanding = "L", VariableEdited = "L", ScaleNPCDamage = "L", ScalePlayerDamage = "L", PlayerInitialSpawn = "L", HandlePlayerJumping = "L", HandlePlayerVaulting = "L", SetupMove = "L", MouthMoveAnimation = "L", FindUseEntity = "L", PlayerSpawnObject = "L", NetworkIDValidated = "L", PhysgunDrop = "L", DoAnimationEvent = "L", VehicleMove = "L", PlayerSpawnVehicle = "L", OnPlayerHitGround = "L", CreateEntityRagdoll = "L", OnPlayerChangedTeam = "L", PlayerUse = "L", DoPlayerDeath = "L", WeaponEquip = "L", }, cookie = { Delete = "L", GetNumber = "L", GetString = "L", Set = "L", }, sql = { TableExists = "L", Begin = "L", Query = "C", QueryRow = "L", QueryValue = "L", SQLStr = "L", Commit = "L", LastError = "L", }, math = { ceil = "C", tan = "C", Clamp = "L", AngleDifference = "L", sinh = "C", BSplinePoint = "L", Rand = "L", ldexp = "C", Max = "C", Round = "L", atan2 = "C", min = "C", calcBSplineN = "L", ApproachAngle = "L", exp = "C", NormalizeAngle = "L", rad = "C", EaseInOut = "L", randomseed = "C", deg = "C", sin = "C", fmod = "C", cos = "C", frexp = "C", random = "C", mod = "C", tanh = "C", pow = "C", cosh = "C", Distance = "L", floor = "C", sqrt = "C", Approach = "L", atan = "C", acos = "C", IntToBin = "L", BinToInt = "L", abs = "C", Min = "C", max = "C", log10 = "C", Dist = "L", Remap = "L", TimeFraction = "L", modf = "C", log = "C", asin = "C", Truncate = "L", }, concommand = { Run = "L", Remove = "L", AutoComplete = "L", GetTable = "L", Add = "L", }, weapons = { OnLoaded = "L", GetStored = "L", IsBasedOn = "L", Register = "L", GetList = "L", Get = "L", }, drive = { Move = "L", PlayerStopDriving = "L", PlayerStartDriving = "L", DestroyMethod = "L", CalcView = "L", Start = "L", Register = "L", GetMethod = "L", StartMove = "L", FinishMove = "L", End = "L", CreateMove = "L", }, bit = { rol = "C", arshift = "C", bor = "C", bswap = "C", bxor = "C", rshift = "C", ror = "C", bnot = "C", tobit = "C", lshift = "C", tohex = "C", band = "C", }, os = { date = "C", time = "C", clock = "C", difftime = "C", }, player_manager = { SetPlayerClass = "L", AddValidModel = "L", RunClass = "L", TranslateToPlayerModelName = "L", AddValidHands = "L", OnPlayerSpawn = "L", AllValidModels = "L", TranslatePlayerHands = "L", GetPlayerClass = "L", ClearPlayerClass = "L", TranslatePlayerModel = "L", RegisterClass = "L", }, construct = { SetPhysProp = "L", Magnet = "L", }, string = { format = "C", Trim = "L", Right = "L", len = "C", ToMinutesSeconds = "L", gsub = "C", Replace = "L", char = "C", SetChar = "L", StartWith = "L", Left = "L", rep = "C", TrimLeft = "L", GetExtensionFromFilename = "L", reverse = "C", Implode = "L", NiceSize = "L", GetPathFromFilename = "L", find = "C", Comma = "L", TrimRight = "L", upper = "C", sub = "C", JavascriptSafe = "L", FormattedTime = "L", ToMinutesSecondsMilliseconds = "L", GetChar = "L", Split = "L", StripExtension = "L", GetFileFromFilename = "L", gfind = "C", NiceTime = "L", gmatch = "C", lower = "C", match = "C", dump = "C", EndsWith = "L", Explode = "L", byte = "C", FromColor = "L", ToTable = "L", PatternSafe = "L", ToColor = "L", }, debug = { setupvalue = "C", getregistry = "C", traceback = "C", setlocal = "C", upvalueid = "C", getupvalue = "C", getlocal = "C", upvaluejoin = "C", getinfo = "C", getfenv = "C", setmetatable = "C", sethook = "C", gethook = "C", debug = "C", getmetatable = "C", setfenv = "C", Trace = "L", }, debugoverlay = { Line = "C", BoxAngles = "C", Sphere = "C", Axis = "C", Box = "C", Grid = "C", SweptBox = "C", EntityTextAtPosition = "C", Triangle = "C", Cross = "C", ScreenText = "C", Text = "C", }, ai = { GetScheduleID = "C", GetTaskID = "C", }, cvars = { Number = "L", RemoveChangeCallback = "L", GetConVarCallbacks = "L", AddChangeCallback = "L", OnConVarChanged = "L", String = "L", Bool = "L", }, }, globals = { tobool = "L", SetPhysConstraintSystem = "C", LerpVector = "C", Sound = "L", SafeRemoveEntityDelayed = "L", Error = "C", rawget = "C", SetGlobal2Var = "C", SortedPairsByMemberValue = "L", OrderVectors = "C", newproxy = "C", SetGlobalInt = "C", print = "C", pcall = "C", gcinfo = "C", ismatrix = "C", DebugInfo = "C", MakeLight = "L", include = "C", SQLStr = "L", AngleRand = "L", TimedSin = "L", GetConVar = "L", SetGlobal2Int = "C", CompileString = "C", Particle = "L", AddOriginToPVS = "C", BroadcastLua = "C", MakeHoverBall = "L", type = "C", DropEntityIfHeld = "C", Model = "L", CreateConVar = "C", isangle = "C", Matrix = "C", GetConVarString = "L", GetGlobalInt = "C", MakeLamp = "L", CurTime = "C", AddConsoleCommand = "C", TypeID = "C", ConVarExists = "C", GetGlobal2String = "C", PrecacheParticleSystem = "C", GetGlobalFloat = "C", HTTP = "C", CheckPropSolid = "L", SafeRemoveEntity = "L", Color = "L", IsEnemyEntityName = "L", Angle = "C", EffectData = "C", ColorToHSV = "C", ServerLog = "C", CC_GMOD_Tool = "L", SetGlobal2Float = "C", SendUserMessage = "L", GetGlobal2Vector = "C", GetGlobal2Float = "C", EmitSound = "C", DamageInfo = "C", DoPlayerEntitySpawn = "L", GetConVar_Internal = "C", Either = "L", EmitSentence = "C", BuildNetworkedVarsTable = "C", collectgarbage = "C", WorldToLocal = "C", select = "C", unpack = "C", getfenv = "C", IsMounted = "L", Format = "C", MsgC = "C", assert = "C", FixInvalidPhysicsObject = "L", SetGlobalVar = "C", PrecacheSentenceFile = "C", GMODSpawnEffect = "L", tonumber = "C", TauntCamera = "L", MakeWheel = "L", SetGlobalEntity = "C", isstring = "C", PrintTable = "L", UnPredictedCurTime = "C", require = "C", istable = "C", isentity = "C", GetGlobalString = "C", isbool = "C", AddCSLuaFile = "C", SetGlobal2Vector = "C", isvector = "C", xpcall = "C", SetGlobalFloat = "C", tostring = "C", module = "C", HSVToColor = "C", GetGlobalVar = "C", Lerp = "L", GetGlobal2Entity = "C", SetGlobalString = "C", IsEntity = "C", PrecacheSentenceGroup = "C", CCGiveSWEP = "L", SortedPairs = "L", rawset = "C", ErrorNoHalt = "C", Vector = "C", IsTableOfEntitiesValid = "L", ipairs = "C", Material = "C", SetGlobal2Entity = "C", GetGlobalAngle = "C", rawequal = "C", ColorAlpha = "L", CCSpawn = "L", Entity = "C", IsColor = "L", GetGlobalEntity = "C", GetGlobalVector = "C", error = "C", GetConVarNumber = "L", next = "C", SysTime = "C", SetGlobalAngle = "C", ParticleEffect = "C", GetGlobal2Var = "C", Msg = "C", FrameTime = "C", SetGlobalVector = "C", Add_NPC_Class = "L", FindMetaTable = "C", RunConsoleCommand = "C", Path = "C", PrecacheScene = "C", isnumber = "C", CompileFile = "C", IncludeCS = "L", RunString = "C", VGUIFrameTime = "C", Spawn_NPC = "L", GetGlobal2Int = "C", SetGlobal2Angle = "C", MsgN = "C", ProtectedCall = "C", ParticleEffectAttach = "C", GetGlobal2Angle = "C", LerpAngle = "C", SoundDuration = "C", MakeThruster = "L", RunStringEx = "C", IsFriendEntityName = "L", MakeBalloon = "L", Spawn_Weapon = "L", MakeDynamite = "L", Spawn_SENT = "L", RealTime = "C", SuppressHostEvents = "C", MakeProp = "L", GetGlobal2Bool = "C", MakeEmitter = "L", PrintMessage = "C", UTIL_IsUselessModel = "L", GetGlobalBool = "C", IsValid = "L", ispanel = "C", setfenv = "C", LocalToWorld = "C", VectorRand = "L", pairs = "C", Player = "C", SetGlobal2Bool = "C", MsgAll = "C", SortedPairsByValue = "L", CreateClientConVar = "L", IsUselessModel = "L", RandomPairs = "L", isfunction = "C", ColorRand = "L", IsFirstTimePredicted = "C", SetGlobalBool = "C", AccessorFunc = "L", TimedCos = "L", CC_Face_Randomize = "L", RecipientFilter = "C", MakeButton = "L", Spawn_Vehicle = "L", GMODSpawnRagdoll = "L", GMODSpawnProp = "L", DoPropSpawnedEffect = "L", setmetatable = "C", GetHostName = "C", SetGlobal2String = "C", STNDRD = "L", getmetatable = "C", CreateSound = "C", DeriveGamemode = "C", }, }
gpl-3.0
RolandKujundzic/rkphplib
test/StringHelper/in/t1.php
82
<?php global $html; print \rkphplib\StringHelper::removeHtmlWhiteSpace($html);
gpl-3.0
AlbertHambardzumyan/Codeforces
problems/src/problem_591/Problem_591A.java
421
package problem_591; import java.util.Scanner; /** * @author Albert Hambardzumyan */ public class Problem_591A { public static void main(String[] args) { Scanner in = new Scanner(System.in); int length = in.nextInt(); int speed1 = in.nextInt(); int speed2 = in.nextInt(); double time = (double) length / (speed1 + speed2); System.out.print(time * speed1); } }
gpl-3.0
alexei38/gshell
src/config.py
8810
# -*- coding: utf-8 -*- import os import uuid import gconf import shutil import base64 from Crypto import Random from AESCipher import AESCipher from ConfigParser import ConfigParser from ConfigParser import NoOptionError DEFAULTS = { 'allow_bold' : True, 'background_color' : '#000000', 'background_darkness' : 0.85, 'background_type' : 'transparent', 'background_image' : None, 'backspace_binding' : 'ascii-del', 'cursor_blink' : True, 'cursor_shape' : 'block', 'emulation' : 'xterm', 'term' : 'xterm', 'colorterm' : 'gnome-terminal', 'font' : 'Mono 10', 'font_host_tree' : 'Mono 8', 'foreground_color' : '#fff', 'scrollbar_position' : "right", 'scroll_background' : True, 'scroll_on_keystroke' : True, 'scroll_on_output' : True, 'scrollback_lines' : 1000, 'scrollback_infinite' : False, 'palette' : '#2e3436:#cc0000:#4e9a06:#c4a000:#3465a4:#75507b:#06989a:#d3d7cf:#555753:#ef2929:#8ae234:#fce94f:#729fcf:#ad7fa8:#34e2e2:#eeeeec', 'word_chars' : '-A-Za-z0-9,./?%&#:_', 'mouse_autohide' : True, 'use_system_font' : True, 'use_theme_colors' : False, 'encoding' : 'UTF-8', 'copy_on_selection' : False, 'alternate_screen_scroll': True, 'inactive_color_offset': 0.8, 'disable_real_transparency' : True, 'window_width' : 0, 'window_height' : 0, 'window_maximize' : True, 'local_keybinder': { ('key_zoom', 'zoom_in') : ['<Control>equal', '<Control>KP_Add'], ('key_zoom', 'zoom_out') : ['<Control>minus', '<Control>KP_Subtract'], ('key_zoom', 'zoom_orig') : ['<Control>KP_0', '<Control>0'], 'menu_open' : '<Shift><Control>O', 'key_close_term' : ['<Shift><Control>w', '<Control>d'], 'menu_copy' : '<Shift><Control>c', 'menu_paste' : '<Shift><Control>v', 'new_terminal' : ['<Shift><Control>t', '<Shift><Control>n'], 'key_next_tab' : '<Control>Page_Down', 'key_prev_tab' : '<Control>Page_Up', 'key_full_screen' : 'F11', 'menu_select_all' : '<Shift><Control>A', 'menu_search' : '<Shift><Control>F', 'key_broadcast' : '<Shift><Control>B', }, 'global_keybinder': { 'show_hide' : '<Control>F12', } } class Config(object): def __init__(self, *args, **kwds): super(Config, self).__init__(*args, **kwds) self.gconf = gconf.client_get_default() self.gconf_path = lambda x: ('/apps/gshell' + x) self.system_font = None self.hosts = [] self.work_dir = os.path.dirname(os.path.realpath(__file__)) self.get_icon = lambda icon: os.path.join(self.work_dir, 'icon', icon) self.conf_dir = os.path.expanduser('~/.gshell') self.host_file = os.path.join(self.conf_dir, 'hosts.ini') self.host_file_backup = os.path.join(self.conf_dir, 'hosts.bck') self.reload_hosts() self.broadcast_images = { 'blue' : self.get_icon('broadcast-blue.png'), 'red' : self.get_icon('broadcast-red.png'), 'green' : self.get_icon('broadcast-green.png'), 'yellow' : self.get_icon('broadcast-yellow.png'), } def __getitem__(self, key): value = DEFAULTS.get(key) func = None if isinstance(value, int): func = self.gconf.get_int if isinstance(value, bool): func = self.gconf.get_bool if isinstance(value, str): func = self.gconf.get_string if func: check = self.gconf.get(self.gconf_path('/general/' + key)) if check: value = func(self.gconf_path('/general/' + key)) return value def __setitem__(self, key, value): func = None if isinstance(value, int): func = self.gconf.set_int if isinstance(value, bool): func = self.gconf.set_bool if isinstance(value, str): func = self.gconf.set_string if func: func(self.gconf_path('/general/' + key), value) def reload_hosts(self): def get_section(parser, section, key, default=''): try: val = parser.get(section, key) if not val: return default return val except NoOptionError: return default self.hosts = [] if os.path.exists(self.host_file): parser = ConfigParser() parser.read(self.host_file) for section in parser.sections(): self.hosts.append({ 'uuid' : section, 'name' : get_section(parser, section, 'name'), 'host' : get_section(parser, section, 'host'), 'port' : get_section(parser, section, 'port', '22'), 'username' : get_section(parser, section, 'username'), 'password' : get_section(parser, section, 'password'), 'group' : get_section(parser, section, 'group'), 'description' : get_section(parser, section, 'description'), 'log' : get_section(parser, section, 'log'), 'ssh_options' : get_section(parser, section, 'ssh_options'), 'start_commands' : get_section(parser, section, 'start_commands'), 'key' : get_section(parser, section, 'key', base64.encodestring(Random.new().read(32)).strip()) }) def save_host(self, new_host): if not new_host['uuid']: new_host['uuid'] = str(uuid.uuid4()) if 'key' not in new_host: new_host['key'] = base64.encodestring(Random.new().read(32)).strip() if os.path.exists(self.host_file_backup): os.remove(self.host_file_backup) if os.path.exists(self.host_file): shutil.copy(self.host_file, self.host_file_backup) parser = ConfigParser() host_saved = False for host in self.hosts: if host['uuid'] == new_host['uuid']: host = new_host host_saved = True host['password'] = self.encrypt_password(host) self.add_host_section(parser, host) if not host_saved: new_host['password'] = self.encrypt_password(new_host) self.add_host_section(parser, new_host) if not os.path.exists(self.conf_dir): os.makedirs(self.conf_dir) fp = open(self.host_file, 'w') parser.write(fp) fp.close() self.reload_hosts() def remove_host(self, remove_host): if remove_host not in self.hosts: return if os.path.exists(self.host_file_backup): os.remove(self.host_file_backup) if os.path.exists(self.host_file): shutil.copy(self.host_file, self.host_file_backup) parser = ConfigParser() for host in self.hosts: if host == remove_host: continue self.add_host_section(parser, host) if not os.path.exists(self.conf_dir): os.makedirs(self.conf_dir) fp = open(self.host_file, 'w') parser.write(fp) fp.close() self.reload_hosts() def add_host_section(self, parser, host): if host['host']: if not host['name']: host['name'] = host['host'] parser.add_section(host['uuid']) for key in ['name', 'host', 'port', 'username', 'group', 'description', 'log', 'ssh_options', 'start_commands', 'key', 'password']: parser.set(host['uuid'], key, host[key]) def encrypt_password(self, host): cipher = AESCipher(base64.decodestring(host['key'])) return cipher.encrypt(host['password']) def decrypt_password(self, host): cipher = AESCipher(base64.decodestring(host['key'])) return cipher.decrypt(host['password']) def get_system_font(self): """Look up the system font""" if self.system_font is not None: return self.system_font else: value = self.gconf.get('/desktop/gnome/interface/monospace_font_name') if value: self.system_font = value.get_string() else: # FIX. if not key in gconf self.system_font = self['font'] return self.system_font
gpl-3.0
libre/webexploitscan
wes/data/rules/fullscan/10092019-MS-PHP-Antimalware-Scanner-260-malware_signature.php
2660
<?php /** * WES WebExploitScan Web GPLv4 http://github.com/libre/webexploitscan * * The PHP page that serves all page requests on WebExploitScan installation. * * The routines here dispatch control to the appropriate handler, which then * prints the appropriate page. * * All WebExploitScan code is released under the GNU General Public License. * See COPYRIGHT.txt and LICENSE.txt. */ $NAME='Php-MS-PHP-Antimalware-Scanner malware_signature- ID 260'; $TAGCLEAR='<?phperror_reporting(d+);echo"[^"]*";if($_(GET|POST|COOKIE|SERVER|REQUEST)["[^"]*"]=="[^"]*"){$w{1,40}=file_get_contents(\'[^\']*\');$w{1,40}=fopen("[^"]*","[^"]*");fwrite($w{1,40},$w{1,40});fclose($w{1,40});$w{1,40}=fopen("[^"]*","[^"]*");fwrite($w{1,40},$w{1,40});fclose($w{1,40});echo"[^"]*";}?>'; $TAGBASE64='PD9waHBlcnJvcl9yZXBvcnRpbmcoZCspO2VjaG8iW14iXSoiO2lmKCRfKEdFVHxQT1NUfENPT0tJRXxTRVJWRVJ8UkVRVUVTVClbIlteIl0qIl09PSJbXiJdKiIpeyR3ezEsNDB9PWZpbGVfZ2V0X2NvbnRlbnRzKFwnW15cJ10qXCcpOyR3ezEsNDB9PWZvcGVuKCJbXiJdKiIsIlteIl0qIik7ZndyaXRlKCR3ezEsNDB9LCR3ezEsNDB9KTtmY2xvc2UoJHd7MSw0MH0pOyR3ezEsNDB9PWZvcGVuKCJbXiJdKiIsIlteIl0qIik7ZndyaXRlKCR3ezEsNDB9LCR3ezEsNDB9KTtmY2xvc2UoJHd7MSw0MH0pO2VjaG8iW14iXSoiO30/Pg=='; $TAGHEX='3c3f7068706572726f725f7265706f7274696e6728642b293b6563686f225b5e225d2a223b696628245f284745547c504f53547c434f4f4b49457c5345525645527c52455155455354295b225b5e225d2a225d3d3d225b5e225d2a22297b24777b312c34307d3d66696c655f6765745f636f6e74656e7473285c275b5e5c275d2a5c27293b24777b312c34307d3d666f70656e28225b5e225d2a222c225b5e225d2a22293b6677726974652824777b312c34307d2c24777b312c34307d293b66636c6f73652824777b312c34307d293b24777b312c34307d3d666f70656e28225b5e225d2a222c225b5e225d2a22293b6677726974652824777b312c34307d2c24777b312c34307d293b66636c6f73652824777b312c34307d293b6563686f225b5e225d2a223b7d3f3e'; $TAGHEXPHP=''; $TAGURI='%3C%3Fphperror_reporting%28d%2B%29%3Becho%22%5B%5E%22%5D%2A%22%3Bif%28%24_%28GET%7CPOST%7CCOOKIE%7CSERVER%7CREQUEST%29%5B%22%5B%5E%22%5D%2A%22%5D%3D%3D%22%5B%5E%22%5D%2A%22%29%7B%24w%7B1%2C40%7D%3Dfile_get_contents%28%5C%27%5B%5E%5C%27%5D%2A%5C%27%29%3B%24w%7B1%2C40%7D%3Dfopen%28%22%5B%5E%22%5D%2A%22%2C%22%5B%5E%22%5D%2A%22%29%3Bfwrite%28%24w%7B1%2C40%7D%2C%24w%7B1%2C40%7D%29%3Bfclose%28%24w%7B1%2C40%7D%29%3B%24w%7B1%2C40%7D%3Dfopen%28%22%5B%5E%22%5D%2A%22%2C%22%5B%5E%22%5D%2A%22%29%3Bfwrite%28%24w%7B1%2C40%7D%2C%24w%7B1%2C40%7D%29%3Bfclose%28%24w%7B1%2C40%7D%29%3Becho%22%5B%5E%22%5D%2A%22%3B%7D%3F%3E'; $TAGCLEAR2=''; $TAGBASE642=''; $TAGHEX2=''; $TAGHEXPHP2=''; $TAGURI2=''; $DATEADD='10/09/2019'; $LINK='Webexploitscan.org ;Php-MS-PHP-Antimalware-Scanner malware_signature- ID 260 '; $ACTIVED='1'; $VSTATR='malware_signature';
gpl-3.0
jd-lang/betaexpansion
betaexpansion/net/minecraft/src/TileEntityRendererTable.java
1567
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) braces deadcode package net.minecraft.src; import net.minecraft.client.Minecraft; import org.lwjgl.opengl.GL11; // Referenced classes of package net.minecraft.src: // TileEntitySpecialRenderer, Block, TileEntityPiston, Tessellator, // RenderHelper, RenderBlocks, BlockPistonBase, BlockPistonExtension, // World, TileEntity public class TileEntityRendererTable extends TileEntitySpecialRenderer { public TileEntityRendererTable() { mc = ModLoader.getMinecraftInstance(); } public void renderTileEntityAt(TileEntity tileentity, double d, double d1, double d2, float f) { Tessellator tessellator = Tessellator.instance; int l = ((TileEntityTable)tileentity).worldObj.getBlockMetadata(((TileEntityTable)tileentity).xCoord, ((TileEntityTable)tileentity).yCoord, ((TileEntityTable)tileentity).zCoord); for(int i = 0; i < 9; i++) { ItemStack itemstack = ((TileEntityTable)tileentity).getStackInSlot(i); if(itemstack != null && itemstack.itemID != 0) { GL11.glPushMatrix(); GL11.glTranslatef((i%3)/3F, 0F, (i/3)/3F); mc.entityRenderer.itemRenderer.doRenderItem_noEntity(itemstack, d+(1/6D), d1+(l<8?1D:0.75D)+0.125D, d2+(1/6D), 1.0F); GL11.glPopMatrix(); } } } private Minecraft mc; }
gpl-3.0
CeusMedia/Common
src/Net/XMPP/XMPPHP/Roster.php
4600
<?php /** * XMPPHP: The PHP XMPP Library * Copyright (C) 2008 Nathanael C. Fritz * This file is part of SleekXMPP. * * XMPPHP is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * XMPPHP 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 XMPPHP; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * @category Library * @package CeusMedia_Common_Net_XMPP_XMPPHP * @author Nathanael C. Fritz <JID: [email protected]> * @author Stephan Wentz <JID: [email protected]> * @author Michael Garvin <JID: [email protected]> * @copyright 2008 Nathanael C. Fritz */ /** * XMPPHP Roster Object * * @category Library * @package CeusMedia_Common_Net_XMPP_XMPPHP * @author Nathanael C. Fritz <JID: [email protected]> * @author Stephan Wentz <JID: [email protected]> * @author Michael Garvin <JID: [email protected]> * @copyright 2008 Nathanael C. Fritz */ class Net_XMPP_XMPPHP_Roster { /** * Roster array, handles contacts and presence. Indexed by jid. * Contains array with potentially two indexes 'contact' and 'presence' * @var array */ public $roster_array = array(); /** * Constructor * */ public function __construct($roster_array = array()) { if ($this->verifyRoster($roster_array)) { $this->roster_array = $roster_array; //Allow for prepopulation with existing roster } else { $this->roster_array = array(); } } /** * * Check that a given roster array is of a valid structure (empty is still valid) * * @param array $roster_array */ protected function verifyRoster($roster_array) { #TODO once we know *what* a valid roster array looks like return True; } /** * * Add given contact to roster * * @param string $jid * @param string $subscription * @param string $name * @param array $groups */ public function addContact($jid, $subscription, $name='', $groups=array()) { $contact = array('jid' => $jid, 'subscription' => $subscription, 'name' => $name, 'groups' => $groups); if ($this->isContact($jid)) { $this->roster_array[$jid]['contact'] = $contact; } else { $this->roster_array[$jid] = array('contact' => $contact); } } /** * * Retrieve contact via jid * * @param string $jid */ public function getContact($jid) { if ($this->isContact($jid)) { return $this->roster_array[$jid]['contact']; } } /** * * Discover if a contact exists in the roster via jid * * @param string $jid */ public function isContact($jid) { return (array_key_exists($jid, $this->roster_array)); } /** * * Set presence * * @param string $presence * @param integer $priority * @param string $show * @param string $status */ public function setPresence($presence, $priority, $show, $status) { list($jid, $resource) = explode("/", $presence); if ($show != 'unavailable') { if (!$this->isContact($jid)) { $this->addContact($jid, 'not-in-roster'); } $resource = $resource ? $resource : ''; $this->roster_array[$jid]['presence'][$resource] = array('priority' => $priority, 'show' => $show, 'status' => $status); } else { //Nuke unavailable resources to save memory unset($this->roster_array[$jid]['resource'][$resource]); } } /* * * Return best presence for jid * * @param string $jid */ public function getPresence($jid) { $split = explode("/", $jid); $jid = $split[0]; if($this->isContact($jid)) { $current = array('resource' => '', 'active' => '', 'priority' => -129, 'show' => '', 'status' => ''); //Priorities can only be -128 = 127 foreach($this->roster_array[$jid]['presence'] as $resource => $presence) { //Highest available priority or just highest priority if ($presence['priority'] > $current['priority'] and (($presence['show'] == "chat" or $presence['show'] == "available") or ($current['show'] != "chat" or $current['show'] != "available"))) { $current = $presence; $current['resource'] = $resource; } } return $current; } } /** * * Get roster * */ public function getRoster() { return $this->roster_array; } }
gpl-3.0
hunger/cleanroom
cleanroom/exceptions.py
1561
# -*- coding: utf-8 -*- """Exceptions used in cleanroom. @author: Tobias Hunger <[email protected]> """ from .location import Location import typing class CleanRoomError(Exception): """Base class for all cleanroom Exceptions.""" def __init__( self, *args: typing.Any, location: typing.Optional[Location] = None, original_exception: typing.Optional[Exception] = None, ) -> None: """Constructor.""" super().__init__(*args) self.location = location self.original_exception = original_exception def set_location(self, location: Location): self.location = location def __str__(self) -> str: """Stringify exception.""" prefix = f"Error in {self.location}" if self.location else "Error" postfix = "" if self.original_exception is not None: if isinstance(self.original_exception, AssertionError): postfix = "\n Trigger: AssertionError." else: postfix = "\n Trigger: " + str(self.original_exception) return f"{prefix}: {super().__str__()}{postfix}" class PreflightError(CleanRoomError): """Error raised in the Preflight Phase.""" pass class ParseError(CleanRoomError): """Error raised while parsing system descriptions.""" pass class GenerateError(CleanRoomError): """Error raised during Generation phase.""" pass class SystemNotFoundError(CleanRoomError): """Error raised when a system could not be found.""" pass
gpl-3.0
concko/PortAIO
Libraries/ValvraveSharp/Evade/EvadeSpellData.cs
5178
namespace Valvrave_Sharp.Evade { #region using LeagueSharp; #endregion using EloBuddy; using EloBuddy.SDK.Menu.Values; using EloBuddy.SDK.Menu; public enum SpellValidTargets { AllyMinions, EnemyMinions, AllyWards, EnemyWards, AllyChampions, EnemyChampions } internal class EvadeSpellData { #region Fields public string CheckBuffName = ""; public string CheckSpellName = ""; public int Delay; public bool ExtraDelay; public bool FixedRange; public bool IsBlink; public bool IsDash; public bool IsInvulnerability; public bool IsMovementSpeedBuff; public bool IsShield; public bool IsSpellShield; public MoveSpeedAmount MoveSpeedTotalAmount; public string Name; public float Range; public bool SelfCast; public SpellSlot Slot; public int Speed; public bool UnderTower; public SpellValidTargets[] ValidTargets; private int dangerLevel; public static bool getCheckBoxItem(string item) { return Config.evadeMenu[item].Cast<CheckBox>().CurrentValue; } public static int getSliderItem(string item) { return Config.evadeMenu[item].Cast<Slider>().CurrentValue; } public static bool getKeyBindItem(string item) { return Config.evadeMenu[item].Cast<KeyBind>().CurrentValue; } public static int getBoxItem(string item) { return Config.evadeMenu[item].Cast<ComboBox>().CurrentValue; } #endregion #region Delegates public delegate float MoveSpeedAmount(); #endregion #region Public Properties public int DangerLevel { get { if (Config.evadeMenu[this.Name + "DangerLevel"] == null) { return this.dangerLevel; } return getSliderItem(this.Name + "DangerLevel"); } set { this.dangerLevel = value; } } public bool Enable => getCheckBoxItem(this.Name + "Enabled"); public bool IsReady => (this.CheckSpellName == "" || Program.Player.Spellbook.GetSpell(this.Slot).SData.Name.ToLower() == this.CheckSpellName) && Program.Player.Spellbook.CanUseSpell(this.Slot) == SpellState.Ready; public bool IsTargetted => this.ValidTargets != null; #endregion } internal class DashData : EvadeSpellData { #region Constructors and Destructors public DashData( string name, SpellSlot slot, float range, bool fixedRange, int delay, int speed, int dangerLevel) { this.Name = name; this.Range = range; this.Slot = slot; this.FixedRange = fixedRange; this.Delay = delay; this.Speed = speed; this.DangerLevel = dangerLevel; this.IsDash = true; } #endregion } internal class BlinkData : EvadeSpellData { #region Constructors and Destructors public BlinkData(string name, SpellSlot slot, float range, int delay, int dangerLevel) { this.Name = name; this.Range = range; this.Slot = slot; this.Delay = delay; this.DangerLevel = dangerLevel; this.IsBlink = true; } #endregion } internal class InvulnerabilityData : EvadeSpellData { #region Constructors and Destructors public InvulnerabilityData(string name, SpellSlot slot, int delay, int dangerLevel) { this.Name = name; this.Slot = slot; this.Delay = delay; this.DangerLevel = dangerLevel; this.IsInvulnerability = true; } #endregion } internal class ShieldData : EvadeSpellData { #region Constructors and Destructors public ShieldData(string name, SpellSlot slot, int delay, int dangerLevel, bool isSpellShield = false) { this.Name = name; this.Slot = slot; this.Delay = delay; this.DangerLevel = dangerLevel; this.IsSpellShield = isSpellShield; this.IsShield = !this.IsSpellShield; } #endregion } internal class MoveBuffData : EvadeSpellData { #region Constructors and Destructors public MoveBuffData(string name, SpellSlot slot, int delay, int dangerLevel, MoveSpeedAmount amount) { this.Name = name; this.Slot = slot; this.Delay = delay; this.DangerLevel = dangerLevel; this.MoveSpeedTotalAmount = amount; this.IsMovementSpeedBuff = true; } #endregion } }
gpl-3.0
mundane799699/ExamAssistant
app/src/main/java/com/mundane/examassistant/db/MyOpenHelper.java
556
package com.mundane.examassistant.db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import com.mundane.examassistant.db.entity.DaoMaster; /** * @author : mundane * @time : 2017/4/14 11:43 * @description : * @file : MyOpenHelper.java */ public class MyOpenHelper extends DaoMaster.OpenHelper { public MyOpenHelper(Context context, String name) { super(context, name); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { super.onUpgrade(db, oldVersion, newVersion); } }
gpl-3.0
Alberto-Beralix/Beralix
i386-squashfs-root/usr/share/system-config-printer/troubleshoot/Shrug.py
3447
#!/usr/bin/python ## Printing troubleshooter ## Copyright (C) 2008, 2009, 2010 Red Hat, Inc. ## Author: Tim Waugh <[email protected]> ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. from base import * class Shrug(Question): def __init__ (self, troubleshooter): Question.__init__ (self, troubleshooter, "Shrug") page = self.initial_vbox (_("Sorry!"), _("There is no obvious solution to this " "problem. Your answers have been " "collected together with " "other useful information. If you " "would like to report a bug, please " "include this information.")) expander = gtk.Expander (_("Diagnostic Output (Advanced)")) expander.set_expanded (False) sw = gtk.ScrolledWindow () expander.add (sw) textview = gtk.TextView () textview.set_editable (False) sw.add (textview) page.pack_start (expander) self.buffer = textview.get_buffer () box = gtk.HButtonBox () box.set_border_width (0) box.set_spacing (3) box.set_layout (gtk.BUTTONBOX_END) page.pack_start (box, False, False, 0) self.save = gtk.Button (stock=gtk.STOCK_SAVE) box.pack_start (self.save, False, False, 0) troubleshooter.new_page (page, self) def display (self): self.buffer.set_text (self.troubleshooter.answers_as_text ()) return True def connect_signals (self, handler): self.save_sigid = self.save.connect ('clicked', self.on_save_clicked) def disconnect_signals (self): self.save.disconnect (self.save_sigid) def on_save_clicked (self, button): dialog = gtk.FileChooserDialog (parent=self.troubleshooter.get_window(), action=gtk.FILE_CHOOSER_ACTION_SAVE, buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK)) dialog.set_do_overwrite_confirmation (True) dialog.set_current_name ("troubleshoot.txt") dialog.set_default_response (gtk.RESPONSE_OK) dialog.set_local_only (True) response = dialog.run () dialog.hide () if response != gtk.RESPONSE_OK: return f = file (dialog.get_filename (), "w") f.write (self.buffer.get_text (self.buffer.get_start_iter (), self.buffer.get_end_iter ())) del f
gpl-3.0
cjparsons74/kupfer
kupfer/plugin_support.py
5558
import gobject try: import keyring except ImportError: keyring = None from kupfer import pretty from kupfer import config from kupfer.core import settings __all__ = [ "UserNamePassword", "PluginSettings", "check_dbus_connection", ] def _is_core_setting(key): return key.startswith("kupfer_") class PluginSettings (gobject.GObject, pretty.OutputMixin): """Allows plugins to have preferences by assigning an instance of this class to the plugin's __kupfer_settings__ attribute. Setting values are accessed by the getitem operator [] with the setting's 'key' attribute Signals: plugin-setting-changed: key, value """ __gtype_name__ = "PluginSettings" def __init__(self, *setdescs): """Create a settings collection by passing in dictionaries as arguments, where each dictionary must have the following keys: key type value (default value) label (localized label) the @key may be any string except strings starting with 'kupfer_', which are reserved """ gobject.GObject.__init__(self) self.setting_descriptions = {} self.setting_key_order = [] req_keys = set(("key", "value", "type", "label")) for desc in setdescs: if not req_keys.issubset(desc.keys()): missing = req_keys.difference(desc.keys()) raise KeyError("Plugin setting missing keys: %s" % missing) self.setting_descriptions[desc["key"]] = dict(desc) self.setting_key_order.append(desc["key"]) def __iter__(self): return iter(self.setting_key_order) def initialize(self, plugin_name): """Init by reading from global settings and setting up callbacks""" setctl = settings.GetSettingsController() for key in self: value_type = self.setting_descriptions[key]["type"] value = setctl.get_plugin_config(plugin_name, key, value_type) if value is not None: self[key] = value elif _is_core_setting(key): default = self.setting_descriptions[key]["value"] setctl.set_plugin_config(plugin_name, key, default, value_type) setctl.connect("value-changed", self._value_changed, plugin_name) def __getitem__(self, key): return self.setting_descriptions[key]["value"] def __setitem__(self, key, value): value_type = self.setting_descriptions[key]["type"] self.setting_descriptions[key]["value"] = value_type(value) if not _is_core_setting(key): self.emit("plugin-setting-changed", key, value) def _value_changed(self, setctl, section, key, value, plugin_name): """Preferences changed, update object""" if key in self and plugin_name in section: self[key] = value def get_value_type(self, key): """Return type of setting @key""" return self.setting_descriptions[key]["type"] def get_label(self, key): """Return label for setting @key""" return self.setting_descriptions[key]["label"] def get_alternatives(self, key): """Return alternatives for setting @key (if any)""" return self.setting_descriptions[key].get("alternatives") def get_tooltip(self, key): """Return tooltip string for setting @key (if any)""" return self.setting_descriptions[key].get("tooltip") def connect_settings_changed_cb(self, callback, *args): self.connect("plugin-setting-changed", callback, *args) # Signature: Key, Value gobject.signal_new("plugin-setting-changed", PluginSettings, gobject.SIGNAL_RUN_LAST, gobject.TYPE_BOOLEAN, (gobject.TYPE_STRING, gobject.TYPE_PYOBJECT)) # Plugin convenience functions for dependencies _has_dbus_connection = None def check_dbus_connection(): """ Check if a connection to the D-Bus daemon is available, else raise ImportError with an explanatory error message. For plugins that can not be used without contact with D-Bus; if this check is used, the plugin may use D-Bus and assume it is available in the Plugin's code. """ global _has_dbus_connection if _has_dbus_connection is None: import dbus try: dbus.Bus() _has_dbus_connection = True except dbus.DBusException, err: _has_dbus_connection = False if not _has_dbus_connection: raise ImportError(_("No D-Bus connection to desktop session")) def check_keyring_support(): """ Check if the UserNamePassword class can be used, else raise ImportError with an explanatory error message. """ import keyring class UserNamePassword (settings.ExtendedSetting): ''' Configuration type for storing username/password values. Username is stored in Kupfer config, password in keyring ''' def __init__(self, obj=None): settings.ExtendedSetting.__init__(self) self._configure_keyring() self.username = None self.password = None if obj: self.username = obj.username self.password = obj.password def __repr__(self): return '<UserNamePassword "%s", %s>' % (self.username, bool(self.password)) @classmethod def _configure_keyring(cls): # Configure the fallback keyring's configuration file if used import keyring.backend kr = keyring.get_keyring() if hasattr(kr, "crypted_password"): keyring.set_keyring(keyring.backend.UncryptedFileKeyring()) kr = keyring.get_keyring() if hasattr(kr, "file_path"): kr.file_path = config.save_config_file("keyring.cfg") def load(self, plugin_id, key, username): self.password = keyring.get_password(plugin_id, username) self.username = username def save(self, plugin_id, key): ''' save @user_password - store password in keyring and return username to save in standard configuration file ''' keyring.set_password(plugin_id, self.username, self.password) return self.username if not keyring: class UserNamePassword (object): pass
gpl-3.0
wakdev/slash-cms
core/plugins/kcfinder/config.php
2458
<?php /** This file is part of KCFinder project * * @desc Base configuration file * @package KCFinder * @version 2.51 * @author Pavel Tzonkov <[email protected]> * @copyright 2010, 2011 KCFinder Project * @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2 * @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2 * @link http://kcfinder.sunhater.com */ // IMPORTANT!!! Do not remove uncommented settings in this file even if // you are using session configuration. // See http://kcfinder.sunhater.com/install for setting descriptions $_CONFIG = array( 'disabled' => true, 'denyZipDownload' => false, 'denyUpdateCheck' => false, 'denyExtensionRename' => false, 'theme' => "oxygen", 'uploadURL' => "/medias", 'uploadDir' => "../../../medias", 'dirPerms' => 0755, 'filePerms' => 0644, 'access' => array( 'files' => array( 'upload' => true, 'delete' => true, 'copy' => true, 'move' => true, 'rename' => true ), 'dirs' => array( 'create' => true, 'delete' => true, 'rename' => true ) ), 'deniedExts' => "exe com msi bat php phps phtml php3 php4 cgi pl", 'types' => array( // CKEditor & FCKEditor types 'files' => "", 'flash' => "swf", 'images' => "*img", // TinyMCE types 'file' => "", 'media' => "swf flv avi mpg mpeg qt mov wmv asf rm", 'image' => "*img", ), 'filenameChangeChars' => array(/* ' ' => "_", ':' => "." */), 'dirnameChangeChars' => array(/* ' ' => "_", ':' => "." */), 'mime_magic' => "", 'maxImageWidth' => 0, 'maxImageHeight' => 0, 'thumbWidth' => 100, 'thumbHeight' => 100, 'thumbsDir' => ".thumbs", 'jpegQuality' => 100, 'cookieDomain' => "", 'cookiePath' => "", 'cookiePrefix' => 'KCFINDER_', // THE FOLLOWING SETTINGS CANNOT BE OVERRIDED WITH SESSION CONFIGURATION '_check4htaccess' => true, //'_tinyMCEPath' => "/tiny_mce", //'_sessionVar' => &$_SESSION['KCFINDER'], '_sessionVar' => &$_SESSION['user_finder'], //'_sessionLifetime' => 30, //'_sessionDir' => "/full/directory/path", '_sessionDomain' => $_SERVER['HTTP_HOST'], '_sessionPath' => "/medias", ); ?>
gpl-3.0
lem9/weblate
weblate/accounts/tests/test_utils.py
1617
# -*- coding: utf-8 -*- # # Copyright © 2012 - 2017 Michal Čihař <[email protected]> # # This file is part of Weblate <https://weblate.org/> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. # """ Tests for various helper utilities. """ from __future__ import unicode_literals from django.test import TestCase from weblate.accounts.pipeline import slugify_username class PipelineTest(TestCase): def test_slugify(self): self.assertEqual( slugify_username('zkouska'), 'zkouska' ) self.assertEqual( slugify_username('Zkouska'), 'Zkouska' ) self.assertEqual( slugify_username('zkouška'), 'zkouska' ) self.assertEqual( slugify_username(' zkouska '), 'zkouska' ) self.assertEqual( slugify_username('ahoj - ahoj'), 'ahoj-ahoj' ) self.assertEqual( slugify_username('..test'), 'test' )
gpl-3.0
EPSZ-DAW2/daw2-2016-actividades-y-eventos
basic/controllers/EtiquetasController.php
8112
<?php namespace app\controllers; use Yii; use app\models\Actividades; use app\models\Etiquetas; use app\models\EtiquetasSearch; use app\models\ActividadEtiquetas; use app\models\ActividadetiquetasSearch; use app\models\Usuarios; use app\models\UsuarioAvisos; use yii\web\Controller; use yii\web\NotFoundHttpException; use yii\filters\VerbFilter; /** * EtiquetasController implements the CRUD actions for Etiquetas model. */ class EtiquetasController extends Controller { /** * @inheritdoc */ public function behaviors() { return [ 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'delete' => ['POST'], ], ], ]; } /** * Lists all Etiquetas models. * @return mixed */ public function actionIndex() { if( Yii::$app->user->isGuest ){//redirigir a busqueda si el usuario no ha realizado login $this->redirect(['busqueda']); } $searchModel = new EtiquetasSearch(); $dataProvider = $searchModel->search(Yii::$app->request->queryParams); $msg=""; if(isset($_SESSION['msg'])){ $msg=$_SESSION['msg']; unset($_SESSION['msg']); } $rol='A'; if(Yii::$app->user->identity){ $u=Usuarios::findOne(Yii::$app->user->identity->id); if($u){ $rol=$u->rol; } } //llamamos a la vista index con los datos obtenidos return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, 'msg'=>$msg, 'rol'=>$rol, ]); } public function actionBusqueda() { $datos = null; $post=Yii::$app->request->post(); //se realiza las busquedas si recibimos datos por POST if (isset($post['Etiquetas']['id'])){ $searchModel = new ActividadEtiquetasSearch(); //se rellena la estructura de datos con los datos de las etiquetas y sus actividades relacionadas $dataProvider = $searchModel->search(['ActividadEtiquetasSearch'=>['etiqueta_id'=>$post['Etiquetas']['id']]]); $relaciones=$dataProvider->getModels(); $datos=array(); foreach($relaciones as $r){ //se recorren todos los datos obteniendo las id de las actividades $model = Actividades::findOne($r->actividad_id); $datos[$model->id]=$model; } } //se envian a la vista buscar el array datos que contiene las ids de las etiquetas y las actividades return $this->render('buscar', ['datos'=>$datos, ]); } /** * Creates a new Etiquetas model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { if( Yii::$app->user->isGuest ){//redirigir a login si no ha hecho login $this->redirect(Yii::$app->request->baseURL."\site\login"); } $model = new Etiquetas(); //se intenta cargar los datos de post y guardarlos en el modelo de datos if ($model->load(Yii::$app->request->post()) && $model->save()) { //se crea un aviso en el sistema de avisos con la fecha, la id de la etiqueta y la id del //usuario que la ha creado $aviso=new UsuarioAvisos(); $aviso->fecha=date("Y/m/d"); $aviso->clase_aviso_id='N'; $aviso->texto="Nueva etiqueta creada ".$model->id." ".$model->nombre; $aviso->destino_usuario_id=0; $aviso->origen_usuario_id=0; if(Yii::$app->user->identity){ $u=Usuarios::findOne(Yii::$app->user->identity->id); if($u){ $aviso->origen_usuario_id=$u->id; } } $aviso->save();//confirmar el guardado del aiso y redirigir a index return $this->redirect(['index']); } else {//si aun n ha recibido datos por post redirigir a a la vista de creacion return $this->render('create', [ 'model' => $model, ]); } } /** * Updates an existing Etiquetas model. * If update is successful, the browser will be redirected to the 'view' page. * @param string $id * @return mixed */ public function actionUpdate($id) { if( Yii::$app->user->isGuest ){//invitados a la pagina de login $this->redirect(Yii::$app->request->baseURL."\site\login"); } if(Yii::$app->user->identity){ $u=Usuarios::findOne(Yii::$app->user->identity->id); if($u){//si el usuario no tiene permisos de administrador redirigir a login if($u->rol!='A') $this->redirect(Yii::$app->request->baseURL."\site\login"); } } $model = $this->findModel($id); if ($model->load(Yii::$app->request->post()) && $model->save()) { //redirigir a index si recibe datos por post return $this->redirect(['index']); } else {//al no recibirlos mostrar todas las etiquetas $etiquetas = Etiquetas::find()->all(); $todas = array(); foreach($etiquetas as $e){ if($e->id!=$id) $todas[$e->id]=$e->nombre; } //llamar a la vista update on el array de las etiquetas return $this->render('update', [ 'model' => $model, 'todas' => $todas ]); } } //esta accion unifica des etiquetas //elimina una segunda etiqueta y mueve las relaciones que tiene a la //primera etiqueta public function actionUnifica($id) { if( Yii::$app->user->isGuest ){ $this->redirect(Yii::$app->request->baseURL."\site\login"); } if(Yii::$app->user->identity){ $u=Usuarios::findOne(Yii::$app->user->identity->id); if($u){ if($u->rol!='A') $this->redirect(Yii::$app->request->baseURL."\site\login"); } } //se encuentran todas las relaciones de etiquetas y actividades y todas las etiquetas $searchModel = new EtiquetasSearch(); $dataProvider = $searchModel->search([]); $relaciones=ActividadEtiquetas::find()->all(); foreach($relaciones as $relacion){//cambiar la relacion de la etiqueta unificada if($relacion->etiqueta_id==Yii::$app->request->queryParams['iduni']){ $relacion->etiqueta_id=Yii::$app->request->queryParams['id']; $relacion->save();//confirmar los cambios } } //eliminar la etiqueta unificada despues de cambiar su relacion $this->findModel(Yii::$app->request->queryParams['iduni'])->delete(); $msg="etiquetas unificadas"; return $this->redirect(['index']); } /** * Deletes an existing Etiquetas model. * If deletion is successful, the browser will be redirected to the 'index' page. * @param string $id * @return mixed */ public function actionDelete($id) { if( Yii::$app->user->isGuest ){ $this->redirect(Yii::$app->request->baseURL."\site\login"); } if(Yii::$app->user->identity){ $u=Usuarios::findOne(Yii::$app->user->identity->id); if($u){//solo pueden eliminar etiquetas los administradores if($u->rol!='A') $this->redirect(Yii::$app->request->baseURL."\site\login"); } } $todos=ActividadEtiquetas::find()->all();//se almacenan todas las etiquetas relacionadas con //una actividad $sepuede=true; foreach($todos as $c){ if($c->etiqueta_id==$id){ //si encuentra una etiqueta en todos, es que esta relacionada //no s epuede eliminar al estar relacionada $sepuede=false; } } if($sepuede){//se procede al borrado si no ha encontrado coincidencias $this->findModel($id)->delete(); return $this->redirect(['index']); }else{ $_SESSION['msg']="No se puede eliminar, la etiqueta tiene actividades relacionadas"; return $this->redirect(['index']); } } /** * Finds the Etiquetas model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param string $id * @return Etiquetas the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = Etiquetas::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } } }
gpl-3.0
maslick/klassy
src/main/java/com/maslick/ai/klassy/classifier/AbstractClassifier.java
3066
package com.maslick.ai.klassy.classifier; import com.maslick.ai.klassy.io.IFileLoader; import com.maslick.ai.klassy.io.IModelLoader; import com.maslick.ai.klassy.io.ModelLoader; import weka.classifiers.Classifier; import weka.core.Attribute; import weka.core.Instance; import weka.core.Instances; import java.io.IOException; import java.util.ArrayList; import static com.maslick.ai.klassy.classifier.ClassifierType.CLASSIFICATION; import static com.maslick.ai.klassy.classifier.Verbosity.DEBUG; import static com.maslick.ai.klassy.classifier.Verbosity.RUNTIME; public abstract class AbstractClassifier<T> implements IClassifier<T> { private IFileLoader fileLoader; public String MODEL = "model.model"; public Classifier classifier; protected int classIndex = -1; protected String relation = "Test relation"; protected ArrayList<Attribute> attributes; protected ClassifierType classifierType; public Verbosity verbosity = RUNTIME; private long timeA = 0; private long timeB = 0; public AbstractClassifier(IFileLoader fileLoader) { this.fileLoader = fileLoader; } public void loadClassifierModel() { try { IModelLoader modelLoader = new ModelLoader(fileLoader); classifier = modelLoader.getClassifierFromFile(MODEL); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } private Instances createInstancesPlaceholder() { if (attributes == null) attributes = createAttributeList(); Instances instances = new Instances(relation, attributes, 1); instances.setClassIndex(classIndex); return instances; } public final String classify(T data) { // 1. load model if (classifier == null) loadClassifierModel(); // 2. create attribute list // 3. create a placeholder with instances Instances instancesPlaceholder = createInstancesPlaceholder(); // 4. calculate features if (verbosity == DEBUG) timeA = System.currentTimeMillis(); Instance features = calculateFeatures(data); if (verbosity == DEBUG) { timeB = System.currentTimeMillis(); System.out.println("Time to calc features (" + MODEL + "): " + (timeB - timeA) + " ms"); } // 5. add features to the placeholder instancesPlaceholder.add(features); // 6. classify String clazz = null; try { Instance instance = instancesPlaceholder.instance(0); Double predictedClass = classifier.classifyInstance(instance); if (classifierType == CLASSIFICATION) clazz = instancesPlaceholder.classAttribute().value((predictedClass.intValue())); else if (classifierType == ClassifierType.REGRESSION) clazz = predictedClass.toString(); } catch (Exception e) { System.out.println("Problem found while classifying"); e.printStackTrace(); } return clazz; } }
gpl-3.0
GordonDiggs/relax
lib/client/stores/menus.js
1292
import {ClientStore} from 'relax-framework'; import MenusCollection from '../collections/menus'; import menuActions from '../actions/menu'; import $ from 'jquery'; import Q from 'q'; class MenusStore extends ClientStore { constructor () { super(); } init () { if (this.isClient()) { this.listenTo(menuActions, 'add', this.add); this.listenTo(menuActions, 'remove', this.remove); this.listenTo(menuActions, 'validateSlug', this.validateSlug); this.listenTo(menuActions, 'update', this.update); } } count (_deferred) { var deferred = _deferred || Q.defer(); $ .get('/api/menu/count') .done((response) => { deferred.resolve(response.count); }) .fail((error) => { deferred.reject(error); }); return deferred.promise; } createCollection () { return new MenusCollection(); } validateSlug (slug, deferred) { return Q() .then(() => { $ .get('/api/menu/slug/'+slug) .done((response) => { deferred.resolve(response.count > 0); }) .fail((error) => { deferred.reject(error); }); }); } findBySlug (slug) { return this.findOne({slug}); } } export default new MenusStore();
gpl-3.0
jogacommuri/ReactShoppingCart
models/books.js
260
"use strict" var mongoose = require('mongoose'); var Schema = mongoose.Schema; var booksSchema = new Schema({ title:String, description: String, images: String, price: Number }); var Books = mongoose.model('Books',booksSchema); module.exports = Books;
gpl-3.0
IntellectualCrafters/PlotSquared
Core/src/main/java/com/plotsquared/core/PlotSquared.java
65931
/* * _____ _ _ _____ _ * | __ \| | | | / ____| | | * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| * | | * |_| * PlotSquared plot management system for Minecraft * Copyright (C) 2021 IntellectualSites * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.plotsquared.core; import com.plotsquared.core.configuration.ConfigurationSection; import com.plotsquared.core.configuration.ConfigurationUtil; import com.plotsquared.core.configuration.MemorySection; import com.plotsquared.core.configuration.Settings; import com.plotsquared.core.configuration.Storage; import com.plotsquared.core.configuration.caption.CaptionMap; import com.plotsquared.core.configuration.caption.DummyCaptionMap; import com.plotsquared.core.configuration.caption.TranslatableCaption; import com.plotsquared.core.configuration.caption.load.CaptionLoader; import com.plotsquared.core.configuration.caption.load.DefaultCaptionProvider; import com.plotsquared.core.configuration.file.YamlConfiguration; import com.plotsquared.core.configuration.serialization.ConfigurationSerialization; import com.plotsquared.core.database.DBFunc; import com.plotsquared.core.database.Database; import com.plotsquared.core.database.MySQL; import com.plotsquared.core.database.SQLManager; import com.plotsquared.core.database.SQLite; import com.plotsquared.core.generator.GeneratorWrapper; import com.plotsquared.core.generator.HybridPlotWorld; import com.plotsquared.core.generator.HybridUtils; import com.plotsquared.core.generator.IndependentPlotGenerator; import com.plotsquared.core.inject.factory.HybridPlotWorldFactory; import com.plotsquared.core.listener.PlotListener; import com.plotsquared.core.location.Location; import com.plotsquared.core.player.PlayerMetaDataKeys; import com.plotsquared.core.plot.BlockBucket; import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.PlotArea; import com.plotsquared.core.plot.PlotAreaTerrainType; import com.plotsquared.core.plot.PlotAreaType; import com.plotsquared.core.plot.PlotCluster; import com.plotsquared.core.plot.PlotId; import com.plotsquared.core.plot.PlotManager; import com.plotsquared.core.plot.expiration.ExpireManager; import com.plotsquared.core.plot.expiration.ExpiryTask; import com.plotsquared.core.plot.flag.GlobalFlagContainer; import com.plotsquared.core.plot.world.PlotAreaManager; import com.plotsquared.core.plot.world.SinglePlotArea; import com.plotsquared.core.plot.world.SinglePlotAreaManager; import com.plotsquared.core.util.EventDispatcher; import com.plotsquared.core.util.FileUtils; import com.plotsquared.core.util.LegacyConverter; import com.plotsquared.core.util.MathMan; import com.plotsquared.core.util.ReflectionUtils; import com.plotsquared.core.util.task.TaskManager; import com.plotsquared.core.uuid.UUIDPipeline; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.math.BlockVector2; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Files; import java.nio.file.StandardOpenOption; import java.sql.SQLException; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import java.util.concurrent.Executors; import java.util.function.Consumer; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; /** * An implementation of the core, with a static getter for easy access. */ @SuppressWarnings({"WeakerAccess"}) public class PlotSquared { private static final Logger LOGGER = LogManager.getLogger("PlotSquared/" + PlotSquared.class.getSimpleName()); private static @MonotonicNonNull PlotSquared instance; // Implementation private final PlotPlatform<?> platform; // Current thread private final Thread thread; // UUID pipelines private final UUIDPipeline impromptuUUIDPipeline = new UUIDPipeline(Executors.newCachedThreadPool()); private final UUIDPipeline backgroundUUIDPipeline = new UUIDPipeline(Executors.newSingleThreadExecutor()); // Localization private final Map<String, CaptionMap> captionMaps = new HashMap<>(); public HashMap<String, HashMap<PlotId, Plot>> plots_tmp; private CaptionLoader captionLoader; // WorldEdit instance private WorldEdit worldedit; private File configFile; private File worldsFile; private YamlConfiguration worldConfiguration; // Temporary hold the plots/clusters before the worlds load private HashMap<String, Set<PlotCluster>> clustersTmp; private YamlConfiguration config; // Platform / Version / Update URL private PlotVersion version; // Files and configuration private File jarFile = null; // This file private File storageFile; private EventDispatcher eventDispatcher; private PlotListener plotListener; /** * Initialize PlotSquared with the desired Implementation class. * * @param iPlotMain Implementation of {@link PlotPlatform} used * @param platform The platform being used */ public PlotSquared( final @NonNull PlotPlatform<?> iPlotMain, final @NonNull String platform ) { if (instance != null) { throw new IllegalStateException("Cannot re-initialize the PlotSquared singleton"); } instance = this; this.thread = Thread.currentThread(); this.platform = iPlotMain; Settings.PLATFORM = platform; // Initialize the class PlayerMetaDataKeys.load(); // // Register configuration serializable classes // ConfigurationSerialization.registerClass(BlockBucket.class, "BlockBucket"); // load configs before reading from settings if (!setupConfigs()) { return; } this.captionLoader = CaptionLoader.of( Locale.ENGLISH, CaptionLoader.patternExtractor(Pattern.compile("messages_(.*)\\.json")), DefaultCaptionProvider.forClassLoaderFormatString( this.getClass().getClassLoader(), "lang/messages_%s.json" // the path in our jar file ), TranslatableCaption.DEFAULT_NAMESPACE ); // Load caption map try { this.loadCaptionMap(); } catch (final Exception e) { LOGGER.error("Failed to load caption map", e); } // Setup the global flag container GlobalFlagContainer.setup(); try { new ReflectionUtils(this.platform.serverNativePackage()); try { URL logurl = PlotSquared.class.getProtectionDomain().getCodeSource().getLocation(); this.jarFile = new File( new URL(logurl.toURI().toString().split("\\!")[0].replaceAll("jar:file", "file")) .toURI().getPath()); } catch (MalformedURLException | URISyntaxException | SecurityException e) { e.printStackTrace(); this.jarFile = new File(this.platform.getDirectory().getParentFile(), "PlotSquared.jar"); if (!this.jarFile.exists()) { this.jarFile = new File( this.platform.getDirectory().getParentFile(), "PlotSquared-" + platform + ".jar" ); } } this.worldedit = WorldEdit.getInstance(); // Create Event utility class this.eventDispatcher = new EventDispatcher(this.worldedit); // Create plot listener this.plotListener = new PlotListener(this.eventDispatcher); // Copy files copyFile("town.template", Settings.Paths.TEMPLATES); copyFile("bridge.template", Settings.Paths.TEMPLATES); copyFile("skyblock.template", Settings.Paths.TEMPLATES); showDebug(); } catch (Throwable e) { e.printStackTrace(); } } /** * Gets an instance of PlotSquared. * * @return instance of PlotSquared */ public static @NonNull PlotSquared get() { return PlotSquared.instance; } /** * Get the platform specific implementation of PlotSquared * * @return Platform implementation */ public static @NonNull PlotPlatform<?> platform() { if (instance != null && instance.platform != null) { return instance.platform; } throw new IllegalStateException("Plot platform implementation is missing"); } public void loadCaptionMap() throws Exception { this.platform.copyCaptionMaps(); // Setup localization CaptionMap captionMap; if (Settings.Enabled_Components.PER_USER_LOCALE) { captionMap = this.captionLoader.loadAll(this.platform.getDirectory().toPath().resolve("lang")); } else { String fileName = "messages_" + Settings.Enabled_Components.DEFAULT_LOCALE + ".json"; captionMap = this.captionLoader.loadSingle(this.platform.getDirectory().toPath().resolve("lang").resolve(fileName)); } this.captionMaps.put(TranslatableCaption.DEFAULT_NAMESPACE, captionMap); LOGGER.info( "Loaded caption map for namespace 'plotsquared': {}", this.captionMaps.get(TranslatableCaption.DEFAULT_NAMESPACE).getClass().getCanonicalName() ); } /** * Get the platform specific {@link PlotAreaManager} instance * * @return Plot area manager */ public @NonNull PlotAreaManager getPlotAreaManager() { return this.platform.plotAreaManager(); } public void startExpiryTasks() { if (Settings.Enabled_Components.PLOT_EXPIRY) { ExpireManager.IMP = new ExpireManager(this.eventDispatcher); ExpireManager.IMP.runAutomatedTask(); for (Settings.Auto_Clear settings : Settings.AUTO_CLEAR.getInstances()) { ExpiryTask task = new ExpiryTask(settings, this.getPlotAreaManager()); ExpireManager.IMP.addTask(task); } } } public boolean isMainThread(final @NonNull Thread thread) { return this.thread == thread; } /** * Check if `version` is &gt;= `version2`. * * @param version First version * @param version2 Second version * @return true if `version` is &gt;= `version2` */ public boolean checkVersion( final int[] version, final int... version2 ) { return version[0] > version2[0] || version[0] == version2[0] && version[1] > version2[1] || version[0] == version2[0] && version[1] == version2[1] && version[2] >= version2[2]; } /** * Gets the current PlotSquared version. * * @return current version in config or null */ public @NonNull PlotVersion getVersion() { return this.version; } /** * Gets the server platform this plugin is running on this is running on. * * <p>This will be either <b>Bukkit</b> or <b>Sponge</b></p> * * @return the server implementation */ public @NonNull String getPlatform() { return Settings.PLATFORM; } /** * Add a global reference to a plot world. * * @param plotArea the {@link PlotArea} to add. * @see #removePlotArea(PlotArea) To remove the reference */ public void addPlotArea(final @NonNull PlotArea plotArea) { HashMap<PlotId, Plot> plots; if (plots_tmp == null || (plots = plots_tmp.remove(plotArea.toString())) == null) { if (plotArea.getType() == PlotAreaType.PARTIAL) { plots = this.plots_tmp != null ? this.plots_tmp.get(plotArea.getWorldName()) : null; if (plots != null) { Iterator<Entry<PlotId, Plot>> iterator = plots.entrySet().iterator(); while (iterator.hasNext()) { Entry<PlotId, Plot> next = iterator.next(); PlotId id = next.getKey(); if (plotArea.contains(id)) { next.getValue().setArea(plotArea); iterator.remove(); } } } } } else { for (Plot entry : plots.values()) { entry.setArea(plotArea); } } Set<PlotCluster> clusters; if (clustersTmp == null || (clusters = clustersTmp.remove(plotArea.toString())) == null) { if (plotArea.getType() == PlotAreaType.PARTIAL) { clusters = this.clustersTmp != null ? this.clustersTmp.get(plotArea.getWorldName()) : null; if (clusters != null) { Iterator<PlotCluster> iterator = clusters.iterator(); while (iterator.hasNext()) { PlotCluster next = iterator.next(); if (next.intersects(plotArea.getMin(), plotArea.getMax())) { next.setArea(plotArea); iterator.remove(); } } } } } else { for (PlotCluster cluster : clusters) { cluster.setArea(plotArea); } } getPlotAreaManager().addPlotArea(plotArea); plotArea.setupBorder(); if (!Settings.Enabled_Components.PERSISTENT_ROAD_REGEN) { return; } File file = new File( this.platform.getDirectory() + File.separator + "persistent_regen_data_" + plotArea.getId() + "_" + plotArea.getWorldName()); if (!file.exists()) { return; } TaskManager.runTaskAsync(() -> { try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) { List<Object> list = (List<Object>) ois.readObject(); ArrayList<int[]> regionInts = (ArrayList<int[]>) list.get(0); ArrayList<int[]> chunkInts = (ArrayList<int[]>) list.get(1); HashSet<BlockVector2> regions = new HashSet<>(); Set<BlockVector2> chunks = new HashSet<>(); regionInts.forEach(l -> regions.add(BlockVector2.at(l[0], l[1]))); chunkInts.forEach(l -> chunks.add(BlockVector2.at(l[0], l[1]))); int height = (int) list.get(2); LOGGER.info( "Incomplete road regeneration found. Restarting in world {} with height {}", plotArea.getWorldName(), height ); LOGGER.info("- Regions: {}", regions.size()); LOGGER.info("- Chunks: {}", chunks.size()); HybridUtils.UPDATE = true; PlotSquared.platform().hybridUtils().scheduleRoadUpdate(plotArea, regions, height, chunks); } catch (IOException | ClassNotFoundException e) { LOGGER.error("Error restarting road regeneration", e); } finally { if (!file.delete()) { LOGGER.error("Error deleting persistent_regen_data_{}. Please delete this file manually", plotArea.getId()); } } }); } /** * Remove a plot world reference. * * @param area the {@link PlotArea} to remove */ public void removePlotArea(final @NonNull PlotArea area) { getPlotAreaManager().removePlotArea(area); setPlotsTmp(area); } public void removePlotAreas(final @NonNull String world) { for (final PlotArea area : this.getPlotAreaManager().getPlotAreasSet(world)) { if (area.getWorldName().equals(world)) { removePlotArea(area); } } } private void setPlotsTmp(final @NonNull PlotArea area) { if (this.plots_tmp == null) { this.plots_tmp = new HashMap<>(); } HashMap<PlotId, Plot> map = this.plots_tmp.computeIfAbsent(area.toString(), k -> new HashMap<>()); for (Plot plot : area.getPlots()) { map.put(plot.getId(), plot); } if (this.clustersTmp == null) { this.clustersTmp = new HashMap<>(); } this.clustersTmp.put(area.toString(), area.getClusters()); } public Set<PlotCluster> getClusters(final @NonNull String world) { final Set<PlotCluster> set = new HashSet<>(); for (final PlotArea area : this.getPlotAreaManager().getPlotAreasSet(world)) { set.addAll(area.getClusters()); } return Collections.unmodifiableSet(set); } public List<Plot> sortPlotsByTemp(Collection<Plot> plots) { int max = 0; int overflowCount = 0; for (Plot plot : plots) { if (plot.temp > 0) { if (plot.temp > max) { max = plot.temp; } } else { overflowCount++; } } Plot[] array = new Plot[max + 1]; List<Plot> overflow = new ArrayList<>(overflowCount); for (Plot plot : plots) { if (plot.temp <= 0) { overflow.add(plot); } else { array[plot.temp] = plot; } } ArrayList<Plot> result = new ArrayList<>(plots.size()); for (Plot plot : array) { if (plot != null) { result.add(plot); } } overflow.sort(Comparator.comparingInt(Plot::hashCode)); result.addAll(overflow); return result; } /** * Sort plots by hashcode. * * @param plots the collection of plots to sort * @return the sorted collection */ private ArrayList<Plot> sortPlotsByHash(Collection<Plot> plots) { int hardmax = 256000; int max = 0; int overflowSize = 0; for (Plot plot : plots) { int hash = MathMan.getPositiveId(plot.hashCode()); if (hash > max) { if (hash >= hardmax) { overflowSize++; } else { max = hash; } } } hardmax = Math.min(hardmax, max); Plot[] cache = new Plot[hardmax + 1]; List<Plot> overflow = new ArrayList<>(overflowSize); ArrayList<Plot> extra = new ArrayList<>(); for (Plot plot : plots) { int hash = MathMan.getPositiveId(plot.hashCode()); if (hash < hardmax) { if (hash >= 0) { cache[hash] = plot; } else { extra.add(plot); } } else if (Math.abs(plot.getId().getX()) > 15446 || Math.abs(plot.getId().getY()) > 15446) { extra.add(plot); } else { overflow.add(plot); } } Plot[] overflowArray = overflow.toArray(new Plot[0]); sortPlotsByHash(overflowArray); ArrayList<Plot> result = new ArrayList<>(cache.length + overflowArray.length); for (Plot plot : cache) { if (plot != null) { result.add(plot); } } Collections.addAll(result, overflowArray); result.addAll(extra); return result; } /** * Unchecked, use {@link #sortPlots(Collection, SortType, PlotArea)} instead which will in turn call this. * * @param input an array of plots to sort */ private void sortPlotsByHash(final @NonNull Plot @NonNull [] input) { List<Plot>[] bucket = new ArrayList[32]; Arrays.fill(bucket, new ArrayList<>()); boolean maxLength = false; int placement = 1; while (!maxLength) { maxLength = true; for (Plot plot : input) { int tmp = MathMan.getPositiveId(plot.hashCode()) / placement; bucket[tmp & 31].add(plot); if (maxLength && tmp > 0) { maxLength = false; } } int a = 0; for (int i = 0; i < 32; i++) { for (Plot plot : bucket[i]) { input[a++] = plot; } bucket[i].clear(); } placement *= 32; } } private @NonNull List<Plot> sortPlotsByTimestamp(final @NonNull Collection<Plot> plots) { int hardMax = 256000; int max = 0; int overflowSize = 0; for (final Plot plot : plots) { int hash = MathMan.getPositiveId(plot.hashCode()); if (hash > max) { if (hash >= hardMax) { overflowSize++; } else { max = hash; } } } hardMax = Math.min(hardMax, max); Plot[] cache = new Plot[hardMax + 1]; List<Plot> overflow = new ArrayList<>(overflowSize); ArrayList<Plot> extra = new ArrayList<>(); for (Plot plot : plots) { int hash = MathMan.getPositiveId(plot.hashCode()); if (hash < hardMax) { if (hash >= 0) { cache[hash] = plot; } else { extra.add(plot); } } else if (Math.abs(plot.getId().getX()) > 15446 || Math.abs(plot.getId().getY()) > 15446) { extra.add(plot); } else { overflow.add(plot); } } Plot[] overflowArray = overflow.toArray(new Plot[0]); sortPlotsByHash(overflowArray); ArrayList<Plot> result = new ArrayList<>(cache.length + overflowArray.length); for (Plot plot : cache) { if (plot != null) { result.add(plot); } } Collections.addAll(result, overflowArray); result.addAll(extra); return result; } /** * Sort plots by creation timestamp. * * @param input Plots to sort * @return Sorted list */ private @NonNull List<Plot> sortPlotsByModified(final @NonNull Collection<Plot> input) { List<Plot> list; if (input instanceof List) { list = (List<Plot>) input; } else { list = new ArrayList<>(input); } list.sort(Comparator.comparingLong(a -> ExpireManager.IMP.getTimestamp(a.getOwnerAbs()))); return list; } /** * Sort a collection of plots by world (with a priority world), then * by hashcode. * * @param plots the plots to sort * @param type The sorting method to use for each world (timestamp, or hash) * @param priorityArea Use null, "world", or "gibberish" if you * want default world order * @return ArrayList of plot */ public @NonNull List<Plot> sortPlots( final @NonNull Collection<Plot> plots, final @NonNull SortType type, final @Nullable PlotArea priorityArea ) { // group by world // sort each HashMap<PlotArea, Collection<Plot>> map = new HashMap<>(); int totalSize = Arrays.stream(this.getPlotAreaManager().getAllPlotAreas()).mapToInt(PlotArea::getPlotCount).sum(); if (plots.size() == totalSize) { for (PlotArea area : getPlotAreaManager().getAllPlotAreas()) { map.put(area, area.getPlots()); } } else { for (PlotArea area : getPlotAreaManager().getAllPlotAreas()) { map.put(area, new ArrayList<>(0)); } Collection<Plot> lastList = null; PlotArea lastWorld = null; for (Plot plot : plots) { if (lastWorld == plot.getArea()) { lastList.add(plot); } else { lastWorld = plot.getArea(); lastList = map.get(lastWorld); lastList.add(plot); } } } List<PlotArea> areas = Arrays.asList(getPlotAreaManager().getAllPlotAreas()); areas.sort((a, b) -> { if (priorityArea != null) { if (a.equals(priorityArea)) { return -1; } else if (b.equals(priorityArea)) { return 1; } } return a.hashCode() - b.hashCode(); }); ArrayList<Plot> toReturn = new ArrayList<>(plots.size()); for (PlotArea area : areas) { switch (type) { case CREATION_DATE: toReturn.addAll(sortPlotsByTemp(map.get(area))); break; case CREATION_DATE_TIMESTAMP: toReturn.addAll(sortPlotsByTimestamp(map.get(area))); break; case DISTANCE_FROM_ORIGIN: toReturn.addAll(sortPlotsByHash(map.get(area))); break; case LAST_MODIFIED: toReturn.addAll(sortPlotsByModified(map.get(area))); break; default: break; } } return toReturn; } public void setPlots(final @NonNull Map<String, HashMap<PlotId, Plot>> plots) { if (this.plots_tmp == null) { this.plots_tmp = new HashMap<>(); } for (final Entry<String, HashMap<PlotId, Plot>> entry : plots.entrySet()) { final String world = entry.getKey(); final PlotArea plotArea = this.getPlotAreaManager().getPlotArea(world, null); if (plotArea == null) { Map<PlotId, Plot> map = this.plots_tmp.computeIfAbsent(world, k -> new HashMap<>()); map.putAll(entry.getValue()); } else { for (Plot plot : entry.getValue().values()) { plot.setArea(plotArea); plotArea.addPlot(plot); } } } } /** * Unregisters a plot from local memory without calling the database. * * @param plot the plot to remove * @param callEvent If to call an event about the plot being removed * @return true if plot existed | false if it didn't */ public boolean removePlot( final @NonNull Plot plot, final boolean callEvent ) { if (plot == null) { return false; } if (callEvent) { eventDispatcher.callDelete(plot); } if (plot.getArea().removePlot(plot.getId())) { PlotId last = (PlotId) plot.getArea().getMeta("lastPlot"); int last_max = Math.max(Math.abs(last.getX()), Math.abs(last.getY())); int this_max = Math.max(Math.abs(plot.getId().getX()), Math.abs(plot.getId().getY())); if (this_max < last_max) { plot.getArea().setMeta("lastPlot", plot.getId()); } if (callEvent) { eventDispatcher.callPostDelete(plot); } return true; } return false; } /** * This method is called by the PlotGenerator class normally. * <ul> * <li>Initializes the PlotArea and PlotManager classes * <li>Registers the PlotArea and PlotManager classes * <li>Loads (and/or generates) the PlotArea configuration * <li>Sets up the world border if configured * </ul> * * <p>If loading an augmented plot world: * <ul> * <li>Creates the AugmentedPopulator classes * <li>Injects the AugmentedPopulator classes if required * </ul> * * @param world the world to load * @param baseGenerator The generator for that world, or null */ public void loadWorld( final @NonNull String world, final @Nullable GeneratorWrapper<?> baseGenerator ) { if (world.equals("CheckingPlotSquaredGenerator")) { return; } this.getPlotAreaManager().addWorld(world); Set<String> worlds; if (this.worldConfiguration.contains("worlds")) { worlds = this.worldConfiguration.getConfigurationSection("worlds").getKeys(false); } else { worlds = new HashSet<>(); } String path = "worlds." + world; ConfigurationSection worldSection = this.worldConfiguration.getConfigurationSection(path); PlotAreaType type; if (worldSection != null) { type = ConfigurationUtil.getType(worldSection); } else { type = PlotAreaType.NORMAL; } if (type == PlotAreaType.NORMAL) { if (getPlotAreaManager().getPlotAreas(world, null).length != 0) { return; } IndependentPlotGenerator plotGenerator; if (baseGenerator != null && baseGenerator.isFull()) { plotGenerator = baseGenerator.getPlotGenerator(); } else if (worldSection != null) { String secondaryGeneratorName = worldSection.getString("generator.plugin"); GeneratorWrapper<?> secondaryGenerator = this.platform.getGenerator(world, secondaryGeneratorName); if (secondaryGenerator != null && secondaryGenerator.isFull()) { plotGenerator = secondaryGenerator.getPlotGenerator(); } else { String primaryGeneratorName = worldSection.getString("generator.init"); GeneratorWrapper<?> primaryGenerator = this.platform.getGenerator(world, primaryGeneratorName); if (primaryGenerator != null && primaryGenerator.isFull()) { plotGenerator = primaryGenerator.getPlotGenerator(); } else { return; } } } else { return; } // Conventional plot generator PlotArea plotArea = plotGenerator.getNewPlotArea(world, null, null, null); PlotManager plotManager = plotArea.getPlotManager(); LOGGER.info("Detected world load for '{}'", world); LOGGER.info("- generator: {}>{}", baseGenerator, plotGenerator); LOGGER.info("- plot world: {}", plotArea.getClass().getCanonicalName()); LOGGER.info("- plot area manager: {}", plotManager.getClass().getCanonicalName()); if (!this.worldConfiguration.contains(path)) { this.worldConfiguration.createSection(path); worldSection = this.worldConfiguration.getConfigurationSection(path); } plotArea.saveConfiguration(worldSection); plotArea.loadDefaultConfiguration(worldSection); try { this.worldConfiguration.save(this.worldsFile); } catch (IOException e) { e.printStackTrace(); } // Now add it addPlotArea(plotArea); plotGenerator.initialize(plotArea); } else { if (!worlds.contains(world)) { return; } ConfigurationSection areasSection = worldSection.getConfigurationSection("areas"); if (areasSection == null) { if (getPlotAreaManager().getPlotAreas(world, null).length != 0) { return; } LOGGER.info("Detected world load for '{}'", world); String gen_string = worldSection.getString("generator.plugin", platform.pluginName()); if (type == PlotAreaType.PARTIAL) { Set<PlotCluster> clusters = this.clustersTmp != null ? this.clustersTmp.get(world) : new HashSet<>(); if (clusters == null) { throw new IllegalArgumentException("No cluster exists for world: " + world); } ArrayDeque<PlotArea> toLoad = new ArrayDeque<>(); for (PlotCluster cluster : clusters) { PlotId pos1 = cluster.getP1(); // Cluster pos1 PlotId pos2 = cluster.getP2(); // Cluster pos2 String name = cluster.getName(); // Cluster name String fullId = name + "-" + pos1 + "-" + pos2; worldSection.createSection("areas." + fullId); DBFunc.replaceWorld(world, world + ";" + name, pos1, pos2); // NPE LOGGER.info("- {}-{}-{}", name, pos1, pos2); GeneratorWrapper<?> areaGen = this.platform.getGenerator(world, gen_string); if (areaGen == null) { throw new IllegalArgumentException("Invalid Generator: " + gen_string); } PlotArea pa = areaGen.getPlotGenerator().getNewPlotArea(world, name, pos1, pos2); pa.saveConfiguration(worldSection); pa.loadDefaultConfiguration(worldSection); try { this.worldConfiguration.save(this.worldsFile); } catch (IOException e) { e.printStackTrace(); } LOGGER.info("| generator: {}>{}", baseGenerator, areaGen); LOGGER.info("| plot world: {}", pa); LOGGER.info("| manager: {}", pa); LOGGER.info("Note: Area created for cluster '{}' (invalid or old configuration?)", name); areaGen.getPlotGenerator().initialize(pa); areaGen.augment(pa); toLoad.add(pa); } for (PlotArea area : toLoad) { addPlotArea(area); } return; } GeneratorWrapper<?> areaGen = this.platform.getGenerator(world, gen_string); if (areaGen == null) { throw new IllegalArgumentException("Invalid Generator: " + gen_string); } PlotArea pa = areaGen.getPlotGenerator().getNewPlotArea(world, null, null, null); pa.saveConfiguration(worldSection); pa.loadDefaultConfiguration(worldSection); try { this.worldConfiguration.save(this.worldsFile); } catch (IOException e) { e.printStackTrace(); } LOGGER.info("- generator: {}>{}", baseGenerator, areaGen); LOGGER.info("- plot world: {}", pa); LOGGER.info("- plot area manager: {}", pa.getPlotManager()); areaGen.getPlotGenerator().initialize(pa); areaGen.augment(pa); addPlotArea(pa); return; } if (type == PlotAreaType.AUGMENTED) { throw new IllegalArgumentException( "Invalid type for multi-area world. Expected `PARTIAL`, got `" + PlotAreaType.AUGMENTED + "`"); } for (String areaId : areasSection.getKeys(false)) { LOGGER.info("- {}", areaId); String[] split = areaId.split("(?<=[^;-])-"); if (split.length != 3) { throw new IllegalArgumentException("Invalid Area identifier: " + areaId + ". Expected form `<name>-<pos1>-<pos2>`"); } String name = split[0]; PlotId pos1 = PlotId.fromString(split[1]); PlotId pos2 = PlotId.fromString(split[2]); if (name.isEmpty()) { throw new IllegalArgumentException("Invalid Area identifier: " + areaId + ". Expected form `<name>-<x1;z1>-<x2;z2>`"); } final PlotArea existing = this.getPlotAreaManager().getPlotArea(world, name); if (existing != null && name.equals(existing.getId())) { continue; } ConfigurationSection section = areasSection.getConfigurationSection(areaId); YamlConfiguration clone = new YamlConfiguration(); for (String key : section.getKeys(true)) { if (section.get(key) instanceof MemorySection) { continue; } if (!clone.contains(key)) { clone.set(key, section.get(key)); } } for (String key : worldSection.getKeys(true)) { if (worldSection.get(key) instanceof MemorySection) { continue; } if (!key.startsWith("areas") && !clone.contains(key)) { clone.set(key, worldSection.get(key)); } } String gen_string = clone.getString("generator.plugin", platform.pluginName()); GeneratorWrapper<?> areaGen = this.platform.getGenerator(world, gen_string); if (areaGen == null) { throw new IllegalArgumentException("Invalid Generator: " + gen_string); } PlotArea pa = areaGen.getPlotGenerator().getNewPlotArea(world, name, pos1, pos2); pa.saveConfiguration(clone); // netSections is the combination of for (String key : clone.getKeys(true)) { if (clone.get(key) instanceof MemorySection) { continue; } if (!worldSection.contains(key)) { worldSection.set(key, clone.get(key)); } else { Object value = worldSection.get(key); if (!Objects.equals(value, clone.get(key))) { section.set(key, clone.get(key)); } } } pa.loadDefaultConfiguration(clone); try { this.worldConfiguration.save(this.worldsFile); } catch (IOException e) { e.printStackTrace(); } LOGGER.info("Detected area load for '{}'", world); LOGGER.info("| generator: {}>{}", baseGenerator, areaGen); LOGGER.info("| plot world: {}", pa); LOGGER.info("| manager: {}", pa.getPlotManager()); areaGen.getPlotGenerator().initialize(pa); areaGen.augment(pa); addPlotArea(pa); } } } /** * Setup the configuration for a plot world based on world arguments. * * * <i>e.g. /mv create &lt;world&gt; normal -g PlotSquared:&lt;args&gt;</i> * * @param world The name of the world * @param args The arguments * @param generator the plot generator * @return boolean | if valid arguments were provided */ public boolean setupPlotWorld( final @NonNull String world, final @Nullable String args, final @NonNull IndependentPlotGenerator generator ) { if (args != null && !args.isEmpty()) { // save configuration final List<String> validArguments = Arrays .asList("s=", "size=", "g=", "gap=", "h=", "height=", "f=", "floor=", "m=", "main=", "w=", "wall=", "b=", "border=" ); // Calculate the number of expected arguments int expected = (int) validArguments.stream() .filter(validArgument -> args.toLowerCase(Locale.ENGLISH).contains(validArgument)) .count(); String[] split = args.toLowerCase(Locale.ENGLISH).split(",(?![^\\(\\[]*[\\]\\)])"); if (split.length > expected) { // This means we have multi-block block buckets String[] combinedArgs = new String[expected]; int index = 0; StringBuilder argBuilder = new StringBuilder(); outer: for (final String string : split) { for (final String validArgument : validArguments) { if (string.contains(validArgument)) { if (!argBuilder.toString().isEmpty()) { combinedArgs[index++] = argBuilder.toString(); argBuilder = new StringBuilder(); } argBuilder.append(string); continue outer; } } if (argBuilder.toString().charAt(argBuilder.length() - 1) != '=') { argBuilder.append(","); } argBuilder.append(string); } if (!argBuilder.toString().isEmpty()) { combinedArgs[index] = argBuilder.toString(); } split = combinedArgs; } final HybridPlotWorldFactory hybridPlotWorldFactory = this.platform .injector() .getInstance(HybridPlotWorldFactory.class); final HybridPlotWorld plotWorld = hybridPlotWorldFactory.create(world, null, generator, null, null); for (String element : split) { String[] pair = element.split("="); if (pair.length != 2) { LOGGER.error("No value provided for '{}'", element); return false; } String key = pair[0].toLowerCase(); String value = pair[1]; try { String base = "worlds." + world + "."; switch (key) { case "s", "size" -> this.worldConfiguration.set( base + "plot.size", ConfigurationUtil.INTEGER.parseString(value).shortValue() ); case "g", "gap" -> this.worldConfiguration.set( base + "road.width", ConfigurationUtil.INTEGER.parseString(value).shortValue() ); case "h", "height" -> { this.worldConfiguration.set( base + "road.height", ConfigurationUtil.INTEGER.parseString(value).shortValue() ); this.worldConfiguration.set( base + "plot.height", ConfigurationUtil.INTEGER.parseString(value).shortValue() ); this.worldConfiguration.set( base + "wall.height", ConfigurationUtil.INTEGER.parseString(value).shortValue() ); } case "f", "floor" -> this.worldConfiguration.set( base + "plot.floor", ConfigurationUtil.BLOCK_BUCKET.parseString(value).toString() ); case "m", "main" -> this.worldConfiguration.set( base + "plot.filling", ConfigurationUtil.BLOCK_BUCKET.parseString(value).toString() ); case "w", "wall" -> this.worldConfiguration.set( base + "wall.filling", ConfigurationUtil.BLOCK_BUCKET.parseString(value).toString() ); case "b", "border" -> this.worldConfiguration.set( base + "wall.block", ConfigurationUtil.BLOCK_BUCKET.parseString(value).toString() ); default -> { LOGGER.error("Key not found: {}", element); return false; } } } catch (Exception e) { LOGGER.error("Invalid value '{}' for arg '{}'", value, element); e.printStackTrace(); return false; } } try { ConfigurationSection section = this.worldConfiguration.getConfigurationSection("worlds." + world); plotWorld.saveConfiguration(section); plotWorld.loadDefaultConfiguration(section); this.worldConfiguration.save(this.worldsFile); } catch (IOException e) { e.printStackTrace(); } } return true; } /** * Copies a file from inside the jar to a location * * @param file Name of the file inside PlotSquared.jar * @param folder The output location relative to /plugins/PlotSquared/ */ public void copyFile( final @NonNull String file, final @NonNull String folder ) { try { File output = this.platform.getDirectory(); if (!output.exists()) { output.mkdirs(); } File newFile = FileUtils.getFile(output, folder + File.separator + file); if (newFile.exists()) { return; } try (InputStream stream = this.platform.getClass().getResourceAsStream(file)) { byte[] buffer = new byte[2048]; if (stream == null) { try (ZipInputStream zis = new ZipInputStream( new FileInputStream(this.jarFile))) { ZipEntry ze = zis.getNextEntry(); while (ze != null) { String name = ze.getName(); if (name.equals(file)) { new File(newFile.getParent()).mkdirs(); try (FileOutputStream fos = new FileOutputStream(newFile)) { int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } } ze = null; } else { ze = zis.getNextEntry(); } } zis.closeEntry(); } return; } newFile.createNewFile(); try (FileOutputStream fos = new FileOutputStream(newFile)) { int len; while ((len = stream.read(buffer)) > 0) { fos.write(buffer, 0, len); } } } } catch (IOException e) { LOGGER.error("Could not save {}", file); e.printStackTrace(); } } /** * Safely closes the database connection. */ public void disable() { try { eventDispatcher.unregisterAll(); checkRoadRegenPersistence(); // Validate that all data in the db is correct final HashSet<Plot> plots = new HashSet<>(); try { forEachPlotRaw(plots::add); } catch (final Exception ignored) { } DBFunc.validatePlots(plots); // Close the connection DBFunc.close(); } catch (NullPointerException throwable) { LOGGER.error("Could not close database connection", throwable); throwable.printStackTrace(); } } /** * Handle road regen persistence */ private void checkRoadRegenPersistence() { if (!HybridUtils.UPDATE || !Settings.Enabled_Components.PERSISTENT_ROAD_REGEN || ( HybridUtils.regions.isEmpty() && HybridUtils.chunks.isEmpty())) { return; } LOGGER.info("Road regeneration incomplete. Saving incomplete regions to disk"); LOGGER.info("- regions: {}", HybridUtils.regions.size()); LOGGER.info("- chunks: {}", HybridUtils.chunks.size()); ArrayList<int[]> regions = new ArrayList<>(); ArrayList<int[]> chunks = new ArrayList<>(); for (BlockVector2 r : HybridUtils.regions) { regions.add(new int[]{r.getBlockX(), r.getBlockZ()}); } for (BlockVector2 c : HybridUtils.chunks) { chunks.add(new int[]{c.getBlockX(), c.getBlockZ()}); } List<Object> list = new ArrayList<>(); list.add(regions); list.add(chunks); list.add(HybridUtils.height); File file = new File( this.platform.getDirectory() + File.separator + "persistent_regen_data_" + HybridUtils.area .getId() + "_" + HybridUtils.area.getWorldName()); if (file.exists() && !file.delete()) { LOGGER.error("persistent_regene_data file already exists and could not be deleted"); return; } try (ObjectOutputStream oos = new ObjectOutputStream( Files.newOutputStream(file.toPath(), StandardOpenOption.CREATE_NEW))) { oos.writeObject(list); } catch (IOException e) { LOGGER.error("Error creating persistent_region_data file", e); } } /** * Setup the database connection. */ public void setupDatabase() { try { if (DBFunc.dbManager != null) { DBFunc.dbManager.close(); } Database database; if (Storage.MySQL.USE) { database = new MySQL(Storage.MySQL.HOST, Storage.MySQL.PORT, Storage.MySQL.DATABASE, Storage.MySQL.USER, Storage.MySQL.PASSWORD ); } else if (Storage.SQLite.USE) { File file = FileUtils.getFile(platform.getDirectory(), Storage.SQLite.DB + ".db"); database = new SQLite(file); } else { LOGGER.error("No storage type is set. Disabling PlotSquared"); this.platform.shutdown(); //shutdown used instead of disable because no database is set return; } DBFunc.dbManager = new SQLManager( database, Storage.PREFIX, this.eventDispatcher, this.plotListener, this.worldConfiguration ); this.plots_tmp = DBFunc.getPlots(); if (getPlotAreaManager() instanceof SinglePlotAreaManager) { SinglePlotArea area = ((SinglePlotAreaManager) getPlotAreaManager()).getArea(); addPlotArea(area); ConfigurationSection section = worldConfiguration.getConfigurationSection("worlds.*"); if (section == null) { section = worldConfiguration.createSection("worlds.*"); } area.saveConfiguration(section); area.loadDefaultConfiguration(section); } this.clustersTmp = DBFunc.getClusters(); LOGGER.info("Connection to database established. Type: {}", Storage.MySQL.USE ? "MySQL" : "SQLite"); } catch (ClassNotFoundException | SQLException e) { LOGGER.error( "Failed to open database connection ({}). Disabling PlotSquared", Storage.MySQL.USE ? "MySQL" : "SQLite" ); LOGGER.error("==== Here is an ugly stacktrace, if you are interested in those things ==="); e.printStackTrace(); LOGGER.error("==== End of stacktrace ===="); LOGGER.error( "Please go to the {} 'storage.yml' and configure the database correctly", platform.pluginName() ); this.platform.shutdown(); //shutdown used instead of disable because of database error } } /** * Setup the default configuration. */ public void setupConfig() { String lastVersionString = this.getConfig().getString("version"); if (lastVersionString != null) { String[] split = lastVersionString.split("\\."); int[] lastVersion = new int[]{Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2])}; if (checkVersion(new int[]{3, 4, 0}, lastVersion)) { Settings.convertLegacy(configFile); if (getConfig().contains("worlds")) { ConfigurationSection worldSection = getConfig().getConfigurationSection("worlds"); worldConfiguration.set("worlds", worldSection); try { worldConfiguration.save(worldsFile); } catch (IOException e) { LOGGER.error("Failed to save worlds.yml", e); e.printStackTrace(); } } Settings.save(configFile); } } Settings.load(configFile); //Sets the version information for the settings.yml file try (InputStream stream = getClass().getResourceAsStream("/plugin.properties")) { try (BufferedReader br = new BufferedReader(new InputStreamReader(stream))) { String versionString = br.readLine(); String commitString = br.readLine(); String dateString = br.readLine(); this.version = PlotVersion.tryParse(versionString, commitString, dateString); } } catch (IOException throwable) { throwable.printStackTrace(); } Settings.save(configFile); config = YamlConfiguration.loadConfiguration(configFile); } /** * Setup all configuration files<br> * - Config: settings.yml<br> * - Storage: storage.yml<br> * * @return success or not */ public boolean setupConfigs() { File folder = new File(this.platform.getDirectory(), "config"); if (!folder.exists() && !folder.mkdirs()) { LOGGER.error("Failed to create the {} config folder. Please create it manually", this.platform.getDirectory()); } try { this.worldsFile = new File(folder, "worlds.yml"); if (!this.worldsFile.exists() && !this.worldsFile.createNewFile()) { LOGGER.error("Could not create the worlds file. Please create 'worlds.yml' manually"); } this.worldConfiguration = YamlConfiguration.loadConfiguration(this.worldsFile); if (this.worldConfiguration.contains("worlds")) { if (!this.worldConfiguration.contains("configuration_version") || ( !this.worldConfiguration.getString("configuration_version") .equalsIgnoreCase(LegacyConverter.CONFIGURATION_VERSION) && !this.worldConfiguration .getString("configuration_version").equalsIgnoreCase("v5"))) { // Conversion needed LOGGER.info("A legacy configuration file was detected. Conversion will be attempted."); try { com.google.common.io.Files .copy(this.worldsFile, new File(folder, "worlds.yml.old")); LOGGER.info("A copy of worlds.yml has been saved in the file worlds.yml.old"); final ConfigurationSection worlds = this.worldConfiguration.getConfigurationSection("worlds"); final LegacyConverter converter = new LegacyConverter(worlds); converter.convert(); this.worldConfiguration.set("worlds", worlds); this.setConfigurationVersion(LegacyConverter.CONFIGURATION_VERSION); LOGGER.info( "The conversion has finished. PlotSquared will now be disabled and the new configuration file will be used at next startup. Please review the new worlds.yml file. Please note that schematics will not be converted, as we are now using WorldEdit to handle schematics. You need to re-generate the schematics."); } catch (final Exception e) { LOGGER.error("Failed to convert the legacy configuration file. See stack trace for information.", e); } // Disable plugin this.platform.shutdown(); return false; } } else { this.worldConfiguration.set("configuration_version", LegacyConverter.CONFIGURATION_VERSION); } } catch (IOException ignored) { LOGGER.error("Failed to save worlds.yml"); } try { this.configFile = new File(folder, "settings.yml"); if (!this.configFile.exists() && !this.configFile.createNewFile()) { LOGGER.error("Could not create the settings file. Please create 'settings.yml' manually"); } this.config = YamlConfiguration.loadConfiguration(this.configFile); setupConfig(); } catch (IOException ignored) { LOGGER.error("Failed to save settings.yml"); } try { this.storageFile = new File(folder, "storage.yml"); if (!this.storageFile.exists() && !this.storageFile.createNewFile()) { LOGGER.error("Could not create the storage settings file. Please create 'storage.yml' manually"); } YamlConfiguration.loadConfiguration(this.storageFile); setupStorage(); } catch (IOException ignored) { LOGGER.error("Failed to save storage.yml"); } return true; } public @NonNull String getConfigurationVersion() { return this.worldConfiguration.get("configuration_version", LegacyConverter.CONFIGURATION_VERSION) .toString(); } public void setConfigurationVersion(final @NonNull String newVersion) throws IOException { this.worldConfiguration.set("configuration_version", newVersion); this.worldConfiguration.save(this.worldsFile); } /** * Setup the storage file (load + save missing nodes). */ private void setupStorage() { Storage.load(storageFile); Storage.save(storageFile); YamlConfiguration.loadConfiguration(storageFile); } /** * Show startup debug information. */ private void showDebug() { if (Settings.DEBUG) { Map<String, Object> components = Settings.getFields(Settings.Enabled_Components.class); for (Entry<String, Object> component : components.entrySet()) { LOGGER.info("Key: {} | Value: {}", component.getKey(), component.getValue()); } } } public void forEachPlotRaw(final @NonNull Consumer<Plot> consumer) { for (final PlotArea area : this.getPlotAreaManager().getAllPlotAreas()) { area.getPlots().forEach(consumer); } if (this.plots_tmp != null) { for (final HashMap<PlotId, Plot> entry : this.plots_tmp.values()) { entry.values().forEach(consumer); } } } /** * Check if the chunk uses vanilla/non-PlotSquared generation * * @param world World name * @param chunkCoordinates Chunk coordinates * @return True if the chunk uses non-standard generation, false if not */ public boolean isNonStandardGeneration( final @NonNull String world, final @NonNull BlockVector2 chunkCoordinates ) { final Location location = Location.at(world, chunkCoordinates.getBlockX() << 4, 64, chunkCoordinates.getBlockZ() << 4); final PlotArea area = getPlotAreaManager().getApplicablePlotArea(location); if (area == null) { return true; } return area.getTerrain() != PlotAreaTerrainType.NONE; } public @NonNull YamlConfiguration getConfig() { return config; } public @NonNull UUIDPipeline getImpromptuUUIDPipeline() { return this.impromptuUUIDPipeline; } public @NonNull UUIDPipeline getBackgroundUUIDPipeline() { return this.backgroundUUIDPipeline; } public @NonNull WorldEdit getWorldEdit() { return this.worldedit; } public @NonNull File getConfigFile() { return this.configFile; } public @NonNull File getWorldsFile() { return this.worldsFile; } public @NonNull YamlConfiguration getWorldConfiguration() { return this.worldConfiguration; } /** * Get the caption map belonging to a namespace. If none exists, a dummy * caption map will be returned. * * @param namespace Namespace * @return Map instance * @see #registerCaptionMap(String, CaptionMap) To register a caption map */ public @NonNull CaptionMap getCaptionMap(final @NonNull String namespace) { return this.captionMaps.computeIfAbsent( namespace.toLowerCase(Locale.ENGLISH), missingNamespace -> new DummyCaptionMap() ); } /** * Register a caption map. The namespace needs be equal to the namespace used for * the {@link TranslatableCaption}s inside the map. * * @param namespace Namespace * @param captionMap Map instance */ public void registerCaptionMap( final @NonNull String namespace, final @NonNull CaptionMap captionMap ) { if (namespace.equalsIgnoreCase(TranslatableCaption.DEFAULT_NAMESPACE)) { throw new IllegalArgumentException("Cannot replace default caption map"); } this.captionMaps.put(namespace.toLowerCase(Locale.ENGLISH), captionMap); } public @NonNull EventDispatcher getEventDispatcher() { return this.eventDispatcher; } public @NonNull PlotListener getPlotListener() { return this.plotListener; } /** * Different ways of sorting {@link Plot plots} */ public enum SortType { /** * Sort plots by their creation, using their index in the database */ CREATION_DATE, /** * Sort plots by their creation timestamp */ CREATION_DATE_TIMESTAMP, /** * Sort plots by when they were last modified */ LAST_MODIFIED, /** * Sort plots based on their distance from the origin of the world */ DISTANCE_FROM_ORIGIN } }
gpl-3.0
a1exsh/yapet
app/helpers/in_place_editing_grid_helper.rb
5562
# TODO: Beware, people are likely to kill those who name functions # like that! # module InPlaceEditingGridHelper include InPlaceMacrosHelper include InPlaceCompleterHelper include AutoCompleteMacrosHelper def self.included(target) target.alias_method_chain(:in_place_editor_field, :customization) target.alias_method_chain(:in_place_completing_editor_field, :customization) target.alias_method_chain(:text_field_with_auto_complete, :skip_style) end def in_place_editor_field_with_customization(object, method, tag_opts = {}, editor_opts = {}) options = process_editor_options(editor_opts) in_place_editor_field_without_customization(object, method, tag_opts, options) end def in_place_completing_editor_field_with_customization(object, method, tag_opts = {}, editor_opts = {}, completion_opts = {}) options = process_editor_options(editor_opts) in_place_completing_editor_field_without_customization(object, method, tag_opts, options, options_for_completer(completion_opts)) end def in_place_editor_grid_field(grid_record, object, method, tag_options = {}, in_place_editor_options = {}) options = grid_editor_options(grid_record, in_place_editor_options) in_place_editor_field_without_customization(object, method, tag_options, options) end def in_place_completing_editor_grid_field(grid_record, object, method, tag_options = {}, in_place_editor_options = {}, completion_options = {}) options = grid_editor_options(grid_record, in_place_editor_options) completion_options = options_for_completer(completion_options) in_place_completing_editor_field_without_customization(object, method, tag_options, options, completion_options) end def in_place_editor_field_with_arithmetic(object, method, tag_opts = {}, editor_opts = {}) editor_opts = editor_opts.merge(options_for_field_arithmetic) in_place_editor_field_with_customization(object, method, tag_opts, editor_opts) end def in_place_editor_grid_field_with_arithmetic(grid_record, object, method, tag_options = {}, editor_opts = {}) editor_opts = editor_opts.merge(options_for_field_arithmetic) options = grid_editor_options(grid_record, editor_opts) in_place_editor_field_without_customization(object, method, tag_options, options) end def text_field_with_auto_complete_with_skip_style(object, method, tag_options = {}, completion_options = {}) completion_options = options_for_completer(completion_options) text_field_with_auto_complete_without_skip_style(object, method, tag_options, completion_options) end protected def default_editor_options in_place_i18n_options.merge(in_place_customization_options) end def process_editor_options(options) default_options = default_editor_options process_status_icon_options(options) process_final_options_merge(default_options, options) end def process_status_icon_options(options) status_icon_id = options[:status_icon_id] unless status_icon_id.blank? reload_js = options[:reload_js] || "" saving_js = "startSpinner('#{status_icon_id}');" success_js = "stopSpinner('#{status_icon_id}');" + reload_js failure_js = <<EOF var errorText = transport.responseText.substring(0, 256); setStatusIcon('#{status_icon_id}', 'error', errorText); alert(errorText); EOF options.merge!(:saving => saving_js, :success => success_js, :failure => failure_js) end end def process_final_options_merge(default_options, options) # TODO: this is messy, to say the least customize_form_js = options.delete(:customize_form) options = default_options.merge(options) options[:customize_form] += ";" + customize_form_js unless customize_form_js.blank? options end def grid_editor_options(grid_record, in_place_editor_options) options = default_editor_options options.merge!(grid_record.ajax_options) options.merge!(:success => grid_record.reload_page_js) process_final_options_merge(options, in_place_editor_options) end def options_for_field_arithmetic { :customize_form => <<EOF var editor = ipe._controls.editor; editor.onchange = function() { calculate_input(editor) }; EOF } end def options_for_completer(completion_options) completion_options.merge(:skip_style => true) end end
gpl-3.0
chipaca/snappy
overlord/devicestate/firstboot_test.go
55411
// -*- Mode: Go; indent-tabs-mode: t -*- /* * Copyright (C) 2015-2019 Canonical Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * 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, see <http://www.gnu.org/licenses/>. * */ package devicestate_test import ( "fmt" "io/ioutil" "os" "path/filepath" "strconv" "strings" "time" . "gopkg.in/check.v1" "gopkg.in/tomb.v2" "github.com/snapcore/snapd/asserts" "github.com/snapcore/snapd/asserts/assertstest" "github.com/snapcore/snapd/asserts/sysdb" "github.com/snapcore/snapd/boot/boottest" "github.com/snapcore/snapd/bootloader" "github.com/snapcore/snapd/bootloader/bootloadertest" "github.com/snapcore/snapd/dirs" "github.com/snapcore/snapd/osutil" "github.com/snapcore/snapd/overlord" "github.com/snapcore/snapd/overlord/assertstate" "github.com/snapcore/snapd/overlord/auth" "github.com/snapcore/snapd/overlord/configstate" "github.com/snapcore/snapd/overlord/configstate/config" "github.com/snapcore/snapd/overlord/devicestate" "github.com/snapcore/snapd/overlord/devicestate/devicestatetest" "github.com/snapcore/snapd/overlord/hookstate" "github.com/snapcore/snapd/overlord/ifacestate" "github.com/snapcore/snapd/overlord/snapstate" "github.com/snapcore/snapd/overlord/state" "github.com/snapcore/snapd/release" "github.com/snapcore/snapd/seed" "github.com/snapcore/snapd/seed/seedtest" "github.com/snapcore/snapd/snap" "github.com/snapcore/snapd/snap/snaptest" "github.com/snapcore/snapd/sysconfig" "github.com/snapcore/snapd/systemd" "github.com/snapcore/snapd/testutil" "github.com/snapcore/snapd/timings" ) type firstBootBaseTest struct { testutil.BaseTest systemctl *testutil.MockCmd devAcct *asserts.Account overlord *overlord.Overlord perfTimings timings.Measurer } func (t *firstBootBaseTest) setupBaseTest(c *C, s *seedtest.SeedSnaps) { t.BaseTest.SetUpTest(c) tempdir := c.MkDir() dirs.SetRootDir(tempdir) t.AddCleanup(func() { dirs.SetRootDir("/") }) t.AddCleanup(release.MockOnClassic(false)) restore := osutil.MockMountInfo("") t.AddCleanup(restore) // mock the world! err := os.MkdirAll(filepath.Join(dirs.SnapSeedDir, "snaps"), 0755) c.Assert(err, IsNil) err = os.MkdirAll(dirs.SnapServicesDir, 0755) c.Assert(err, IsNil) os.Setenv("SNAPPY_SQUASHFS_UNPACK_FOR_TESTS", "1") t.AddCleanup(func() { os.Unsetenv("SNAPPY_SQUASHFS_UNPACK_FOR_TESTS") }) t.systemctl = testutil.MockCommand(c, "systemctl", "") t.AddCleanup(t.systemctl.Restore) s.SetupAssertSigning("canonical") s.Brands.Register("my-brand", brandPrivKey, map[string]interface{}{ "verification": "verified", }) t.devAcct = assertstest.NewAccount(s.StoreSigning, "developer", map[string]interface{}{ "account-id": "developerid", }, "") t.AddCleanup(sysdb.InjectTrusted([]asserts.Assertion{s.StoreSigning.TrustedKey})) t.AddCleanup(ifacestate.MockSecurityBackends(nil)) t.perfTimings = timings.New(nil) r := devicestate.MockCloudInitStatus(func() (sysconfig.CloudInitState, error) { return sysconfig.CloudInitRestrictedBySnapd, nil }) t.AddCleanup(r) } // startOverlord will setup and create a new overlord, note that it will not // stop any pre-existing overlord and it will be overwritten, for more fine // control create your own overlord // also note that as long as you don't run overlord.Loop() this is safe to call // multiple times to clear overlord state, if you call Loop() call Stop() on // your own before calling this again func (t *firstBootBaseTest) startOverlord(c *C) { ovld, err := overlord.New(nil) c.Assert(err, IsNil) ovld.InterfaceManager().DisableUDevMonitor() t.overlord = ovld c.Assert(ovld.StartUp(), IsNil) // don't actually try to talk to the store on snapstate.Ensure // needs doing after the call to devicestate.Manager (which happens in // overlord.New) snapstate.CanAutoRefresh = nil } type firstBoot16BaseTest struct { *firstBootBaseTest // TestingSeed16 helps populating seeds (it provides // MakeAssertedSnap, WriteAssertions etc.) for tests. *seedtest.TestingSeed16 } func (t *firstBoot16BaseTest) setup16BaseTest(c *C, bt *firstBootBaseTest) { t.firstBootBaseTest = bt t.setupBaseTest(c, &t.TestingSeed16.SeedSnaps) } type firstBoot16Suite struct { firstBootBaseTest firstBoot16BaseTest } var _ = Suite(&firstBoot16Suite{}) func (s *firstBoot16Suite) SetUpTest(c *C) { s.TestingSeed16 = &seedtest.TestingSeed16{} s.setup16BaseTest(c, &s.firstBootBaseTest) s.startOverlord(c) s.SeedDir = dirs.SnapSeedDir err := os.MkdirAll(filepath.Join(dirs.SnapSeedDir, "assertions"), 0755) c.Assert(err, IsNil) // mock the snap mapper as core here to make sure that other tests don't // set it inadvertently to the snapd mapper and break the 16 tests s.AddCleanup(ifacestate.MockSnapMapper(&ifacestate.CoreCoreSystemMapper{})) } func checkTrivialSeeding(c *C, tsAll []*state.TaskSet) { // run internal core config and mark seeded c.Check(tsAll, HasLen, 2) tasks := tsAll[0].Tasks() c.Check(tasks, HasLen, 1) c.Assert(tasks[0].Kind(), Equals, "run-hook") var hooksup hookstate.HookSetup err := tasks[0].Get("hook-setup", &hooksup) c.Assert(err, IsNil) c.Check(hooksup.Hook, Equals, "configure") c.Check(hooksup.Snap, Equals, "core") tasks = tsAll[1].Tasks() c.Check(tasks, HasLen, 1) c.Check(tasks[0].Kind(), Equals, "mark-seeded") } func modelHeaders(modelStr string, reqSnaps ...string) map[string]interface{} { headers := map[string]interface{}{ "architecture": "amd64", "store": "canonical", } if strings.HasSuffix(modelStr, "-classic") { headers["classic"] = "true" } else { headers["kernel"] = "pc-kernel" headers["gadget"] = "pc" } if len(reqSnaps) != 0 { reqs := make([]interface{}, len(reqSnaps)) for i, req := range reqSnaps { reqs[i] = req } headers["required-snaps"] = reqs } return headers } func (s *firstBoot16BaseTest) makeModelAssertionChain(c *C, modName string, extraHeaders map[string]interface{}, reqSnaps ...string) []asserts.Assertion { return s.MakeModelAssertionChain("my-brand", modName, modelHeaders(modName, reqSnaps...), extraHeaders) } func (s *firstBoot16Suite) TestPopulateFromSeedOnClassicNoop(c *C) { restore := release.MockOnClassic(true) defer restore() st := s.overlord.State() st.Lock() defer st.Unlock() err := os.Remove(filepath.Join(dirs.SnapSeedDir, "assertions")) c.Assert(err, IsNil) tsAll, err := devicestate.PopulateStateFromSeedImpl(st, nil, s.perfTimings) c.Assert(err, IsNil) checkTrivialSeeding(c, tsAll) // already set the fallback model // verify that the model was added db := assertstate.DB(st) as, err := db.Find(asserts.ModelType, map[string]string{ "series": "16", "brand-id": "generic", "model": "generic-classic", }) c.Assert(err, IsNil) _, ok := as.(*asserts.Model) c.Check(ok, Equals, true) ds, err := devicestatetest.Device(st) c.Assert(err, IsNil) c.Check(ds.Brand, Equals, "generic") c.Check(ds.Model, Equals, "generic-classic") } func (s *firstBoot16Suite) TestPopulateFromSeedOnClassicNoSeedYaml(c *C) { restore := release.MockOnClassic(true) defer restore() ovld, err := overlord.New(nil) c.Assert(err, IsNil) st := ovld.State() // add the model assertion and its chain assertsChain := s.makeModelAssertionChain(c, "my-model-classic", nil) s.WriteAssertions("model.asserts", assertsChain...) st.Lock() defer st.Unlock() tsAll, err := devicestate.PopulateStateFromSeedImpl(st, nil, s.perfTimings) c.Assert(err, IsNil) checkTrivialSeeding(c, tsAll) ds, err := devicestatetest.Device(st) c.Assert(err, IsNil) c.Check(ds.Brand, Equals, "my-brand") c.Check(ds.Model, Equals, "my-model-classic") } func (s *firstBoot16Suite) TestPopulateFromSeedOnClassicEmptySeedYaml(c *C) { restore := release.MockOnClassic(true) defer restore() ovld, err := overlord.New(nil) c.Assert(err, IsNil) st := ovld.State() // add the model assertion and its chain assertsChain := s.makeModelAssertionChain(c, "my-model-classic", nil) s.WriteAssertions("model.asserts", assertsChain...) // create an empty seed.yaml err = ioutil.WriteFile(filepath.Join(dirs.SnapSeedDir, "seed.yaml"), nil, 0644) c.Assert(err, IsNil) st.Lock() defer st.Unlock() _, err = devicestate.PopulateStateFromSeedImpl(st, nil, s.perfTimings) c.Assert(err, ErrorMatches, "cannot proceed, no snaps to seed") st.Unlock() st.Lock() // note, cannot use st.Tasks() here as it filters out tasks with no change c.Check(st.TaskCount(), Equals, 0) } func (s *firstBoot16Suite) TestPopulateFromSeedOnClassicNoSeedYamlWithCloudInstanceData(c *C) { restore := release.MockOnClassic(true) defer restore() st := s.overlord.State() // add the model assertion and its chain assertsChain := s.makeModelAssertionChain(c, "my-model-classic", nil) s.WriteAssertions("model.asserts", assertsChain...) // write cloud instance data const instData = `{ "v1": { "availability-zone": "us-east-2b", "cloud-name": "aws", "instance-id": "i-03bdbe0d89f4c8ec9", "local-hostname": "ip-10-41-41-143", "region": "us-east-2" } }` err := os.MkdirAll(filepath.Dir(dirs.CloudInstanceDataFile), 0755) c.Assert(err, IsNil) err = ioutil.WriteFile(dirs.CloudInstanceDataFile, []byte(instData), 0600) c.Assert(err, IsNil) st.Lock() defer st.Unlock() tsAll, err := devicestate.PopulateStateFromSeedImpl(st, nil, s.perfTimings) c.Assert(err, IsNil) checkTrivialSeeding(c, tsAll) ds, err := devicestatetest.Device(st) c.Assert(err, IsNil) c.Check(ds.Brand, Equals, "my-brand") c.Check(ds.Model, Equals, "my-model-classic") // now run the change and check the result // use the expected kind otherwise settle will start another one chg := st.NewChange("seed", "run the populate from seed changes") for _, ts := range tsAll { chg.AddAll(ts) } c.Assert(st.Changes(), HasLen, 1) // avoid device reg chg1 := st.NewChange("become-operational", "init device") chg1.SetStatus(state.DoingStatus) st.Unlock() err = s.overlord.Settle(settleTimeout) st.Lock() c.Assert(chg.Err(), IsNil) c.Assert(err, IsNil) // check marked seeded var seeded bool err = st.Get("seeded", &seeded) c.Assert(err, IsNil) c.Check(seeded, Equals, true) // check captured cloud information tr := config.NewTransaction(st) var cloud auth.CloudInfo err = tr.Get("core", "cloud", &cloud) c.Assert(err, IsNil) c.Check(cloud.Name, Equals, "aws") c.Check(cloud.Region, Equals, "us-east-2") c.Check(cloud.AvailabilityZone, Equals, "us-east-2b") } func (s *firstBoot16Suite) TestPopulateFromSeedErrorsOnState(c *C) { st := s.overlord.State() st.Lock() defer st.Unlock() st.Set("seeded", true) _, err := devicestate.PopulateStateFromSeedImpl(st, nil, s.perfTimings) c.Assert(err, ErrorMatches, "cannot populate state: already seeded") // note, cannot use st.Tasks() here as it filters out tasks with no change c.Check(st.TaskCount(), Equals, 0) } func (s *firstBoot16BaseTest) makeCoreSnaps(c *C, extraGadgetYaml string) (coreFname, kernelFname, gadgetFname string) { files := [][]string{} if strings.Contains(extraGadgetYaml, "defaults:") { files = [][]string{{"meta/hooks/configure", ""}} } // put core snap into the SnapBlobDir snapYaml := `name: core version: 1.0 type: os` coreFname, coreDecl, coreRev := s.MakeAssertedSnap(c, snapYaml, files, snap.R(1), "canonical") s.WriteAssertions("core.asserts", coreRev, coreDecl) // put kernel snap into the SnapBlobDir snapYaml = `name: pc-kernel version: 1.0 type: kernel` kernelFname, kernelDecl, kernelRev := s.MakeAssertedSnap(c, snapYaml, files, snap.R(1), "canonical") s.WriteAssertions("kernel.asserts", kernelRev, kernelDecl) gadgetYaml := ` volumes: volume-id: bootloader: grub ` gadgetYaml += extraGadgetYaml // put gadget snap into the SnapBlobDir files = append(files, []string{"meta/gadget.yaml", gadgetYaml}) snapYaml = `name: pc version: 1.0 type: gadget` gadgetFname, gadgetDecl, gadgetRev := s.MakeAssertedSnap(c, snapYaml, files, snap.R(1), "canonical") s.WriteAssertions("gadget.asserts", gadgetRev, gadgetDecl) return coreFname, kernelFname, gadgetFname } func checkOrder(c *C, tsAll []*state.TaskSet, snaps ...string) { matched := 0 var prevTask *state.Task for i, ts := range tsAll { task0 := ts.Tasks()[0] waitTasks := task0.WaitTasks() if i == 0 { c.Check(waitTasks, HasLen, 0) } else { c.Check(waitTasks, testutil.Contains, prevTask) } prevTask = task0 if task0.Kind() != "prerequisites" { continue } snapsup, err := snapstate.TaskSnapSetup(task0) c.Assert(err, IsNil, Commentf("%#v", task0)) c.Check(snapsup.InstanceName(), Equals, snaps[matched]) matched++ } c.Check(matched, Equals, len(snaps)) } func checkSeedTasks(c *C, tsAll []*state.TaskSet) { // the last taskset is just mark-seeded lastTasks := tsAll[len(tsAll)-1].Tasks() c.Check(lastTasks, HasLen, 1) markSeededTask := lastTasks[0] c.Check(markSeededTask.Kind(), Equals, "mark-seeded") // and mark-seeded must wait for the other tasks prevTasks := tsAll[len(tsAll)-2].Tasks() otherTask := prevTasks[len(prevTasks)-1] c.Check(markSeededTask.WaitTasks(), testutil.Contains, otherTask) } func (s *firstBoot16BaseTest) makeSeedChange(c *C, st *state.State, opts *devicestate.PopulateStateFromSeedOptions, checkTasks func(c *C, tsAll []*state.TaskSet), checkOrder func(c *C, tsAll []*state.TaskSet, snaps ...string)) (*state.Change, *asserts.Model) { coreFname, kernelFname, gadgetFname := s.makeCoreSnaps(c, "") s.WriteAssertions("developer.account", s.devAcct) // put a firstboot snap into the SnapBlobDir snapYaml := `name: foo version: 1.0` fooFname, fooDecl, fooRev := s.MakeAssertedSnap(c, snapYaml, nil, snap.R(128), "developerid") s.WriteAssertions("foo.snap-declaration", fooDecl) s.WriteAssertions("foo.snap-revision", fooRev) // put a firstboot local snap into the SnapBlobDir snapYaml = `name: local version: 1.0` mockSnapFile := snaptest.MakeTestSnapWithFiles(c, snapYaml, nil) targetSnapFile2 := filepath.Join(dirs.SnapSeedDir, "snaps", filepath.Base(mockSnapFile)) err := os.Rename(mockSnapFile, targetSnapFile2) c.Assert(err, IsNil) // add a model assertion and its chain var model *asserts.Model = nil assertsChain := s.makeModelAssertionChain(c, "my-model", nil, "foo") for i, as := range assertsChain { if as.Type() == asserts.ModelType { model = as.(*asserts.Model) } s.WriteAssertions(strconv.Itoa(i), as) } c.Assert(model, NotNil) // create a seed.yaml content := []byte(fmt.Sprintf(` snaps: - name: core file: %s - name: pc-kernel file: %s - name: pc file: %s - name: foo file: %s devmode: true contact: mailto:[email protected] - name: local unasserted: true file: %s `, coreFname, kernelFname, gadgetFname, fooFname, filepath.Base(targetSnapFile2))) err = ioutil.WriteFile(filepath.Join(dirs.SnapSeedDir, "seed.yaml"), content, 0644) c.Assert(err, IsNil) // run the firstboot stuff st.Lock() defer st.Unlock() tsAll, err := devicestate.PopulateStateFromSeedImpl(st, opts, s.perfTimings) c.Assert(err, IsNil) // now run the change and check the result // use the expected kind otherwise settle with start another one chg := st.NewChange("seed", "run the populate from seed changes") for _, ts := range tsAll { chg.AddAll(ts) } c.Assert(st.Changes(), HasLen, 1) checkOrder(c, tsAll, "core", "pc-kernel", "pc", "foo", "local") checkTasks(c, tsAll) // avoid device reg chg1 := st.NewChange("become-operational", "init device") chg1.SetStatus(state.DoingStatus) return chg, model } func (s *firstBoot16Suite) TestPopulateFromSeedHappy(c *C) { bloader := boottest.MockUC16Bootenv(bootloadertest.Mock("mock", c.MkDir())) bootloader.Force(bloader) defer bootloader.Force(nil) bloader.SetBootKernel("pc-kernel_1.snap") bloader.SetBootBase("core_1.snap") st := s.overlord.State() chg, model := s.makeSeedChange(c, st, nil, checkSeedTasks, checkOrder) err := s.overlord.Settle(settleTimeout) c.Assert(err, IsNil) st.Lock() defer st.Unlock() c.Assert(chg.Err(), IsNil) // and check the snap got correctly installed c.Check(osutil.FileExists(filepath.Join(dirs.SnapMountDir, "foo", "128", "meta", "snap.yaml")), Equals, true) c.Check(osutil.FileExists(filepath.Join(dirs.SnapMountDir, "local", "x1", "meta", "snap.yaml")), Equals, true) // verify r, err := os.Open(dirs.SnapStateFile) c.Assert(err, IsNil) state, err := state.ReadState(nil, r) c.Assert(err, IsNil) state.Lock() defer state.Unlock() // check core, kernel, gadget _, err = snapstate.CurrentInfo(state, "core") c.Assert(err, IsNil) _, err = snapstate.CurrentInfo(state, "pc-kernel") c.Assert(err, IsNil) _, err = snapstate.CurrentInfo(state, "pc") c.Assert(err, IsNil) // ensure required flag is set on all essential snaps var snapst snapstate.SnapState for _, reqName := range []string{"core", "pc-kernel", "pc"} { err = snapstate.Get(state, reqName, &snapst) c.Assert(err, IsNil) c.Assert(snapst.Required, Equals, true, Commentf("required not set for %v", reqName)) } // check foo info, err := snapstate.CurrentInfo(state, "foo") c.Assert(err, IsNil) c.Assert(info.SnapID, Equals, "foodidididididididididididididid") c.Assert(info.Revision, Equals, snap.R(128)) c.Assert(info.Contact, Equals, "mailto:[email protected]") pubAcct, err := assertstate.Publisher(st, info.SnapID) c.Assert(err, IsNil) c.Check(pubAcct.AccountID(), Equals, "developerid") err = snapstate.Get(state, "foo", &snapst) c.Assert(err, IsNil) c.Assert(snapst.DevMode, Equals, true) c.Assert(snapst.Required, Equals, true) // check local info, err = snapstate.CurrentInfo(state, "local") c.Assert(err, IsNil) c.Assert(info.SnapID, Equals, "") c.Assert(info.Revision, Equals, snap.R("x1")) var snapst2 snapstate.SnapState err = snapstate.Get(state, "local", &snapst2) c.Assert(err, IsNil) c.Assert(snapst2.Required, Equals, false) // and ensure state is now considered seeded var seeded bool err = state.Get("seeded", &seeded) c.Assert(err, IsNil) c.Check(seeded, Equals, true) // check we set seed-time var seedTime time.Time err = state.Get("seed-time", &seedTime) c.Assert(err, IsNil) c.Check(seedTime.IsZero(), Equals, false) var whatseeded []devicestate.SeededSystem err = state.Get("seeded-systems", &whatseeded) c.Assert(err, IsNil) c.Assert(whatseeded, DeepEquals, []devicestate.SeededSystem{{ System: "", Model: "my-model", BrandID: "my-brand", Revision: model.Revision(), Timestamp: model.Timestamp(), SeedTime: seedTime, }}) } func (s *firstBoot16Suite) TestPopulateFromSeedMissingBootloader(c *C) { st0 := s.overlord.State() st0.Lock() db := assertstate.DB(st0) st0.Unlock() // we run only with the relevant managers to produce the error // situation o := overlord.Mock() st := o.State() snapmgr, err := snapstate.Manager(st, o.TaskRunner()) c.Assert(err, IsNil) o.AddManager(snapmgr) ifacemgr, err := ifacestate.Manager(st, nil, o.TaskRunner(), nil, nil) c.Assert(err, IsNil) o.AddManager(ifacemgr) c.Assert(o.StartUp(), IsNil) hookMgr, err := hookstate.Manager(st, o.TaskRunner()) c.Assert(err, IsNil) _, err = devicestate.Manager(st, hookMgr, o.TaskRunner(), nil) c.Assert(err, IsNil) st.Lock() assertstate.ReplaceDB(st, db.(*asserts.Database)) st.Unlock() o.AddManager(o.TaskRunner()) chg, _ := s.makeSeedChange(c, st, nil, checkSeedTasks, checkOrder) se := o.StateEngine() // we cannot use Settle because the Change will not become Clean // under the subset of managers for i := 0; i < 25 && !chg.IsReady(); i++ { se.Ensure() se.Wait() } st.Lock() defer st.Unlock() c.Assert(chg.Err(), ErrorMatches, `(?s).* cannot determine bootloader.*`) } func (s *firstBoot16Suite) TestPopulateFromSeedHappyMultiAssertsFiles(c *C) { bloader := boottest.MockUC16Bootenv(bootloadertest.Mock("mock", c.MkDir())) bootloader.Force(bloader) defer bootloader.Force(nil) bloader.SetBootKernel("pc-kernel_1.snap") bloader.SetBootBase("core_1.snap") coreFname, kernelFname, gadgetFname := s.makeCoreSnaps(c, "") // put a firstboot snap into the SnapBlobDir snapYaml := `name: foo version: 1.0` fooFname, fooDecl, fooRev := s.MakeAssertedSnap(c, snapYaml, nil, snap.R(128), "developerid") s.WriteAssertions("foo.asserts", s.devAcct, fooRev, fooDecl) // put a 2nd firstboot snap into the SnapBlobDir snapYaml = `name: bar version: 1.0` barFname, barDecl, barRev := s.MakeAssertedSnap(c, snapYaml, nil, snap.R(65), "developerid") s.WriteAssertions("bar.asserts", s.devAcct, barDecl, barRev) // add a model assertion and its chain assertsChain := s.makeModelAssertionChain(c, "my-model", nil) s.WriteAssertions("model.asserts", assertsChain...) // create a seed.yaml content := []byte(fmt.Sprintf(` snaps: - name: core file: %s - name: pc-kernel file: %s - name: pc file: %s - name: foo file: %s - name: bar file: %s `, coreFname, kernelFname, gadgetFname, fooFname, barFname)) err := ioutil.WriteFile(filepath.Join(dirs.SnapSeedDir, "seed.yaml"), content, 0644) c.Assert(err, IsNil) // run the firstboot stuff st := s.overlord.State() st.Lock() defer st.Unlock() tsAll, err := devicestate.PopulateStateFromSeedImpl(st, nil, s.perfTimings) c.Assert(err, IsNil) // use the expected kind otherwise settle with start another one chg := st.NewChange("seed", "run the populate from seed changes") for _, ts := range tsAll { chg.AddAll(ts) } c.Assert(st.Changes(), HasLen, 1) // avoid device reg chg1 := st.NewChange("become-operational", "init device") chg1.SetStatus(state.DoingStatus) st.Unlock() err = s.overlord.Settle(settleTimeout) st.Lock() c.Assert(chg.Err(), IsNil) c.Assert(err, IsNil) // and check the snap got correctly installed c.Check(osutil.FileExists(filepath.Join(dirs.SnapMountDir, "foo", "128", "meta", "snap.yaml")), Equals, true) // and check the snap got correctly installed c.Check(osutil.FileExists(filepath.Join(dirs.SnapMountDir, "bar", "65", "meta", "snap.yaml")), Equals, true) // verify r, err := os.Open(dirs.SnapStateFile) c.Assert(err, IsNil) state, err := state.ReadState(nil, r) c.Assert(err, IsNil) state.Lock() defer state.Unlock() // check foo info, err := snapstate.CurrentInfo(state, "foo") c.Assert(err, IsNil) c.Check(info.SnapID, Equals, "foodidididididididididididididid") c.Check(info.Revision, Equals, snap.R(128)) pubAcct, err := assertstate.Publisher(st, info.SnapID) c.Assert(err, IsNil) c.Check(pubAcct.AccountID(), Equals, "developerid") // check bar info, err = snapstate.CurrentInfo(state, "bar") c.Assert(err, IsNil) c.Check(info.SnapID, Equals, "bardidididididididididididididid") c.Check(info.Revision, Equals, snap.R(65)) pubAcct, err = assertstate.Publisher(st, info.SnapID) c.Assert(err, IsNil) c.Check(pubAcct.AccountID(), Equals, "developerid") } func (s *firstBoot16Suite) TestPopulateFromSeedConfigureHappy(c *C) { bloader := boottest.MockUC16Bootenv(bootloadertest.Mock("mock", c.MkDir())) bootloader.Force(bloader) defer bootloader.Force(nil) bloader.SetBootKernel("pc-kernel_1.snap") bloader.SetBootBase("core_1.snap") const defaultsYaml = ` defaults: foodidididididididididididididid: foo-cfg: foo. 99T7MUlRhtI3U0QFgl5mXXESAiSwt776: # core core-cfg: core_cfg_defl pckernelidididididididididididid: pc-kernel-cfg: pc-kernel_cfg_defl pcididididididididididididididid: pc-cfg: pc_cfg_defl ` coreFname, kernelFname, gadgetFname := s.makeCoreSnaps(c, defaultsYaml) s.WriteAssertions("developer.account", s.devAcct) // put a firstboot snap into the SnapBlobDir files := [][]string{{"meta/hooks/configure", ""}} snapYaml := `name: foo version: 1.0` fooFname, fooDecl, fooRev := s.MakeAssertedSnap(c, snapYaml, files, snap.R(128), "developerid") s.WriteAssertions("foo.asserts", fooDecl, fooRev) // add a model assertion and its chain assertsChain := s.makeModelAssertionChain(c, "my-model", nil, "foo") s.WriteAssertions("model.asserts", assertsChain...) // create a seed.yaml content := []byte(fmt.Sprintf(` snaps: - name: core file: %s - name: pc-kernel file: %s - name: pc file: %s - name: foo file: %s `, coreFname, kernelFname, gadgetFname, fooFname)) err := ioutil.WriteFile(filepath.Join(dirs.SnapSeedDir, "seed.yaml"), content, 0644) c.Assert(err, IsNil) // run the firstboot stuff st := s.overlord.State() st.Lock() defer st.Unlock() tsAll, err := devicestate.PopulateStateFromSeedImpl(st, nil, s.perfTimings) c.Assert(err, IsNil) checkSeedTasks(c, tsAll) // now run the change and check the result // use the expected kind otherwise settle with start another one chg := st.NewChange("seed", "run the populate from seed changes") for _, ts := range tsAll { chg.AddAll(ts) } c.Assert(st.Changes(), HasLen, 1) var configured []string hookInvoke := func(ctx *hookstate.Context, tomb *tomb.Tomb) ([]byte, error) { ctx.Lock() defer ctx.Unlock() // we have a gadget at this point(s) ok, err := snapstate.HasSnapOfType(st, snap.TypeGadget) c.Check(err, IsNil) c.Check(ok, Equals, true) configured = append(configured, ctx.InstanceName()) return nil, nil } rhk := hookstate.MockRunHook(hookInvoke) defer rhk() // ensure we have something that captures the core config restore := configstate.MockConfigcoreRun(func(config.Conf) error { configured = append(configured, "configcore") return nil }) defer restore() // avoid device reg chg1 := st.NewChange("become-operational", "init device") chg1.SetStatus(state.DoingStatus) st.Unlock() err = s.overlord.Settle(settleTimeout) st.Lock() c.Assert(chg.Err(), IsNil) c.Assert(err, IsNil) // and check the snap got correctly installed c.Check(osutil.FileExists(filepath.Join(dirs.SnapMountDir, "foo", "128", "meta", "snap.yaml")), Equals, true) // verify r, err := os.Open(dirs.SnapStateFile) c.Assert(err, IsNil) state, err := state.ReadState(nil, r) c.Assert(err, IsNil) state.Lock() defer state.Unlock() tr := config.NewTransaction(state) var val string // check core, kernel, gadget _, err = snapstate.CurrentInfo(state, "core") c.Assert(err, IsNil) err = tr.Get("core", "core-cfg", &val) c.Assert(err, IsNil) c.Check(val, Equals, "core_cfg_defl") _, err = snapstate.CurrentInfo(state, "pc-kernel") c.Assert(err, IsNil) err = tr.Get("pc-kernel", "pc-kernel-cfg", &val) c.Assert(err, IsNil) c.Check(val, Equals, "pc-kernel_cfg_defl") _, err = snapstate.CurrentInfo(state, "pc") c.Assert(err, IsNil) err = tr.Get("pc", "pc-cfg", &val) c.Assert(err, IsNil) c.Check(val, Equals, "pc_cfg_defl") // check foo info, err := snapstate.CurrentInfo(state, "foo") c.Assert(err, IsNil) c.Assert(info.SnapID, Equals, "foodidididididididididididididid") c.Assert(info.Revision, Equals, snap.R(128)) pubAcct, err := assertstate.Publisher(st, info.SnapID) c.Assert(err, IsNil) c.Check(pubAcct.AccountID(), Equals, "developerid") // check foo config err = tr.Get("foo", "foo-cfg", &val) c.Assert(err, IsNil) c.Check(val, Equals, "foo.") c.Check(configured, DeepEquals, []string{"configcore", "pc-kernel", "pc", "foo"}) // and ensure state is now considered seeded var seeded bool err = state.Get("seeded", &seeded) c.Assert(err, IsNil) c.Check(seeded, Equals, true) } func (s *firstBoot16Suite) TestPopulateFromSeedGadgetConnectHappy(c *C) { bloader := boottest.MockUC16Bootenv(bootloadertest.Mock("mock", c.MkDir())) bootloader.Force(bloader) defer bootloader.Force(nil) bloader.SetBootKernel("pc-kernel_1.snap") bloader.SetBootBase("core_1.snap") const connectionsYaml = ` connections: - plug: foodidididididididididididididid:network-control ` coreFname, kernelFname, gadgetFname := s.makeCoreSnaps(c, connectionsYaml) s.WriteAssertions("developer.account", s.devAcct) snapYaml := `name: foo version: 1.0 plugs: network-control: ` fooFname, fooDecl, fooRev := s.MakeAssertedSnap(c, snapYaml, nil, snap.R(128), "developerid") s.WriteAssertions("foo.asserts", fooDecl, fooRev) // add a model assertion and its chain assertsChain := s.makeModelAssertionChain(c, "my-model", nil, "foo") s.WriteAssertions("model.asserts", assertsChain...) // create a seed.yaml content := []byte(fmt.Sprintf(` snaps: - name: core file: %s - name: pc-kernel file: %s - name: pc file: %s - name: foo file: %s `, coreFname, kernelFname, gadgetFname, fooFname)) err := ioutil.WriteFile(filepath.Join(dirs.SnapSeedDir, "seed.yaml"), content, 0644) c.Assert(err, IsNil) // run the firstboot stuff st := s.overlord.State() st.Lock() defer st.Unlock() tsAll, err := devicestate.PopulateStateFromSeedImpl(st, nil, s.perfTimings) c.Assert(err, IsNil) checkSeedTasks(c, tsAll) // now run the change and check the result // use the expected kind otherwise settle with start another one chg := st.NewChange("seed", "run the populate from seed changes") for _, ts := range tsAll { chg.AddAll(ts) } c.Assert(st.Changes(), HasLen, 1) // avoid device reg chg1 := st.NewChange("become-operational", "init device") chg1.SetStatus(state.DoingStatus) st.Unlock() err = s.overlord.Settle(settleTimeout) st.Lock() c.Assert(chg.Err(), IsNil) c.Assert(err, IsNil) // and check the snap got correctly installed c.Check(osutil.FileExists(filepath.Join(dirs.SnapMountDir, "foo", "128", "meta", "snap.yaml")), Equals, true) // verify r, err := os.Open(dirs.SnapStateFile) c.Assert(err, IsNil) state, err := state.ReadState(nil, r) c.Assert(err, IsNil) state.Lock() defer state.Unlock() // check foo info, err := snapstate.CurrentInfo(state, "foo") c.Assert(err, IsNil) c.Assert(info.SnapID, Equals, "foodidididididididididididididid") c.Assert(info.Revision, Equals, snap.R(128)) pubAcct, err := assertstate.Publisher(st, info.SnapID) c.Assert(err, IsNil) c.Check(pubAcct.AccountID(), Equals, "developerid") // check connection var conns map[string]interface{} err = state.Get("conns", &conns) c.Assert(err, IsNil) c.Check(conns, HasLen, 1) c.Check(conns, DeepEquals, map[string]interface{}{ "foo:network-control core:network-control": map[string]interface{}{ "interface": "network-control", "auto": true, "by-gadget": true, }, }) // and ensure state is now considered seeded var seeded bool err = state.Get("seeded", &seeded) c.Assert(err, IsNil) c.Check(seeded, Equals, true) } func (s *firstBoot16Suite) TestImportAssertionsFromSeedClassicModelMismatch(c *C) { restore := release.MockOnClassic(true) defer restore() ovld, err := overlord.New(nil) c.Assert(err, IsNil) st := ovld.State() // add the odel assertion and its chain assertsChain := s.makeModelAssertionChain(c, "my-model", nil) s.WriteAssertions("model.asserts", assertsChain...) // import them st.Lock() defer st.Unlock() deviceSeed, err := seed.Open(dirs.SnapSeedDir, "") c.Assert(err, IsNil) _, err = devicestate.ImportAssertionsFromSeed(st, deviceSeed) c.Assert(err, ErrorMatches, "cannot seed a classic system with an all-snaps model") } func (s *firstBoot16Suite) TestImportAssertionsFromSeedAllSnapsModelMismatch(c *C) { ovld, err := overlord.New(nil) c.Assert(err, IsNil) st := ovld.State() // add the model assertion and its chain assertsChain := s.makeModelAssertionChain(c, "my-model-classic", nil) s.WriteAssertions("model.asserts", assertsChain...) // import them st.Lock() defer st.Unlock() deviceSeed, err := seed.Open(dirs.SnapSeedDir, "") c.Assert(err, IsNil) _, err = devicestate.ImportAssertionsFromSeed(st, deviceSeed) c.Assert(err, ErrorMatches, "cannot seed an all-snaps system with a classic model") } func (s *firstBoot16Suite) TestImportAssertionsFromSeedHappy(c *C) { ovld, err := overlord.New(nil) c.Assert(err, IsNil) st := ovld.State() // add a bunch of assertions (model assertion and its chain) assertsChain := s.makeModelAssertionChain(c, "my-model", nil) for i, as := range assertsChain { fname := strconv.Itoa(i) if as.Type() == asserts.ModelType { fname = "model" } s.WriteAssertions(fname, as) } // import them st.Lock() defer st.Unlock() deviceSeed, err := seed.Open(dirs.SnapSeedDir, "") c.Assert(err, IsNil) model, err := devicestate.ImportAssertionsFromSeed(st, deviceSeed) c.Assert(err, IsNil) c.Assert(model, NotNil) // verify that the model was added db := assertstate.DB(st) as, err := db.Find(asserts.ModelType, map[string]string{ "series": "16", "brand-id": "my-brand", "model": "my-model", }) c.Assert(err, IsNil) _, ok := as.(*asserts.Model) c.Check(ok, Equals, true) ds, err := devicestatetest.Device(st) c.Assert(err, IsNil) c.Check(ds.Brand, Equals, "my-brand") c.Check(ds.Model, Equals, "my-model") c.Check(model.BrandID(), Equals, "my-brand") c.Check(model.Model(), Equals, "my-model") } func (s *firstBoot16Suite) TestImportAssertionsFromSeedMissingSig(c *C) { st := s.overlord.State() st.Lock() defer st.Unlock() // write out only the model assertion assertsChain := s.makeModelAssertionChain(c, "my-model", nil) for _, as := range assertsChain { if as.Type() == asserts.ModelType { s.WriteAssertions("model", as) break } } deviceSeed, err := seed.Open(dirs.SnapSeedDir, "") c.Assert(err, IsNil) // try import and verify that its rejects because other assertions are // missing _, err = devicestate.ImportAssertionsFromSeed(st, deviceSeed) c.Assert(err, ErrorMatches, "cannot resolve prerequisite assertion: account-key .*") } func (s *firstBoot16Suite) TestImportAssertionsFromSeedTwoModelAsserts(c *C) { st := s.overlord.State() st.Lock() defer st.Unlock() // write out two model assertions model := s.Brands.Model("my-brand", "my-model", modelHeaders("my-model")) s.WriteAssertions("model", model) model2 := s.Brands.Model("my-brand", "my-second-model", modelHeaders("my-second-model")) s.WriteAssertions("model2", model2) deviceSeed, err := seed.Open(dirs.SnapSeedDir, "") c.Assert(err, IsNil) // try import and verify that its rejects because other assertions are // missing _, err = devicestate.ImportAssertionsFromSeed(st, deviceSeed) c.Assert(err, ErrorMatches, "cannot have multiple model assertions in seed") } func (s *firstBoot16Suite) TestImportAssertionsFromSeedNoModelAsserts(c *C) { st := s.overlord.State() st.Lock() defer st.Unlock() assertsChain := s.makeModelAssertionChain(c, "my-model", nil) for i, as := range assertsChain { if as.Type() != asserts.ModelType { s.WriteAssertions(strconv.Itoa(i), as) } } deviceSeed, err := seed.Open(dirs.SnapSeedDir, "") c.Assert(err, IsNil) // try import and verify that its rejects because other assertions are // missing _, err = devicestate.ImportAssertionsFromSeed(st, deviceSeed) c.Assert(err, ErrorMatches, "seed must have a model assertion") } type core18SnapsOpts struct { classic bool gadget bool } func (s *firstBoot16BaseTest) makeCore18Snaps(c *C, opts *core18SnapsOpts) (core18Fn, snapdFn, kernelFn, gadgetFn string) { if opts == nil { opts = &core18SnapsOpts{} } files := [][]string{} core18Yaml := `name: core18 version: 1.0 type: base` core18Fname, core18Decl, core18Rev := s.MakeAssertedSnap(c, core18Yaml, files, snap.R(1), "canonical") s.WriteAssertions("core18.asserts", core18Rev, core18Decl) snapdYaml := `name: snapd version: 1.0 ` snapdFname, snapdDecl, snapdRev := s.MakeAssertedSnap(c, snapdYaml, nil, snap.R(2), "canonical") s.WriteAssertions("snapd.asserts", snapdRev, snapdDecl) var kernelFname string if !opts.classic { kernelYaml := `name: pc-kernel version: 1.0 type: kernel` fname, kernelDecl, kernelRev := s.MakeAssertedSnap(c, kernelYaml, files, snap.R(1), "canonical") s.WriteAssertions("kernel.asserts", kernelRev, kernelDecl) kernelFname = fname } if !opts.classic { gadgetYaml := ` volumes: volume-id: bootloader: grub ` files = append(files, []string{"meta/gadget.yaml", gadgetYaml}) } var gadgetFname string if !opts.classic || opts.gadget { gaYaml := `name: pc version: 1.0 type: gadget base: core18 ` fname, gadgetDecl, gadgetRev := s.MakeAssertedSnap(c, gaYaml, files, snap.R(1), "canonical") s.WriteAssertions("gadget.asserts", gadgetRev, gadgetDecl) gadgetFname = fname } return core18Fname, snapdFname, kernelFname, gadgetFname } func (s *firstBoot16Suite) TestPopulateFromSeedWithBaseHappy(c *C) { var sysdLog [][]string systemctlRestorer := systemd.MockSystemctl(func(cmd ...string) ([]byte, error) { sysdLog = append(sysdLog, cmd) return []byte("ActiveState=inactive\n"), nil }) defer systemctlRestorer() bloader := boottest.MockUC16Bootenv(bootloadertest.Mock("mock", c.MkDir())) bootloader.Force(bloader) defer bootloader.Force(nil) bloader.SetBootKernel("pc-kernel_1.snap") bloader.SetBootBase("core18_1.snap") core18Fname, snapdFname, kernelFname, gadgetFname := s.makeCore18Snaps(c, nil) s.WriteAssertions("developer.account", s.devAcct) // add a model assertion and its chain assertsChain := s.makeModelAssertionChain(c, "my-model", map[string]interface{}{"base": "core18"}) s.WriteAssertions("model.asserts", assertsChain...) // create a seed.yaml content := []byte(fmt.Sprintf(` snaps: - name: snapd file: %s - name: core18 file: %s - name: pc-kernel file: %s - name: pc file: %s `, snapdFname, core18Fname, kernelFname, gadgetFname)) err := ioutil.WriteFile(filepath.Join(dirs.SnapSeedDir, "seed.yaml"), content, 0644) c.Assert(err, IsNil) // run the firstboot stuff st := s.overlord.State() st.Lock() defer st.Unlock() tsAll, err := devicestate.PopulateStateFromSeedImpl(st, nil, s.perfTimings) c.Assert(err, IsNil) checkOrder(c, tsAll, "snapd", "pc-kernel", "core18", "pc") // now run the change and check the result // use the expected kind otherwise settle with start another one chg := st.NewChange("seed", "run the populate from seed changes") for _, ts := range tsAll { chg.AddAll(ts) } c.Assert(st.Changes(), HasLen, 1) c.Assert(chg.Err(), IsNil) // avoid device reg chg1 := st.NewChange("become-operational", "init device") chg1.SetStatus(state.DoingStatus) // run change until it wants to restart st.Unlock() err = s.overlord.Settle(settleTimeout) st.Lock() c.Assert(err, IsNil) // at this point the system is "restarting", pretend the restart has // happened c.Assert(chg.Status(), Equals, state.DoingStatus) state.MockRestarting(st, state.RestartUnset) st.Unlock() err = s.overlord.Settle(settleTimeout) st.Lock() c.Assert(err, IsNil) c.Assert(chg.Status(), Equals, state.DoneStatus) // verify r, err := os.Open(dirs.SnapStateFile) c.Assert(err, IsNil) state, err := state.ReadState(nil, r) c.Assert(err, IsNil) state.Lock() defer state.Unlock() // check snapd, core18, kernel, gadget _, err = snapstate.CurrentInfo(state, "snapd") c.Check(err, IsNil) _, err = snapstate.CurrentInfo(state, "core18") c.Check(err, IsNil) _, err = snapstate.CurrentInfo(state, "pc-kernel") c.Check(err, IsNil) _, err = snapstate.CurrentInfo(state, "pc") c.Check(err, IsNil) // ensure required flag is set on all essential snaps var snapst snapstate.SnapState for _, reqName := range []string{"snapd", "core18", "pc-kernel", "pc"} { err = snapstate.Get(state, reqName, &snapst) c.Assert(err, IsNil) c.Assert(snapst.Required, Equals, true, Commentf("required not set for %v", reqName)) } // the right systemd commands were run c.Check(sysdLog, testutil.DeepContains, []string{"start", "usr-lib-snapd.mount"}) // and ensure state is now considered seeded var seeded bool err = state.Get("seeded", &seeded) c.Assert(err, IsNil) c.Check(seeded, Equals, true) // check we set seed-time var seedTime time.Time err = state.Get("seed-time", &seedTime) c.Assert(err, IsNil) c.Check(seedTime.IsZero(), Equals, false) } func (s *firstBoot16Suite) TestPopulateFromSeedOrdering(c *C) { s.WriteAssertions("developer.account", s.devAcct) // add a model assertion and its chain assertsChain := s.makeModelAssertionChain(c, "my-model", map[string]interface{}{"base": "core18"}) s.WriteAssertions("model.asserts", assertsChain...) core18Fname, snapdFname, kernelFname, gadgetFname := s.makeCore18Snaps(c, nil) snapYaml := `name: snap-req-other-base version: 1.0 base: other-base ` snapFname, snapDecl, snapRev := s.MakeAssertedSnap(c, snapYaml, nil, snap.R(128), "developerid") s.WriteAssertions("snap-req-other-base.asserts", s.devAcct, snapRev, snapDecl) baseYaml := `name: other-base version: 1.0 type: base ` baseFname, baseDecl, baseRev := s.MakeAssertedSnap(c, baseYaml, nil, snap.R(127), "developerid") s.WriteAssertions("other-base.asserts", s.devAcct, baseRev, baseDecl) // create a seed.yaml content := []byte(fmt.Sprintf(` snaps: - name: snapd file: %s - name: core18 file: %s - name: pc-kernel file: %s - name: pc file: %s - name: snap-req-other-base file: %s - name: other-base file: %s `, snapdFname, core18Fname, kernelFname, gadgetFname, snapFname, baseFname)) err := ioutil.WriteFile(filepath.Join(dirs.SnapSeedDir, "seed.yaml"), content, 0644) c.Assert(err, IsNil) // run the firstboot stuff st := s.overlord.State() st.Lock() defer st.Unlock() tsAll, err := devicestate.PopulateStateFromSeedImpl(st, nil, s.perfTimings) c.Assert(err, IsNil) checkOrder(c, tsAll, "snapd", "pc-kernel", "core18", "pc", "other-base", "snap-req-other-base") } func (s *firstBoot16Suite) TestFirstbootGadgetBaseModelBaseMismatch(c *C) { s.WriteAssertions("developer.account", s.devAcct) // add a model assertion and its chain assertsChain := s.makeModelAssertionChain(c, "my-model", map[string]interface{}{"base": "core18"}) s.WriteAssertions("model.asserts", assertsChain...) core18Fname, snapdFname, kernelFname, _ := s.makeCore18Snaps(c, nil) // take the gadget without "base: core18" _, _, gadgetFname := s.makeCoreSnaps(c, "") // create a seed.yaml content := []byte(fmt.Sprintf(` snaps: - name: snapd file: %s - name: core18 file: %s - name: pc-kernel file: %s - name: pc file: %s `, snapdFname, core18Fname, kernelFname, gadgetFname)) err := ioutil.WriteFile(filepath.Join(dirs.SnapSeedDir, "seed.yaml"), content, 0644) c.Assert(err, IsNil) // run the firstboot stuff st := s.overlord.State() st.Lock() defer st.Unlock() _, err = devicestate.PopulateStateFromSeedImpl(st, nil, s.perfTimings) c.Assert(err, ErrorMatches, `cannot use gadget snap because its base "core" is different from model base "core18"`) // note, cannot use st.Tasks() here as it filters out tasks with no change c.Check(st.TaskCount(), Equals, 0) } func (s *firstBoot16Suite) TestPopulateFromSeedWrongContentProviderOrder(c *C) { bloader := boottest.MockUC16Bootenv(bootloadertest.Mock("mock", c.MkDir())) bootloader.Force(bloader) defer bootloader.Force(nil) bloader.SetBootKernel("pc-kernel_1.snap") bloader.SetBootBase("core_1.snap") coreFname, kernelFname, gadgetFname := s.makeCoreSnaps(c, "") // a snap that uses content providers snapYaml := `name: gnome-calculator version: 1.0 plugs: gtk-3-themes: interface: content default-provider: gtk-common-themes target: $SNAP/data-dir/themes ` calcFname, calcDecl, calcRev := s.MakeAssertedSnap(c, snapYaml, nil, snap.R(128), "developerid") s.WriteAssertions("calc.asserts", s.devAcct, calcRev, calcDecl) // put a 2nd firstboot snap into the SnapBlobDir snapYaml = `name: gtk-common-themes version: 1.0 slots: gtk-3-themes: interface: content source: read: - $SNAP/share/themes/Adawaita ` themesFname, themesDecl, themesRev := s.MakeAssertedSnap(c, snapYaml, nil, snap.R(65), "developerid") s.WriteAssertions("themes.asserts", s.devAcct, themesDecl, themesRev) // add a model assertion and its chain assertsChain := s.makeModelAssertionChain(c, "my-model", nil) s.WriteAssertions("model.asserts", assertsChain...) // create a seed.yaml content := []byte(fmt.Sprintf(` snaps: - name: core file: %s - name: pc-kernel file: %s - name: pc file: %s - name: gnome-calculator file: %s - name: gtk-common-themes file: %s `, coreFname, kernelFname, gadgetFname, calcFname, themesFname)) err := ioutil.WriteFile(filepath.Join(dirs.SnapSeedDir, "seed.yaml"), content, 0644) c.Assert(err, IsNil) // run the firstboot stuff st := s.overlord.State() st.Lock() defer st.Unlock() tsAll, err := devicestate.PopulateStateFromSeedImpl(st, nil, s.perfTimings) c.Assert(err, IsNil) // use the expected kind otherwise settle with start another one chg := st.NewChange("seed", "run the populate from seed changes") for _, ts := range tsAll { chg.AddAll(ts) } c.Assert(st.Changes(), HasLen, 1) // avoid device reg chg1 := st.NewChange("become-operational", "init device") chg1.SetStatus(state.DoingStatus) st.Unlock() err = s.overlord.Settle(settleTimeout) st.Lock() c.Assert(chg.Err(), IsNil) c.Assert(err, IsNil) // verify the result var conns map[string]interface{} err = st.Get("conns", &conns) c.Assert(err, IsNil) c.Check(conns, HasLen, 1) conn, hasConn := conns["gnome-calculator:gtk-3-themes gtk-common-themes:gtk-3-themes"] c.Check(hasConn, Equals, true) c.Check(conn.(map[string]interface{})["auto"], Equals, true) c.Check(conn.(map[string]interface{})["interface"], Equals, "content") } func (s *firstBoot16Suite) TestPopulateFromSeedMissingBase(c *C) { s.WriteAssertions("developer.account", s.devAcct) // add a model assertion and its chain assertsChain := s.makeModelAssertionChain(c, "my-model", nil) s.WriteAssertions("model.asserts", assertsChain...) coreFname, kernelFname, gadgetFname := s.makeCoreSnaps(c, "") // TODO: this test doesn't particularly need to use a local snap // local snap with unknown base snapYaml = `name: local base: foo version: 1.0` mockSnapFile := snaptest.MakeTestSnapWithFiles(c, snapYaml, nil) localFname := filepath.Base(mockSnapFile) targetSnapFile2 := filepath.Join(dirs.SnapSeedDir, "snaps", localFname) c.Assert(os.Rename(mockSnapFile, targetSnapFile2), IsNil) // create a seed.yaml content := []byte(fmt.Sprintf(` snaps: - name: core file: %s - name: pc-kernel file: %s - name: pc file: %s - name: local unasserted: true file: %s `, coreFname, kernelFname, gadgetFname, localFname)) c.Assert(ioutil.WriteFile(filepath.Join(dirs.SnapSeedDir, "seed.yaml"), content, 0644), IsNil) // run the firstboot stuff st := s.overlord.State() st.Lock() defer st.Unlock() _, err := devicestate.PopulateStateFromSeedImpl(st, nil, s.perfTimings) c.Assert(err, ErrorMatches, `cannot use snap "local": base "foo" is missing`) } func (s *firstBoot16Suite) TestPopulateFromSeedOnClassicWithSnapdOnlyHappy(c *C) { restore := release.MockOnClassic(true) defer restore() var sysdLog [][]string systemctlRestorer := systemd.MockSystemctl(func(cmd ...string) ([]byte, error) { sysdLog = append(sysdLog, cmd) return []byte("ActiveState=inactive\n"), nil }) defer systemctlRestorer() core18Fname, snapdFname, _, _ := s.makeCore18Snaps(c, &core18SnapsOpts{ classic: true, }) // put a firstboot snap into the SnapBlobDir snapYaml := `name: foo version: 1.0 base: core18 ` fooFname, fooDecl, fooRev := s.MakeAssertedSnap(c, snapYaml, nil, snap.R(128), "developerid") s.WriteAssertions("foo.asserts", s.devAcct, fooRev, fooDecl) // add a model assertion and its chain assertsChain := s.makeModelAssertionChain(c, "my-model-classic", nil) s.WriteAssertions("model.asserts", assertsChain...) // create a seed.yaml content := []byte(fmt.Sprintf(` snaps: - name: snapd file: %s - name: foo file: %s - name: core18 file: %s `, snapdFname, fooFname, core18Fname)) err := ioutil.WriteFile(filepath.Join(dirs.SnapSeedDir, "seed.yaml"), content, 0644) c.Assert(err, IsNil) // run the firstboot stuff st := s.overlord.State() st.Lock() defer st.Unlock() tsAll, err := devicestate.PopulateStateFromSeedImpl(st, nil, s.perfTimings) c.Assert(err, IsNil) checkOrder(c, tsAll, "snapd", "core18", "foo") // now run the change and check the result // use the expected kind otherwise settle with start another one chg := st.NewChange("seed", "run the populate from seed changes") for _, ts := range tsAll { chg.AddAll(ts) } c.Assert(st.Changes(), HasLen, 1) c.Assert(chg.Err(), IsNil) // avoid device reg chg1 := st.NewChange("become-operational", "init device") chg1.SetStatus(state.DoingStatus) // run change until it wants to restart st.Unlock() err = s.overlord.Settle(settleTimeout) st.Lock() c.Assert(err, IsNil) // at this point the system is "restarting", pretend the restart has // happened c.Assert(chg.Status(), Equals, state.DoingStatus) state.MockRestarting(st, state.RestartUnset) st.Unlock() err = s.overlord.Settle(settleTimeout) st.Lock() c.Assert(err, IsNil) c.Assert(chg.Status(), Equals, state.DoneStatus) // verify r, err := os.Open(dirs.SnapStateFile) c.Assert(err, IsNil) state, err := state.ReadState(nil, r) c.Assert(err, IsNil) state.Lock() defer state.Unlock() // check snapd, core18, kernel, gadget _, err = snapstate.CurrentInfo(state, "snapd") c.Check(err, IsNil) _, err = snapstate.CurrentInfo(state, "core18") c.Check(err, IsNil) _, err = snapstate.CurrentInfo(state, "foo") c.Check(err, IsNil) // and ensure state is now considered seeded var seeded bool err = state.Get("seeded", &seeded) c.Assert(err, IsNil) c.Check(seeded, Equals, true) // check we set seed-time var seedTime time.Time err = state.Get("seed-time", &seedTime) c.Assert(err, IsNil) c.Check(seedTime.IsZero(), Equals, false) } func (s *firstBoot16Suite) TestPopulateFromSeedMissingAssertions(c *C) { restore := release.MockOnClassic(true) defer restore() core18Fname, snapdFname, _, _ := s.makeCore18Snaps(c, &core18SnapsOpts{}) // create a seed.yaml content := []byte(fmt.Sprintf(` snaps: - name: snapd file: %s - name: core18 file: %s `, snapdFname, core18Fname)) err := ioutil.WriteFile(filepath.Join(dirs.SnapSeedDir, "seed.yaml"), content, 0644) c.Assert(err, IsNil) // run the firstboot stuff st := s.overlord.State() st.Lock() defer st.Unlock() _, err = devicestate.PopulateStateFromSeedImpl(st, nil, s.perfTimings) c.Assert(err, NotNil) // note, cannot use st.Tasks() here as it filters out tasks with no change c.Check(st.TaskCount(), Equals, 0) } func (s *firstBoot16Suite) TestPopulateFromSeedOnClassicWithSnapdOnlyAndGadgetHappy(c *C) { restore := release.MockOnClassic(true) defer restore() var sysdLog [][]string systemctlRestorer := systemd.MockSystemctl(func(cmd ...string) ([]byte, error) { sysdLog = append(sysdLog, cmd) return []byte("ActiveState=inactive\n"), nil }) defer systemctlRestorer() core18Fname, snapdFname, _, gadgetFname := s.makeCore18Snaps(c, &core18SnapsOpts{ classic: true, gadget: true, }) // put a firstboot snap into the SnapBlobDir snapYaml := `name: foo version: 1.0 base: core18 ` fooFname, fooDecl, fooRev := s.MakeAssertedSnap(c, snapYaml, nil, snap.R(128), "developerid") s.WriteAssertions("foo.asserts", s.devAcct, fooRev, fooDecl) // add a model assertion and its chain assertsChain := s.makeModelAssertionChain(c, "my-model-classic", map[string]interface{}{"gadget": "pc"}) s.WriteAssertions("model.asserts", assertsChain...) // create a seed.yaml content := []byte(fmt.Sprintf(` snaps: - name: snapd file: %s - name: foo file: %s - name: core18 file: %s - name: pc file: %s `, snapdFname, fooFname, core18Fname, gadgetFname)) err := ioutil.WriteFile(filepath.Join(dirs.SnapSeedDir, "seed.yaml"), content, 0644) c.Assert(err, IsNil) // run the firstboot stuff st := s.overlord.State() st.Lock() defer st.Unlock() tsAll, err := devicestate.PopulateStateFromSeedImpl(st, nil, s.perfTimings) c.Assert(err, IsNil) checkOrder(c, tsAll, "snapd", "core18", "pc", "foo") // now run the change and check the result // use the expected kind otherwise settle with start another one chg := st.NewChange("seed", "run the populate from seed changes") for _, ts := range tsAll { chg.AddAll(ts) } c.Assert(st.Changes(), HasLen, 1) c.Assert(chg.Err(), IsNil) // avoid device reg chg1 := st.NewChange("become-operational", "init device") chg1.SetStatus(state.DoingStatus) // run change until it wants to restart st.Unlock() err = s.overlord.Settle(settleTimeout) st.Lock() c.Assert(err, IsNil) // at this point the system is "restarting", pretend the restart has // happened c.Assert(chg.Status(), Equals, state.DoingStatus) state.MockRestarting(st, state.RestartUnset) st.Unlock() err = s.overlord.Settle(settleTimeout) st.Lock() c.Assert(err, IsNil) c.Assert(chg.Status(), Equals, state.DoneStatus, Commentf("%s", chg.Err())) // verify r, err := os.Open(dirs.SnapStateFile) c.Assert(err, IsNil) state, err := state.ReadState(nil, r) c.Assert(err, IsNil) state.Lock() defer state.Unlock() // check snapd, core18, kernel, gadget _, err = snapstate.CurrentInfo(state, "snapd") c.Check(err, IsNil) _, err = snapstate.CurrentInfo(state, "core18") c.Check(err, IsNil) _, err = snapstate.CurrentInfo(state, "pc") c.Check(err, IsNil) _, err = snapstate.CurrentInfo(state, "foo") c.Check(err, IsNil) // and ensure state is now considered seeded var seeded bool err = state.Get("seeded", &seeded) c.Assert(err, IsNil) c.Check(seeded, Equals, true) // check we set seed-time var seedTime time.Time err = state.Get("seed-time", &seedTime) c.Assert(err, IsNil) c.Check(seedTime.IsZero(), Equals, false) } func (s *firstBoot16Suite) TestCriticalTaskEdgesForPreseed(c *C) { st := s.overlord.State() st.Lock() defer st.Unlock() t1 := st.NewTask("task1", "") t2 := st.NewTask("task2", "") t3 := st.NewTask("task2", "") ts := state.NewTaskSet(t1, t2, t3) ts.MarkEdge(t1, snapstate.BeginEdge) ts.MarkEdge(t2, snapstate.BeforeHooksEdge) ts.MarkEdge(t3, snapstate.HooksEdge) beginEdge, beforeHooksEdge, hooksEdge, err := devicestate.CriticalTaskEdges(ts) c.Assert(err, IsNil) c.Assert(beginEdge, NotNil) c.Assert(beforeHooksEdge, NotNil) c.Assert(hooksEdge, NotNil) c.Check(beginEdge.Kind(), Equals, "task1") c.Check(beforeHooksEdge.Kind(), Equals, "task2") c.Check(hooksEdge.Kind(), Equals, "task2") } func (s *firstBoot16Suite) TestCriticalTaskEdgesForPreseedMissing(c *C) { st := s.overlord.State() st.Lock() defer st.Unlock() t1 := st.NewTask("task1", "") t2 := st.NewTask("task2", "") t3 := st.NewTask("task2", "") ts := state.NewTaskSet(t1, t2, t3) ts.MarkEdge(t1, snapstate.BeginEdge) _, _, _, err := devicestate.CriticalTaskEdges(ts) c.Assert(err, NotNil) ts = state.NewTaskSet(t1, t2, t3) ts.MarkEdge(t1, snapstate.BeginEdge) ts.MarkEdge(t2, snapstate.BeforeHooksEdge) _, _, _, err = devicestate.CriticalTaskEdges(ts) c.Assert(err, NotNil) ts = state.NewTaskSet(t1, t2, t3) ts.MarkEdge(t1, snapstate.BeginEdge) ts.MarkEdge(t3, snapstate.HooksEdge) _, _, _, err = devicestate.CriticalTaskEdges(ts) c.Assert(err, NotNil) }
gpl-3.0
pts-eduardoacuna/pachy-learning
vendor/gonum.org/v1/gonum/mat/eigen_test.go
3852
// Copyright ©2013 The gonum Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package mat import ( "math/rand" "testing" "gonum.org/v1/gonum/floats" ) func TestEigen(t *testing.T) { for i, test := range []struct { a *Dense values []complex128 left *Dense right *Dense }{ { a: NewDense(3, 3, []float64{ 1, 0, 0, 0, 1, 0, 0, 0, 1, }), values: []complex128{1, 1, 1}, left: NewDense(3, 3, []float64{ 1, 0, 0, 0, 1, 0, 0, 0, 1, }), right: NewDense(3, 3, []float64{ 1, 0, 0, 0, 1, 0, 0, 0, 1, }), }, } { var e1, e2, e3, e4 Eigen ok := e1.Factorize(test.a, true, true) if !ok { panic("bad factorization") } e2.Factorize(test.a, false, true) e3.Factorize(test.a, true, false) e4.Factorize(test.a, false, false) v1 := e1.Values(nil) if !cmplxEqual(v1, test.values) { t.Errorf("eigenvector mismatch. Case %v", i) } if !Equal(e1.LeftVectors(), test.left) { t.Errorf("left eigenvector mismatch. Case %v", i) } if !Equal(e1.Vectors(), test.right) { t.Errorf("right eigenvector mismatch. Case %v", i) } // Check that the eigenvectors and values are the same in all combinations. if !cmplxEqual(v1, e2.Values(nil)) { t.Errorf("eigenvector mismatch. Case %v", i) } if !cmplxEqual(v1, e3.Values(nil)) { t.Errorf("eigenvector mismatch. Case %v", i) } if !cmplxEqual(v1, e4.Values(nil)) { t.Errorf("eigenvector mismatch. Case %v", i) } if !Equal(e1.Vectors(), e2.Vectors()) { t.Errorf("right eigenvector mismatch. Case %v", i) } if !Equal(e1.LeftVectors(), e3.LeftVectors()) { t.Errorf("right eigenvector mismatch. Case %v", i) } // TODO(btracey): Also add in a test for correctness when #308 is // resolved and we have a CMat.Mul(). } } func cmplxEqual(v1, v2 []complex128) bool { for i, v := range v1 { if v != v2[i] { return false } } return true } func TestSymEigen(t *testing.T) { // Hand coded tests with results from lapack. for _, test := range []struct { mat *SymDense values []float64 vectors *Dense }{ { mat: NewSymDense(3, []float64{8, 2, 4, 2, 6, 10, 4, 10, 5}), values: []float64{-4.707679201365891, 6.294580208480216, 17.413098992885672}, vectors: NewDense(3, 3, []float64{ -0.127343483135656, -0.902414161226903, -0.411621572466779, -0.664177720955769, 0.385801900032553, -0.640331827193739, 0.736648893495999, 0.191847792659746, -0.648492738712395, }), }, } { var es EigenSym ok := es.Factorize(test.mat, true) if !ok { t.Errorf("bad factorization") } if !floats.EqualApprox(test.values, es.values, 1e-14) { t.Errorf("Eigenvalue mismatch") } if !EqualApprox(test.vectors, es.vectors, 1e-14) { t.Errorf("Eigenvector mismatch") } var es2 EigenSym es2.Factorize(test.mat, false) if !floats.EqualApprox(es2.values, es.values, 1e-14) { t.Errorf("Eigenvalue mismatch when no vectors computed") } } // Randomized tests rnd := rand.New(rand.NewSource(1)) for _, n := range []int{3, 5, 10, 70} { for cas := 0; cas < 10; cas++ { a := make([]float64, n*n) for i := range a { a[i] = rnd.NormFloat64() } s := NewSymDense(n, a) var es EigenSym ok := es.Factorize(s, true) if !ok { t.Errorf("Bad test") } // Check that the eigenvectors are orthonormal. if !isOrthonormal(es.vectors, 1e-8) { t.Errorf("Eigenvectors not orthonormal") } // Check that the eigenvalues are actually eigenvalues. for i := 0; i < n; i++ { v := NewVecDense(n, Col(nil, i, es.vectors)) var m VecDense m.MulVec(s, v) var scal VecDense scal.ScaleVec(es.values[i], v) if !EqualApprox(&m, &scal, 1e-8) { t.Errorf("Eigenvalue does not match") } } } } }
gpl-3.0
kebechsenuef/borrow_land
_06_objekteSuche-3-1.inc.php
7042
<? session_start(); //Funktionen ///////////////////////////////////////////// $includeName="_00_basic_func.inc.php"; if (file_exists($includeName)) { require($includeName); } else { echo '<br><br><div class="meldung_fehler"><img src="BL_BILDER/Meldungen_Warning.png"> <br>FU_ALL_LOAD_01</div><br><br>'; exit(); } ///////////////////////////////////////////// //Datenbank Verbindung ///////////////////////////////////////////// $includeName="_01_basic_db.inc.php"; if (file_exists($includeName)) { require($includeName); } else { echo '<br><br><div class="meldung_fehler"><img src="BL_BILDER/Meldungen_Warning.png"> <br>DB_FU_LOAD_01</div><br><br>'; exit(); } ///////////////////////////////////////////// //Sessions ///////////////////////////////////////////// $includeName="_01_basic_sess.inc.php"; if (file_exists($includeName)) { require($includeName); } else { echo '<br><br><div class="meldung_fehler"><img src="BL_BILDER/Meldungen_Warning.png"> <br>SESS_FU_LOAD_01</div><br><br>'; exit(); } ///////////////////////////////////////////// if (isset($_SESSION["User_ID"])) { $tagsArray = explode("|", ($_GET['fdc'])); echo "<br><br>"; if (count($tagsArray)>=1) { //1. nachsehen ob alle tags in irgendeine objekt vorhanden sind //$comma_separated = implode($tagsArray,","); //namen der hauptgruppen $namenHauptGruppen=array_keys($_SESSION["aktuelleObjekte"]); //wieviele hauptgruppen existieren überhaupt? $anzahlHG=count($namenHauptGruppen); if ($anzahlHG>=1) { for ($k=0;$k < $anzahlHG;$k++) { for ($l=0;$l<count($_SESSION["aktuelleObjekte"][$namenHauptGruppen[$k]]);$l++) { //metatags von dem objekt heraussuchen, die nicht leer sind $sql = 'SELECT metatags FROM `04_obj_objekte` WHERE `specid_obj` = \''.$_SESSION["aktuelleObjekte"][$namenHauptGruppen[$k]][$l].'\' AND `metatags` != \'\''; $metaObj = mysql_query($sql); $metaObjText = mysql_fetch_row($metaObj); $tagsAusArray = explode(",", $metaObjText[0]); $result = array_intersect($tagsArray, $tagsAusArray); if ($metaObjText[0]!="") { //rückwerte: gleihe anzahl an elementen=volltreffer; weniger elemente als angefragte tags: teilerfolg; keine elemente: unwichtig if (count($result)==count($tagsArray) && count($result)!=0) { //hauptobjekte $hauptobjekte[]=$_SESSION["aktuelleObjekte"][$namenHauptGruppen[$k]][$l]; } } unset($tagsAusArray); unset($result); } } //fehlermeldung wnen keine objekte gefunden worden sin if (!isset($hauptobjekte)) { echo "Die angegebenden Schlagwörter stimmen mit keinem Objekt überein"; } else { //var_dump($hauptobjekte); } } } for ($i=0;$i<count($hauptobjekte);$i++) { //echo klarNameObj($hauptobjekte[$i])."<br>"; //objekte echo '<table style="margin-top:5px" objT_id="'.base64_encode(serialize($hauptobjekte[$i])).'" class="clear ui-widget-content" border="0" cellpadding="3" cellspacing="0" width="896px" height="100px">'; //erste zeile echo '<tr height="40" class="ui-widget-header"><td style="margin: 10px;padding:10px"> '; echo utf8_encode(klarNameObj($hauptobjekte[$i])); //PDF Info, wenn Datei vorhanden if (is_file('BL_MEDIA/PDF_OBJ/'.base64_encode(serialize($hauptobjekte[$i])).'.pdf') || is_file('BL_MEDIA/PDF_OBJ/'.base64_encode(serialize($hauptobjekte[$i])).'.PDF')) { echo " <a href='"."BL_MEDIA/PDF_OBJ/".base64_encode(serialize($hauptobjekte[$i])).".pdf' target='_blank'><img align='absmiddle' src='BL_BILDER/pdf.png'></a>"; } //ende pdf info echo '</td><td width="60px" align="right" valign="top" colspan="3">'; if (is_file('BL_MEDIA/PIC_OBJ/'.base64_encode(serialize($hauptobjekte[$i])).'.jpg') || is_file('BL_MEDIA/PIC_OBJ/'.base64_encode(serialize($hauptobjekte[$i])).'.JPG')) { echo '<img uiz68="BL_MEDIA/PIC_OBJ/'.base64_encode(serialize($hauptobjekte[$i])).'.jpg'.'" hspace="60" src="galPrev3.php?a='.base64_encode(serialize($hauptobjekte[$i])).'">'; } echo '</td>'; echo '</tr>'; //ende erste zeile //zweite zeile: beschreibung echo '<tr class="ui-widget-content"><td style="margin: 15px;padding:15px" colspan="4">'; //lange beschreibung $sql = "SELECT langeBeschre FROM `04_obj_objekte` WHERE `specid_obj` = \"".$hauptobjekte[$i]."\" LIMIT 1 "; $DateLangBe = mysql_query($sql); $langeBeschIngo = mysql_fetch_row($DateLangBe); //gucken ob mehr als 285 zeichen if (strlen($langeBeschIngo[0]) > 264) { $textEdit = substr($langeBeschIngo[0], 0, 260 ); echo "<div class='Standard_Verdana_12'>".utf8_encode($textEdit)." <a title='".utf8_encode($langeBeschIngo[0])."'>...</a></div>"; } else { echo "<div class='Standard_Verdana_12'>".utf8_encode($langeBeschIngo[0])."</div>"; } unset($langeBeschIngo[0]); unset($textEdit); //ende lange beschreibung echo '</td></tr>'; //ende zweite zeile //dritte zeile: warenkorb echo '<tr class="ui-widget-content ui-corner-all"><td colspan="4" align="right" valign="bottom">'; echo '<br><a inWK_to_oV="_1_'.base64_encode(serialize($hauptobjekte[$i])).'" href="#link" title="In den Warenkorb (Vor-Ort Abholung)"><div style="float:right;" class="ui-state-default ui-corner-all"><span class="ui-icon ui-icon-circle-plus"></span></div></a>'; if ($_SESSION['SE_versandMod']=="1") { echo '<a inWK_to_mV="_2_'.base64_encode(serialize($hauptobjekte[$i])).'" href="#link" title="In den Warenkorb (Versand)"><div style="float:right;" class="ui-state-default ui-corner-all"><span class="ui-icon ui-icon-mail-open"></span></div></a>'; } echo '</td></tr>'; //ende dritte zeile echo '</table>'; } } ?> <script> $("a[inWK_to_oV^=_1_]").click(function(event) { $("#wk").load("_07_wko3.inc.php?wk1="+$(this).attr("inWK_to_oV")); $("a[inWK_to_oV^=_1_]").hide(); <? //nur wenn versandmodul aktiviert ist, werden auch die symbole ausgeblendet bei einer warenkorb aktion if ($_SESSION['SE_versandMod']=="1") { echo '$("a[inWK_to_mV^=_2_]").hide();'; } ?> }); <? if ($_SESSION['SE_versandMod']=="1") { //nur wenn versandmodul aktiviert ist, werden auch die symbole ausgeblendet bei einer warenkorb aktion ?> $("a[inWK_to_mV^=_2_]").click(function(event) { $("#wk").load("_07_wko3.inc.php?wk2="+$(this).attr("inWK_to_mV")); $("a[inWK_to_mV^=_2_]").hide(); $("a[inWK_to_oV^=_1_]").hide(); }); <? } ?> $("#loadingAj").hide(); $('table img,div img').imgPreview({ containerID: 'imgPreviewWithStyles', srcAttr: 'uiz68', preloadImages: 'false', imgCSS: { // Limit preview size: height: 200 }, // When container is shown: onShow: function(link){ // Animate link: $(link).stop().animate({opacity:0.4}); // Reset image: $('img', this).stop().css({opacity:0}); }, // When image has loaded: onLoad: function(){ // Animate image $(this).animate({opacity:1}, 300); }, // When container hides: onHide: function(link){ // Animate link: $(link).stop().animate({opacity:1}); } }); </script>
gpl-3.0
preea/apericraft
Common/net/preea/apericraft/blocks/Titanium_Block.java
785
package net.preea.apericraft.blocks; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.preea.apericraft.declarations.ACreativeTabs; import net.preea.apericraft.lib.Reference; public class Titanium_Block extends Block{ public Titanium_Block(){ super(Material.rock); this.setStepSound(Block.soundTypeMetal); this.setCreativeTab(ACreativeTabs.TabABlocks); this.setHardness(4F); this.setResistance(10F); } @SideOnly(Side.CLIENT) public void registerBlockIcons(IIconRegister IconRegister){ this.blockIcon = IconRegister.registerIcon(Reference.MODID + ":" +(this.getUnlocalizedName().substring(5))); } }
gpl-3.0
piracarter/radiognu
src/org/radiognu/radiognu/serviceplayerstreaming.java
4872
package org.radiognu.radiognu; import java.io.IOException; import android.app.ProgressDialog; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.os.AsyncTask; import android.os.Binder; import android.os.IBinder; import android.widget.Toast; public class serviceplayerstreaming extends Service { private MediaPlayer mediaPlayer; @Override public IBinder onBind(Intent arg0) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { Toast.makeText(this, "Servicio en Ejecucion", Toast.LENGTH_SHORT).show(); return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); mediaPlayer.stop(); mediaPlayer.reset(); unregisterReceiver(receiver); Toast.makeText(this, getResources().getString(R.string.exit_service), Toast.LENGTH_SHORT).show(); } @Override public void onCreate() { super.onCreate(); mediaPlayer = new MediaPlayer(); Player player = new Player(); player.execute(getResources().getString(R.string.URL_AUDIO)); IntentFilter filter = new IntentFilter(); filter.addAction("NOTIFY_AUDIO"); filter.addAction("FINISH_APP"); registerReceiver(receiver, filter); } class Player extends AsyncTask<String, Void, Boolean> { private ProgressDialog progressDialog; @Override protected void onPreExecute() { super.onPreExecute(); progressDialog = new ProgressDialog(MainActivity.getContext()); progressDialog.setMessage(getResources().getString(R.string.message_conn2)); progressDialog.setCancelable(false); progressDialog.show(); //this.progress.setMessage("Buffering..."); //this.progress.show(); } @Override protected Boolean doInBackground(String... params) { Boolean prepared; try { mediaPlayer.setDataSource(params[0]); mediaPlayer.setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mediaPlayer.stop(); mediaPlayer.reset(); } }); mediaPlayer.prepare(); prepared = true; MainActivity.setEstatusPlayStreaming(1); /* Se esta reproduciendo el streaming */ } catch (IllegalArgumentException e) { prepared = false; e.printStackTrace(); } catch (SecurityException e) { prepared = false; e.printStackTrace(); } catch (IllegalStateException e) { prepared = false; e.printStackTrace(); } catch (IOException e) { prepared = false; e.printStackTrace(); } return prepared; } @Override protected void onPostExecute(Boolean result) { progressDialog.dismiss(); if (result) { mediaPlayer.start(); } else { mediaPlayer.reset(); Intent broadcastIntent = new Intent(); broadcastIntent.setAction("NOTIFY_SERVICE"); broadcastIntent.putExtra("state", "update ui"); sendBroadcast(broadcastIntent); stopService(); } } public Player() { //progress = new ProgressDialog(getActivity()); } } public class LocalBinder extends Binder { public serviceplayerstreaming getService() { return serviceplayerstreaming.this; } } private final BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if(action.equals("NOTIFY_AUDIO")){ /* * En caso de enviar stop */ if (intent.getStringExtra("state").equals("stop")) { if (mediaPlayer.isPlaying()) { mediaPlayer.pause(); MainActivity.setEstatusPlayStreaming(0); } } /* * En caso de enviar resume */ if (intent.getStringExtra("state").equals("resume")) { if (!mediaPlayer.isPlaying()) { mediaPlayer.start(); MainActivity.setEstatusPlayStreaming(1); } } } } }; public void stopService() { this.stopSelf(); MainActivity.setEstatusPlayStreaming(0); MainActivity.setPlay(false); } }
gpl-3.0
bowhan/piPipes
misc_tools/include/thread.hpp
2698
/* # Copyright (C) 2014 Bo Han, Wei Wang, Zhiping Weng, Phillip Zamore # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef bowhan_thread_h #define bowhan_thread_h #include <thread> #include <condition_variable> #include "boost/optional.hpp" #include "generic_container.hpp" /* implementation of thread safe queue */ template <typename T, template <typename, typename...> class C> class ThreadSafeQueue { public: ThreadSafeQueue<T, C>() {} bool empty() const { return _quene.empty(); } bool done() const { return _finished; } void setDone() noexcept { std::unique_lock<std::mutex> lock(_mx); _finished = true; _cond.notify_all(); } void push(T&& data) { std::unique_lock<std::mutex> lock(_mx); bool const was_empty = _quene.empty(); containerPolicy<T, C>::push(_quene, std::forward(data)); lock.unlock(); if (was_empty) _cond.notify_one(); } void push(char *data) { std::unique_lock<std::mutex> lock(_mx); bool const was_empty = _quene.empty(); containerPolicy<T, C>::push(_quene, T{data}); lock.unlock(); if (was_empty) { _cond.notify_one(); } } bool try_pop(T& data) { std::unique_lock<std::mutex> lock(_mx); _cond.wait(lock, [this]() -> bool { return !_quene.empty() || _finished; }); if (_quene.empty()) return false; else { data = containerPolicy<T, C>::top(_quene); containerPolicy<T, C>::pop(_quene); return true; } } private: C<T> _quene; bool _finished = false; mutable std::mutex _mx; std::condition_variable _cond; ThreadSafeQueue<T, C>(const ThreadSafeQueue<T, C>&) = delete; ThreadSafeQueue<T, C>(ThreadSafeQueue<T, C>&&) = delete; ThreadSafeQueue<T, C> operator=(const ThreadSafeQueue<T, C>&) = delete; ThreadSafeQueue<T, C> operator=(ThreadSafeQueue<T, C>&&) = delete; }; #endif
gpl-3.0
RedFantom/GSF-Parser
frames/chat.py
6693
""" Author: RedFantom License: GNU GPLv3 Copyright (c) 2018 RedFantom """ # Standard Library from datetime import datetime from multiprocessing import Pipe from six import reraise from typing import List, Tuple # UI Libraries from tkinter import messagebox import tkinter as tk from tkinter import ttk # Project Modules from parsing.chat import ChatParser from widgets.results.chat import ChatWindow class ChatFrame(ttk.Frame): """ Frame containing ChatWindow and parsing control buttons Controls a ChatParser instance. Requires the selection of a correct character in order to perform operations. Reads the messages and inserts them into the ChatWindow. """ def __init__(self, master, window): """Initialize with master widget""" self._highlight = False self._parser: ChatParser = None self._pipe = None self._after_id = None ttk.Frame.__init__(self, master) self.window = window self._scroll = ttk.Scrollbar(self) self._chat = ChatWindow(self, width=785, height=320, scrollbar=self._scroll) self._chars: dict = window.characters_frame.characters.copy() self.server, self.character = tk.StringVar(), tk.StringVar() servers = ("Choose Server",) + tuple(self.window.characters_frame.servers.values()) self.server_dropdown = ttk.OptionMenu(self, self.server, *servers, command=self.update_characters) self.character_dropdown = ttk.OptionMenu(self, self.character, *("Choose Character",)) self.start_button = ttk.Button(self, command=self.start_parsing, text="Start", width=20) self._accuracy = tk.DoubleVar() self._accuracy_scale = ttk.Scale(self, variable=self._accuracy, from_=1, to=4, length=200) self._accuracy_start = ttk.Label(self, text="Speed") self._accuracy_end = ttk.Label(self, text="Accuracy") self.grid_widgets() def grid_widgets(self): """Configure the widgets in the grid geometry manager""" self._chat.grid(row=0, column=0, padx=5, pady=5, columnspan=3, sticky="nswe") self._scroll.grid(row=0, column=3, padx=(0, 5), pady=5, sticky="nswe") self.server_dropdown.grid(row=1, column=0, padx=5, pady=(0, 5), sticky="nswe") self.character_dropdown.grid(row=1, column=1, padx=(0, 5), pady=(0, 5), sticky="nswe") self.start_button.grid(row=1, column=2, padx=(0, 5), pady=(0, 5), sticky="nswe") self._accuracy_start.grid(row=2, column=0, sticky="se", padx=(0, 10)) self._accuracy_scale.grid(row=2, column=1, sticky="we") self._accuracy_end.grid(row=2, column=2, sticky="sw", padx=(10, 0)) def highlight(self): """Create or remove a red higlight on the missing data attrs""" style = ttk.Style() if self._highlight: color = style.lookup(".", "foreground", default="black") else: color = "red" self._highlight = not self._highlight style.configure("Highlight.TMenubutton", foreground=color) for w in (self.server_dropdown, self.character_dropdown): w.configure(style="Highlight.TMenubutton") def check_start(self): """Determine whether parsing can be started""" if self.selected_character is None: self.highlight() self.after(2000, self.highlight) return False return True def start_parsing(self): """Start the parsing if it can be started""" if self.check_start() is False: return self._pipe, conn = Pipe() try: server, character = self.selected_character self._parser = ChatParser(character, server, conn, self._accuracy.get()) self._parser.start() except RuntimeError: messagebox.showerror("Error", "An error occurred while starting the ChatParser.") raise self.start_button.config(state=tk.DISABLED, text="Starting...") self._after_id = self.after(1000, self.check_status) def check_status(self): """Periodically called function to update ChatWindow""" self._after_id = None while self._pipe.poll(): messages = self._pipe.recv() if isinstance(messages, str): self.start_button.config(text=messages) continue elif isinstance(messages, tuple): self.start_button.config(text="An error occurred") reraise(*messages) self.insert_messages(messages) if not self._parser.is_alive(): self.stop_parsing() return self._after_id = self.after(100, self.check_status) def insert_messages(self, messages: List[Tuple[str, str, str, str]]): """Insert a list of messages into the ChatWindow""" print("[ChatFrame] Inserting {} messages".format(len(messages))) for message in messages: time, channel, author, text = message if not isinstance(time, datetime): time = datetime.now() self._chat.create_message(time, author, text, "lightblue", redraw=False) def stop_parsing(self): """Stop the active parser""" if self._after_id is not None: self.after_cancel(self._after_id) self._parser.join() self.start_button.config(state=tk.NORMAL, text="Start") self._parser = None def update_characters(self, *args): """Update the character_dropdown""" if len(args) == 0: return server = args[0] if "Choose" in server: return self.character_dropdown["menu"].delete(0, tk.END) characters = ["Choose Character"] if server not in self.window.characters_frame.servers.values(): return for data in self.window.characters_frame.characters: character_server = self.window.characters_frame.servers[data[0]] if character_server != server: continue characters.append(data[1]) for character in sorted(characters): self.character_dropdown["menu"].add_command( label=character, command=lambda value=character: self.character.set(value)) @property def selected_character(self) -> Tuple[str, str]: """Return the selected character""" if "Choose" in self.server.get() or "Choose" in self.character.get(): return None reverse_servers = {value: key for key, value in self.window.characters_frame.servers.items()} server = reverse_servers[self.server.get()] return server, self.character.get()
gpl-3.0
rudametw/rudametw.github.io.backup-repo
src/_plugins/gallery_generator.rb
5149
require 'rubygems' require 'exifr' require 'RMagick' include Magick include FileUtils $image_extensions = [".png", ".jpg", ".jpeg", ".gif"] module Jekyll class GalleryFile < StaticFile def write(dest) return false end end class GalleryIndex < Page def initialize(site, base, dir, galleries) @site = site @base = base @dir = dir.gsub("source/", "") @name = "index.html" config = site.config["gallery"] || {} self.process(@name) self.read_yaml(File.join(base, "_layouts"), "gallery_index.html") self.data["title"] = config["title"] || "Photos" self.data["galleries"] = [] begin sort_field = config["sort_field"] || "date_time" galleries.sort! {|a,b| b.data[sort_field] <=> a.data[sort_field]} rescue Exception => e puts "Error sorting galleries: #{e}" puts e.backtrace end if config["sort_reverse"] galleries.reverse! end galleries.each {|gallery| unless gallery.hidden self.data["galleries"].push(gallery.data) end } end end class GalleryPage < Page attr_reader :hidden def initialize(site, base, dir, gallery_name) @site = site @base = base @dest_dir = dir.gsub("source/", "") @dir = @dest_dir @name = "index.html" @images = [] @hidden = false config = site.config["gallery"] || {} gallery_config = {} best_image = nil max_size_x = 400 max_size_y = 400 scale_method = config["scale_method"] || "fit" begin max_size_x = config["thumbnail_size"]["x"] rescue end begin max_size_y = config["thumbnail_size"]["y"] rescue end begin gallery_config = config["galleries"][gallery_name] || {} rescue end self.process(@name) self.read_yaml(File.join(base, "_layouts"), "gallery_page.html") self.data["gallery"] = gallery_name gallery_title_prefix = config["title_prefix"] || "Photos: " gallery_name = gallery_name.gsub("_", " ").gsub(/\w+/) {|word| word.capitalize} begin gallery_name = gallery_config["name"] || gallery_name rescue end self.data["name"] = gallery_name self.data["title"] = "#{gallery_title_prefix}#{gallery_name}" thumbs_dir = "#{site.dest}/#{@dest_dir}/thumbs" begin @hidden = gallery_config["hidden"] || false rescue end if @hidden self.data["sitemap"] = false end FileUtils.mkdir_p(thumbs_dir, :mode => 0755) Dir.foreach(dir) do |image| if image.chars.first != "." and image.downcase().end_with?(*$image_extensions) @images.push(image) best_image = image @site.static_files << GalleryFile.new(site, base, "#{@dest_dir}/thumbs/", image) if File.file?("#{thumbs_dir}/#{image}") == false or File.mtime("#{dir}/#{image}") > File.mtime("#{thumbs_dir}/#{image}") begin m_image = ImageList.new("#{dir}/#{image}") m_image.send("resize_to_#{scale_method}!", max_size_x, max_size_y) puts "Writing thumbnail to #{thumbs_dir}/#{image}" m_image.write("#{thumbs_dir}/#{image}") rescue e puts "Error generating thumbnail for #{dir}/#{image}: #{e}" puts e.backtrace end GC.start end end end begin @images.sort! if gallery_config["sort_reverse"] @images.reverse! end rescue Exception => e puts "Error sorting images in gallery #{gallery_name}: #{e}" puts e.backtrace end self.data["images"] = @images self.data["best_image"] = gallery_config["best_image"] || best_image begin self.data["date_time"] = EXIFR::JPEG.new("#{dir}/#{best_image}").date_time.to_i rescue Exception => e self.data["date_time"] = 0 puts "Error getting date_time for #{dir}/#{best_image}: #{e}" end end end class GalleryGenerator < Generator safe true def generate(site) unless site.layouts.key? "gallery_index" return end config = site.config["gallery"] || {} dir = config["dir"] || "photos" galleries = [] begin Dir.foreach(dir) do |gallery_dir| gallery_path = File.join(dir, gallery_dir) if File.directory?(gallery_path) and gallery_dir.chars.first != "." gallery = GalleryPage.new(site, site.source, gallery_path, gallery_dir) gallery.render(site.layouts, site.site_payload) gallery.write(site.dest) site.pages << gallery galleries << gallery end end rescue Exception => e puts "Error generating galleries: #{e}" puts e.backtrace end gallery_index = GalleryIndex.new(site, site.source, dir, galleries) gallery_index.render(site.layouts, site.site_payload) gallery_index.write(site.dest) site.pages << gallery_index end end end
gpl-3.0
gaborfeher/grantmaster
grantmaster/src/test/java/com/github/gaborfeher/grantmaster/logic/wrappers/ProjectExpenseWrapperTest.java
26647
package com.github.gaborfeher.grantmaster.logic.wrappers; import com.github.gaborfeher.grantmaster.framework.base.RowEditState; import com.github.gaborfeher.grantmaster.framework.utils.DatabaseSingleton; import com.github.gaborfeher.grantmaster.framework.utils.Utils; import com.github.gaborfeher.grantmaster.logic.entities.BudgetCategory; import com.github.gaborfeher.grantmaster.logic.entities.Currency; import com.github.gaborfeher.grantmaster.logic.entities.CurrencyPair; import com.github.gaborfeher.grantmaster.logic.entities.Project; import com.github.gaborfeher.grantmaster.logic.entities.ProjectExpense; import com.github.gaborfeher.grantmaster.logic.entities.ProjectReport; import java.math.BigDecimal; import java.time.LocalDate; import java.util.List; import javax.persistence.EntityManager; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; import static com.github.gaborfeher.grantmaster.logic.wrappers.TestUtils.assertBigDecimalEquals; import java.time.Month; public class ProjectExpenseWrapperTest extends TestBase { Currency HUF; Currency USD; Currency EUR; BudgetCategory SOME_GRANT; BudgetCategory SOME_EXPENSE; Project PROJECT1; ProjectReport PROJECT1_REPORT1; ProjectReport PROJECT1_REPORT2; Project PROJECT2_OVERRIDE; ProjectReport PROJECT2_OVERRIDE_REPORT1; public ProjectExpenseWrapperTest() { } @Before public void setUp() { assertTrue(DatabaseSingleton.INSTANCE.connectToMemoryFileForTesting()); assertTrue(DatabaseSingleton.INSTANCE.transaction((EntityManager em) -> { HUF = TestUtils.createCurrency(em, "HUF"); USD = TestUtils.createCurrency(em, "USD"); EUR = TestUtils.createCurrency(em, "EUR"); SOME_GRANT = new BudgetCategory( BudgetCategory.Direction.INCOME, "i.stuff", "Some kind of project grant"); em.persist(SOME_GRANT); SOME_EXPENSE = new BudgetCategory( BudgetCategory.Direction.PAYMENT, "p.stuff", "Some kind of payment"); em.persist(SOME_EXPENSE); PROJECT1 = TestUtils.createProject( em, "project1", USD, HUF, SOME_GRANT, Project.ExpenseMode.NORMAL_AUTO_BY_SOURCE); PROJECT1_REPORT1 = TestUtils.createProjectReport( em, PROJECT1, LocalDate.of(2015, 4, 1)); PROJECT1_REPORT2 = TestUtils.createProjectReport( em, PROJECT1, LocalDate.of(2015, 8, 1)); // The below is the order in which the sources will be filled, because // report date takes precedence at sorting. TestUtils.createProjectSource( em, PROJECT1, LocalDate.of(2015, 2, 1), PROJECT1_REPORT1, "100", "1000"); TestUtils.createProjectSource( em, PROJECT1, LocalDate.of(2015, 4, 1), PROJECT1_REPORT1, "200", "1000"); TestUtils.createProjectSource( em, PROJECT1, LocalDate.of(2015, 3, 1), PROJECT1_REPORT2, "300", "1000"); PROJECT2_OVERRIDE = TestUtils.createProject( em, "project2", USD, HUF, SOME_GRANT, Project.ExpenseMode.OVERRIDE_AUTO_BY_RATE_TABLE); PROJECT2_OVERRIDE_REPORT1 = TestUtils.createProjectReport( em, PROJECT2_OVERRIDE, LocalDate.of(2015, 7, 1)); CurrencyPair currencyPair = TestUtils.createCurrencyPair(em, HUF, USD); TestUtils.createExchangeRate(em, currencyPair, LocalDate.of(2015, 8, 20), "1000"); TestUtils.createExchangeRate(em, currencyPair, LocalDate.of(2015, 8, 21), "2000"); return true; })); } @After public void tearDown() { DatabaseSingleton.INSTANCE.close(); } @Test public void testCreateExpense() { final ObjectHolder<ProjectExpenseWrapper> newExpense = new ObjectHolder<>(); assertTrue(DatabaseSingleton.INSTANCE.query((EntityManager em) -> { newExpense.set(ProjectExpenseWrapper.createNew(em, PROJECT1)); return true; })); newExpense.get().setState(RowEditState.EDITING_NEW); newExpense.get().setProperty( "paymentDate", LocalDate.of(2015, 3, 4), LocalDate.class); newExpense.get().setProperty( "budgetCategory", SOME_EXPENSE, BudgetCategory.class); newExpense.get().setProperty( "originalAmount", new BigDecimal("100000.5", Utils.MC),BigDecimal.class); newExpense.get().setProperty( "accountingCurrencyAmount", new BigDecimal("100000.5", Utils.MC), BigDecimal.class); newExpense.get().setProperty( "report", PROJECT1_REPORT1, ProjectReport.class); assertTrue(DatabaseSingleton.INSTANCE.transaction(newExpense.get()::save)); assertEquals(RowEditState.SAVED, newExpense.get().getState()); DatabaseSingleton.INSTANCE.query((EntityManager em) -> { List<ProjectExpenseWrapper> expenses = ProjectExpenseWrapper.getProjectExpenseList(em, PROJECT1); assertEquals(1, expenses.size()); ProjectExpenseWrapper expenseWrapper = expenses.get(0); ProjectExpense expense = expenseWrapper.getEntity(); assertEquals(LocalDate.of(2015, 3, 4), expense.getPaymentDate()); assertNull(expense.getAccountNo()); assertNull(expense.getPartnerName()); assertNull(expense.getComment1()); assertNull(expense.getComment2()); assertEquals(HUF, expense.getOriginalCurrency()); // should be default assertBigDecimalEquals("100000.5", expense.getOriginalAmount()); assertBigDecimalEquals("100000.5", expenseWrapper.getAccountingCurrencyAmount()); return true; }); } @Test public void testCreateMultiSourceExpenseAfterReportTime() { // This covers a bug in which expenses before the report time were never updated. final ObjectHolder<ProjectExpenseWrapper> newExpense = new ObjectHolder<>(); assertTrue(DatabaseSingleton.INSTANCE.query((EntityManager em) -> { newExpense.set(ProjectExpenseWrapper.createNew(em, PROJECT1)); return true; })); newExpense.get().setState(RowEditState.EDITING_NEW); newExpense.get().setProperty( "paymentDate", LocalDate.of(2015, 5, 1), LocalDate.class); // After REPORT1's time. newExpense.get().setProperty( "budgetCategory", SOME_EXPENSE, BudgetCategory.class); newExpense.get().setProperty( "originalAmount", new BigDecimal("300000", Utils.MC),BigDecimal.class); newExpense.get().setProperty( "accountingCurrencyAmount", new BigDecimal("300000", Utils.MC), BigDecimal.class); newExpense.get().setProperty( "report", PROJECT1_REPORT1, ProjectReport.class); assertTrue(DatabaseSingleton.INSTANCE.transaction(newExpense.get()::save)); assertEquals(RowEditState.SAVED, newExpense.get().getState()); DatabaseSingleton.INSTANCE.query((EntityManager em) -> { List<ProjectExpenseWrapper> expenses = ProjectExpenseWrapper.getProjectExpenseList(em, PROJECT1); assertEquals(1, expenses.size()); ProjectExpenseWrapper expenseWrapper = expenses.get(0); assertBigDecimalEquals("300000", expenseWrapper.getAccountingCurrencyAmount()); assertBigDecimalEquals("150", expenseWrapper.getExchangeRate()); return true; }); } /** * Make sure that the sorting used for recalculating * project expense-source allocations * is correct. */ @Test public void testSortingForAllocation() { final ObjectHolder<Long> expenseId1 = new ObjectHolder<>(); final ObjectHolder<Long> expenseId2 = new ObjectHolder<>(); final ObjectHolder<Long> expenseId3 = new ObjectHolder<>(); final ObjectHolder<Long> expenseId4 = new ObjectHolder<>(); // Setup. assertTrue(DatabaseSingleton.INSTANCE.transaction((EntityManager em) -> { expenseId1.set( TestUtils.createProjectExpense( em, PROJECT1, SOME_GRANT, LocalDate.of(2014, 2, 1), PROJECT1_REPORT2, "200421", HUF, "200000.1" ).getId()); expenseId2.set( TestUtils.createProjectExpense( em, PROJECT1, SOME_GRANT, LocalDate.of(2014, 4, 2), PROJECT1_REPORT1, "200422", HUF, "200000.2" ).getId()); expenseId3.set( TestUtils.createProjectExpense( em, PROJECT1, SOME_GRANT, LocalDate.of(2014, 1, 1), PROJECT1_REPORT2, "200423", HUF, "200000.3" ).getId()); expenseId4.set( TestUtils.createProjectExpense( em, PROJECT1, SOME_GRANT, LocalDate.of(2014, 4, 1), PROJECT1_REPORT1, "200424", HUF, "200000.4" ).getId()); return true; })); // Check order. assertTrue(DatabaseSingleton.INSTANCE.query((EntityManager em) -> { List<ProjectExpenseWrapper> expenses = ProjectExpenseWrapper.getProjectExpenseListForAllocation(em, PROJECT1, null, null); assertEquals(4, expenses.size()); assertEquals(expenseId4.get(), expenses.get(0).getId()); assertEquals(expenseId2.get(), expenses.get(1).getId()); assertEquals(expenseId3.get(), expenses.get(2).getId()); assertEquals(expenseId1.get(), expenses.get(3).getId()); return true; })); } /** * Test the thresholding used to decide which expenses are to be reallocated * when something has changed. */ @Test public void testGetProjectExpenseListForAllocation() { final ObjectHolder<Long> expenseId1 = new ObjectHolder<>(); final ObjectHolder<Long> expenseId2 = new ObjectHolder<>(); final ObjectHolder<Long> expenseId3 = new ObjectHolder<>(); final ObjectHolder<Long> expenseId4 = new ObjectHolder<>(); // Setup. assertTrue(DatabaseSingleton.INSTANCE.transaction((EntityManager em) -> { expenseId1.set( TestUtils.createProjectExpense( em, PROJECT1, SOME_GRANT, LocalDate.of(2016, 2, 1), PROJECT1_REPORT2, "200421", HUF, "200000.1" ).getId()); expenseId2.set( TestUtils.createProjectExpense( em, PROJECT1, SOME_GRANT, LocalDate.of(2016, 4, 2), PROJECT1_REPORT1, "200422", HUF, "200000.2" ).getId()); expenseId3.set( TestUtils.createProjectExpense( em, PROJECT1, SOME_GRANT, LocalDate.of(2016, 1, 1), PROJECT1_REPORT2, "200423", HUF, "200000.3" ).getId()); expenseId4.set( TestUtils.createProjectExpense( em, PROJECT1, SOME_GRANT, LocalDate.of(2016, 4, 1), PROJECT1_REPORT1, "200424", HUF, "200000.4" ).getId()); return true; })); // Check order. assertTrue(DatabaseSingleton.INSTANCE.query((EntityManager em) -> { List<ProjectExpenseWrapper> expenses = ProjectExpenseWrapper.getProjectExpenseListForAllocation( em, PROJECT1, LocalDate.of(2015, 3, 30), // just before PROJECT1_REPORT1 null); assertEquals(4, expenses.size()); assertEquals(expenseId4.get(), expenses.get(0).getId()); assertEquals(expenseId2.get(), expenses.get(1).getId()); assertEquals(expenseId3.get(), expenses.get(2).getId()); assertEquals(expenseId1.get(), expenses.get(3).getId()); expenses = ProjectExpenseWrapper.getProjectExpenseListForAllocation( em, PROJECT1, LocalDate.of(2015, 7, 29), // just before PROJECT1_REPORT2 null); assertEquals(2, expenses.size()); assertEquals(expenseId3.get(), expenses.get(0).getId()); assertEquals(expenseId1.get(), expenses.get(1).getId()); expenses = ProjectExpenseWrapper.getProjectExpenseListForAllocation( em, PROJECT1, LocalDate.of(2015, 4, 1), // PROJECT1_REPORT1 LocalDate.of(2016, 4, 2)); // expenseId2 assertEquals(3, expenses.size()); assertEquals(expenseId2.get(), expenses.get(0).getId()); assertEquals(expenseId3.get(), expenses.get(1).getId()); assertEquals(expenseId1.get(), expenses.get(2).getId()); expenses = ProjectExpenseWrapper.getProjectExpenseListForAllocation( em, PROJECT1, LocalDate.of(2015, 8, 1), // PROJECT1_REPORT2 LocalDate.of(2016, 1, 1)); // expenseId3 assertEquals(2, expenses.size()); assertEquals(expenseId3.get(), expenses.get(0).getId()); assertEquals(expenseId1.get(), expenses.get(1).getId()); expenses = ProjectExpenseWrapper.getProjectExpenseListForAllocation( em, PROJECT1, LocalDate.of(2015, 8, 1), // PROJECT1_REPORT2 LocalDate.of(2016, 2, 2)); // one day after expenseId4 assertEquals(0, expenses.size()); return true; })); } @Test public void testShiftExpenseForward() { final ObjectHolder<Long> expenseId1 = new ObjectHolder<>(); final ObjectHolder<Long> expenseId2 = new ObjectHolder<>(); assertTrue(DatabaseSingleton.INSTANCE.transaction((EntityManager em) -> { expenseId1.set( TestUtils.createProjectExpense( em, PROJECT1, SOME_GRANT, LocalDate.of(2014, 2, 1), PROJECT1_REPORT2, // the later report "100000", HUF, "100000" ).getId()); return true; })); assertTrue(DatabaseSingleton.INSTANCE.transaction((EntityManager em) -> { expenseId2.set( TestUtils.createProjectExpense( em, PROJECT1, SOME_GRANT, LocalDate.of(2014, 2, 2), PROJECT1_REPORT1, // the earlier report "200000", HUF, "200000" ).getId()); return true; })); assertTrue(DatabaseSingleton.INSTANCE.query((EntityManager em) -> { ProjectExpenseWrapper expense1 = TestUtils.findExpenseById(em, PROJECT1, expenseId1.get()); ProjectExpenseWrapper expense2 = TestUtils.findExpenseById(em, PROJECT1, expenseId2.get()); assertBigDecimalEquals("100000", expense1.getAccountingCurrencyAmount()); assertBigDecimalEquals("200", expense1.getExchangeRate()); assertBigDecimalEquals("500", expense1.getGrantCurrencyAmount()); assertBigDecimalEquals("200000", expense2.getAccountingCurrencyAmount()); BigDecimal value133_33 = new BigDecimal("200000", Utils.MC).divide(new BigDecimal("1500", Utils.MC), Utils.MC); assertBigDecimalEquals(value133_33, expense2.getExchangeRate()); assertBigDecimalEquals("1500", expense2.getGrantCurrencyAmount()); return true; })); } @Test public void testShiftExpenseBackward() { final ObjectHolder<Long> expenseId1 = new ObjectHolder<>(); final ObjectHolder<Long> expenseId2 = new ObjectHolder<>(); final ObjectHolder<Long> expenseId3 = new ObjectHolder<>(); // Setup. assertTrue(DatabaseSingleton.INSTANCE.transaction((EntityManager em) -> { expenseId1.set( TestUtils.createProjectExpense( em, PROJECT1, SOME_GRANT, LocalDate.of(2014, 2, 1), PROJECT1_REPORT1, "200042", HUF, "200000.1" ).getId()); expenseId2.set( TestUtils.createProjectExpense( em, PROJECT1, SOME_GRANT, LocalDate.of(2014, 2, 2), PROJECT1_REPORT1, "200043", HUF, "200000.2" ).getId()); expenseId3.set( TestUtils.createProjectExpense( em, PROJECT1, SOME_GRANT, LocalDate.of(2014, 1, 1), PROJECT1_REPORT2, "2000044", HUF, "200000.3" ).getId()); return true; })); // Sanity checks. assertTrue(DatabaseSingleton.INSTANCE.query((EntityManager em) -> { List<ProjectExpenseWrapper> expenses = ProjectExpenseWrapper.getProjectExpenseList(em, PROJECT1); assertEquals(3, expenses.size()); ProjectExpenseWrapper expense1 = TestUtils.findExpenseById(em, PROJECT1, expenseId1.get()); ProjectExpenseWrapper expense2 = TestUtils.findExpenseById(em, PROJECT1, expenseId2.get()); ProjectExpenseWrapper expense3 = TestUtils.findExpenseById(em, PROJECT1, expenseId3.get()); assertBigDecimalEquals("200000.1", expense1.getAccountingCurrencyAmount()); assertBigDecimalEquals("200000.2", expense2.getAccountingCurrencyAmount()); assertBigDecimalEquals("200000.3", expense3.getAccountingCurrencyAmount()); return true; })); // Commit deletion assertTrue(DatabaseSingleton.INSTANCE.transaction((EntityManager em) -> { TestUtils.findExpenseById(em, PROJECT1, expenseId2.get()).delete(em); return true; })); // Check results. assertTrue(DatabaseSingleton.INSTANCE.query((EntityManager em) -> { List<ProjectExpenseWrapper> expenses = ProjectExpenseWrapper.getProjectExpenseList(em, PROJECT1); assertEquals(2, expenses.size()); ProjectExpenseWrapper expense1 = TestUtils.findExpenseById(em, PROJECT1, expenseId1.get()); ProjectExpenseWrapper expense2 = TestUtils.findExpenseById(em, PROJECT1, expenseId2.get()); ProjectExpenseWrapper expense3 = TestUtils.findExpenseById(em, PROJECT1, expenseId3.get()); assertBigDecimalEquals("200000.1", expense1.getAccountingCurrencyAmount()); assertNull(expense2); assertBigDecimalEquals("200000.3", expense3.getAccountingCurrencyAmount()); return true; })); } @Test public void testCreateOvershootExpense() { final ObjectHolder<ProjectExpenseWrapper> newExpense = new ObjectHolder<>(); assertTrue(DatabaseSingleton.INSTANCE.query((EntityManager em) -> { newExpense.set(ProjectExpenseWrapper.createNew(em, PROJECT1)); return true; })); newExpense.get().setState(RowEditState.EDITING_NEW); newExpense.get().setProperty( "paymentDate", LocalDate.of(2015, 3, 4), LocalDate.class); newExpense.get().setProperty( "budgetCategory", SOME_EXPENSE, BudgetCategory.class); newExpense.get().setProperty( "originalAmount", new BigDecimal("1.5", Utils.MC),BigDecimal.class); newExpense.get().setProperty( "accountingCurrencyAmount", new BigDecimal("700000", Utils.MC), BigDecimal.class); // 700000 is more than the combined value of all the sources. newExpense.get().setProperty( "report", PROJECT1_REPORT1, ProjectReport.class); assertTrue(DatabaseSingleton.INSTANCE.transaction(newExpense.get()::save)); assertEquals(RowEditState.SAVED, newExpense.get().getState()); DatabaseSingleton.INSTANCE.query((EntityManager em) -> { List<ProjectExpenseWrapper> expenses = ProjectExpenseWrapper.getProjectExpenseList(em, PROJECT1); assertEquals(1, expenses.size()); ProjectExpenseWrapper expenseWrapper = expenses.get(0); assertBigDecimalEquals("700000", expenseWrapper.getAccountingCurrencyAmount()); return true; }); } @Test public void testSetOriginalAmountWhenTied() { final ObjectHolder<ProjectExpenseWrapper> expense = new ObjectHolder<>(); assertTrue(DatabaseSingleton.INSTANCE.transaction((EntityManager em) -> { expense.set(TestUtils.createProjectExpense(em, PROJECT1, SOME_GRANT, LocalDate.of(2015, 7, 8), PROJECT1_REPORT1, "15.0", HUF, "15.0")); return true; })); assertTrue(DatabaseSingleton.INSTANCE.transaction((EntityManager em) -> { expense.get().setProperty("originalAmount", new BigDecimal("16", Utils.MC), BigDecimal.class); return true; })); assertBigDecimalEquals("16", expense.get().getProperty("originalAmount")); assertBigDecimalEquals("16", expense.get().getProperty("accountingCurrencyAmount")); } @Test public void testSetOriginalAmountWhenNotTied() { final ObjectHolder<ProjectExpenseWrapper> expense = new ObjectHolder<>(); assertTrue(DatabaseSingleton.INSTANCE.transaction((EntityManager em) -> { expense.set(TestUtils.createProjectExpense(em, PROJECT1, SOME_GRANT, LocalDate.of(2015, 7, 8), PROJECT1_REPORT1, "15.0", EUR, "4500.0")); return true; })); assertTrue(DatabaseSingleton.INSTANCE.transaction((EntityManager em) -> { expense.get().setProperty("originalAmount", new BigDecimal("16", Utils.MC), BigDecimal.class); return true; })); assertBigDecimalEquals("16", expense.get().getProperty("originalAmount")); assertBigDecimalEquals("4500", expense.get().getProperty("accountingCurrencyAmount")); } @Test public void testSetAccountingCurrencyAmountWhenTied() { final ObjectHolder<ProjectExpenseWrapper> expense = new ObjectHolder<>(); assertTrue(DatabaseSingleton.INSTANCE.transaction((EntityManager em) -> { expense.set(TestUtils.createProjectExpense(em, PROJECT1, SOME_GRANT, LocalDate.of(2015, 7, 8), PROJECT1_REPORT1, "15.0", HUF, "15.0")); return true; })); assertTrue(DatabaseSingleton.INSTANCE.transaction((EntityManager em) -> { expense.get().setProperty("accountingCurrencyAmount", new BigDecimal("16", Utils.MC), BigDecimal.class); return true; })); assertBigDecimalEquals("16", expense.get().getProperty("originalAmount")); assertBigDecimalEquals("16", expense.get().getProperty("accountingCurrencyAmount")); } @Test public void testSetAccountingCurrencyAmountWhenNotTied() { final ObjectHolder<ProjectExpenseWrapper> expense = new ObjectHolder<>(); assertTrue(DatabaseSingleton.INSTANCE.transaction((EntityManager em) -> { expense.set(TestUtils.createProjectExpense(em, PROJECT1, SOME_GRANT, LocalDate.of(2015, 7, 8), PROJECT1_REPORT1, "15.0", EUR, "4500.0")); return true; })); assertTrue(DatabaseSingleton.INSTANCE.transaction((EntityManager em) -> { expense.get().setProperty("accountingCurrencyAmount", new BigDecimal("4600", Utils.MC), BigDecimal.class); return true; })); assertBigDecimalEquals("15", expense.get().getProperty("originalAmount")); assertBigDecimalEquals("4600", expense.get().getProperty("accountingCurrencyAmount")); } @Test public void testCreateExpenseInOverriddenModeManual() { final ObjectHolder<ProjectExpenseWrapper> newExpense = new ObjectHolder<>(); assertTrue(DatabaseSingleton.INSTANCE.query((EntityManager em) -> { newExpense.set(ProjectExpenseWrapper.createNew(em, PROJECT2_OVERRIDE)); return true; })); newExpense.get().setState(RowEditState.EDITING_NEW); newExpense.get().setProperty( "paymentDate", LocalDate.of(2015, 3, 4), LocalDate.class); newExpense.get().setProperty( "budgetCategory", SOME_EXPENSE, BudgetCategory.class); newExpense.get().setProperty( "originalAmount", new BigDecimal("100000.5", Utils.MC),BigDecimal.class); newExpense.get().setProperty( "accountingCurrencyAmount", new BigDecimal("100000.5", Utils.MC), BigDecimal.class); newExpense.get().setProperty("exchangeRate", new BigDecimal("1000"), BigDecimal.class); newExpense.get().setProperty( "report", PROJECT2_OVERRIDE_REPORT1, ProjectReport.class); assertTrue(DatabaseSingleton.INSTANCE.transaction(newExpense.get()::save)); assertEquals(RowEditState.SAVED, newExpense.get().getState()); assertBigDecimalEquals("1000", newExpense.get().getExchangeRate()); assertBigDecimalEquals("100000.5", newExpense.get().getAccountingCurrencyAmount()); assertBigDecimalEquals("100.0005", newExpense.get().getGrantCurrencyAmount()); } @Test public void testCreateExpenseInOverrideModeAuto() { final ObjectHolder<ProjectExpenseWrapper> expense0820 = new ObjectHolder<>(); final ObjectHolder<ProjectExpenseWrapper> expense0821 = new ObjectHolder<>(); assertTrue(DatabaseSingleton.INSTANCE.query((EntityManager em) -> { expense0820.set(ProjectExpenseWrapper.createNew(em, PROJECT2_OVERRIDE)); expense0821.set(ProjectExpenseWrapper.createNew(em, PROJECT2_OVERRIDE)); return true; })); expense0820.get().setState(RowEditState.EDITING_NEW); expense0820.get().setProperty( "paymentDate", LocalDate.of(2015, 8, 20), LocalDate.class); expense0820.get().setProperty( "budgetCategory", SOME_EXPENSE, BudgetCategory.class); expense0820.get().setProperty( "originalAmount", new BigDecimal("100000", Utils.MC),BigDecimal.class); expense0820.get().setProperty( "accountingCurrencyAmount", new BigDecimal("100000", Utils.MC), BigDecimal.class); expense0820.get().setProperty( "report", PROJECT2_OVERRIDE_REPORT1, ProjectReport.class); expense0821.get().setState(RowEditState.EDITING_NEW); expense0821.get().setProperty( "paymentDate", LocalDate.of(2015, 8, 21), LocalDate.class); expense0821.get().setProperty( "budgetCategory", SOME_EXPENSE, BudgetCategory.class); expense0821.get().setProperty( "originalAmount", new BigDecimal("100000", Utils.MC),BigDecimal.class); expense0821.get().setProperty( "accountingCurrencyAmount", new BigDecimal("100000", Utils.MC), BigDecimal.class); expense0821.get().setProperty( "report", PROJECT2_OVERRIDE_REPORT1, ProjectReport.class); assertTrue(DatabaseSingleton.INSTANCE.transaction(expense0820.get()::save)); assertTrue(DatabaseSingleton.INSTANCE.transaction(expense0821.get()::save)); assertEquals(RowEditState.SAVED, expense0820.get().getState()); assertEquals(RowEditState.SAVED, expense0821.get().getState()); // 1000 is the exchange rate for 2015-08-20 assertBigDecimalEquals("1000", expense0820.get().getExchangeRate()); // 2000 is the exchange rate for 2015-08-21 assertBigDecimalEquals("2000", expense0821.get().getExchangeRate()); assertBigDecimalEquals("100000", expense0820.get().getAccountingCurrencyAmount()); assertBigDecimalEquals("100000", expense0821.get().getAccountingCurrencyAmount()); assertBigDecimalEquals("100", expense0820.get().getGrantCurrencyAmount()); assertBigDecimalEquals("50", expense0821.get().getGrantCurrencyAmount()); } }
gpl-3.0
sapia-oss/corus
samples/corus_sample_jetty/src/main/java/org/sapia/corus/sample/jetty/session/SessionServer.java
509
package org.sapia.corus.sample.jetty.session; import java.io.File; public class SessionServer { public static void main(String[] args) throws Exception{ File configFile = new File( System.getProperty("user.dir")+ File.separator+ "etc/ehcache.xml" ); SessionCache cache = new SessionCacheImpl(configFile); Remoting.bind(cache); System.out.println("Session server started"); while(true){ Thread.sleep(100000); } } }
gpl-3.0
unicesi/academ
ACADEM-EJBClient/ejbModule/co/edu/icesi/academ/evaluaciones/EvaluacionBeanRemote.java
5888
/** * Copyright © 2013 Universidad Icesi * * This file is part of ACADEM. * * ACADEM is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ACADEM 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 ACADEM. If not, see <http://www.gnu.org/licenses/>. **/ package co.edu.icesi.academ.evaluaciones; import java.util.List; import javax.ejb.Remote; import co.edu.icesi.academ.bo.CalificacionRolBO; import co.edu.icesi.academ.bo.EvaluacionBO; import co.edu.icesi.academ.bo.CalificacionBO; import co.edu.icesi.academ.bo.FactorDeImpactoBO; import co.edu.icesi.academ.bo.NivelDeConocimientoBO; import co.edu.icesi.academ.bo.ProgramaBO; import co.edu.icesi.academ.bo.ResultadoAprendizajeBO; import co.edu.icesi.academ.bo.RolBO; import co.edu.icesi.academ.bo.RubricaBO; import co.edu.icesi.academ.bo.TemaBO; import co.edu.icesi.academ.bo.UsuarioBO; import co.edu.icesi.academ.excepciones.CrearEvaluacionException; import co.edu.icesi.academ.excepciones.EditarEvaluacionException; import co.edu.icesi.academ.excepciones.EvaluacionException; @Remote public interface EvaluacionBeanRemote { public List<EvaluacionBO> obtenerEvaluacionesDePropietario(UsuarioBO propietario); public EvaluacionBO crearEvaluacion(EvaluacionBO evaluacionBO) throws CrearEvaluacionException; public EvaluacionBO guardarEvaluadores(EvaluacionBO evaluacionBO); public EvaluacionBO configurarRolesDeEvaluacion(EvaluacionBO evaluacionBO); public List<EvaluacionBO> obtenerEvaluacionesDeEvaluador(UsuarioBO evaluador); public List<TemaBO> obtenerTemas(); public List<NivelDeConocimientoBO> obtenerNivelesDeConocimiento(); public void guardarCalificacionEvaluacion(List<CalificacionBO> calificacionesBO); public List<UsuarioBO> obtenerUsuariosDisponibles(EvaluacionBO evaluacionBO); public List<UsuarioBO> obtenerEvaluadoresDeEvaluacion(EvaluacionBO evaluacionBO); public EvaluacionBO obtenerEvaluacion(EvaluacionBO evaluacionBO); public List<CalificacionBO> obtenerCalificacionesEvaluadorEvaluacion(UsuarioBO evaluadorBO, EvaluacionBO evaluacionBO); public List<EvaluacionBO> obtenerEvaluaciones(); public List<ProgramaBO> obtenerProgramas(); public EvaluacionBO editarEvaluacion(EvaluacionBO evaluacionBO) throws EditarEvaluacionException; public List<RolBO> obtenerRolesEvaluacion(EvaluacionBO evaluacionBO); /** * <b>pre:</b>El orden de lista de calificaciones de un evaluador a otro no varia. * Este método permite calcular el nivel de conocimiento promedio por rol en cada uno de los temas de la evaluacion * @param evaluacionBO !=null.La evaluacion de la cual se desea obtener la informacion. * @param rolBO !=null. El rol del cual se quiere saber los promedios. * @return Una lista de objetos de la clase CalificacionRolBO donde se encuentra la informacion requerida. * <b>post:</b> Se ha creado una nueva lista con la calificacion promedio por rol en cada tema. */ public List<CalificacionRolBO>obtenerPromedioPorRol(EvaluacionBO evaluacionBO,RolBO rolBO); public List<FactorDeImpactoBO> obtenerFactoresDeImpacto(EvaluacionBO evaluacionBO, UsuarioBO usuarioBO); public void guardarFactoresDeImpacto(List<FactorDeImpactoBO> factoresDeImpacto); public List<FactorDeImpactoBO> obtenerFactoresDeImpactoRol(EvaluacionBO evaluacionBO, RolBO rolBO); /** * Este metodo calcula el promedio ponderado segun el promedio que arroja las calificaciones de cada rol asignado a la evaluacionBO * @param evaluacionBO - evaluacion para promediar * @return listado con los promedios */ public List<Integer> obtenerPromedioGlobal(EvaluacionBO evaluacionBO); public List<CalificacionBO> obtenerCalificacionesEvaluacion(EvaluacionBO evaluacionBO); /** * Crea una rubrica a un resultado de aprendizaje * Si el resultado de aprendizaje ya tiene una rubrica, esta es reemplazada por la nueva rubrica * @param resultadoDeAprendizajeBO El resultado de aprendizaje al cual se le va a crear la rubrica * @param rubricaBO La rubrica que se desea crear. * @return El objeto BO de la rubrica que se ha creado * @throws EvaluacionException - Si rubricaBO es nulo * - Si el resultado de aprendizaje no existe */ public RubricaBO guardarRubrica( RubricaBO rubricaBO ) throws EvaluacionException; /** * Recupera la rubrica de un resultado de aprendizaje * @param resultadoDeAprendizajeBO * @return La rubrica del resultado de aprendizaje. * @throws EvaluacionException Si el resultado de aprendizaje no existe */ public RubricaBO obtenerRubrica( ResultadoAprendizajeBO resultadoBO ) throws EvaluacionException; /** * Guarda los roles que tiene un usario en la su lista de roles y elimina los que no se encuentran en dicha lista * @param usuarioBO El usuario al que se le van a guardar los roles * @return El usuario con los roles guardados * @throws EvaluacionException - Si el parametro es nulo * - Si algun rol en la lista de roles no existe. */ public UsuarioBO guardarRoles( UsuarioBO usuarioBO )throws EvaluacionException; public void guardarResultadosAprendizajes(List<ResultadoAprendizajeBO> ListaResultadosAprendizajeBO, ProgramaBO programaBO); /** * Obtiene los resultados de aprendizaje asosciados a un programa * @param programaBO El programa del que se quieren los resultados * @return La lista de resultados de aprendizaje del programa. */ public List<ResultadoAprendizajeBO> obtenerResultadosAprendizaje( ProgramaBO programaBO ); }
gpl-3.0
654955321/HY_Recommend
功能脚本/【红叶推介】Ev躲避/SpellDatabase.cs
151544
// Copyright 2014 - 2014 Esk0r // SpellDatabase.cs is part of Evade. // // Evade is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Evade 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 Evade. If not, see <http://www.gnu.org/licenses/>. #region using System; using System.Collections.Generic; using System.Linq; using LeagueSharp; #endregion namespace Evade { public static class SpellDatabase { public static List<SpellData> Spells = new List<SpellData>(); static SpellDatabase() { //Add spells to the database #region Test if (Config.TestOnAllies) { Spells.Add( new SpellData { ChampionName = ObjectManager.Player.ChampionName, SpellName = "TestSkillShot", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCircle, Delay = 600, Range = 650, Radius = 350, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 5, IsDangerous = true, MissileSpellName = "TestSkillShot", }); } #endregion Test #region Aatrox Spells.Add( new SpellData { ChampionName = "Aatrox", SpellName = "AatroxQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotCircle, Delay = 600, Range = 650, Radius = 250, MissileSpeed = 2000, FixedRange = false, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "", }); Spells.Add( new SpellData { ChampionName = "Aatrox", SpellName = "AatroxE", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1075, Radius = 35, MissileSpeed = 1250, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = false, MissileSpellName = "AatroxEConeMissile", }); #endregion Aatrox #region Ahri Spells.Add( new SpellData { ChampionName = "Ahri", SpellName = "AhriOrbofDeception", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1000, Radius = 100, MissileSpeed = 2500, MissileAccel = -3200, MissileMaxSpeed = 2500, MissileMinSpeed = 400, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "AhriOrbMissile", CanBeRemoved = true, ForceRemove = true, CollisionObjects = new[] {CollisionObjectTypes.YasuoWall} }); Spells.Add( new SpellData { ChampionName = "Ahri", SpellName = "AhriOrbReturn", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1000, Radius = 100, MissileSpeed = 60, MissileAccel = 1900, MissileMinSpeed = 60, MissileMaxSpeed = 2600, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileFollowsUnit = true, CanBeRemoved = true, ForceRemove = true, MissileSpellName = "AhriOrbReturn", CollisionObjects = new[] {CollisionObjectTypes.YasuoWall} }); Spells.Add( new SpellData { ChampionName = "Ahri", SpellName = "AhriSeduce", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1000, Radius = 60, MissileSpeed = 1550, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "AhriSeduceMissile", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall} }); #endregion Ahri #region Amumu Spells.Add( new SpellData { ChampionName = "Amumu", SpellName = "BandageToss", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1100, Radius = 90, MissileSpeed = 2000, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "SadMummyBandageToss", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall} }); Spells.Add( new SpellData { ChampionName = "Amumu", SpellName = "CurseoftheSadMummy", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 0, Radius = 550, MissileSpeed = int.MaxValue, FixedRange = true, AddHitbox = false, DangerValue = 5, IsDangerous = true, MissileSpellName = "", }); #endregion Amumu #region Anivia Spells.Add( new SpellData { ChampionName = "Anivia", SpellName = "FlashFrost", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1100, Radius = 110, MissileSpeed = 850, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "FlashFrostSpell", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.AllyObjects}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.YasuoWall} }); #endregion Anivia #region Annie Spells.Add( new SpellData { ChampionName = "Annie", SpellName = "Incinerate", Slot = SpellSlot.W, Type = SkillShotType.SkillshotCone, Delay = 250, Range = 825, Radius = 80, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = false, DangerValue = 2, IsDangerous = false, MissileSpellName = "", }); Spells.Add( new SpellData { ChampionName = "Annie", SpellName = "InfernalGuardian", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 600, Radius = 251, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 5, IsDangerous = true, MissileSpellName = "", }); #endregion Annie #region Ashe Spells.Add( new SpellData { ChampionName = "Ashe", SpellName = "Volley", Slot = SpellSlot.W, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1250, Radius = 60, MissileSpeed = 1500, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "VolleyAttack", MultipleNumber = 9, MultipleAngle = 4.62f*(float) Math.PI/180, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.YasuoWall, CollisionObjectTypes.Minion} }); Spells.Add( new SpellData { ChampionName = "Ashe", SpellName = "EnchantedCrystalArrow", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 20000, Radius = 130, MissileSpeed = 1600, FixedRange = true, AddHitbox = true, DangerValue = 5, IsDangerous = true, MissileSpellName = "EnchantedCrystalArrow", EarlyEvade = new[] {EarlyObjects.Allies}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.YasuoWall} }); #endregion Ashe #region Bard Spells.Add( new SpellData { ChampionName = "Bard", SpellName = "BardQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 950, Radius = 60, MissileSpeed = 1600, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "BardQMissile", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.YasuoWall} }); Spells.Add( new SpellData { ChampionName = "Bard", SpellName = "BardR", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCircle, Delay = 500, Range = 3400, Radius = 350, MissileSpeed = 2100, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "BardR", }); #endregion #region Blatzcrink Spells.Add( new SpellData { ChampionName = "Blitzcrank", SpellName = "RocketGrab", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1050, Radius = 70, MissileSpeed = 1800, FixedRange = true, AddHitbox = true, DangerValue = 4, IsDangerous = true, MissileSpellName = "RocketGrabMissile", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall} }); Spells.Add( new SpellData { ChampionName = "Blitzcrank", SpellName = "StaticField", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 0, Radius = 600, MissileSpeed = int.MaxValue, FixedRange = true, AddHitbox = false, DangerValue = 2, IsDangerous = false, MissileSpellName = "", }); #endregion Blatzcrink #region Brand Spells.Add( new SpellData { ChampionName = "Brand", SpellName = "BrandBlaze", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1100, Radius = 60, MissileSpeed = 1600, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "BrandBlazeMissile", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall} }); Spells.Add( new SpellData { ChampionName = "Brand", SpellName = "BrandFissure", Slot = SpellSlot.W, Type = SkillShotType.SkillshotCircle, Delay = 850, Range = 900, Radius = 240, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "", }); #endregion Brand #region Braum Spells.Add( new SpellData { ChampionName = "Braum", SpellName = "BraumQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1050, Radius = 60, MissileSpeed = 1700, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "BraumQMissile", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall} }); Spells.Add( new SpellData { ChampionName = "Braum", SpellName = "BraumRWrapper", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 500, Range = 1200, Radius = 115, MissileSpeed = 1400, FixedRange = true, AddHitbox = true, DangerValue = 4, IsDangerous = true, MissileSpellName = "braumrmissile", CollisionObjects = new[] {CollisionObjectTypes.YasuoWall} }); #endregion Braum #region Caitlyn Spells.Add( new SpellData { ChampionName = "Caitlyn", SpellName = "CaitlynPiltoverPeacemaker", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 625, Range = 1300, Radius = 90, MissileSpeed = 2200, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "CaitlynPiltoverPeacemaker", CollisionObjects = new[] {CollisionObjectTypes.YasuoWall} }); Spells.Add( new SpellData { ChampionName = "Caitlyn", SpellName = "CaitlynEntrapment", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 125, Range = 1000, Radius = 80, MissileSpeed = 2000, FixedRange = true, AddHitbox = true, DangerValue = 1, IsDangerous = false, MissileSpellName = "CaitlynEntrapmentMissile", CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall} }); #endregion Caitlyn #region Cassiopeia Spells.Add( new SpellData { ChampionName = "Cassiopeia", SpellName = "CassiopeiaNoxiousBlast", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotCircle, Delay = 750, Range = 850, Radius = 150, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "CassiopeiaNoxiousBlast", }); Spells.Add( new SpellData { ChampionName = "Cassiopeia", SpellName = "CassiopeiaPetrifyingGaze", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCone, Delay = 600, Range = 825, Radius = 80, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = false, DangerValue = 5, IsDangerous = true, MissileSpellName = "CassiopeiaPetrifyingGaze", }); #endregion Cassiopeia #region Chogath Spells.Add( new SpellData { ChampionName = "Chogath", SpellName = "Rupture", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotCircle, Delay = 1200, Range = 950, Radius = 250, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 3, IsDangerous = false, MissileSpellName = "Rupture", }); #endregion Chogath #region Corki Spells.Add( new SpellData { ChampionName = "Corki", SpellName = "PhosphorusBomb", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotCircle, Delay = 300, Range = 825, Radius = 250, MissileSpeed = 1000, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "PhosphorusBombMissile", CollisionObjects = new[] {CollisionObjectTypes.YasuoWall} }); Spells.Add( new SpellData { ChampionName = "Corki", SpellName = "MissileBarrage", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 200, Range = 1300, Radius = 40, MissileSpeed = 2000, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "MissileBarrageMissile", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall} }); Spells.Add( new SpellData { ChampionName = "Corki", SpellName = "MissileBarrage2", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 200, Range = 1500, Radius = 40, MissileSpeed = 2000, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "MissileBarrageMissile2", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall} }); #endregion Corki #region Darius Spells.Add( new SpellData { ChampionName = "Darius", SpellName = "DariusCleave", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotCircle, Delay = 750, Range = 0, Radius = 425 - 50, MissileSpeed = int.MaxValue, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = false, MissileSpellName = "DariusCleave", FollowCaster = true, DisabledByDefault = true, }); Spells.Add( new SpellData { ChampionName = "Darius", SpellName = "DariusAxeGrabCone", Slot = SpellSlot.E, Type = SkillShotType.SkillshotCone, Delay = 250, Range = 550, Radius = 80, MissileSpeed = int.MaxValue, FixedRange = true, AddHitbox = false, DangerValue = 3, IsDangerous = true, MissileSpellName = "DariusAxeGrabCone", }); #endregion Darius #region Diana Spells.Add( new SpellData { ChampionName = "Diana", SpellName = "DianaArc", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 895, Radius = 195, MissileSpeed = 1400, FixedRange = false, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "DianaArcArc", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.AllyObjects}, CollisionObjects = new[] {CollisionObjectTypes.YasuoWall} }); Spells.Add( new SpellData { ChampionName = "Diana", SpellName = "DianaArcArc", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotArc, Delay = 250, Range = 895, Radius = 195, DontCross = true, MissileSpeed = 1400, FixedRange = false, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "DianaArcArc", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.AllyObjects}, TakeClosestPath = true, CollisionObjects = new[] {CollisionObjectTypes.YasuoWall} }); #endregion Diana #region DrMundo Spells.Add( new SpellData { ChampionName = "DrMundo", SpellName = "InfectedCleaverMissileCast", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1050, Radius = 60, MissileSpeed = 2000, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = false, MissileSpellName = "InfectedCleaverMissile", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall} }); #endregion DrMundo #region Draven Spells.Add( new SpellData { ChampionName = "Draven", SpellName = "DravenDoubleShot", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1100, Radius = 130, MissileSpeed = 1400, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "DravenDoubleShotMissile", CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.YasuoWall} }); Spells.Add( new SpellData { ChampionName = "Draven", SpellName = "DravenRCast", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 400, Range = 20000, Radius = 160, MissileSpeed = 2000, FixedRange = true, AddHitbox = true, DangerValue = 5, IsDangerous = true, MissileSpellName = "DravenR", CollisionObjects = new[] {CollisionObjectTypes.YasuoWall} }); #endregion Draven #region Ekko Spells.Add( new SpellData { ChampionName = "Ekko", SpellName = "EkkoQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 950, Radius = 60, MissileSpeed = 1650, FixedRange = true, AddHitbox = true, DangerValue = 4, IsDangerous = true, MissileSpellName = "ekkoqmis", CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.YasuoWall} }); Spells.Add( new SpellData { ChampionName = "Ekko", SpellName = "EkkoW", Slot = SpellSlot.W, Type = SkillShotType.SkillshotCircle, Delay = 3750, Range = 1600, Radius = 375, MissileSpeed = 1650, FixedRange = false, DisabledByDefault = true, AddHitbox = false, DangerValue = 3, IsDangerous = false, MissileSpellName = "EkkoW", CanBeRemoved = true }); Spells.Add( new SpellData { ChampionName = "Ekko", SpellName = "EkkoR", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 1600, Radius = 375, MissileSpeed = 1650, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = false, MissileSpellName = "EkkoR", CanBeRemoved = true, FromObjects = new[] {"Ekko_Base_R_TrailEnd.troy"} }); #endregion Ekko #region Elise Spells.Add( new SpellData { ChampionName = "Elise", SpellName = "EliseHumanE", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1100, Radius = 55, MissileSpeed = 1600, FixedRange = true, AddHitbox = true, DangerValue = 4, IsDangerous = true, MissileSpellName = "EliseHumanE", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall} }); #endregion Elise #region Evelynn Spells.Add( new SpellData { ChampionName = "Evelynn", SpellName = "EvelynnR", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 650, Radius = 350, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 5, IsDangerous = true, MissileSpellName = "EvelynnR", }); #endregion Evelynn #region Ezreal Spells.Add( new SpellData { ChampionName = "Ezreal", SpellName = "EzrealMysticShot", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1200, Radius = 60, MissileSpeed = 2000, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "EzrealMysticShotMissile", ExtraMissileNames = new[] {"EzrealMysticShotPulseMissile"}, EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall}, Id = 229, }); Spells.Add( new SpellData { ChampionName = "Ezreal", SpellName = "EzrealEssenceFlux", Slot = SpellSlot.W, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1050, Radius = 80, MissileSpeed = 1600, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "EzrealEssenceFluxMissile", CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); Spells.Add( new SpellData { ChampionName = "Ezreal", SpellName = "EzrealTrueshotBarrage", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 1000, Range = 20000, Radius = 160, MissileSpeed = 2000, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "EzrealTrueshotBarrage", CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, Id = 245, }); #endregion Ezreal #region Fiora Spells.Add( new SpellData { ChampionName = "Fiora", SpellName = "FioraW", Slot = SpellSlot.W, Type = SkillShotType.SkillshotMissileLine, Delay = 500, Range = 800, Radius = 70, MissileSpeed = 3200, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "FioraWMissile", CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); #endregion Fiora #region Fizz Spells.Add( new SpellData { ChampionName = "Fizz", SpellName = "FizzMarinerDoom", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1300, Radius = 120, MissileSpeed = 1350, FixedRange = false, AddHitbox = true, DangerValue = 5, IsDangerous = true, MissileSpellName = "FizzMarinerDoomMissile", EarlyEvade = new[] {EarlyObjects.Allies}, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.YasuoWall}, CanBeRemoved = true, }); #endregion Fizz #region Galio Spells.Add( new SpellData { ChampionName = "Galio", SpellName = "GalioResoluteSmite", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 900, Radius = 200, MissileSpeed = 1300, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "GalioResoluteSmite", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, }); Spells.Add( new SpellData { ChampionName = "Galio", SpellName = "GalioRighteousGust", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1200, Radius = 120, MissileSpeed = 1200, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "GalioRighteousGust", CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); Spells.Add( new SpellData { ChampionName = "Galio", SpellName = "GalioIdolOfDurand", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 0, Radius = 550, MissileSpeed = int.MaxValue, FixedRange = true, AddHitbox = false, DangerValue = 5, IsDangerous = true, MissileSpellName = "", }); #endregion Galio #region Gnar Spells.Add( new SpellData { ChampionName = "Gnar", SpellName = "GnarQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1125, Radius = 60, MissileSpeed = 2500, MissileAccel = -3000, MissileMaxSpeed = 2500, MissileMinSpeed = 1400, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, CanBeRemoved = true, ForceRemove = true, MissileSpellName = "gnarqmissile", CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); Spells.Add( new SpellData { ChampionName = "Gnar", SpellName = "GnarQReturn", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 0, Range = 2500, Radius = 75, MissileSpeed = 60, MissileAccel = 800, MissileMaxSpeed = 2600, MissileMinSpeed = 60, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, CanBeRemoved = true, ForceRemove = true, MissileSpellName = "GnarQMissileReturn", DisableFowDetection = false, DisabledByDefault = true, CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); Spells.Add( new SpellData { ChampionName = "Gnar", SpellName = "GnarBigQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 500, Range = 1150, Radius = 90, MissileSpeed = 2100, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "GnarBigQMissile", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); Spells.Add( new SpellData { ChampionName = "Gnar", SpellName = "GnarBigW", Slot = SpellSlot.W, Type = SkillShotType.SkillshotLine, Delay = 600, Range = 600, Radius = 80, MissileSpeed = int.MaxValue, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "GnarBigW", }); Spells.Add( new SpellData { ChampionName = "Gnar", SpellName = "GnarE", Slot = SpellSlot.E, Type = SkillShotType.SkillshotCircle, Delay = 0, Range = 473, Radius = 150, MissileSpeed = 903, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "GnarE", }); Spells.Add( new SpellData { ChampionName = "Gnar", SpellName = "GnarBigE", Slot = SpellSlot.E, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 475, Radius = 200, MissileSpeed = 1000, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "GnarBigE", }); Spells.Add( new SpellData { ChampionName = "Gnar", SpellName = "GnarR", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 0, Radius = 500, MissileSpeed = int.MaxValue, FixedRange = true, AddHitbox = false, DangerValue = 5, IsDangerous = true, MissileSpellName = "", }); #endregion #region Gragas Spells.Add( new SpellData { ChampionName = "Gragas", SpellName = "GragasQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 1100, Radius = 275, MissileSpeed = 1300, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "GragasQMissile", ExtraDuration = 4500, ToggleParticleName = "Gragas_.+_Q_(Enemy|Ally)", DontCross = true, }); Spells.Add( new SpellData { ChampionName = "Gragas", SpellName = "GragasE", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 0, Range = 950, Radius = 200, MissileSpeed = 1200, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "GragasE", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = true, ExtraRange = 300, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.Minion}, }); Spells.Add( new SpellData { ChampionName = "Gragas", SpellName = "GragasR", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 1050, Radius = 375, MissileSpeed = 1800, FixedRange = false, AddHitbox = true, DangerValue = 5, IsDangerous = true, MissileSpellName = "GragasRBoom", CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); #endregion Gragas #region Graves Spells.Add( new SpellData { ChampionName = "Graves", SpellName = "GravesClusterShot", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1000, Radius = 50, MissileSpeed = 2000, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "GravesClusterShotAttack", CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, MultipleNumber = 3, MultipleAngle = 15*(float) Math.PI/180, }); Spells.Add( new SpellData { ChampionName = "Graves", SpellName = "GravesChargeShot", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1100, Radius = 100, MissileSpeed = 2100, FixedRange = true, AddHitbox = true, DangerValue = 5, IsDangerous = true, MissileSpellName = "GravesChargeShotShot", CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall}, }); #endregion Graves #region Heimerdinger Spells.Add( new SpellData { ChampionName = "Heimerdinger", SpellName = "Heimerdingerwm", Slot = SpellSlot.W, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1500, Radius = 70, MissileSpeed = 1800, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "HeimerdingerWAttack2", CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); Spells.Add( new SpellData { ChampionName = "Heimerdinger", SpellName = "HeimerdingerE", Slot = SpellSlot.E, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 925, Radius = 100, MissileSpeed = 1200, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "heimerdingerespell", CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); #endregion Heimerdinger #region Irelia Spells.Add( new SpellData { ChampionName = "Irelia", SpellName = "IreliaTranscendentBlades", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 0, Range = 1200, Radius = 65, MissileSpeed = 1600, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "IreliaTranscendentBlades", CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); #endregion Irelia #region Janna Spells.Add( new SpellData { ChampionName = "Janna", SpellName = "JannaQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1700, Radius = 120, MissileSpeed = 900, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "HowlingGaleSpell", CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); #endregion Janna #region JarvanIV Spells.Add( new SpellData { ChampionName = "JarvanIV", SpellName = "JarvanIVDragonStrike", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotLine, Delay = 600, Range = 770, Radius = 70, MissileSpeed = int.MaxValue, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = false, }); Spells.Add( new SpellData { ChampionName = "JarvanIV", SpellName = "JarvanIVEQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 880, Radius = 70, MissileSpeed = 1450, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, }); Spells.Add( new SpellData { ChampionName = "JarvanIV", SpellName = "JarvanIVDemacianStandard", Slot = SpellSlot.E, Type = SkillShotType.SkillshotCircle, Delay = 500, Range = 860, Radius = 175, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "JarvanIVDemacianStandard", }); #endregion JarvanIV #region Jayce Spells.Add( new SpellData { ChampionName = "Jayce", SpellName = "jayceshockblast", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1300, Radius = 70, MissileSpeed = 1450, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "JayceShockBlastMis", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall}, }); Spells.Add( new SpellData { ChampionName = "Jayce", SpellName = "JayceQAccel", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1300, Radius = 70, MissileSpeed = 2350, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "JayceShockBlastWallMis", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall}, }); #endregion Jayce #region Jinx //TODO: Detect the animation from fow instead of the missile. Spells.Add( new SpellData { ChampionName = "Jinx", SpellName = "JinxW", Slot = SpellSlot.W, Type = SkillShotType.SkillshotMissileLine, Delay = 600, Range = 1500, Radius = 60, MissileSpeed = 3300, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "JinxWMissile", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall}, }); Spells.Add( new SpellData { ChampionName = "Jinx", SpellName = "JinxR", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 600, Range = 20000, Radius = 140, MissileSpeed = 1700, FixedRange = true, AddHitbox = true, DangerValue = 5, IsDangerous = true, MissileSpellName = "JinxR", EarlyEvade = new[] {EarlyObjects.Allies}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.YasuoWall}, }); #endregion Jinx #region Kalista Spells.Add( new SpellData { ChampionName = "Kalista", SpellName = "KalistaMysticShot", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1200, Radius = 40, MissileSpeed = 1700, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "kalistamysticshotmis", ExtraMissileNames = new[] {"kalistamysticshotmistrue"}, EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall}, }); #endregion Kalista #region Karma Spells.Add( new SpellData { ChampionName = "Karma", SpellName = "KarmaQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1050, Radius = 60, MissileSpeed = 1700, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "KarmaQMissile", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall}, }); //TODO: add the circle at the end. Spells.Add( new SpellData { ChampionName = "Karma", SpellName = "KarmaQMantra", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 950, Radius = 80, MissileSpeed = 1700, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "KarmaQMissileMantra", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall}, }); #endregion Karma #region Karthus Spells.Add( new SpellData { ChampionName = "Karthus", SpellName = "KarthusLayWasteA2", ExtraSpellNames = new[] { "karthuslaywastea3", "karthuslaywastea1", "karthuslaywastedeada1", "karthuslaywastedeada2", "karthuslaywastedeada3" }, Slot = SpellSlot.Q, Type = SkillShotType.SkillshotCircle, Delay = 625, Range = 875, Radius = 160, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "", }); #endregion Karthus #region Kassadin Spells.Add( new SpellData { ChampionName = "Kassadin", SpellName = "RiftWalk", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 450, Radius = 270, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "RiftWalk", }); #endregion Kassadin #region Kennen Spells.Add( new SpellData { ChampionName = "Kennen", SpellName = "KennenShurikenHurlMissile1", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 125, Range = 1050, Radius = 50, MissileSpeed = 1700, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "KennenShurikenHurlMissile1", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall}, }); #endregion Kennen #region Khazix Spells.Add( new SpellData { ChampionName = "Khazix", SpellName = "KhazixW", ExtraSpellNames = new[] {"khazixwlong"}, Slot = SpellSlot.W, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1025, Radius = 73, MissileSpeed = 1700, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "KhazixWMissile", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = true, MultipleNumber = 3, MultipleAngle = 22f*(float) Math.PI/180, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall}, }); Spells.Add( new SpellData { ChampionName = "Khazix", SpellName = "KhazixE", Slot = SpellSlot.E, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 600, Radius = 300, MissileSpeed = 1500, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "KhazixE", }); #endregion Khazix #region Kogmaw Spells.Add( new SpellData { ChampionName = "Kogmaw", SpellName = "KogMawQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1200, Radius = 70, MissileSpeed = 1650, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "KogMawQMis", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall}, }); Spells.Add( new SpellData { ChampionName = "Kogmaw", SpellName = "KogMawVoidOoze", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1360, Radius = 120, MissileSpeed = 1400, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "KogMawVoidOozeMissile", CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); Spells.Add( new SpellData { ChampionName = "Kogmaw", SpellName = "KogMawLivingArtillery", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCircle, Delay = 1200, Range = 1800, Radius = 150, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "KogMawLivingArtillery", }); #endregion Kogmaw #region Leblanc Spells.Add( new SpellData { ChampionName = "Leblanc", SpellName = "LeblancSlide", Slot = SpellSlot.W, Type = SkillShotType.SkillshotCircle, Delay = 0, Range = 600, Radius = 220, MissileSpeed = 1450, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "LeblancSlide", }); Spells.Add( new SpellData { ChampionName = "Leblanc", SpellName = "LeblancSlideM", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCircle, Delay = 0, Range = 600, Radius = 220, MissileSpeed = 1450, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "LeblancSlideM", }); Spells.Add( new SpellData { ChampionName = "Leblanc", SpellName = "LeblancSoulShackle", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 950, Radius = 70, MissileSpeed = 1600, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "LeblancSoulShackle", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall}, }); Spells.Add( new SpellData { ChampionName = "Leblanc", SpellName = "LeblancSoulShackleM", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 950, Radius = 70, MissileSpeed = 1600, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "LeblancSoulShackleM", CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall}, }); #endregion Leblanc #region LeeSin Spells.Add( new SpellData { ChampionName = "LeeSin", SpellName = "BlindMonkQOne", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1100, Radius = 65, MissileSpeed = 1800, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "BlindMonkQOne", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall}, }); #endregion LeeSin #region Leona Spells.Add( new SpellData { ChampionName = "Leona", SpellName = "LeonaZenithBlade", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 905, Radius = 70, MissileSpeed = 2000, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, TakeClosestPath = true, MissileSpellName = "LeonaZenithBladeMissile", EarlyEvade = new[] {EarlyObjects.Allies}, CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); Spells.Add( new SpellData { ChampionName = "Leona", SpellName = "LeonaSolarFlare", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCircle, Delay = 1000, Range = 1200, Radius = 300, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 5, IsDangerous = true, MissileSpellName = "LeonaSolarFlare", }); #endregion Leona #region Lissandra Spells.Add( new SpellData { ChampionName = "Lissandra", SpellName = "LissandraQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 700, Radius = 75, MissileSpeed = 2200, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "LissandraQMissile", CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); Spells.Add( new SpellData { ChampionName = "Lissandra", SpellName = "LissandraQShards", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 700, Radius = 90, MissileSpeed = 2200, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "lissandraqshards", CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); Spells.Add( new SpellData { ChampionName = "Lissandra", SpellName = "LissandraE", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1025, Radius = 125, MissileSpeed = 850, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "LissandraEMissile", CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); #endregion Lulu #region Lucian Spells.Add( new SpellData { ChampionName = "Lucian", SpellName = "LucianQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotLine, Delay = 500, Range = 1300, Radius = 65, MissileSpeed = int.MaxValue, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "LucianQ", }); Spells.Add( new SpellData { ChampionName = "Lucian", SpellName = "LucianW", Slot = SpellSlot.W, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1000, Radius = 55, MissileSpeed = 1600, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "lucianwmissile", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, }); Spells.Add( new SpellData { ChampionName = "Lucian", SpellName = "LucianRMis", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 500, Range = 1400, Radius = 110, MissileSpeed = 2800, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "lucianrmissileoffhand", ExtraMissileNames = new[] {"lucianrmissile"}, EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, DontCheckForDuplicates = true, DisabledByDefault = true, }); #endregion Lucian #region Lulu Spells.Add( new SpellData { ChampionName = "Lulu", SpellName = "LuluQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 950, Radius = 60, MissileSpeed = 1450, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "LuluQMissile", CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); Spells.Add( new SpellData { ChampionName = "Lulu", SpellName = "LuluQPix", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 950, Radius = 60, MissileSpeed = 1450, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "LuluQMissileTwo", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); #endregion Lulu #region Lux Spells.Add( new SpellData { ChampionName = "Lux", SpellName = "LuxLightBinding", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1300, Radius = 70, MissileSpeed = 1200, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "LuxLightBindingMis", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, //CanBeRemoved = true, //CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall, }, }); Spells.Add( new SpellData { ChampionName = "Lux", SpellName = "LuxLightStrikeKugel", Slot = SpellSlot.E, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 1100, Radius = 275, MissileSpeed = 1300, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "LuxLightStrikeKugel", ExtraDuration = 5500, ToggleParticleName = "Lux_.+_E_tar_aoe_", DontCross = true, CanBeRemoved = true, DisabledByDefault = true, CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); Spells.Add( new SpellData { ChampionName = "Lux", SpellName = "LuxMaliceCannon", Slot = SpellSlot.R, Type = SkillShotType.SkillshotLine, Delay = 1000, Range = 3500, Radius = 190, MissileSpeed = int.MaxValue, FixedRange = true, AddHitbox = true, DangerValue = 5, IsDangerous = true, MissileSpellName = "LuxMaliceCannon", }); #endregion Lux #region Malphite Spells.Add( new SpellData { ChampionName = "Malphite", SpellName = "UFSlash", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCircle, Delay = 0, Range = 1000, Radius = 270, MissileSpeed = 1500, FixedRange = false, AddHitbox = true, DangerValue = 5, IsDangerous = true, MissileSpellName = "UFSlash", }); #endregion Malphite #region Malzahar Spells.Add( new SpellData { ChampionName = "Malzahar", SpellName = "AlZaharCalloftheVoid", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotLine, Delay = 1000, Range = 900, Radius = 85, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, DontCross = true, MissileSpellName = "AlZaharCalloftheVoid", }); #endregion Malzahar #region Morgana Spells.Add( new SpellData { ChampionName = "Morgana", SpellName = "DarkBindingMissile", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1300, Radius = 80, MissileSpeed = 1200, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "DarkBindingMissile", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall}, }); #endregion Morgana #region Nami Spells.Add( new SpellData { ChampionName = "Nami", SpellName = "NamiQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotCircle, Delay = 950, Range = 1625, Radius = 150, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "namiqmissile", }); Spells.Add( new SpellData { ChampionName = "Nami", SpellName = "NamiR", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 500, Range = 2750, Radius = 260, MissileSpeed = 850, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "NamiRMissile", CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); #endregion Nami #region Nautilus Spells.Add( new SpellData { ChampionName = "Nautilus", SpellName = "NautilusAnchorDrag", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1250, Radius = 90, MissileSpeed = 2000, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "NautilusAnchorDragMissile", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects, EarlyObjects.Wall }, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall}, //walls? }); #endregion Nautilus #region Nocturne Spells.Add( new SpellData { ChampionName = "Nocturne", SpellName = "NocturneDuskbringer", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1125, Radius = 60, MissileSpeed = 1400, DangerValue = 2, IsDangerous = false, MissileSpellName = "NocturneDuskbringer", CollisionObjects = new[] {CollisionObjectTypes.YasuoWall} }); #endregion Nocturne #region Nidalee Spells.Add( new SpellData { ChampionName = "Nidalee", SpellName = "JavelinToss", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1500, Radius = 40, MissileSpeed = 1300, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "JavelinToss", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall}, }); #endregion Nidalee #region Olaf Spells.Add( new SpellData { ChampionName = "Olaf", SpellName = "OlafAxeThrowCast", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1000, ExtraRange = 150, Radius = 105, MissileSpeed = 1600, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "olafaxethrow", CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.YasuoWall} }); #endregion Olaf #region Orianna Spells.Add( new SpellData { ChampionName = "Orianna", SpellName = "OriannasQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 0, Range = 1500, Radius = 80, MissileSpeed = 1200, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "orianaizuna", CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); Spells.Add( new SpellData { ChampionName = "Orianna", SpellName = "OriannaQend", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotCircle, Delay = 0, Range = 1500, Radius = 90, MissileSpeed = 1200, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "", CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); Spells.Add( new SpellData { ChampionName = "Orianna", SpellName = "OrianaDissonanceCommand", Slot = SpellSlot.W, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 0, Radius = 255, MissileSpeed = int.MaxValue, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "OrianaDissonanceCommand", FromObject = "yomu_ring_", }); Spells.Add( new SpellData { ChampionName = "Orianna", SpellName = "OriannasE", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 0, Range = 1500, Radius = 85, MissileSpeed = 1850, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "orianaredact", CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); Spells.Add( new SpellData { ChampionName = "Orianna", SpellName = "OrianaDetonateCommand", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCircle, Delay = 700, Range = 0, Radius = 410, MissileSpeed = int.MaxValue, FixedRange = true, AddHitbox = true, DangerValue = 5, IsDangerous = true, MissileSpellName = "OrianaDetonateCommand", FromObject = "yomu_ring_", }); #endregion Orianna #region Quinn Spells.Add( new SpellData { ChampionName = "Quinn", SpellName = "QuinnQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1050, Radius = 80, MissileSpeed = 1550, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "QuinnQMissile", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall}, }); #endregion Quinn #region Rengar Spells.Add( new SpellData { ChampionName = "Rengar", SpellName = "RengarE", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1000, Radius = 70, MissileSpeed = 1500, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "RengarEFinal", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall}, }); #endregion Rengar #region RekSai Spells.Add( new SpellData { ChampionName = "RekSai", SpellName = "reksaiqburrowed", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 500, Range = 1625, Radius = 60, MissileSpeed = 1950, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = false, MissileSpellName = "RekSaiQBurrowedMis", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall}, }); #endregion RekSai #region Riven Spells.Add( new SpellData { ChampionName = "Riven", SpellName = "rivenizunablade", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1100, Radius = 125, MissileSpeed = 1600, FixedRange = false, AddHitbox = false, DangerValue = 5, IsDangerous = true, MultipleNumber = 3, MultipleAngle = 15*(float) Math.PI/180, MissileSpellName = "RivenLightsaberMissile", ExtraMissileNames = new[] {"RivenLightsaberMissileSide"} }); #endregion Riven #region Rumble Spells.Add( new SpellData { ChampionName = "Rumble", SpellName = "RumbleGrenade", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 950, Radius = 60, MissileSpeed = 2000, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "RumbleGrenade", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall}, }); Spells.Add( new SpellData { ChampionName = "Rumble", SpellName = "RumbleCarpetBombM", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 400, MissileDelayed = true, Range = 1200, Radius = 200, MissileSpeed = 1600, FixedRange = true, AddHitbox = true, DangerValue = 4, IsDangerous = false, MissileSpellName = "RumbleCarpetBombMissile", CanBeRemoved = false, CollisionObjects = new CollisionObjectTypes[] {}, }); #endregion Rumble #region Ryze Spells.Add( new SpellData { ChampionName = "Ryze", SpellName = "RyzeQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 900, Radius = 50, MissileSpeed = 1700, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "RyzeQ", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall}, }); Spells.Add( new SpellData { ChampionName = "Ryze", SpellName = "ryzerq", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 900, Radius = 50, MissileSpeed = 1700, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "ryzerq", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall}, }); #endregion #region Sejuani Spells.Add( new SpellData { ChampionName = "Sejuani", SpellName = "SejuaniArcticAssault", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 0, Range = 900, Radius = 70, MissileSpeed = 1600, FixedRange = false, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, ExtraRange = 200, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall}, }); //TODO: fix? Spells.Add( new SpellData { ChampionName = "Sejuani", SpellName = "SejuaniGlacialPrisonStart", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1100, Radius = 110, MissileSpeed = 1600, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "sejuaniglacialprison", CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.YasuoWall}, }); #endregion Sejuani #region Sion Spells.Add( new SpellData { ChampionName = "Sion", SpellName = "SionE", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 800, Radius = 80, MissileSpeed = 1800, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "SionEMissile", CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.YasuoWall}, }); Spells.Add( new SpellData { ChampionName = "Sion", SpellName = "SionR", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 500, Range = 800, Radius = 120, MissileSpeed = 1000, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, EarlyEvade = new[] {EarlyObjects.Allies}, CollisionObjects = new[] {CollisionObjectTypes.Champions}, }); #endregion Sion #region Soraka Spells.Add( new SpellData { ChampionName = "Soraka", SpellName = "SorakaQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotCircle, Delay = 500, Range = 950, Radius = 300, MissileSpeed = 1750, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "", CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); #endregion Soraka #region Shen Spells.Add( new SpellData { ChampionName = "Shen", SpellName = "ShenShadowDash", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 0, Range = 650, Radius = 50, MissileSpeed = 1600, FixedRange = false, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "ShenShadowDash", ExtraRange = 200, CollisionObjects = new[] {CollisionObjectTypes.Minion, CollisionObjectTypes.Champions, CollisionObjectTypes.YasuoWall}, }); #endregion Shen #region Shyvana Spells.Add( new SpellData { ChampionName = "Shyvana", SpellName = "ShyvanaFireball", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 950, Radius = 60, MissileSpeed = 1700, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "ShyvanaFireballMissile", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CollisionObjects = new[] {CollisionObjectTypes.Minion, CollisionObjectTypes.Champions, CollisionObjectTypes.YasuoWall}, }); Spells.Add( new SpellData { ChampionName = "Shyvana", SpellName = "ShyvanaTransformCast", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1000, Radius = 150, MissileSpeed = 1500, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "ShyvanaTransformCast", ExtraRange = 200, }); #endregion Shyvana #region Sivir Spells.Add( new SpellData { ChampionName = "Sivir", SpellName = "SivirQReturn", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 0, Range = 1250, Radius = 100, MissileSpeed = 1350, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "SivirQMissileReturn", DisableFowDetection = false, MissileFollowsUnit = true, CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); Spells.Add( new SpellData { ChampionName = "Sivir", SpellName = "SivirQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1250, Radius = 90, MissileSpeed = 1350, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "SivirQMissile", CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); #endregion Sivir #region Skarner Spells.Add( new SpellData { ChampionName = "Skarner", SpellName = "SkarnerFracture", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1000, Radius = 70, MissileSpeed = 1500, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "SkarnerFractureMissile", CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); #endregion Skarner #region Sona Spells.Add( new SpellData { ChampionName = "Sona", SpellName = "SonaR", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1000, Radius = 140, MissileSpeed = 2400, FixedRange = true, AddHitbox = true, DangerValue = 5, IsDangerous = true, MissileSpellName = "SonaR", CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); #endregion Sona #region Swain Spells.Add( new SpellData { ChampionName = "Swain", SpellName = "SwainShadowGrasp", Slot = SpellSlot.W, Type = SkillShotType.SkillshotCircle, Delay = 1100, Range = 900, Radius = 180, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "SwainShadowGrasp", }); #endregion Swain #region Syndra Spells.Add( new SpellData { ChampionName = "Syndra", SpellName = "SyndraQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotCircle, Delay = 600, Range = 800, Radius = 150, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "SyndraQ", }); Spells.Add( new SpellData { ChampionName = "Syndra", SpellName = "syndrawcast", Slot = SpellSlot.W, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 950, Radius = 210, MissileSpeed = 1450, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "syndrawcast", }); Spells.Add( new SpellData { ChampionName = "Syndra", SpellName = "syndrae5", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 300, Range = 950, Radius = 90, MissileSpeed = 1601, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "syndrae5", DisableFowDetection = true, }); Spells.Add( new SpellData { ChampionName = "Syndra", SpellName = "SyndraE", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 300, Range = 950, Radius = 90, MissileSpeed = 1601, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, DisableFowDetection = true, MissileSpellName = "SyndraE", }); #endregion Syndra #region Talon Spells.Add( new SpellData { ChampionName = "Talon", SpellName = "TalonRake", Slot = SpellSlot.W, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 800, Radius = 80, MissileSpeed = 2300, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = true, MultipleNumber = 3, MultipleAngle = 20*(float) Math.PI/180, MissileSpellName = "talonrakemissileone", }); Spells.Add( new SpellData { ChampionName = "Talon", SpellName = "TalonRakeReturn", Slot = SpellSlot.W, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 800, Radius = 80, MissileSpeed = 1850, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = true, MultipleNumber = 3, MultipleAngle = 20*(float) Math.PI/180, MissileSpellName = "talonrakemissiletwo", }); #endregion Riven #region Tahm Kench Spells.Add( new SpellData { ChampionName = "TahmKench", SpellName = "TahmKenchQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 951, Radius = 90, MissileSpeed = 2800, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "tahmkenchqmissile", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Minion, CollisionObjectTypes.Champions, CollisionObjectTypes.YasuoWall}, }); #endregion Tahm Kench #region Thresh Spells.Add( new SpellData { ChampionName = "Thresh", SpellName = "ThreshQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 500, Range = 1100, Radius = 70, MissileSpeed = 1900, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "ThreshQMissile", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Minion, CollisionObjectTypes.Champions, CollisionObjectTypes.YasuoWall}, }); Spells.Add( new SpellData { ChampionName = "Thresh", SpellName = "ThreshEFlay", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 125, Range = 1075, Radius = 110, MissileSpeed = 2000, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, Centered = true, MissileSpellName = "ThreshEMissile1", }); #endregion Thresh #region Tristana Spells.Add( new SpellData { ChampionName = "Tristana", SpellName = "RocketJump", Slot = SpellSlot.W, Type = SkillShotType.SkillshotCircle, Delay = 500, Range = 900, Radius = 270, MissileSpeed = 1500, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "RocketJump", }); #endregion Tristana #region Tryndamere Spells.Add( new SpellData { ChampionName = "Tryndamere", SpellName = "slashCast", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 0, Range = 660, Radius = 93, MissileSpeed = 1300, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "slashCast", }); #endregion Tryndamere #region TwistedFate Spells.Add( new SpellData { ChampionName = "TwistedFate", SpellName = "WildCards", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1450, Radius = 40, MissileSpeed = 1000, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "SealFateMissile", MultipleNumber = 3, MultipleAngle = 28*(float) Math.PI/180, CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); #endregion TwistedFate #region Twitch Spells.Add( new SpellData { ChampionName = "Twitch", SpellName = "TwitchVenomCask", Slot = SpellSlot.W, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 900, Radius = 275, MissileSpeed = 1400, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "TwitchVenomCaskMissile", CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); #endregion Twitch #region Urgot Spells.Add( new SpellData { ChampionName = "Urgot", SpellName = "UrgotHeatseekingLineMissile", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 125, Range = 1000, Radius = 60, MissileSpeed = 1600, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "UrgotHeatseekingLineMissile", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = true, }); Spells.Add( new SpellData { ChampionName = "Urgot", SpellName = "UrgotPlasmaGrenade", Slot = SpellSlot.E, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 1100, Radius = 210, MissileSpeed = 1500, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "UrgotPlasmaGrenadeBoom", }); #endregion Urgot #region Varus Spells.Add( new SpellData { ChampionName = "Varus", SpellName = "VarusQMissilee", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1800, Radius = 70, MissileSpeed = 1900, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "VarusQMissile", CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); Spells.Add( new SpellData { ChampionName = "Varus", SpellName = "VarusE", Slot = SpellSlot.E, Type = SkillShotType.SkillshotCircle, Delay = 1000, Range = 925, Radius = 235, MissileSpeed = 1500, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "VarusE", }); Spells.Add( new SpellData { ChampionName = "Varus", SpellName = "VarusR", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1200, Radius = 120, MissileSpeed = 1950, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "VarusRMissile", EarlyEvade = new[] {EarlyObjects.Allies}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Champions, CollisionObjectTypes.YasuoWall}, }); #endregion Varus #region Veigar Spells.Add( new SpellData { ChampionName = "Veigar", SpellName = "VeigarBalefulStrike", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 950, Radius = 70, MissileSpeed = 2000, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "VeigarBalefulStrikeMis", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); Spells.Add( new SpellData { ChampionName = "Veigar", SpellName = "VeigarDarkMatter", Slot = SpellSlot.W, Type = SkillShotType.SkillshotCircle, Delay = 1350, Range = 900, Radius = 225, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "", }); Spells.Add( new SpellData { ChampionName = "Veigar", SpellName = "VeigarEventHorizon", Slot = SpellSlot.E, Type = SkillShotType.SkillshotRing, Delay = 500, Range = 700, Radius = 80, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = false, DangerValue = 3, IsDangerous = true, DontAddExtraDuration = true, RingRadius = 350, ExtraDuration = 3300, DontCross = true, MissileSpellName = "", }); #endregion Veigar #region Velkoz Spells.Add( new SpellData { ChampionName = "Velkoz", SpellName = "VelkozQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1100, Radius = 50, MissileSpeed = 1300, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "VelkozQMissile", CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Minion, CollisionObjectTypes.Champions, CollisionObjectTypes.YasuoWall}, }); Spells.Add( new SpellData { ChampionName = "Velkoz", SpellName = "VelkozQSplit", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1100, Radius = 55, MissileSpeed = 2100, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "VelkozQMissileSplit", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Minion, CollisionObjectTypes.Champions, CollisionObjectTypes.YasuoWall}, }); Spells.Add( new SpellData { ChampionName = "Velkoz", SpellName = "VelkozW", Slot = SpellSlot.W, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1200, Radius = 88, MissileSpeed = 1700, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "VelkozWMissile", }); Spells.Add( new SpellData { ChampionName = "Velkoz", SpellName = "VelkozE", Slot = SpellSlot.E, Type = SkillShotType.SkillshotCircle, Delay = 500, Range = 800, Radius = 225, MissileSpeed = 1500, FixedRange = false, AddHitbox = false, DangerValue = 2, IsDangerous = false, MissileSpellName = "VelkozEMissile", }); #endregion Velkoz #region Vi Spells.Add( new SpellData { ChampionName = "Vi", SpellName = "Vi-q", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1000, Radius = 90, MissileSpeed = 1500, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "ViQMissile", EarlyEvade = new[] {EarlyObjects.Allies}, }); #endregion Vi #region Viktor Spells.Add( new SpellData { ChampionName = "Viktor", SpellName = "Laser", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1500, Radius = 80, MissileSpeed = 780, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "ViktorDeathRayMissile", ExtraMissileNames = new[] {"viktoreaugmissile"}, CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); #endregion Viktor #region Xerath Spells.Add( new SpellData { ChampionName = "Xerath", SpellName = "xeratharcanopulse2", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotLine, Delay = 600, Range = 1600, Radius = 100, MissileSpeed = int.MaxValue, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "xeratharcanopulse2", }); Spells.Add( new SpellData { ChampionName = "Xerath", SpellName = "XerathArcaneBarrage2", Slot = SpellSlot.W, Type = SkillShotType.SkillshotCircle, Delay = 700, Range = 1000, Radius = 200, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "XerathArcaneBarrage2", }); Spells.Add( new SpellData { ChampionName = "Xerath", SpellName = "XerathMageSpear", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 200, Range = 1150, Radius = 60, MissileSpeed = 1400, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = true, MissileSpellName = "XerathMageSpearMissile", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = true, CollisionObjects = new[] {CollisionObjectTypes.Minion, CollisionObjectTypes.Champions, CollisionObjectTypes.YasuoWall}, }); Spells.Add( new SpellData { ChampionName = "Xerath", SpellName = "xerathrmissilewrapper", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCircle, Delay = 700, Range = 5600, Radius = 120, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "xerathrmissilewrapper", }); #endregion Xerath #region Yasuo Spells.Add( new SpellData { ChampionName = "Yasuo", SpellName = "yasuoq2", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotLine, Delay = 400, Range = 550, Radius = 20, MissileSpeed = int.MaxValue, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = true, MissileSpellName = "yasuoq2", Invert = true, }); Spells.Add( new SpellData { ChampionName = "Yasuo", SpellName = "yasuoq3w", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 500, Range = 1150, Radius = 90, MissileSpeed = 1500, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "yasuoq3w", CollisionObjects = new[] {CollisionObjectTypes.YasuoWall} }); Spells.Add( new SpellData { ChampionName = "Yasuo", SpellName = "yasuoq", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotLine, Delay = 400, Range = 550, Radius = 20, MissileSpeed = int.MaxValue, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = true, MissileSpellName = "yasuoq", Invert = true, }); #endregion Yasuo #region Zac Spells.Add( new SpellData { ChampionName = "Zac", SpellName = "ZacQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotLine, Delay = 500, Range = 550, Radius = 120, MissileSpeed = int.MaxValue, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "ZacQ", }); #endregion Zac #region Zed Spells.Add( new SpellData { ChampionName = "Zed", SpellName = "ZedQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 925, Radius = 50, MissileSpeed = 1700, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "ZedQMissile", //FromObjects = new[] { "Zed_Clone_idle.troy", "Zed_Clone_Idle.troy" }, FromObjects = new[] {"Zed_Base_W_tar.troy", "Zed_Base_W_cloneswap_buf.troy"}, CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); #endregion Zed #region Ziggs Spells.Add( new SpellData { ChampionName = "Ziggs", SpellName = "ZiggsQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 850, Radius = 140, MissileSpeed = 1700, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "ZiggsQSpell", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = false, DisableFowDetection = true, }); Spells.Add( new SpellData { ChampionName = "Ziggs", SpellName = "ZiggsQBounce1", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 850, Radius = 140, MissileSpeed = 1700, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "ZiggsQSpell2", ExtraMissileNames = new[] {"ZiggsQSpell2"}, EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = false, DisableFowDetection = true, }); Spells.Add( new SpellData { ChampionName = "Ziggs", SpellName = "ZiggsQBounce2", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 850, Radius = 160, MissileSpeed = 1700, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "ZiggsQSpell3", ExtraMissileNames = new[] {"ZiggsQSpell3"}, EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CanBeRemoved = false, DisableFowDetection = true, }); Spells.Add( new SpellData { ChampionName = "Ziggs", SpellName = "ZiggsW", Slot = SpellSlot.W, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 1000, Radius = 275, MissileSpeed = 1750, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "ZiggsW", DisableFowDetection = true, CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); Spells.Add( new SpellData { ChampionName = "Ziggs", SpellName = "ZiggsE", Slot = SpellSlot.E, Type = SkillShotType.SkillshotCircle, Delay = 500, Range = 900, Radius = 235, MissileSpeed = 1750, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "ZiggsE", DisableFowDetection = true, }); Spells.Add( new SpellData { ChampionName = "Ziggs", SpellName = "ZiggsR", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCircle, Delay = 0, Range = 5300, Radius = 500, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "ZiggsR", DisableFowDetection = true, }); #endregion Ziggs #region Zilean Spells.Add( new SpellData { ChampionName = "Zilean", SpellName = "ZileanQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotCircle, Delay = 300, Range = 900, Radius = 210, MissileSpeed = 2000, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "ZileanQMissile", CollisionObjects = new[] {CollisionObjectTypes.YasuoWall} }); #endregion Zilean #region Zyra Spells.Add( new SpellData { ChampionName = "Zyra", SpellName = "ZyraQFissure", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotCircle, Delay = 850, Range = 800, Radius = 220, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "ZyraQFissure", }); Spells.Add( new SpellData { ChampionName = "Zyra", SpellName = "ZyraGraspingRoots", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1150, Radius = 70, MissileSpeed = 1150, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "ZyraGraspingRoots", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); Spells.Add( new SpellData { ChampionName = "Zyra", SpellName = "zyrapassivedeathmanager", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 500, Range = 1474, Radius = 70, MissileSpeed = 2000, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "zyrapassivedeathmanager", EarlyEvade = new[] {EarlyObjects.Allies, EarlyObjects.Minions, EarlyObjects.AllyObjects}, CollisionObjects = new[] {CollisionObjectTypes.YasuoWall}, }); #endregion Zyra //Console.WriteLine("Added " + Spells.Count + " spells."); } public static SpellData GetByName(string spellName) { spellName = spellName.ToLower(); foreach (var spellData in Spells) { if (spellData.SpellName.ToLower() == spellName || spellData.ExtraSpellNames.Contains(spellName)) { return spellData; } } return null; } public static SpellData GetByMissileName(string missileSpellName) { missileSpellName = missileSpellName.ToLower(); foreach (var spellData in Spells) { if (spellData.MissileSpellName != null && spellData.MissileSpellName.ToLower() == missileSpellName || spellData.ExtraMissileNames.Contains(missileSpellName)) { return spellData; } } return null; } public static SpellData GetBySpeed(string ChampionName, int speed, int id = -1) { foreach (var spellData in Spells) { if (spellData.ChampionName == ChampionName && spellData.MissileSpeed == speed && (spellData.Id == -1 || id == spellData.Id)) { return spellData; } } return null; } } }
gpl-3.0
jzebedee/ttwinstaller
Installer/Patching/IBsaDiff.cs
380
using System.Collections.Generic; using BSAsharp; namespace TaleOfTwoWastelands.Patching { public interface IBsaDiff { bool PatchBsa(CompressionOptions bsaOptions, string oldBSA, string newBSA, bool simulate = false); bool PatchBsaFile(BSAFile bsaFile, PatchInfo patch, FileValidation targetChk); void RenameFiles(BSA bsa, IDictionary<string, string> renameDict); } }
gpl-3.0
libeastwood/main
python/src/pypalfile.cpp
3569
// TODO: This is *very* crude for now, need to figure out some neat way for // python to deal with C++ streams ... #include <istream> #include <fstream> #include <sstream> #include "pyeastwood.h" #include "eastwood/PalFile.h" #include "eastwood/StdDef.h" #include "pypalfile.h" #include "pypalette.h" using namespace eastwood; PyDoc_STRVAR(PalFile_init__doc__, "PalFile(data) -> PalFile object\n\ \n\ Creates a PalpFile from data.\n\ "); static int PalFile_init(Py_PalFile *self, PyObject *args) { Py_buffer pdata; if (!PyArg_ParseTuple(args, "s*", &pdata)) return -1; self->stream = new std::istream(new std::stringbuf(std::string(reinterpret_cast<char*>(pdata.buf), pdata.len))); if(!self->stream->good()) { PyErr_SetFromErrno(PyExc_IOError); PyBuffer_Release(&pdata); return -1; } self->palFile = new PalFile(*self->stream); PyBuffer_Release(&pdata); return 0; } static PyObject * PalFile_alloc(PyTypeObject *type, Py_ssize_t nitems) { Py_PalFile *self = (Py_PalFile *)PyType_GenericAlloc(type, nitems); self->palFile = nullptr; self->stream = nullptr; return (PyObject *)self; } static void PalFile_dealloc(Py_PalFile *self) { if(self->palFile) delete self->palFile; if(self->stream) { delete self->stream->rdbuf(); delete self->stream; } PyObject_Del((PyObject*)self); } PyDoc_STRVAR(PalFile_getPalette__doc__, "getPalette() -> Palette object\n\ \n\ Returns a Palette object.\n\ "); static PyObject * PalFile_getPalette(Py_PalFile *self) { Palette *palette = new Palette(self->palFile->getPalette()); PyObject *pypalette = Palette_Type.tp_new(&Palette_Type, reinterpret_cast<PyObject*>(palette), nullptr); return pypalette; } static PyMethodDef PalFile_methods[] = { {"getPalette", (PyCFunction)PalFile_getPalette, METH_NOARGS, PalFile_getPalette__doc__}, {nullptr, nullptr, 0, nullptr} /* sentinel */ }; PyTypeObject PalFile_Type = { PyObject_HEAD_INIT(nullptr) 0, /*ob_size*/ "pyeastwood.PalFile", /*tp_name*/ sizeof(Py_PalFile), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)PalFile_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/ PalFile_init__doc__, /*tp_doc*/ 0, /*tp_traverse*/ 0, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ PalFile_methods, /*tp_methods*/ 0, /*tp_members*/ 0, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ (initproc)PalFile_init, /*tp_init*/ PalFile_alloc, /*tp_alloc*/ PyType_GenericNew, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ 0, /*tp_bases*/ 0, /*tp_mro*/ 0, /*tp_cache*/ 0, /*tp_subclasses*/ 0, /*tp_weaklist*/ 0, /*tp_del*/ 0 /*tp_version_tag*/ };
gpl-3.0
KamranMackey/Buildcraft-Additions
src/main/java/buildcraftAdditions/blocks/BlockBasicDuster.java
2211
package buildcraftAdditions.blocks; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; import net.minecraft.world.World; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraftforge.common.util.ForgeDirection; import buildcraftAdditions.tileEntities.TileBasicDuster; import buildcraftAdditions.utils.RenderUtils; /** * Copyright (c) 2014-2015, AEnterprise * http://buildcraftadditions.wordpress.com/ * Buildcraft Additions is distributed under the terms of GNU GPL v3.0 * Please check the contents of the license located in * http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/ */ public class BlockBasicDuster extends BlockDusterBase { @SideOnly(Side.CLIENT) private IIcon front, back, sides, top, bottom; public BlockBasicDuster() { super("Basic"); } @Override public TileEntity createNewTileEntity(World world, int variable) { return new TileBasicDuster(); } @Override public void onFallenUpon(World world, int x, int y, int z, Entity entity, float fallDistance) { if (entity instanceof EntityPlayer) { TileEntity tileEntity = world.getTileEntity(x, y, z); if (tileEntity instanceof TileBasicDuster) ((TileBasicDuster) tileEntity).makeProgress((EntityPlayer) entity); } } @Override @SideOnly(Side.CLIENT) public IIcon getIcon(int side, int meta) { if (meta == 0 && side == 3) return front; if (side == meta && meta > 1) return front; switch (side) { case 0: return bottom; case 1: return top; } if (side == ForgeDirection.getOrientation(meta).getOpposite().ordinal()) return back; return sides; } @Override @SideOnly(Side.CLIENT) public void registerBlockIcons(IIconRegister register) { front = RenderUtils.registerIcon(register, "dusterFront"); back = RenderUtils.registerIcon(register, "dusterBack"); sides = RenderUtils.registerIcon(register, "dusterSides"); top = RenderUtils.registerIcon(register, "dusterTop"); bottom = RenderUtils.registerIcon(register, "dusterBottom"); } }
gpl-3.0
pojome/elementor
assets/dev/js/editor/elements/views/base.js
19419
import environment from 'elementor-common/utils/environment'; import DocumentUtils from 'elementor-document/utils/helpers'; var ControlsCSSParser = require( 'elementor-editor-utils/controls-css-parser' ), Validator = require( 'elementor-validator/base' ), BaseContainer = require( 'elementor-views/base-container' ), BaseElementView; BaseElementView = BaseContainer.extend( { tagName: 'div', controlsCSSParser: null, allowRender: true, toggleEditTools: false, renderAttributes: {}, className() { let classes = 'elementor-element elementor-element-edit-mode ' + this.getElementUniqueID(); if ( this.toggleEditTools ) { classes += ' elementor-element--toggle-edit-tools'; } return classes; }, attributes() { return { 'data-id': this.getID(), 'data-element_type': this.model.get( 'elType' ), }; }, ui() { return { tools: '> .elementor-element-overlay > .elementor-editor-element-settings', editButton: '> .elementor-element-overlay .elementor-editor-element-edit', duplicateButton: '> .elementor-element-overlay .elementor-editor-element-duplicate', addButton: '> .elementor-element-overlay .elementor-editor-element-add', removeButton: '> .elementor-element-overlay .elementor-editor-element-remove', }; }, behaviors() { const groups = elementor.hooks.applyFilters( 'elements/' + this.options.model.get( 'elType' ) + '/contextMenuGroups', this.getContextMenuGroups(), this ); const behaviors = { contextMenu: { behaviorClass: require( 'elementor-behaviors/context-menu' ), groups: groups, }, }; return elementor.hooks.applyFilters( 'elements/base/behaviors', behaviors, this ); }, getBehavior( name ) { return this._behaviors[ Object.keys( this.behaviors() ).indexOf( name ) ]; }, events() { return { mousedown: 'onMouseDown', 'click @ui.editButton': 'onEditButtonClick', 'click @ui.duplicateButton': 'onDuplicateButtonClick', 'click @ui.addButton': 'onAddButtonClick', 'click @ui.removeButton': 'onRemoveButtonClick', }; }, getElementType() { return this.model.get( 'elType' ); }, getIDInt() { return parseInt( this.getID(), 16 ); }, getChildType() { return elementor.helpers.getElementChildType( this.getElementType() ); }, getChildView( model ) { let ChildView; const elType = model.get( 'elType' ); if ( 'section' === elType ) { ChildView = require( 'elementor-elements/views/section' ); } else if ( 'column' === elType ) { ChildView = require( 'elementor-elements/views/column' ); } else { ChildView = elementor.modules.elements.views.Widget; } return elementor.hooks.applyFilters( 'element/view', ChildView, model, this ); }, getTemplateType() { return 'js'; }, getEditModel() { return this.model; }, getContainer() { if ( ! this.container ) { const settingsModel = this.model.get( 'settings' ); this.container = new elementorModules.editor.Container( { type: this.model.get( 'elType' ), id: this.model.id, model: this.model, settings: settingsModel, view: this, parent: this._parent.getContainer() || {}, children: [], label: elementor.helpers.getModelLabel( this.model ), controls: settingsModel.options.controls, } ); } return this.container; }, getContextMenuGroups() { const controlSign = environment.mac ? '⌘' : '^'; return [ { name: 'general', actions: [ { name: 'edit', icon: 'eicon-edit', title: elementor.translate( 'edit_element', [ this.options.model.getTitle() ] ), callback: () => $e.run( 'panel/editor/open', { model: this.options.model, // Todo: remove on merge router view: this, // Todo: remove on merge router container: this.getContainer(), } ), }, { name: 'duplicate', icon: 'eicon-clone', title: elementor.translate( 'duplicate' ), shortcut: controlSign + '+D', callback: () => $e.run( 'document/elements/duplicate', { container: this.getContainer() } ), }, ], }, { name: 'clipboard', actions: [ { name: 'copy', title: elementor.translate( 'copy' ), shortcut: controlSign + '+C', callback: () => $e.run( 'document/elements/copy', { container: this.getContainer() } ), }, { name: 'paste', title: elementor.translate( 'paste' ), shortcut: controlSign + '+V', isEnabled: () => DocumentUtils.isPasteEnabled( this.getContainer() ), callback: () => $e.run( 'document/ui/paste', { container: this.getContainer(), } ), }, { name: 'pasteStyle', title: elementor.translate( 'paste_style' ), shortcut: controlSign + '+⇧+V', isEnabled: () => !! elementorCommon.storage.get( 'clipboard' ), callback: () => $e.run( 'document/elements/paste-style', { container: this.getContainer() } ), }, { name: 'resetStyle', title: elementor.translate( 'reset_style' ), callback: () => $e.run( 'document/elements/reset-style', { container: this.getContainer() } ), }, ], }, { name: 'delete', actions: [ { name: 'delete', icon: 'eicon-trash', title: elementor.translate( 'delete' ), shortcut: '⌦', callback: () => $e.run( 'document/elements/delete', { container: this.getContainer() } ), }, ], }, ]; }, getEditButtons: function() { return {}; }, initialize() { BaseContainer.prototype.initialize.apply( this, arguments ); const editModel = this.getEditModel(); if ( this.collection && this.onCollectionChanged ) { elementorCommon.helpers.softDeprecated( 'onCollectionChanged', '2.8.0', '$e.events || $e.hooks' ); this.listenTo( this.collection, 'add remove reset', this.onCollectionChanged, this ); } if ( this.onSettingsChanged ) { elementorCommon.helpers.softDeprecated( 'onSettingsChanged', '2.8.0', '$e.events || $e.hooks' ); this.listenTo( editModel.get( 'settings' ), 'change', this.onSettingsChanged ); } this.listenTo( editModel.get( 'editSettings' ), 'change', this.onEditSettingsChanged ) .listenTo( this.model, 'request:edit', this.onEditRequest ) .listenTo( this.model, 'request:toggleVisibility', this.toggleVisibility ); this.initControlsCSSParser(); }, getHandlesOverlay: function() { const $handlesOverlay = jQuery( '<div>', { class: 'elementor-element-overlay' } ), $overlayList = jQuery( '<ul>', { class: `elementor-editor-element-settings elementor-editor-${ this.getElementType() }-settings` } ); jQuery.each( this.getEditButtons(), ( toolName, tool ) => { const $item = jQuery( '<li>', { class: `elementor-editor-element-setting elementor-editor-element-${ toolName }`, title: tool.title } ), $icon = jQuery( '<i>', { class: `eicon-${ tool.icon }`, 'aria-hidden': true } ), $a11y = jQuery( '<span>', { class: 'elementor-screen-only' } ); $a11y.text( tool.title ); $item.append( $icon, $a11y ); $overlayList.append( $item ); } ); $handlesOverlay.append( $overlayList ); return $handlesOverlay; }, attachElContent: function( html ) { this.$el.empty().append( this.getHandlesOverlay(), html ); }, startTransport() { elementorCommon.helpers.softDeprecated( 'element.startTransport', '2.8.0', "$e.run( 'document/elements/copy' )" ); $e.run( 'document/elements/copy', { container: this.getContainer(), } ); }, copy() { elementorCommon.helpers.softDeprecated( 'element.copy', '2.8.0', "$e.run( 'document/elements/copy' )" ); $e.run( 'document/elements/copy', { container: this.getContainer(), } ); }, cut() { elementorCommon.helpers.softDeprecated( 'element.cut', '2.8.0' ); }, paste() { elementorCommon.helpers.softDeprecated( 'element.paste', '2.8.0', "$e.run( 'document/elements/paste' )" ); $e.run( 'document/elements/paste', { container: this.getContainer(), at: this._parent.collection.indexOf( this.model ), } ); }, duplicate() { elementorCommon.helpers.softDeprecated( 'element.duplicate', '2.8.0', "$e.run( 'document/elements/duplicate' )" ); $e.run( 'document/elements/duplicate', { container: this.getContainer(), } ); }, pasteStyle() { elementorCommon.helpers.softDeprecated( 'element.pasteStyle', '2.8.0', "$e.run( 'document/elements/paste-style' )" ); $e.run( 'document/elements/paste-style', { container: this.getContainer(), } ); }, resetStyle() { elementorCommon.helpers.softDeprecated( 'element.resetStyle', '2.8.0', "$e.run( 'document/elements/reset-style' )" ); $e.run( 'document/elements/reset-style', { container: this.getContainer(), } ); }, isStyleTransferControl( control ) { if ( undefined !== control.style_transfer ) { return control.style_transfer; } return 'content' !== control.tab || control.selectors || control.prefix_class; }, toggleVisibility() { this.model.set( 'hidden', ! this.model.get( 'hidden' ) ); this.toggleVisibilityClass(); }, toggleVisibilityClass() { this.$el.toggleClass( 'elementor-edit-hidden', ! ! this.model.get( 'hidden' ) ); }, addElementFromPanel( options ) { options = options || {}; const elementView = elementor.channels.panelElements.request( 'element:selected' ), model = { elType: elementView.model.get( 'elType' ), }; if ( elementor.helpers.maybeDisableWidget() ) { return; } if ( 'widget' === model.elType ) { model.widgetType = elementView.model.get( 'widgetType' ); } else if ( 'section' === model.elType ) { model.isInner = true; } else { return; } const customData = elementView.model.get( 'custom' ); if ( customData ) { jQuery.extend( model, customData ); } return $e.run( 'document/elements/create', { container: this.getContainer(), model, options, } ); }, // TODO: Unused function. addControlValidator( controlName, validationCallback ) { validationCallback = validationCallback.bind( this ); const validator = new Validator( { customValidationMethod: validationCallback } ), validators = this.getEditModel().get( 'settings' ).validators; if ( ! validators[ controlName ] ) { validators[ controlName ] = []; } validators[ controlName ].push( validator ); }, addRenderAttribute( element, key, value, overwrite ) { const self = this; if ( 'object' === typeof element ) { jQuery.each( element, ( elementKey, elementValue ) => { self.addRenderAttribute( elementKey, elementValue, null, overwrite ); } ); return self; } if ( 'object' === typeof key ) { jQuery.each( key, ( attributeKey, attributeValue ) => { self.addRenderAttribute( element, attributeKey, attributeValue, overwrite ); } ); return self; } if ( ! self.renderAttributes[ element ] ) { self.renderAttributes[ element ] = {}; } if ( ! self.renderAttributes[ element ][ key ] ) { self.renderAttributes[ element ][ key ] = []; } if ( ! Array.isArray( value ) ) { value = [ value ]; } if ( overwrite ) { self.renderAttributes[ element ][ key ] = value; } else { self.renderAttributes[ element ][ key ] = self.renderAttributes[ element ][ key ].concat( value ); } }, getRenderAttributeString( element ) { if ( ! this.renderAttributes[ element ] ) { return ''; } const renderAttributes = this.renderAttributes[ element ], attributes = []; jQuery.each( renderAttributes, ( attributeKey, attributeValue ) => { attributes.push( attributeKey + '="' + _.escape( attributeValue.join( ' ' ) ) + '"' ); } ); return attributes.join( ' ' ); }, isInner: function() { return !! this.model.get( 'isInner' ); }, initControlsCSSParser() { this.controlsCSSParser = new ControlsCSSParser( { id: this.model.cid, settingsModel: this.getEditModel().get( 'settings' ), dynamicParsing: this.getDynamicParsingSettings(), } ); }, enqueueFonts() { const editModel = this.getEditModel(), settings = editModel.get( 'settings' ); jQuery.each( settings.getFontControls(), ( index, control ) => { const fontFamilyName = editModel.getSetting( control.name ); if ( ! fontFamilyName ) { return; } elementor.helpers.enqueueFont( fontFamilyName ); } ); // Enqueue Icon Fonts jQuery.each( settings.getIconsControls(), ( index, control ) => { const iconType = editModel.getSetting( control.name ); if ( ! iconType || ! iconType.library ) { return; } elementor.helpers.enqueueIconFonts( iconType.library ); } ); }, renderStyles( settings ) { if ( ! settings ) { settings = this.getEditModel().get( 'settings' ); } this.controlsCSSParser.stylesheet.empty(); this.controlsCSSParser.addStyleRules( settings.getStyleControls(), settings.attributes, this.getEditModel().get( 'settings' ).controls, [ /{{ID}}/g, /{{WRAPPER}}/g ], [ this.getID(), '#elementor .' + this.getElementUniqueID() ] ); this.controlsCSSParser.addStyleToDocument(); const extraCSS = elementor.hooks.applyFilters( 'editor/style/styleText', '', this ); if ( extraCSS ) { this.controlsCSSParser.elements.$stylesheetElement.append( extraCSS ); } }, renderCustomClasses() { const self = this; const settings = self.getEditModel().get( 'settings' ), classControls = settings.getClassControls(); // Remove all previous classes _.each( classControls, ( control ) => { let previousClassValue = settings.previous( control.name ); if ( control.classes_dictionary ) { if ( undefined !== control.classes_dictionary[ previousClassValue ] ) { previousClassValue = control.classes_dictionary[ previousClassValue ]; } } self.$el.removeClass( control.prefix_class + previousClassValue ); } ); // Add new classes _.each( classControls, ( control ) => { const value = settings.attributes[ control.name ]; let classValue = value; if ( control.classes_dictionary ) { if ( undefined !== control.classes_dictionary[ value ] ) { classValue = control.classes_dictionary[ value ]; } } const isVisible = elementor.helpers.isActiveControl( control, settings.attributes ); if ( isVisible && ( classValue || 0 === classValue ) ) { self.$el.addClass( control.prefix_class + classValue ); } } ); self.$el.addClass( _.result( self, 'className' ) ); self.toggleVisibilityClass(); }, renderCustomElementID() { const customElementID = this.getEditModel().get( 'settings' ).get( '_element_id' ); this.$el.attr( 'id', customElementID ); }, renderUI: function() { this.renderStyles(); this.renderCustomClasses(); this.renderCustomElementID(); this.enqueueFonts(); }, runReadyTrigger: function() { const self = this; _.defer( function() { elementorFrontend.elementsHandler.runReadyTrigger( self.el ); if ( ! elementorFrontend.isEditMode() ) { return; } // In edit mode - handle an external elements that loaded by another elements like shortcode etc. self.$el.find( '.elementor-element.elementor-' + self.model.get( 'elType' ) + ':not(.elementor-element-edit-mode)' ).each( function() { elementorFrontend.elementsHandler.runReadyTrigger( this ); } ); } ); }, getID() { return this.model.get( 'id' ); }, getElementUniqueID() { return 'elementor-element-' + this.getID(); }, renderHTML: function() { const templateType = this.getTemplateType(), editModel = this.getEditModel(); if ( 'js' === templateType ) { this.getEditModel().setHtmlCache(); this.render(); editModel.renderOnLeave = true; } else { editModel.renderRemoteServer(); } }, renderOnChange( settings ) { if ( ! this.allowRender ) { return; } // Make sure is correct model if ( settings instanceof elementorModules.editor.elements.models.BaseSettings ) { const hasChanged = settings.hasChanged(); let isContentChanged = ! hasChanged, isRenderRequired = ! hasChanged; _.each( settings.changedAttributes(), ( settingValue, settingKey ) => { const control = settings.getControl( settingKey ); if ( '_column_size' === settingKey ) { isRenderRequired = true; return; } if ( ! control ) { isRenderRequired = true; isContentChanged = true; return; } if ( 'none' !== control.render_type ) { isRenderRequired = true; } if ( -1 !== [ 'none', 'ui' ].indexOf( control.render_type ) ) { return; } if ( 'template' === control.render_type || ( ! settings.isStyleControl( settingKey ) && ! settings.isClassControl( settingKey ) && '_element_id' !== settingKey ) ) { isContentChanged = true; } } ); if ( ! isRenderRequired ) { return; } if ( ! isContentChanged ) { this.renderUI(); return; } } // Re-render the template this.renderHTML(); }, getDynamicParsingSettings() { const self = this; return { onServerRequestStart() { self.$el.addClass( 'elementor-loading' ); }, onServerRequestEnd() { self.render(); self.$el.removeClass( 'elementor-loading' ); }, }; }, serializeData() { const data = BaseContainer.prototype.serializeData.apply( this, arguments ); data.settings = this.getEditModel().get( 'settings' ).parseDynamicSettings( data.settings, this.getDynamicParsingSettings() ); return data; }, save() { $e.route( 'library/save-template', { model: this.model, } ); }, onBeforeRender() { this.renderAttributes = {}; }, onRender() { this.renderUI(); this.runReadyTrigger(); if ( this.toggleEditTools ) { const editButton = this.ui.editButton; // Since this.ui.tools does not exist while testing. if ( this.ui.tools ) { this.ui.tools.hoverIntent( function() { editButton.addClass( 'elementor-active' ); }, function() { editButton.removeClass( 'elementor-active' ); }, { timeout: 500 } ); } } }, onEditSettingsChanged( changedModel ) { elementor.channels.editor.trigger( 'change:editSettings', changedModel, this ); }, onEditButtonClick() { this.model.trigger( 'request:edit' ); }, onEditRequest( options = {} ) { if ( 'edit' !== elementor.channels.dataEditMode.request( 'activeMode' ) ) { return; } const model = this.getEditModel(), panel = elementor.getPanelView(); if ( $e.routes.isPartOf( 'panel/editor' ) && panel.getCurrentPageView().model === model ) { return; } if ( options.scrollIntoView ) { elementor.helpers.scrollToView( this.$el, 200 ); } $e.run( 'panel/editor/open', { model: model, view: this, } ); }, onDuplicateButtonClick( event ) { event.stopPropagation(); $e.run( 'document/elements/duplicate', { container: this.getContainer() } ); }, onRemoveButtonClick( event ) { event.stopPropagation(); $e.run( 'document/elements/delete', { container: this.getContainer() } ); }, /* jQuery ui sortable preventing any `mousedown` event above any element, and as a result is preventing the `blur` * event on the currently active element. Therefor, we need to blur the active element manually. */ onMouseDown( event ) { if ( jQuery( event.target ).closest( '.elementor-inline-editing' ).length ) { return; } elementorFrontend.elements.window.document.activeElement.blur(); }, onDestroy() { this.controlsCSSParser.removeStyleFromDocument(); this.getEditModel().get( 'settings' ).validators = {}; elementor.channels.data.trigger( 'element:destroy', this.model ); }, } ); module.exports = BaseElementView;
gpl-3.0
ranjitjc/ticket-system
client/src/app/status/detail/status.detail.component.ts
8962
import { Component, OnInit, AfterViewInit, OnDestroy, ViewChildren, ElementRef, ViewContainerRef } from '@angular/core'; import { FormBuilder, FormGroup, FormControl, FormArray, Validators, FormControlName } from '@angular/forms'; import { Router, ActivatedRoute } from '@angular/router'; import {MdSnackBar, MdSnackBarConfig} from '@angular/material'; import {MdDialog, MdDialogRef, MdDialogConfig} from '@angular/material'; import { Observable, BehaviorSubject } from 'rxjs/Rx'; import { Subscription } from 'rxjs/Subscription'; //services import { StatusService } from '../../services/status.service'; //models import { MessageModel, MessageType , TicketStatus, Notification, NotificationType} from '../../model/models' //shared import { NumberValidators, GenericValidator, ConfirmationService , NotificationService } from '../../shared/shared.module'; @Component({ selector: 'app-status-detail', templateUrl: './status.detail.component.html', styleUrls: ['./status.detail.component.scss'], }) export class StatusDetailComponent implements OnInit, AfterViewInit, OnDestroy { @ViewChildren(FormControlName, { read: ElementRef }) formInputElements: ElementRef[]; isLoading:Boolean; isSaving:Boolean; isError:Boolean =false; ticketStatus: TicketStatus; private sub: Subscription; ticketStatusForm: FormGroup; SortOrders : number[]; errorMessage:any; message:MessageModel; pageTitle:string; totalCount : number; // Use with the generic validation message class displayMessage: { [key: string]: string } = {}; private validationMessages: { [key: string]: { [key: string]: string } }; private genericValidator: GenericValidator; //snackBar variables //snakMessage: string = 'Snack Bar opened.'; actionButtonLabel: string = 'Retry'; action: boolean = false; setAutoHide: boolean = true; autoHide: number = 2000; constructor(private fb: FormBuilder, private route: ActivatedRoute, private router: Router, public snackBar: MdSnackBar, public confirmService: ConfirmationService, private viewContainerRef: ViewContainerRef, private _service: StatusService, private _notification: NotificationService) { this.isLoading= true; // Defines all of the validation messages for the form. // These could instead be retrieved from a file or database. this.validationMessages = { name: { required: 'Status is required.', minlength: 'Status must be at least three characters.', maxlength: 'Status cannot exceed 50 characters.' }, sortOrder: { required: 'Status is required.', range: 'Rate the product between 1 (lowest) and 5 (highest).' } }; // Define an instance of the validator for use with this form, // passing in this form's set of validation messages. this.genericValidator = new GenericValidator(this.validationMessages); this.SortOrders = []; } ngOnInit() { this.sub = this.route.params.subscribe( params => { let id = params['id']; console.log('id :' + id); this.getTicketStatus(id); }); this.sub = this.route.queryParams.subscribe( params => { this.totalCount = params['count'] ; this.totalCount++; for (var _i = 1; _i <= this.totalCount ; _i++) { this.SortOrders.push(_i); } console.log('id :' + this.totalCount); }); this.ticketStatusForm = this.fb.group({ name : ['', [Validators.required, Validators.minLength(3), Validators.maxLength(50)] ], //sortOrder: ['', NumberValidators.range(1, 5)], sortOrder: ['',[Validators.required]], isDefault : 0 }); //Testing // this.message = {messageType : MessageType.INFO, // messageIcon:"warning", // messageText : "From Parent"}; } ngAfterViewInit(): void { // Watch for the blur event from any input element on the form. let controlBlurs: Observable<any>[] = this.formInputElements .map((formControl: ElementRef) => Observable.fromEvent(formControl.nativeElement, 'blur')); // Merge the blur event observable with the valueChanges observable Observable.merge(this.ticketStatusForm.valueChanges, ...controlBlurs).debounceTime(800).subscribe(value => { this.displayMessage = this.genericValidator.processMessages(this.ticketStatusForm); }); } ngOnDestroy() { this.sub.unsubscribe(); } notify(action, message){ let notify : Notification = { type :NotificationType.LOG, action : action, component : "StatusDetailComponent", message : message, time : new Date() } console.log('from StatusDetailComponent:' + action + " : " + message); this._notification.publish(notify); } getTicketStatus(id:Number){ if (id >0){ this._service.GetById(id).subscribe( data => { this.onTicketStatusRetrieved(data); this.isLoading= false; console.table(data); }, (error:any) => this.errorMessage = <any>error ) }else{ //New var ticketStatus = {id:0, name:'', sortOrder:this.totalCount, isDefault:0}; this.onTicketStatusRetrieved( ticketStatus); this.isLoading= false; } } onTicketStatusRetrieved(ticketStatus: TicketStatus): void { if(this.ticketStatusForm){ this.ticketStatusForm.reset(); } this.ticketStatus = ticketStatus; if (this.ticketStatus.id === 0) { this.pageTitle = 'Add New Ticket Status'; } else { this.pageTitle = `Edit Ticket Status : ${this.ticketStatus.name}`; this.ticketStatusForm.patchValue({ name : ticketStatus.name, sortOrder: ticketStatus.sortOrder, isDefault : ticketStatus.isDefault }); } } save(){ if (this.ticketStatusForm.dirty && this.ticketStatusForm.valid) { let status = Object.assign({}, this.ticketStatus, this.ticketStatusForm.value); //TODO:call service to detele the current TicketStatus this.isError=false; this.isSaving= true; let msg = `New TicketStatus [${status.name}] has been created.`; if (status.id > 0){ msg = `[${status.name}]] TicketStatus has been updated.`; } this._service.save(status).subscribe( data => { // for (let i:number=0; i<100000000000; i++){ // let d= i++; // } console.log(data); this.notify("Save Ticket Status",msg); this.openSnackBar('Successfully saved'); this.onSaveComplete(); this.isSaving= false; }, (error:any) => { this.message = {messageType : MessageType.ERROR, messageIcon:"error", messageText : <any>error}; this.isError=true; this.isSaving= false; } ) }else if (!this.ticketStatusForm.dirty) { this.onSaveComplete(); this.isSaving= false; } } onSaveComplete(): void { // Reset the form to clear the flags this.ticketStatusForm.reset(); this.router.navigate(['/status']); } delete(){ if (this.ticketStatusForm.valid) { let status = Object.assign({}, this.ticketStatus, this.ticketStatusForm.value); this.confirmService .confirm('Delete Confirmation', 'Are you sure to delete this Status?', this.viewContainerRef) .subscribe( result => { if (result ){ //TODO:call service to detele the current TicketStatus this.isSaving= true; this._service.delete(status.id).subscribe( data => { console.log(data); this.notify("Delete Ticket Status",`[${status.name}] TicketStatus has been deleted.`) this.openSnackBar('Successfully deleted'); this.onSaveComplete(); this.isSaving= false; }, (error:any) => { this.errorMessage = <any>error; this.isSaving= false; } ) } }); }else{ } } openSnackBar(message) { let config = new MdSnackBarConfig(); config.duration = this.autoHide; this.snackBar.open(message, this.action && this.actionButtonLabel, config); } onBack(): void { this.router.navigate(['/status']); } }
gpl-3.0
AshtreeCC/Ashtree
Javascript/jquery.anymenu.js
1181
/* * jQuery Any Menu * @version 1.0 (2012-20-20) * @requires jQuery 1.4+ * @author andrew.nash */ (function($) { $.fn.anymenu = function(user_options) { var options = $.extend({ 'data' : false, 'type' : 'dropdown' }, user_options); $(this).each(function(){ var UL = $(this); // Prepare the top level for children UL.addClass('anymenu topmenu') .css({ 'position' : 'relative' }); // Hide all submenus $('ul', UL).addClass('anymenu submenu'); $('ul > li', UL).hide(); // Position the second level items $('> li > ul', UL) .css({ 'position' : 'absolute' }); // Show/hide the submenu being hovered over $('body').on('mouseenter.anymenu', '.anymenu.topmenu li', function(){ $('> ul > li', this).slideDown(); $('> a', this).addClass('hover'); }); $('body').on('mouseenter.anymenu', '.anymenu.submenu li', function(){ $('> ul > li', this).show('slide', 'left', 1000); }); $('body').on('mouseleave.anymenu', '.anymenu li', function(){ $('> ul > li', this).slideUp(); $('> a', this).removeClass('hover'); }); }); return $(this); } })(jQuery);
gpl-3.0
rohitink/subsimple
sidebar.php
858
<?php /** * The Sidebar containing the main widget areas. * * @package subsimple */ ?> <div id="secondary" class="widget-area" role="complementary"> <?php do_action( 'before_sidebar' ); ?> <?php if ( ! dynamic_sidebar( 'sidebar-1' ) ) : ?> <aside id="search" class="widget widget_search"> <?php get_search_form(); ?> </aside> <aside id="archives" class="widget"> <h1 class="widget-title"><?php _e( 'Archives', 'subsimple' ); ?></h1> <ul> <?php wp_get_archives( array( 'type' => 'monthly' ) ); ?> </ul> </aside> <aside id="meta" class="widget"> <h1 class="widget-title"><?php _e( 'Meta', 'subsimple' ); ?></h1> <ul> <?php wp_register(); ?> <li><?php wp_loginout(); ?></li> <?php wp_meta(); ?> </ul> </aside> <?php endif; // end sidebar widget area ?> </div><!-- #secondary -->
gpl-3.0
GARUMFundatio/Bazar
app/models/pais.rb
509
class Pais < ActiveRecord::Base has_many :ciudades default_scope :order => 'descripcion' has_friendly_id :descripcion , :use_slug => true, :strip_non_ascii => true def to_s;self.descripcion;end def self.paisestocsv csv = "country_code,value\\n" max = Pais.count_by_sql("select max(total_empresas_mercado) from paises") for pais in Pais.where('total_empresas_mercado > 0') csv += "#{pais.cod3},#{(pais.total_empresas_mercado*10)/max}\\n" end return csv end end
gpl-3.0
mrtrizer/LispSSS
src/functions/func_func.cpp
1139
#include "func_func.h" #include "atomnildata.h" #include "funcdata.h" #include "lispfunction.h" #include "lispnode.h" #include "listdata.h" #include "atomdata.h" Result Func_func::run_(const Arguments & arguments, Memory *stack) const { (void) stack; (void) arguments; //return Result(new AtomNilData()); int argCount = 0; int minArgCount = 0; std::vector<LispNode>::const_iterator i; ListData * listData = (ListData *)arguments[0].getData(); for (i = listData->list.begin();i != listData->list.end(); i++) { if(i->data->getDataType() == Data::ATOM) { if (((AtomData *)i->data)->getName() == "...") { minArgCount = argCount; argCount = -1; break; } else argCount++; } else ERROR_MESSAGE ("All argument names must be atoms."); } return Result(new FuncData(new LispFunction(Function::EXPR,argCount,minArgCount,arguments[1].getData()->getClone(), (ListData*)arguments[0].getData()->getClone(),executer),0)); }
gpl-3.0
run2fail/locker
locker/container.py
39471
''' This module provides an extended lxc container class. ''' import logging import os import re import shutil import time from collections import OrderedDict from functools import wraps import iptc import locker.project import lxc import netaddr from colorama import Fore from locker.etchosts import Hosts from locker.network import Network from locker.util import (regex_cgroup, regex_container_name, regex_link, regex_ports, regex_volumes, rule_to_str) class CommandFailed(RuntimeError): ''' Generic command failed RuntimeError ''' pass def return_if_not_defined(func): ''' Return if the container has not been defined ''' @wraps(func) def return_if_not_defined_wrapper(*args, **kwargs): if not args[0].defined: args[0].logger.debug('Container is not yet defined') return else: return func(*args, **kwargs) return return_if_not_defined_wrapper def return_if_defined(func): ''' Return if the container has been defined ''' @wraps(func) def return_if_defined_wrapper(*args, **kwargs): if args[0].defined: args[0].logger.debug('Container is defined') return else: return func(*args, **kwargs) return return_if_defined_wrapper def return_if_not_running(func): ''' Return if the container is not running ''' @wraps(func) def return_if_not_running_wrapper(*args, **kwargs): if not args[0].running: args[0].logger.debug('Container is stopped') return else: return func(*args, **kwargs) return return_if_not_running_wrapper class Container(lxc.Container): ''' Extended lxc.Container class This class adds: - Checks and logging - Locker specific attributes - Handling of project specifc parameters ''' def __init__(self, name, yml, project, color='', config_path=None): ''' Init instance with custom property values and init base class :param name: Name of the container :param project: Project instance of this container :param color: ASCII color escape sequence for log messages :param config_path: Path to the container's config file ''' if not re.match(regex_container_name, name): raise ValueError('Invalid value for container name: %s' % name) self.yml = yml self.project = project self.color = color self.logger = logging.getLogger(name) if self.logger.propagate: self.logger.propagate = False reset_color = Fore.RESET if self.color else '' sname = name.split('_')[1] formatter = logging.Formatter('%(asctime)s, %(levelname)8s: ' + color + '[' + sname + '] %(message)s' + reset_color) handler = logging.StreamHandler() handler.setFormatter(formatter) self.logger.addHandler(handler) lxc.Container.__init__(self, name, config_path) def __str__(self): return self.name def __repr__(self): return 'Container(%s: project=%s, config_path=%s)' % (self, self.project.name, self.get_config_path()) @staticmethod def get_containers(project, yml): ''' Generate a list of container objects Returns lists of containers that have been defined in the YAML configuration file. TODO Use dict instead of list :param yml: YAML project configuration :returns: (List of selected containers, List of all containers) ''' containers = list() all_containers = list() colors = [Fore.RED, Fore.GREEN, Fore.YELLOW, Fore.BLUE, Fore.MAGENTA, Fore.CYAN] for num, name in enumerate(sorted(yml['containers'].keys())): pname = '%s_%s' % (project.name, name) if pname not in lxc.list_containers(): logging.debug('Container does not exist yet or is not accessible: %s', pname) color = colors[num % len(colors)] if not project.args.get('no_color', False) else '' lxcpath = project.args.get('lxcpath', '/var/lib/lxc') container = Container(pname, yml['containers'][name], project, color, lxcpath) all_containers.append(container) if ('containers' in project.args and # required for cleanup command len(project.args['containers']) and name not in project.args['containers']): continue containers.append(container) logging.debug('Selected containers: %s', [con.name for con in containers]) return (containers, all_containers) def _network_conf(self): ''' Apply network configuration The the container's network configuration in the config file. ''' ip = self.project.network.get_ip(self) gateway = self.project.network.gateway link = self.project.network.bridge_ifname veth_pair = self.name #self.network[0].link = link #self.network[0].veth_pair = veth_pair #self.network[0].ipv4 = ip #self.network[0].ipv4_gateway = gateway self.set_config_item('lxc.network.0.link', link) self.set_config_item('lxc.network.0.veth.pair', veth_pair) self.set_config_item('lxc.network.0.ipv4', ip) self.set_config_item('lxc.network.0.ipv4.gateway', gateway) self.save_config() def _get_dns(self): ''' Get DNS server configuration as defined in the yml configuration Creates a list of DNS servers to use by this container based on the YAML configuration file. The following are supported: - Magic word "$bridge": takes the project bridges IP address, e.g., if you are running a custom dnsmasq process listening on this interface - Magic word "$copy": copies the DNS from the container's host system - Any valid IP address as string Additionally, the default DNS configuration is evaluated and used to derive the container's nameserver configuration. Container specific DNS servers have precedence over the default configuration. :returns: list of DNS IP addresses (as strings) ''' list_of_dns = list() try: defaults = self.project.yml['defaults'] except KeyError: defaults = {} defaults_dns = defaults.get('dns', []) container_dns = self.yml.get('dns', []) dns_list = container_dns + defaults_dns for dns in list(OrderedDict.fromkeys(dns_list)): if dns == "$bridge": list_of_dns.append(self.project.network.gateway) elif dns == "$copy": list_of_dns.extend(Network.get_dns_from_host()) else: try: list_of_dns.append(str(netaddr.IPAddress(dns))) except netaddr.AddrFormatError: self.logger.warning('Invalid DNS address specified: %s', dns) # remove duplicates but keep original order return list(OrderedDict.fromkeys(list_of_dns)) @return_if_not_defined def _enable_dns(self, dns=[], files=['/etc/resolv.conf', '/etc/resolvconf/resolv.conf.d/base']): ''' Set DNS servers in /etc/resolv.conf and further files Write the specified DNS server IP addresses as name server entries to the specified files. Please note that the file will be overwritten but will not be created if missing. :param dns: List of IPs (as string) to set as name servers :param files: List of filenames where to write the name server entries ''' self.logger.debug('Enabling name resolution: %s', dns) assert self.rootfs.startswith(self.project.args.get('lxcpath', '/var/lib/lxc')) _files = ['%s/%s' % (self.rootfs, rfile) for rfile in files] for rconf_file in _files: try: with open(rconf_file, 'w') as rconf: for server in dns: self.logger.debug('Adding nameserver: %s (in %s)', server, rconf_file) rconf.write('nameserver %s\n' % server) rconf.write('\n') except Exception as exception: self.logger.warning('Could not update nameservers in %s: %s', rconf_file, exception) self.logger.debug('Updated: %s', rconf_file) @return_if_not_defined def cgroup(self): ''' Apply cgroup settings Apply the cgroup configuration that is available as key-value pair in the YAML configuration file in the "cgroups" subtree. The method will update the current values of the container if it is running and always write the new values to the container's config file. ''' self.logger.info('Setting cgroup configuration') regex = re.compile(regex_cgroup) try: defaults = self.project.yml['defaults'] except KeyError: defaults = {} defaults_cgroup = defaults.get('cgroup', []) container_cgroup = self.yml.get('cgroup', []) cgroup_items = dict() for cgroup in defaults_cgroup + container_cgroup: # defaults go first match = regex.match(cgroup) if not match: self.logger.warning('Malformed cgroup setting: %s', cgroup) continue key = match.group(1) value = match.group(2) cgroup_items[key] = value # will overwrite defaults for key, value in cgroup_items.items(): if self.running and not self.set_cgroup_item(key, value): self.logger.warning('Was not able to set while running: %s = %s', key, value) elif not self.set_config_item('lxc.cgroup.' + key, value): self.logger.warning('Was not able to set in config: %s = %s', key, value) self.save_config() @return_if_not_defined @return_if_not_running def get_ips(self, retries=10, family='inet'): ''' Get IP addresses of the container Sleeps for 1s between each retry. :param retries: Try a again this many times if IPs are not available yet :param family: Filter by the address family :returns: List of IPs or None if the container is not defined or stopped ''' ips = lxc.Container.get_ips(self, family=family) while len(ips) == 0 and self.running and retries > 0: self.logger.debug('Waiting to acquire an IP address') time.sleep(1) ips = lxc.Container.get_ips(self, family=family) retries -= 1 return ips @property def project(self): return self._project @project.setter def project(self, value): if not isinstance(value, locker.Project): raise TypeError('Invalid type for property project: %s, required type = %s' % (type(value), type(locker.Project))) self._project = value @property def color(self): return self._color @color.setter def color(self, value): valid_colors = [Fore.BLACK, Fore.RED, Fore.GREEN, Fore.YELLOW, Fore.BLUE, Fore.MAGENTA, Fore.CYAN, Fore.WHITE, ''] if value not in valid_colors: raise ValueError('Invalid color: %s' % value) self._color = value @property def yml(self): return self._yml @yml.setter def yml(self, value): if not isinstance(value, dict): raise TypeError('Invalid type for value: %s' % type(value)) self._yml = value @property def logger(self): return self._logger @logger.setter def logger(self, value): if not isinstance(value, logging.Logger): raise TypeError('Invalid type for property logger: %s, required type = %s' % (type(value), type(logging.Logger))) self._logger = value @property def rootfs(self): rootfs = self.get_config_item('lxc.rootfs') if not len(rootfs): raise ValueError('rootfs is empty, container defined = %s', self.defined) return rootfs @return_if_not_defined def start(self): ''' Start container Starts the container after: - Generation of the fstab file for bind mount support - Setting the hostname inside the rootfs - Setting the network ocnfiguration in the container's config file - Setting the nameservers in the rootfs :raises: CommandFailed ''' if self.running: self.logger.debug('Container is already running') if not self.project.args.get('restart', False): self.logger.debug('Container will not be restarted') return self.logger.info('Restarting container') try: self.stop() except CommandFailed: raise self._generate_fstab() self._set_hostname() self._network_conf() self._enable_dns(dns=self._get_dns()) self.logger.info('Starting container') lxc.Container.start(self) if not self.running: self.logger.critical('Could not start container') raise CommandFailed('Could not start container') @return_if_not_defined @return_if_not_running def stop(self): ''' Stop container :raises: CommandFailed ''' self.logger.info('Stopping container') self.rmlinks() if not self.shutdown(self.project.args.get('timeout', 30)): self.logger.warning('Could not shutdown, forcing stop') lxc.Container.stop(self) if self.running: self.logger.critical('Could not stop container') raise CommandFailed('Could not stop container') @return_if_defined def create(self): ''' Create container based on template or as clone :raises: CommandFailed ''' def _create_from_template(self): ''' Create container from template specified in YAML configuration The "template" subtree in the YAML configuration will be provided as arguments to the template. ''' self.logger.info('Creating container from template: %s', self.yml['template']['name']) flags = lxc.LXC_CREATE_QUIET if self.project.args.get('verbose', False): flags = 0 lxc.Container.create(self, self.yml['template']['name'], flags, args=self.yml['template']) if not self.defined: self.logger.error('Creation failed from template: %s', self.yml['template']['name']) self.logger.error('Try again with \"--verbose\" for more information') raise CommandFailed('Creation failed from template: %s' % self.yml['template']['name']) self._move_dirs() def _clone_from_existing(self): ''' Clone container from an existing container This method is a little "awkward" because this container (self) will create a new, temp. container instance of the container to clone from which then creates the clone. Hence the clone and this instance (self) are not the same. The Python lxc bindings allow to create multiple lxc.Container instances for the same lxc container. As the clone is only of type lxc.Container and not locker.Container, we will use this container instance (self) for further actions. ''' clone = self.yml['clone'] self.logger.debug('Config patch: %s', self.project.args.get('lxcpath', '/var/lib/lxc')) if clone not in lxc.list_containers(config_path=self.project.args.get('lxcpath', '/var/lib/lxc')): self.logger.error('Cannot clone, container does not exist or is not accessible: %s', clone) raise ValueError('Cannot clone, container does not exist or is not accessible: %s' % clone) origin = lxc.Container(clone, self.project.args.get('lxcpath', '/var/lib/lxc')) assert origin.defined self.logger.info('Cloning from: %s', origin.name) cloned = origin.clone(self.name, config_path=self.project.args.get('lxcpath', '/var/lib/lxc')) if not cloned or not cloned.defined: self.logger.error('Cloning failed from: %s', origin.name) raise CommandFailed('Cloning failed from: %s' % origin.name) self._move_dirs() def _download(self): ''' Create container by downloading a base image The "download" subtree in the YAML configuration will be provided as arguments to the download template. ''' try: dist = self.yml['download']['dist'] except KeyError: self.logger.error('Missing value for key: %s', 'dist') return try: arch = self.yml['download']['arch'] except KeyError: self.logger.error('Missing value for key: %s', 'arch') return try: release = self.yml['download']['release'] except KeyError: self.logger.error('Missing value for key: %s', 'release') return self.logger.info('Downloading base image: dist=%s, release=%s, arch=%s', dist, release, arch) flags = lxc.LXC_CREATE_QUIET if self.project.args.get('verbose', False): flags = 0 lxc.Container.create(self, 'download', flags, args=self.yml['download']) if not self.defined: self.logger.error('Download of base image failed') self.logger.error('Try again with \"--verbose\" for more information') raise CommandFailed('Download of base image failed') self._move_dirs() if len([x for x in self.yml if x in ['template', 'clone', 'download']]) != 1: self.logger.error('You must provide either "template", "clone", or "download" in the container configuration') raise ValueError('You must provide either "template", "clone", or "download" in the container configuration') if 'template' in self.yml: _create_from_template(self) elif 'clone' in self.yml: _clone_from_existing(self) else: _download(self) @return_if_not_defined def remove(self): ''' Destroy container Stops the container and deletes the image. The user must confirm the deletion (of each container) if --delete-dont-ask was not provided. :raises: CommandFailed ''' self.logger.info('Removing container') if not self.project.args.get('force_delete', False): # TODO Implement a timeout here?!? input_var = input("Delete %s? [y/N]: " % (self.name.split('_')[1])) if input_var not in ['y', 'Y']: self.logger.info('Skipping deletion') return try: try: self.stop() except CommandFailed: raise if not lxc.Container.destroy(self): self.logger.error('Container was not deleted') raise CommandFailed('Container was not deleted') except CommandFailed: raise def rmports(self): ''' Remove netfilter rules that enable port forwarding This method removes all netfilter that have been added to make ports of the container accessible from external sources. This will not remove the netfilter rules added for linking! ''' self.logger.info('Removing netfilter rules') if self.running: self.logger.warning('Container is still running, services will be unavailable') nat_table = iptc.Table(iptc.Table.NAT) locker_chain = iptc.Chain(nat_table, 'LOCKER_PREROUTING') Network._delete_if_comment(self.name, nat_table, locker_chain) filter_table = iptc.Table(iptc.Table.FILTER) forward_chain = iptc.Chain(filter_table, 'LOCKER_FORWARD') Network._delete_if_comment(self.name, filter_table, forward_chain) def _has_netfilter_rules(self): ''' Check if there are any netfilter rules for this container Netfilter rules are matched by the comment - if it exists. :returns: True if any rule found, else False ''' self.logger.debug('Checking if container has already rules') nat_table = iptc.Table(iptc.Table.NAT) locker_chain = iptc.Chain(nat_table, 'LOCKER_PREROUTING') filter_table = iptc.Table(iptc.Table.FILTER) forward_chain = iptc.Chain(filter_table, 'LOCKER_FORWARD') return Network.find_comment_in_chain(self.name, locker_chain) or Network.find_comment_in_chain(self.name, forward_chain) def _add_port_rules(self, container_ip, port_conf, locker_chain, forward_chain): ''' Add rule to the LOCKER chain in the NAT table and to the FORWARD chain in the FILTER table :param container_ip: IP addresss of the container :param port_conf: dictionary with parsed port configuration :param locker_chain: LOCKER chain in the NAT table :param forward_chain: FORWARD chain in the FILTER table ''' locker_rule = iptc.Rule() locker_rule.protocol = port_conf['proto'] if port_conf['host_ip']: locker_rule.dst = port_conf['host_ip'] locker_rule.in_interface = '!%s' % self.project.network.bridge_ifname tcp_match = locker_rule.create_match(port_conf['proto']) tcp_match.dport = port_conf['host_port'] comment_match = locker_rule.create_match('comment') comment_match.comment = self.name target = locker_rule.create_target('DNAT') target.to_destination = '%s:%s' % (container_ip, port_conf['container_port']) locker_chain.insert_rule(locker_rule) forward_rule = iptc.Rule() forward_rule.protocol = port_conf['proto'] forward_rule.dst = container_ip forward_rule.in_interface = '!%s' % self.project.network.bridge_ifname forward_rule.out_interface = self.project.network.bridge_ifname tcp_match = forward_rule.create_match(port_conf['proto']) tcp_match.dport = port_conf['container_port'] comment_match = forward_rule.create_match('comment') comment_match.comment = self.name forward_rule.create_target('ACCEPT') forward_chain.insert_rule(forward_rule) @return_if_not_defined @return_if_not_running def ports(self, indirect=False): ''' Add netfilter rules to enable port forwarding :param indirect: Set to True to avoid the warning output that there already are netfilter rules for this container. This is usualy desired when ports() is indirectly called via the "start" command. ''' def _parse_port_conf(self, fwport): ''' Split port forward directive in parts :param fwport: Port forwarding configuration :raises: ValueError if fwport is invalid ''' regex = re.compile(regex_ports) match = regex.match(fwport) if not match: raise ValueError('Invalid port forwarding directive: %s', fwport) mdict = match.groupdict() mdict['proto'] = mdict['proto_udp'] or 'tcp' return mdict self.logger.info('Adding port forwarding rules') if not 'ports' in self.yml: self.logger.debug('No port forwarding rules found') return locker_nat_chain = iptc.Chain(iptc.Table(iptc.Table.NAT), 'LOCKER_PREROUTING') filter_forward = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'LOCKER_FORWARD') if self._has_netfilter_rules(): if not indirect: self.logger.warning('Existing netfilter rules found - must be removed first') return for fwport in self.yml['ports']: try: port_conf = _parse_port_conf(self, fwport) except ValueError: continue for container_ip in self.get_ips(): self._add_port_rules(container_ip, port_conf, locker_nat_chain, filter_forward) def _set_hostname(self): ''' Set container hostname Sets the container's hostname and FQDN in /etc/hosts and /etc/hostname if fqdn is specified in the YAML configuration. ''' fqdn = self.yml.get('fqdn', None) if not fqdn: self.logger.debug('Empty fqdn') return hostname = fqdn.split('.')[0] etc_hosts = '%s/etc/hosts' % (self.rootfs) try: hosts = Hosts(etc_hosts, self.logger) names = [fqdn, hostname] hosts.update_ip('127.0.1.1', names) hosts.save() except: pass etc_hostname = '%s/etc/hostname' % (self.rootfs) with open(etc_hostname, 'w+') as hostname_fd: hostname_fd.write('%s\d' % hostname) @return_if_not_defined def _generate_fstab(self): ''' Generate a file system table for the container This function generates a fstab file based on the volume information in the YAML configuration. Currently only bind mounted directories are supported. TODO Revvaluate if the fstab file is better than lxc.mount.entry ''' fstab_file = self.get_config_item('lxc.mount') if not fstab_file: fstab_file = os.path.join(*[self.get_config_path(), self.name, 'fstab']) self.logger.debug('Generating fstab: %s', fstab_file) with open(fstab_file, 'w+') as fstab: if 'volumes' in self.yml: regex = re.compile(regex_volumes) for volume in self.yml['volumes']: match = regex.match(volume) if not match: logging.warning('Invalid volume specification: %s', volume) continue remote = locker.util.expand_vars(match.group(1), self) mountpt = locker.util.expand_vars(match.group(2), self) self.logger.debug('Adding to fstab: %s %s none bind 0 0', remote, mountpt) fstab.write('%s %s none bind 0 0\n' % (remote, mountpt)) fstab.write('\n') def get_port_rules(self): ''' Get port forwarding netfilter rules of the container This method only searches the LOCKER chain in the NAT table and ignores the FORWARD chain in the FILTER table! :returns: list of rules as tuple (protocol, (dst, port), (ip, port)) ''' nat_table = iptc.Table(iptc.Table.NAT) locker_nat_chain = iptc.Chain(nat_table, 'LOCKER_PREROUTING') dnat_rules = list() try: self.logger.debug('Searching netfilter rules') for rule in [rul for rul in locker_nat_chain.rules if rul.protocol in ['tcp', 'udp']]: for match in rule.matches: if match.name == 'comment' and match.comment == self.name: dport = [m.dport for m in rule.matches if m.name in ['tcp', 'udp']][0] to_ip, to_port = rule.target.to_destination.split(':') dnat_rules.append((rule.protocol, (rule.dst, dport), (to_ip, to_port))) except iptc.IPTCError as err: self.logger.warning('An arror occured searching the netfiler rules: %s', err) return dnat_rules def _move_dirs(self): ''' Move directories from inside the container to the host This method optionally enables to move data from inside the container to the host so that non-empty bind mounts can be set up. If a directory does not exist within the container, it will be created. This method moves the data from the container to the host to preserve the owner, group, and mode configuration. TODO Is there no way to "cp -ar" with shutil or another module? ''' def _remove_slash(string): ''' Temp. work-around ''' if string.endswith('/'): return string[:-1] return string if self.project.args.get('no_move', False): self.logger.debug('Skipping moving of directories from container to host system') return if 'volumes' not in self.yml: self.logger.debug('No volumes defined') return rootfs = self.rootfs for volume in self.yml['volumes']: # TODO Use regex! outside, inside = [_remove_slash(locker.util.expand_vars(s.strip(), self)) for s in volume.split(':')] outside_parent = os.path.dirname(outside) if os.path.exists(outside): self.logger.warning('Directory exists on host system, skipping: %s', outside) continue if os.path.isfile(rootfs+inside): self.logger.warning('Files are not supported, skipping: %s', rootfs+inside) continue if not os.path.exists(outside_parent): try: os.makedirs(outside_parent) except OSError as error: self.logger.error('Could not create parent directory on host system: %s, %s', outside_parent, error) continue else: self.logger.debug('Created parent directory on host system: %s', outside_parent) if os.path.isdir(rootfs+inside): # Move should preseve owner and group, # recreate dir afterwards in container again as mount point self.logger.debug('Moving directory: %s -> %s', rootfs+inside, outside) try: shutil.move(rootfs+inside, outside) except shutil.Error as error: self.logger.error('Could not move directory: %s', error) continue try: os.mkdir(rootfs+inside) except OSError: self.logger.error('Could not create directory in the container: %s', rootfs+inside) continue continue try: os.makedirs(outside) except OSError: self.logger.error('Could not create directory on host system: %s', outside) continue else: self.logger.info('Created empty on host system: %s', outside) try: os.makedirs(rootfs+inside) except OSError: self.logger.error('Could not create directory in the container: %s', rootfs+inside) continue else: self.logger.info('Created empty directory in the container: %s', rootfs+inside) @return_if_not_defined def links(self, auto_update=False): ''' Link container with other containers Links the container to any other container that is specified in the particular "links" subtree in YAML file. :param auto_update: Set to True to suppress some logger output because the container to link to is purposely stopped and unavailable. ''' self.logger.info('Updating links') if not 'links' in self.yml: self.logger.debug('No links defined') return link_regex = re.compile(regex_link) hosts_entries = list() for link in self.yml['links']: match = link_regex.match(link) if not match: self.logger.error('Invalid link statement: %s', link) continue group_dict = match.groupdict() name = group_dict['name'] container = self.project.get_container(name) if not container: self.logger.error('Cannot link with unavailable container: %s', name) continue if not container.running: # Suppress message when it's clear that the particular container # may have been stopped if auto_update: self.logger.debug('Cannot link with stopped container: %s', name) else: self.logger.warning('Cannot link with stopped container: %s', name) continue names = [container.yml.get('fqdn', None), name, group_dict.get('alias', None)] names = [x for x in names if x] hosts_entries.extend([(ip, name, names) for ip in container.get_ips()]) self._update_etc_hosts(hosts_entries) self._update_link_rules(hosts_entries) @return_if_not_defined @return_if_not_running def freeze(self): self.logger.info('Freezing') if not lxc.Container.freeze(self): self.logger.warning('Could not freeze') @return_if_not_defined @return_if_not_running def unfreeze(self): self.logger.info('Unfreezing') if not lxc.Container.unfreeze(self): self.logger.warning('Could not unfreeze') @return_if_not_running def _add_link_rules(self, entries): ''' Add netfilter rules to enable communication between containers This method adds netfilter rules that enable this container to communicate with the linked containers. Communication is allowing using any port and any protocol. These netfilter rules are required if the policy of the forward chain in the filter table has been set to drop. :params: List of entries to add, format (ipaddr, container name, names) ''' forward_chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'LOCKER_FORWARD') if Network.find_comment_in_chain(self.name + ':link', forward_chain): self.logger.debug('Found netfilter link rules, skipping') return for ipaddr, _name, _names in entries: for ip in self.get_ips(): # self -> other containers rule = iptc.Rule() rule.src = ip rule.dst = ipaddr rule.in_interface = self.project.network.bridge_ifname rule.out_interface = self.project.network.bridge_ifname comment_match = rule.create_match('comment') comment_match.comment = self.name + ':link' rule.create_target('ACCEPT') forward_chain.insert_rule(rule) # other containers -> self rule = iptc.Rule() rule.src = ipaddr rule.dst = ip rule.in_interface = self.project.network.bridge_ifname rule.out_interface = self.project.network.bridge_ifname comment_match = rule.create_match('comment') comment_match.comment = self.name + ':link' rule.create_target('ACCEPT') forward_chain.insert_rule(rule) def _remove_link_rules(self): ''' Remove netfilter rules required for link support ''' filter_table = iptc.Table(iptc.Table.FILTER) forward_chain = iptc.Chain(filter_table, 'LOCKER_FORWARD') Network._delete_if_comment(self.name + ':link', filter_table, forward_chain) def _update_link_rules(self, entries): ''' Wrapper that first removes all rules and then adds the specified ones TODO Find a better solution than completely removing all rules first :params: List of entries to add, format (ipaddr, container name, names) ''' self._remove_link_rules() self._add_link_rules(entries) @return_if_not_defined def _update_etc_hosts(self, entries): ''' Update /etc/hosts with new entries This method deletes old, project specific entries from /etc/hosts and then adds the specified ones. Locker entries are suffixed with the project name as comment :params: List of entries to add, format (ipaddr, container name, names) ''' etc_hosts = '%s/etc/hosts' % (self.rootfs) try: hosts = Hosts(etc_hosts, self.logger) hosts.remove_by_comment('^%s_.*$' % self.project.name) for ipaddr, name, names in entries: comment = '%s_%s' % (self.project.name, name) hosts.add(ipaddr, names, comment) hosts.save() except: pass def rmlinks(self): ''' Update /etc/hosts by removing all links ''' self.logger.info('Removing links') self._update_etc_hosts([]) self._remove_link_rules() @return_if_not_defined def linked_to(self): ''' Return list of linked containers based on /etc/hosts Does not evaluate the YAML configuration but the actual state of the container. TODO Does not yet check netfilter rules :returns: List of linked containers ''' linked = list() etc_hosts = '%s/etc/hosts' % (self.rootfs) try: with open(etc_hosts, 'r') as etc_hosts_fd: lines = etc_hosts_fd.readlines() except FileNotFoundError: return linked # TODO Use a better regex regex = re.compile('^.* # %s_(.+)$' % self.project.name) for line in lines: match = regex.match(line) if match: linked.append(match.group(1)) return linked def get_cgroup_item(self, key): ''' Get cgroup item Tries to get the cgroup item and returns only single item if a list was returned. The method first tries to query the key's value from the running container and if this fails tries to get the value from the config file. :param key: The key / name of the cgroup item :returns: cgroup item ''' self.logger.debug('Getting cgroup item: %s', key) try: # will fail if the container is not running value = lxc.Container.get_cgroup_item(self, key) return value except KeyError: pass try: # 2nd try: get value from config file # get_config_item() can return either # - an empty string # - a list with a single value # - something else that I do not expect value = self.get_config_item('lxc.cgroup.' + key) except KeyError: return None if value == '': # This seems to be the standard value if the key was not found pass elif isinstance(value, list) and len(value) == 1: # Locker relevant cgroup keys should always return only one # value but this may still be a list. value = value[0] else: raise ValueError('Unexpected value for cgroup item: %s = %s' % (key, value)) return value
gpl-3.0
cocodedesigns/green-lily
single-event.php
4957
<?php get_header(); $startdate = get_post_meta( get_the_ID(), 'lvk_events_startdate', true ); $startdate = explode( '-', $startdate ); $eventallday = get_post_meta( get_the_ID(), 'lvk_events_allday', true ); if ( $eventallday == '1' ) { $starthour = '00'; $startmin = '00'; } else { $starthour = get_post_meta( get_the_ID(), 'lvk_events_starthour', true ); $startmin = get_post_meta( get_the_ID(), 'lvk_events_startmin', true ); } $startdatetime = strtotime($startdate[1].'/'.$startdate[2].'/'.$startdate[0].' '.$starthour.':'.$startmin.':00'); $startclock = date( 'j F Y H:i:s', $startdatetime ); ?> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <div class="container"> <?php if ( has_post_thumbnail() ) { $fImg = wp_get_attachment_image_src( get_post_thumbnail_id( get_the_ID() ), 'full' ); $featImg = $fImg[0]; $classes = "featured-image has-fi"; } else { $classes = "no-fi";} ?> <div id="single-event-title" class="pagewide-title <?php echo $classes; ?>" <?php if ( has_post_thumbnail() ) { echo 'style="background-image: url(\''.$featImg.'\')"'; } ?>> <div class="inner-title"> <div class="page-title"> <h1 class="event-title"><?php the_title(); ?></h1> <h2 class="event-date"><?php echo date( 'F j, Y', $startdatetime ); ?></h2> <h3 class="event-time"><?php if ( $eventallday == '1' ) { ?>All day event<?php } else { ?>Starts at <?php echo date( 'h:i a', $startdatetime ); } ?></h3> </div> </div> </div> <div id="event-<?php the_ID(); ?>" <?php post_class( array('single-event-post', 'event-post', 'single-event', 'event', 'event-main') ); ?>> <div class="page-content event-content-wrapper>"> <div class="item-timer"> <?php if ( strtotime( date("Y-m-d H:i:s") ) > $startdatetime ) { if ( date ( 'Ymd' ) != date ( 'Ymd', $startdatetime ) ) { ?> <div id="event-countdown"> <div id="event-countdown-now">This event has passed!</div> </div> <?php } else { ?> <div id="event-countdown"> <div id="event-countdown-now">This event is on now!</div> </div> <?php } } else { ?> <div id="event-countdown"> <div id="event-countdown-clock"> <div class="count event-countdown-label"> <span class="label">Event starts in:</span> </div> <div class="count"> <span class="days"></span> <div class="smalltext">Days</div> </div> <div class="count"> <span class="hours"></span> <div class="smalltext">Hours</div> </div> <div class="count"> <span class="minutes"></span> <div class="smalltext">Minutes</div> </div> <div class="count"> <span class="seconds"></span> <div class="smalltext">Seconds</div> </div> </div> </div> <script> var deadline = new Date( Date.parse('<?php echo date( 'M j, Y H:i:s', $startdatetime ); ?>') ); initializeClock('event-countdown', deadline); </script> <?php } ?> </div> <div class="event-content"> <?php the_content(); ?> </div> <div class="event-location-info"> <?php if ( get_post_meta( get_the_ID(), 'lvk_events_location', true ) ) { ?> <p class="event-location"><?php echo get_post_meta( get_the_ID(), 'lvk_events_location', true ); ?></p> <?php } else { } if ( get_post_meta( get_the_ID(), 'lvk_events_address', true ) ) { ?> <p class="event-address"><?php echo get_post_meta( get_the_ID(), 'lvk_events_address', true ); ?></p> <?php } else { } ?> </div> <?php if ( get_post_meta( get_the_ID(), 'lvk_events_address', true ) ) { ?> <div class="event-map"> <?php echo do_shortcode('[map address="'.get_post_meta( get_the_ID(), 'lvk_events_address', true ).'" place="'.get_post_meta( get_the_ID(), 'lvk_events_location', true ).'"]'); ?> </div> <?php } ?> <div class="event-share-links share-links"> <?php include TEMPLATEPATH . '/inc/sharelinks.php'; /* if ( function_exists( 'sharing_display' ) ) { sharing_display( '', true ); } if ( class_exists( 'Jetpack_Likes' ) ) { $custom_likes = new Jetpack_Likes; echo $custom_likes->post_likes( '' ); } */ ?> </div> </div> </div> </div> <?php endwhile; endif; ?> <?php get_footer(); ?>
gpl-3.0
Arp-/curse_impact
renderer/inc/pixel_info.hpp
470
#ifndef CURSE_IMPACT_RENDERER_PIXEL_INFO_HPP #define CURSE_IMPACT_RENDERER_PIXEL_INFO_HPP namespace renderer { struct pixel_info { enum class axis { X_EQ_0, // - Y_EQ_0, // | X_EQ_MINUS_X, // backslash X_EQ_PLUS_X, // / }; enum class side { LEFT, RIGHT, }; axis axis; side side; float percentage; // should be between 1.0 and 0.0 inclusive }; } // namespace renderer #endif // CURSE_IMPACT_RENDERER_PIXEL_INFO_HPP
gpl-3.0
Vrend/JBot
src/main/java/JBOT/Commands/list.java
998
package JBOT.Commands; import JBOT.Util.BadCommandException; import JBOT.Util.Command; import JBOT.Util.IO; import net.dv8tion.jda.core.events.message.MessageReceivedEvent; import java.util.HashMap; public class list implements Command { @Override public void run(MessageReceivedEvent e, String[] args) throws BadCommandException { String output = "```PUBLIC CHATS\n"; HashMap<String, Boolean> rooms = IO.getRooms(e.getGuild().getId()); for(String room : rooms.keySet()) { if(!rooms.get(room)) { output += "* " + room + "\n"; } } output += "\nPRIVATE CHATS\n"; for(String room : rooms.keySet()) { if(rooms.get(room)) { output += "* " + room + "\n"; } } output += "```"; e.getChannel().sendMessage(output).queue(); } @Override public int getPermLevel() { return 0; } }
gpl-3.0
Narfinger/qamster
go-appengine/main.go
2191
package qamster import ( "bytes" "encoding/json" "net/http" "net/url" "strings" "time" // "html/template" ) //json function func js_timetable(w http.ResponseWriter, r *http.Request) { tasks := make([]Task, 0) ds_getTasks(&tasks, r) json.NewEncoder(w).Encode(tasks) } //json function func js_running(w http.ResponseWriter, r *http.Request) { var ir, rt = ds_getRunning(r) var s = IsRunningStruct{IsRunningField: ir, RunningTask: rt} json.NewEncoder(w).Encode(s) } func js_addTask(w http.ResponseWriter, r *http.Request) { // c := appengine.NewContext(r) var isRunning, runningTask = ds_getRunning(r) buf := new(bytes.Buffer) buf.ReadFrom(r.Body) s := buf.String() defer r.Body.Close() if isRunning { js_stop(w, r) } var splitstring = strings.Split(s, "@") if len(splitstring) <= 1 { runningTask = Task{Start: time.Now(), Title: splitstring[0], Category: ""} } else { runningTask = Task{Start: time.Now(), Title: splitstring[0], Category: splitstring[1]} } ds_setRunning(true, runningTask, r) ch_addTask(runningTask, r) } func js_stop(w http.ResponseWriter, r *http.Request) { var ir, finishedTask = ds_getRunning(r) if ir { finishedTask.End = time.Now() ds_appendTask(finishedTask, r) var runningTask = Task{} ds_setRunning(false, runningTask, r) ch_stopTask(r) } } func js_statusbar(w http.ResponseWriter, r *http.Request) { var status = ds_getStatusBar(r) json.NewEncoder(w).Encode(status) } func js_searchtask(w http.ResponseWriter, r *http.Request) { m, _ := url.ParseQuery(r.URL.RawQuery) var s []string if val, ok := m["q"]; ok == false { s = ds_queryTask(r, "") } else { s = ds_queryTask(r, val[0]) } json.NewEncoder(w).Encode(s) } func init() { http.HandleFunc("/go/running", js_running) http.HandleFunc("/go/timetable", js_timetable) http.HandleFunc("/go/addTask", js_addTask) http.HandleFunc("/go/stop", js_stop) http.HandleFunc("/go/statusbar", js_statusbar) http.HandleFunc("/go/searchTask", js_searchtask) http.HandleFunc("/go/createchannel", ch_createchannel) http.HandleFunc("/_ah/channel/connected/", ch_clientConnected) http.HandleFunc("/_ah/channel/disconnected/", ch_clientDisconnected) }
gpl-3.0
Artur-Biniek/TBX32
src/Simulator/Memory.cs
767
using System.Collections.Generic; namespace ArturBiniek.Tbx32.Simulator { public class Memory { Dictionary<uint, int> _ram = new Dictionary<uint, int>(); public int UsedCellsCount { get { return _ram.Keys.Count; } } public void Reset() { _ram = new Dictionary<uint, int>(); } public int this[uint address] { get { if (!_ram.ContainsKey(address)) { _ram[address] = 0; } return _ram[address]; } set { _ram[address] = value; } } } }
gpl-3.0
ShapeChange/ShapeChange
src/main/java/de/interactive_instruments/ShapeChange/Transformation/Profiling/ProfileLoaderConfigurationValidator.java
5944
/** * ShapeChange - processing application schemas for geographic information * * This file is part of ShapeChange. ShapeChange takes a ISO 19109 * Application Schema from a UML model and translates it into a * GML Application Schema or other implementation representations. * * Additional information about the software can be found at * http://shapechange.net/ * * (c) 2002-2017 interactive instruments GmbH, Bonn, Germany * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact: * interactive instruments GmbH * Trierer Strasse 70-72 * 53115 Bonn * Germany */ package de.interactive_instruments.ShapeChange.Transformation.Profiling; import java.io.File; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.SortedSet; import java.util.TreeSet; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.io.FileUtils; import de.interactive_instruments.ShapeChange.AbstractConfigurationValidator; import de.interactive_instruments.ShapeChange.Options; import de.interactive_instruments.ShapeChange.ProcessConfiguration; import de.interactive_instruments.ShapeChange.ShapeChangeResult; import de.interactive_instruments.ShapeChange.ModelDiff.DiffElement.ElementType; /** * @author Johannes Echterhoff (echterhoff at interactive-instruments dot de) * */ public class ProfileLoaderConfigurationValidator extends AbstractConfigurationValidator { protected SortedSet<String> allowedParametersWithStaticNames = new TreeSet<>(Stream.of( ProfileLoader.PARAM_DIFF_ELEMENT_TYPES, ProfileLoader.PARAM_INPUT_MODEL_EXPLICIT_PROFILES, ProfileLoader.PARAM_LOAD_MODEL_DIRECTORY, ProfileLoader.PARAM_LOAD_MODEL_FILE_REGEX, ProfileLoader.PARAM_PROCESS_ALL_SCHEMAS, ProfileLoader.PARAM_PROFILES_FOR_CLASSES_WITHOUT_EXPLICIT_PROFILES, ProfileLoader.PARAM_PROFILES_TO_LOAD).collect(Collectors.toSet())); protected List<Pattern> regexForAllowedParametersWithDynamicNames = null; @Override public boolean isValid(ProcessConfiguration config, Options options, ShapeChangeResult result) { boolean isValid = true; allowedParametersWithStaticNames.addAll(getCommonTransformerParameters()); isValid = validateParameters(allowedParametersWithStaticNames, regexForAllowedParametersWithDynamicNames, config.getParameters().keySet(), result) && isValid; // validate PARAM_LOAD_MODEL_FILE_REGEX if (config.hasParameter(ProfileLoader.PARAM_LOAD_MODEL_FILE_REGEX)) { try { Pattern.compile(config.parameterAsString(ProfileLoader.PARAM_LOAD_MODEL_FILE_REGEX, "", false, true)); } catch (PatternSyntaxException e) { isValid = false; result.addError(this, 103, ProfileLoader.PARAM_LOAD_MODEL_FILE_REGEX, e.getMessage()); } } if (!config.hasParameter(ProfileLoader.PARAM_LOAD_MODEL_DIRECTORY)) { isValid = false; result.addError(this, 100, ProfileLoader.PARAM_LOAD_MODEL_DIRECTORY); } else { String loadModelDirectory = config.getParameterValue(ProfileLoader.PARAM_LOAD_MODEL_DIRECTORY); // ensure that directory exists File loadModelDirectoryFile = new File(loadModelDirectory); boolean exi = loadModelDirectoryFile.exists(); boolean dir = loadModelDirectoryFile.isDirectory(); boolean rea = loadModelDirectoryFile.canRead(); if (!exi || !dir || !rea) { isValid = false; result.addError(this, 101, ProfileLoader.PARAM_LOAD_MODEL_DIRECTORY, loadModelDirectory); } else { Collection<File> files = FileUtils.listFiles(loadModelDirectoryFile, new String[] { "xml", "zip" }, false); if (files.isEmpty()) { result.addWarning(this, 102, loadModelDirectory); } } } // validate PARAM_DIFF_ELEMENT_TYPES List<String> diffElementTypeNames = config.parameterAsStringList(ProfileLoader.PARAM_DIFF_ELEMENT_TYPES, ProfileLoader.DEFAULT_DIFF_ELEMENT_TYPES, true, true); Collections.sort(diffElementTypeNames); for (String detn : diffElementTypeNames) { try { ElementType.valueOf(detn.toUpperCase(Locale.ENGLISH)); } catch (IllegalArgumentException e) { result.addWarning(this, 104, ProfileLoader.PARAM_DIFF_ELEMENT_TYPES, detn); } } return isValid; } @Override public String message(int mnr) { switch (mnr) { case 1: return "Context: class $1$"; case 2: return "Context: property $1$"; case 3: return "Context: association role (end1) '$1$'"; case 4: return "Context: association role (end2) '$1$'"; case 100: return "Transformation parameter '$1$' is required, but was not found in the configuration."; case 101: return "Value '$1$' of transformation parameter '$2$' does not identify an existing directory that can be read."; case 102: return "The directory '$1$', from which profiles shall be loaded, is empty."; case 103: return "Syntax exception while compiling the regular expression defined by transformation parameter '$1$': '$2$'."; case 104: return "Element '$2$' from the value of transformation parameter '$1$' is unknown (even when ignoring case). The element will be ignored."; default: return "(Unknown message in " + this.getClass().getName() + ". Message number was: " + mnr + ")"; } } }
gpl-3.0
danyalzia/ShortestPath
src/GraphHopperAPI.java
3023
import com.graphhopper.GHRequest; import com.graphhopper.GHResponse; import com.graphhopper.GraphHopper; import com.graphhopper.routing.util.EncodingManager; import com.graphhopper.util.GPXEntry; import com.graphhopper.util.Instruction; import com.graphhopper.util.InstructionList; import com.graphhopper.util.PointList; import java.io.File; import java.util.List; import java.util.Locale; import java.util.Map; public class GraphHopperAPI { boolean offlineMode; boolean inputLatLong; double distanceInMeters; double timeInMs; double minLat; double minLon; double maxLat; double maxLon; GHResponse rsp; GraphHopper hopper; public GraphHopperAPI(File file) { // create singleton hopper = new GraphHopper().forServer(); hopper.setOSMFile(file.getName()); // where to store graphhopper files? hopper.setGraphHopperLocation("."); hopper.setEncodingManager(new EncodingManager("car")); // now this can take minutes if it imports or a few seconds for loading // of course this is dependent on the area you import hopper.importOrLoad(); minLat = hopper.getGraphHopperStorage().getBounds().minLat; minLon = hopper.getGraphHopperStorage().getBounds().minLon; maxLat = hopper.getGraphHopperStorage().getBounds().maxLat; maxLon = hopper.getGraphHopperStorage().getBounds().maxLon; } public void setRequest(double initialLat, double initialLong, double finalLat, double finalLong, String vehicle) { // simple configuration of the request object, see the GraphHopperServlet classs for more possibilities. GHRequest req = new GHRequest(initialLat, initialLong, finalLat, finalLong). setWeighting("fastest"). setVehicle(vehicle); //setLocale(Locale.US); rsp = hopper.route(req); } public void calculate() { // first check for errors if(rsp.hasErrors()) { // handle them! System.out.println(rsp.getErrors()); return; } // points, distance in meters and time in millis of the full path PointList pointList = rsp.getPoints(); double distance = rsp.getDistance(); long time = rsp.getTime(); distanceInMeters = distance; timeInMs = time; System.out.println(distanceInMeters); System.out.println(minLat); System.out.println(minLon); System.out.println(maxLat); System.out.println(maxLon); InstructionList il = rsp.getInstructions(); // iterate over every turn instruction for(Instruction instruction : il) { instruction.getDistance(); } // or get the json List<Map<String, Object>> iList = il.createJson(); // or get the result as gpx entries: List<GPXEntry> list = il.createGPXList(); } }
gpl-3.0