repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
jaywink/cartridge-reservable | cartridge/shop/management/__init__.py | 1932 | from __future__ import print_function
from __future__ import unicode_literals
from future.builtins import input
import sys
from django.conf import settings
from django.core.management import call_command
from django.db.models.signals import post_syncdb
from mezzanine.utils.tests import copy_test_to_media
from cartridge.shop.models import Product
from cartridge.shop import models as shop_app
def create_product(app, created_models, verbosity, interactive, **kwargs):
if Product in created_models:
call_command("loaddata", "cartridge_required.json")
if interactive:
confirm = input("\nWould you like to install an initial "
"demo product and sale? (yes/no): ")
while True:
if confirm == "yes":
break
elif confirm == "no":
return
confirm = input("Please enter either 'yes' or 'no': ")
# This is a hack. Ideally to split fixtures between optional
# and required, we'd use the same approach Mezzanine does,
# within a ``createdb`` management command. Ideally to do this,
# we'd subclass Mezzanine's createdb command and shadow it,
# but to do that, the cartridge.shop app would need to appear
# *after* mezzanine.core in the INSTALLED_APPS setting, but the
# reverse is needed for template overriding (and probably other
# bits) to work correctly.
# SO........... we just cheat, and check sys.argv here. Namaste.
elif "--nodata" in sys.argv:
return
if verbosity >= 1:
print()
print("Creating demo product and sale ...")
print()
call_command("loaddata", "cartridge_optional.json")
copy_test_to_media("cartridge.shop", "product")
if not settings.TESTING:
post_syncdb.connect(create_product, sender=shop_app)
| bsd-2-clause |
mahori/homebrew-cask | Casks/tunnelblick.rb | 1767 | cask "tunnelblick" do
version "3.8.7a,5770"
sha256 "bb5858619a58561d07d23df470b9548b82c1544cea9ffade30c4362dc8f3bd93"
url "https://github.com/Tunnelblick/Tunnelblick/releases/download/v#{version.csv.first}/Tunnelblick_#{version.csv.first}_build_#{version.csv.second}.dmg",
verified: "github.com/Tunnelblick/Tunnelblick/"
name "Tunnelblick"
desc "Free and open-source OpenVPN client"
homepage "https://www.tunnelblick.net/"
# We need to check all releases since the current latest release is a beta version.
livecheck do
url "https://github.com/Tunnelblick/Tunnelblick/releases"
strategy :page_match do |page|
match = page.match(%r{href=.*?/Tunnelblick[._-]v?(\d+(?:\.\d+)*[a-z]?)_build_(\d+)\.dmg}i)
next if match.blank?
"#{match[1]},#{match[2]}"
end
end
auto_updates true
depends_on macos: ">= :yosemite"
app "Tunnelblick.app"
uninstall_preflight do
set_ownership "#{appdir}/Tunnelblick.app"
end
uninstall launchctl: [
"net.tunnelblick.tunnelblick.LaunchAtLogin",
"net.tunnelblick.tunnelblick.tunnelblickd",
],
delete: "/Library/Application Support/Tunnelblick",
quit: "net.tunnelblick.tunnelblick"
zap trash: [
"~/Library/Application Support/Tunnelblick",
"~/Library/Caches/com.apple.helpd/SDMHelpData/Other/English/HelpSDMIndexFile/Tunnelblick*",
"~/Library/Caches/net.tunnelblick.tunnelblick",
"~/Library/Cookies/net.tunnelblick.tunnelblick.binarycookies",
"~/Library/HTTPStorages/net.tunnelblick.tunnelblick",
"~/Library/Preferences/net.tunnelblick.tunnelblick.plist",
]
caveats <<~EOS
For security reasons, #{token} must be installed to /Applications,
and will request to be moved at launch.
EOS
end
| bsd-2-clause |
justjoheinz/homebrew | Library/Formula/juju.rb | 963 | require 'formula'
class Juju < Formula
homepage 'https://juju.ubuntu.com'
url 'https://launchpad.net/juju-core/1.18/1.18.3/+download/juju-core_1.18.3.tar.gz'
sha1 '9290acb390d7bcefd56212de1a8a36c008f5db89'
devel do
url "https://launchpad.net/juju-core/trunk/1.19.1/+download/juju-core_1.19.1.tar.gz"
sha1 "0bf1f8fcf5788907b960c1581007f9fd45126d21"
end
bottle do
sha1 "08b825b39bf16375b17cd4b4d73a95093936d41c" => :mavericks
sha1 "1f5775826a2414f9741b90ce2c27a1c4e3a1cfe1" => :mountain_lion
sha1 "fd95734a178d909409670ca74cb29d06e384f3db" => :lion
end
depends_on 'go' => :build
def install
ENV['GOPATH'] = buildpath
args = %w(install launchpad.net/juju-core/cmd/juju)
args.insert(1, "-v") if ARGV.verbose?
system "go", *args
bin.install 'bin/juju'
bash_completion.install "src/launchpad.net/juju-core/etc/bash_completion.d/juju-core"
end
test do
system "#{bin}/juju", "version"
end
end
| bsd-2-clause |
epiqc/ScaffCC | clang/test/OpenMP/taskloop_firstprivate_codegen.cpp | 31291 | // RUN: %clang_cc1 -verify -fopenmp -x c++ -triple x86_64-apple-darwin10 -emit-llvm %s -o - | FileCheck %s
// RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -triple x86_64-apple-darwin10 -emit-pch -o %t %s
// RUN: %clang_cc1 -fopenmp -x c++ -triple x86_64-apple-darwin10 -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s
// RUN: %clang_cc1 -verify -fopenmp -x c++ -std=c++11 -DLAMBDA -triple x86_64-apple-darwin10 -emit-llvm %s -o - | FileCheck -check-prefix=LAMBDA %s
// RUN: %clang_cc1 -verify -fopenmp -x c++ -fblocks -DBLOCKS -triple x86_64-apple-darwin10 -emit-llvm %s -o - | FileCheck -check-prefix=BLOCKS %s
// RUN: %clang_cc1 -verify -fopenmp -x c++ -std=c++11 -DARRAY -triple x86_64-apple-darwin10 -emit-llvm %s -o - | FileCheck -check-prefix=ARRAY %s
// RUN: %clang_cc1 -verify -fopenmp-simd -x c++ -triple x86_64-apple-darwin10 -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY0 %s
// RUN: %clang_cc1 -fopenmp-simd -x c++ -std=c++11 -triple x86_64-apple-darwin10 -emit-pch -o %t %s
// RUN: %clang_cc1 -fopenmp-simd -x c++ -triple x86_64-apple-darwin10 -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck --check-prefix SIMD-ONLY0 %s
// RUN: %clang_cc1 -verify -fopenmp-simd -x c++ -std=c++11 -DLAMBDA -triple x86_64-apple-darwin10 -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY0 %s
// RUN: %clang_cc1 -verify -fopenmp-simd -x c++ -fblocks -DBLOCKS -triple x86_64-apple-darwin10 -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY0 %s
// RUN: %clang_cc1 -verify -fopenmp-simd -x c++ -std=c++11 -DARRAY -triple x86_64-apple-darwin10 -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY0 %s
// SIMD-ONLY0-NOT: {{__kmpc|__tgt}}
// expected-no-diagnostics
#ifndef ARRAY
#ifndef HEADER
#define HEADER
template <class T>
struct S {
T f;
S(T a) : f(a) {}
S() : f() {}
S(const S &s, T t = T()) : f(s.f + t) {}
operator T() { return T(); }
~S() {}
};
volatile double g;
// CHECK-DAG: [[KMP_TASK_T_TY:%.+]] = type { i8*, i32 (i32, i8*)*, i32, %union{{.+}}, %union{{.+}}, i64, i64, i64, i32, i8* }
// CHECK-DAG: [[S_DOUBLE_TY:%.+]] = type { double }
// CHECK-DAG: [[PRIVATES_MAIN_TY:%.+]] = type {{.?}}{ [2 x [[S_DOUBLE_TY]]], [[S_DOUBLE_TY]], i32, [2 x i32]
// CHECK-DAG: [[CAP_MAIN_TY:%.+]] = type {{.*}}{ [2 x i32]*, i32, {{.*}}[2 x [[S_DOUBLE_TY]]]*, [[S_DOUBLE_TY]]*, i{{[0-9]+}}
// CHECK-DAG: [[KMP_TASK_MAIN_TY:%.+]] = type { [[KMP_TASK_T_TY]], [[PRIVATES_MAIN_TY]] }
// CHECK-DAG: [[S_INT_TY:%.+]] = type { i32 }
// CHECK-DAG: [[CAP_TMAIN_TY:%.+]] = type { [2 x i32]*, i32*, [2 x [[S_INT_TY]]]*, [[S_INT_TY]]* }
// CHECK-DAG: [[PRIVATES_TMAIN_TY:%.+]] = type { i32, [2 x i32], [2 x [[S_INT_TY]]], [[S_INT_TY]], [104 x i8] }
// CHECK-DAG: [[KMP_TASK_TMAIN_TY:%.+]] = type { [[KMP_TASK_T_TY]], [{{[0-9]+}} x i8], [[PRIVATES_TMAIN_TY]] }
template <typename T>
T tmain() {
S<T> ttt;
S<T> test(ttt);
T t_var __attribute__((aligned(128))) = T();
T vec[] = {1, 2};
S<T> s_arr[] = {1, 2};
S<T> var(3);
#pragma omp taskloop firstprivate(t_var, vec, s_arr, s_arr, var, var)
for (int i = 0; i < 10; ++i) {
vec[0] = t_var;
s_arr[0] = var;
}
return T();
}
int main() {
static int sivar;
#ifdef LAMBDA
// LAMBDA: [[G:@.+]] = global double
// LAMBDA: [[SIVAR:@.+]] = internal global i{{[0-9]+}} 0,
// LAMBDA-LABEL: @main
// LAMBDA: call{{( x86_thiscallcc)?}} void [[OUTER_LAMBDA:@.+]](
[&]() {
// LAMBDA: define{{.*}} internal{{.*}} void [[OUTER_LAMBDA]](
// LAMBDA: [[RES:%.+]] = call i8* @__kmpc_omp_task_alloc(%{{[^ ]+}} @{{[^,]+}}, i32 %{{[^,]+}}, i32 1, i64 96, i64 16, i32 (i32, i8*)* bitcast (i32 (i32, %{{[^*]+}}*)* [[TASK_ENTRY:@[^ ]+]] to i32 (i32, i8*)*))
// LAMBDA: [[PRIVATES:%.+]] = getelementptr inbounds %{{.+}}, %{{.+}}* %{{.+}}, i{{.+}} 0, i{{.+}} 1
// LAMBDA: [[G_PRIVATE_ADDR:%.+]] = getelementptr inbounds %{{.+}}, %{{.+}}* [[PRIVATES]], i{{.+}} 0, i{{.+}} 0
// LAMBDA: [[G_ADDR_REF:%.+]] = getelementptr inbounds %{{.+}}, %{{.+}}* %{{.+}}, i{{.+}} 0, i{{.+}} 0
// LAMBDA: [[G_VAL:%.+]] = load volatile double, double* [[G_ADDR_REF]]
// LAMBDA: store volatile double [[G_VAL]], double* [[G_PRIVATE_ADDR]]
// LAMBDA: [[SIVAR_PRIVATE_ADDR:%.+]] = getelementptr inbounds %{{.+}}, %{{.+}}* [[PRIVATES]], i{{.+}} 0, i{{.+}} 1
// LAMBDA: [[SIVAR_ADDR_REF:%.+]] = getelementptr inbounds %{{.+}}, %{{.+}}* %{{.+}}, i{{.+}} 0, i{{.+}} 1
// LAMBDA: [[SIVAR_VAL:%.+]] = load i{{[0-9]+}}, i{{[0-9]+}}* [[SIVAR_ADDR_REF]]
// LAMBDA: store i{{[0-9]+}} [[SIVAR_VAL]], i{{[0-9]+}}* [[SIVAR_PRIVATE_ADDR]]
// LAMBDA: call void @__kmpc_taskloop(%{{.+}}* @{{.+}}, i32 %{{.+}}, i8* [[RES]], i32 1, i64* %{{.+}}, i64* %{{.+}}, i64 %{{.+}}, i32 1, i32 0, i64 0, i8* null)
// LAMBDA: ret
#pragma omp taskloop firstprivate(g, sivar)
for (int i = 0; i < 10; ++i) {
// LAMBDA: define {{.+}} void [[INNER_LAMBDA:@.+]](%{{.+}}* [[ARG_PTR:%.+]])
// LAMBDA: store %{{.+}}* [[ARG_PTR]], %{{.+}}** [[ARG_PTR_REF:%.+]],
// LAMBDA: [[ARG_PTR:%.+]] = load %{{.+}}*, %{{.+}}** [[ARG_PTR_REF]]
// LAMBDA: [[G_PTR_REF:%.+]] = getelementptr inbounds %{{.+}}, %{{.+}}* [[ARG_PTR]], i{{[0-9]+}} 0, i{{[0-9]+}} 0
// LAMBDA: [[G_REF:%.+]] = load double*, double** [[G_PTR_REF]]
// LAMBDA: store double 2.0{{.+}}, double* [[G_REF]]
// LAMBDA: store double* %{{.+}}, double** %{{.+}},
// LAMBDA: define internal i32 [[TASK_ENTRY]](i32 %0, %{{.+}}* noalias %1)
g = 1;
sivar = 11;
// LAMBDA: store double 1.0{{.+}}, double* %{{.+}},
// LAMBDA: store i{{[0-9]+}} 11, i{{[0-9]+}}* %{{.+}},
// LAMBDA: call void [[INNER_LAMBDA]](%
// LAMBDA: ret
[&]() {
g = 2;
sivar = 22;
}();
}
}();
return 0;
#elif defined(BLOCKS)
// BLOCKS: [[G:@.+]] = global double
// BLOCKS-LABEL: @main
// BLOCKS: call void {{%.+}}(i8
^{
// BLOCKS: define{{.*}} internal{{.*}} void {{.+}}(i8*
// BLOCKS: [[RES:%.+]] = call i8* @__kmpc_omp_task_alloc(%{{[^ ]+}} @{{[^,]+}}, i32 %{{[^,]+}}, i32 1, i64 96, i64 16, i32 (i32, i8*)* bitcast (i32 (i32, %{{[^*]+}}*)* [[TASK_ENTRY:@[^ ]+]] to i32 (i32, i8*)*))
// BLOCKS: [[PRIVATES:%.+]] = getelementptr inbounds %{{.+}}, %{{.+}}* %{{.+}}, i{{.+}} 0, i{{.+}} 1
// BLOCKS: [[G_PRIVATE_ADDR:%.+]] = getelementptr inbounds %{{.+}}, %{{.+}}* [[PRIVATES]], i{{.+}} 0, i{{.+}} 0
// BLOCKS: [[G_ADDR_REF:%.+]] = getelementptr inbounds %{{.+}}, %{{.+}}* %{{.+}}, i{{.+}} 0, i{{.+}} 0
// BLOCKS: [[G_VAL:%.+]] = load volatile double, double* [[G_ADDR_REF]]
// BLOCKS: store volatile double [[G_VAL]], double* [[G_PRIVATE_ADDR]]
// BLOCKS: [[SIVAR_PRIVATE_ADDR:%.+]] = getelementptr inbounds %{{.+}}, %{{.+}}* [[PRIVATES]], i{{.+}} 0, i{{.+}} 1
// BLOCKS: [[SIVAR_ADDR_REF:%.+]] = getelementptr inbounds %{{.+}}, %{{.+}}* %{{.+}}, i{{.+}} 0, i{{.+}} 1
// BLOCKS: [[SIVAR_VAL:%.+]] = load i{{[0-9]+}}, i{{[0-9]+}}* [[SIVAR_ADDR_REF]]
// BLOCKS: store i{{[0-9]+}} [[SIVAR_VAL]], i{{[0-9]+}}* [[SIVAR_PRIVATE_ADDR]]
// BLOCKS: call void @__kmpc_taskloop(%{{.+}}* @{{.+}}, i32 %{{.+}}, i8* [[RES]], i32 1, i64* %{{.+}}, i64* %{{.+}}, i64 %{{.+}}, i32 1, i32 0, i64 0, i8* null)
// BLOCKS: ret
#pragma omp taskloop firstprivate(g, sivar)
for (int i = 0; i < 10; ++i) {
// BLOCKS: define {{.+}} void {{@.+}}(i8*
// BLOCKS-NOT: [[G]]{{[[^:word:]]}}
// BLOCKS: store double 2.0{{.+}}, double*
// BLOCKS-NOT: [[G]]{{[[^:word:]]}}
// BLOCKS-NOT: [[ISVAR]]{{[[^:word:]]}}
// BLOCKS: store i{{[0-9]+}} 22, i{{[0-9]+}}*
// BLOCKS-NOT: [[SIVAR]]{{[[^:word:]]}}
// BLOCKS: ret
// BLOCKS: store double* %{{.+}}, double** %{{.+}},
// BLOCKS: store i{{[0-9]+}}* %{{.+}}, i{{[0-9]+}}** %{{.+}},
// BLOCKS: define internal i32 [[TASK_ENTRY]](i32 %0, %{{.+}}* noalias %1)
g = 1;
sivar = 11;
// BLOCKS: store double 1.0{{.+}}, double* %{{.+}},
// BLOCKS-NOT: [[G]]{{[[^:word:]]}}
// BLOCKS: store i{{[0-9]+}} 11, i{{[0-9]+}}* %{{.+}},
// BLOCKS-NOT: [[SIVAR]]{{[[^:word:]]}}
// BLOCKS: call void {{%.+}}(i8
^{
g = 2;
sivar = 22;
}();
}
}();
return 0;
#else
S<double> ttt;
S<double> test(ttt);
int t_var = 0;
int vec[] = {1, 2};
S<double> s_arr[] = {1, 2};
S<double> var(3);
#pragma omp taskloop firstprivate(var, t_var, s_arr, vec, s_arr, var, sivar)
for (int i = 0; i < 10; ++i) {
vec[0] = t_var;
s_arr[0] = var;
sivar = 33;
}
return tmain<int>();
#endif
}
// CHECK: [[SIVAR:.+]] = internal global i{{[0-9]+}} 0,
// CHECK: define i{{[0-9]+}} @main()
// CHECK: alloca [[S_DOUBLE_TY]],
// CHECK: [[TEST:%.+]] = alloca [[S_DOUBLE_TY]],
// CHECK: [[T_VAR_ADDR:%.+]] = alloca i32,
// CHECK: [[VEC_ADDR:%.+]] = alloca [2 x i32],
// CHECK: [[S_ARR_ADDR:%.+]] = alloca [2 x [[S_DOUBLE_TY]]],
// CHECK: [[VAR_ADDR:%.+]] = alloca [[S_DOUBLE_TY]],
// CHECK: [[GTID:%.+]] = call i32 @__kmpc_global_thread_num([[LOC:%.+]])
// CHECK: call {{.*}} [[S_DOUBLE_TY_COPY_CONSTR:@.+]]([[S_DOUBLE_TY]]* [[TEST]],
// Store original variables in capture struct.
// CHECK: [[VEC_REF:%.+]] = getelementptr inbounds [[CAP_MAIN_TY]], [[CAP_MAIN_TY]]* %{{.+}}, i{{[0-9]+}} 0, i{{[0-9]+}} 0
// CHECK: store [2 x i32]* [[VEC_ADDR]], [2 x i32]** [[VEC_REF]],
// CHECK: [[T_VAR_REF:%.+]] = getelementptr inbounds [[CAP_MAIN_TY]], [[CAP_MAIN_TY]]* %{{.+}}, i{{[0-9]+}} 0, i{{[0-9]+}} 1
// CHECK: [[T_VAR_VAL:%.+]] = load i32, i32* [[T_VAR_ADDR]],
// CHECK: store i32 [[T_VAR_VAL]], i32* [[T_VAR_REF]],
// CHECK: [[S_ARR_REF:%.+]] = getelementptr inbounds [[CAP_MAIN_TY]], [[CAP_MAIN_TY]]* %{{.+}}, i{{[0-9]+}} 0, i{{[0-9]+}} 3
// CHECK: store [2 x [[S_DOUBLE_TY]]]* [[S_ARR_ADDR]], [2 x [[S_DOUBLE_TY]]]** [[S_ARR_REF]],
// CHECK: [[VAR_REF:%.+]] = getelementptr inbounds [[CAP_MAIN_TY]], [[CAP_MAIN_TY]]* %{{.+}}, i{{[0-9]+}} 0, i{{[0-9]+}} 4
// CHECK: store [[S_DOUBLE_TY]]* [[VAR_ADDR]], [[S_DOUBLE_TY]]** [[VAR_REF]],
// CHECK: [[SIVAR_REF:%.+]] = getelementptr inbounds [[CAP_MAIN_TY]], [[CAP_MAIN_TY]]* %{{.+}}, i{{[0-9]+}} 0, i{{[0-9]+}} 5
// CHECK: [[SIVAR_VAL:%.+]] = load i32, i32* [[SIVAR]],
// CHECK: store i{{[0-9]+}} [[SIVAR_VAL]], i{{[0-9]+}}* [[SIVAR_REF]],
// Allocate task.
// Returns struct kmp_task_t {
// [[KMP_TASK_T]] task_data;
// [[KMP_TASK_MAIN_TY]] privates;
// };
// CHECK: [[RES:%.+]] = call i8* @__kmpc_omp_task_alloc([[LOC]], i32 [[GTID]], i32 9, i64 120, i64 40, i32 (i32, i8*)* bitcast (i32 (i32, [[KMP_TASK_MAIN_TY]]*)* [[TASK_ENTRY:@[^ ]+]] to i32 (i32, i8*)*))
// CHECK: [[RES_KMP_TASK:%.+]] = bitcast i8* [[RES]] to [[KMP_TASK_MAIN_TY]]*
// Fill kmp_task_t->shareds by copying from original capture argument.
// CHECK: [[TASK:%.+]] = getelementptr inbounds [[KMP_TASK_MAIN_TY]], [[KMP_TASK_MAIN_TY]]* [[RES_KMP_TASK]], i{{[0-9]+}} 0, i{{[0-9]+}} 0
// CHECK: [[SHAREDS_REF_ADDR:%.+]] = getelementptr inbounds [[KMP_TASK_T_TY]], [[KMP_TASK_T_TY]]* [[TASK]], i{{[0-9]+}} 0, i{{[0-9]+}} 0
// CHECK: [[SHAREDS_REF:%.+]] = load i8*, i8** [[SHAREDS_REF_ADDR]],
// CHECK: [[CAPTURES_ADDR:%.+]] = bitcast [[CAP_MAIN_TY]]* %{{.+}} to i8*
// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 8 [[SHAREDS_REF]], i8* align 8 [[CAPTURES_ADDR]], i64 40, i1 false)
// Initialize kmp_task_t->privates with default values (no init for simple types, default constructors for classes).
// Also copy address of private copy to the corresponding shareds reference.
// CHECK: [[PRIVATES:%.+]] = getelementptr inbounds [[KMP_TASK_MAIN_TY]], [[KMP_TASK_MAIN_TY]]* [[RES_KMP_TASK]], i{{[0-9]+}} 0, i{{[0-9]+}} 1
// CHECK: [[SHAREDS:%.+]] = bitcast i8* [[SHAREDS_REF]] to [[CAP_MAIN_TY]]*
// Constructors for s_arr and var.
// s_arr;
// CHECK: [[PRIVATE_S_ARR_REF:%.+]] = getelementptr inbounds [[PRIVATES_MAIN_TY]], [[PRIVATES_MAIN_TY]]* [[PRIVATES]], i{{[0-9]+}} 0, i{{[0-9]+}} 0
// CHECK: [[S_ARR_ADDR_REF:%.+]] = getelementptr inbounds [[CAP_MAIN_TY]], [[CAP_MAIN_TY]]* [[SHAREDS]], i{{.+}} 0, i{{.+}} 3
// CHECK: load [2 x [[S_DOUBLE_TY]]]*, [2 x [[S_DOUBLE_TY]]]** [[S_ARR_ADDR_REF]],
// CHECK: call void [[S_DOUBLE_TY_COPY_CONSTR]]([[S_DOUBLE_TY]]* [[S_ARR_CUR:%[^,]+]],
// CHECK: getelementptr [[S_DOUBLE_TY]], [[S_DOUBLE_TY]]* [[S_ARR_CUR]], i{{.+}} 1
// CHECK: getelementptr [[S_DOUBLE_TY]], [[S_DOUBLE_TY]]* %{{.+}}, i{{.+}} 1
// CHECK: icmp eq
// CHECK: br i1
// var;
// CHECK: [[PRIVATE_VAR_REF:%.+]] = getelementptr inbounds [[PRIVATES_MAIN_TY]], [[PRIVATES_MAIN_TY]]* [[PRIVATES]], i{{.+}} 0, i{{.+}} 1
// CHECK: [[VAR_ADDR_REF:%.+]] = getelementptr inbounds [[CAP_MAIN_TY]], [[CAP_MAIN_TY]]* [[SHAREDS]], i{{.+}} 0, i{{.+}} 4
// CHECK: [[VAR_REF:%.+]] = load [[S_DOUBLE_TY]]*, [[S_DOUBLE_TY]]** [[VAR_ADDR_REF]],
// CHECK: call void [[S_DOUBLE_TY_COPY_CONSTR]]([[S_DOUBLE_TY]]* [[PRIVATE_VAR_REF]], [[S_DOUBLE_TY]]* {{.*}}[[VAR_REF]],
// t_var;
// CHECK: [[PRIVATE_T_VAR_REF:%.+]] = getelementptr inbounds [[PRIVATES_MAIN_TY]], [[PRIVATES_MAIN_TY]]* [[PRIVATES]], i{{.+}} 0, i{{.+}} 2
// CHECK: [[T_VAR_ADDR_REF:%.+]] = getelementptr inbounds [[CAP_MAIN_TY]], [[CAP_MAIN_TY]]* [[SHAREDS]], i{{.+}} 0, i{{.+}} 1
// CHECK: [[T_VAR:%.+]] = load i{{.+}}, i{{.+}}* [[T_VAR_ADDR_REF]],
// CHECK: store i32 [[T_VAR]], i32* [[PRIVATE_T_VAR_REF]],
// vec;
// CHECK: [[PRIVATE_VEC_REF:%.+]] = getelementptr inbounds [[PRIVATES_MAIN_TY]], [[PRIVATES_MAIN_TY]]* [[PRIVATES]], i{{.+}} 0, i{{.+}} 3
// CHECK: [[VEC_ADDR_REF:%.+]] = getelementptr inbounds [[CAP_MAIN_TY]], [[CAP_MAIN_TY]]* [[SHAREDS]], i{{.+}} 0, i{{.+}} 0
// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(
// sivar;
// CHECK: [[PRIVATE_SIVAR_REF:%.+]] = getelementptr inbounds [[PRIVATES_MAIN_TY]], [[PRIVATES_MAIN_TY]]* [[PRIVATES]], i{{.+}} 0, i{{.+}} 4
// CHECK: [[SIVAR_ADDR_REF:%.+]] = getelementptr inbounds [[CAP_MAIN_TY]], [[CAP_MAIN_TY]]* [[SHAREDS]], i{{.+}} 0, i{{.+}} 5
// CHECK: [[SIVAR:%.+]] = load i{{.+}}, i{{.+}}* [[SIVAR_ADDR_REF]],
// CHECK: store i32 [[SIVAR]], i32* [[PRIVATE_SIVAR_REF]],
// Provide pointer to destructor function, which will destroy private variables at the end of the task.
// CHECK: [[DESTRUCTORS_REF:%.+]] = getelementptr inbounds [[KMP_TASK_T_TY]], [[KMP_TASK_T_TY]]* [[TASK]], i{{.+}} 0, i{{.+}} 3
// CHECK: [[DESTRUCTORS_PTR:%.+]] = bitcast %union{{.+}}* [[DESTRUCTORS_REF]] to i32 (i32, i8*)**
// CHECK: store i32 (i32, i8*)* bitcast (i32 (i32, [[KMP_TASK_MAIN_TY]]*)* [[DESTRUCTORS:@.+]] to i32 (i32, i8*)*), i32 (i32, i8*)** [[DESTRUCTORS_PTR]],
// Start task.
// CHECK: call void @__kmpc_taskloop([[LOC]], i32 [[GTID]], i8* [[RES]], i32 1, i64* %{{.+}}, i64* %{{.+}}, i64 %{{.+}}, i32 1, i32 0, i64 0, i8* bitcast (void ([[KMP_TASK_MAIN_TY]]*, [[KMP_TASK_MAIN_TY]]*, i32)* [[MAIN_DUP:@.+]] to i8*))
// CHECK: = call i{{.+}} [[TMAIN_INT:@.+]]()
// No destructors must be called for private copies of s_arr and var.
// CHECK-NOT: getelementptr inbounds [[PRIVATES_MAIN_TY]], [[PRIVATES_MAIN_TY]]* [[PRIVATES]], i{{.+}} 0, i{{.+}} 2
// CHECK-NOT: getelementptr inbounds [[PRIVATES_MAIN_TY]], [[PRIVATES_MAIN_TY]]* [[PRIVATES]], i{{.+}} 0, i{{.+}} 3
// CHECK: call void [[S_DOUBLE_TY_DESTR:@.+]]([[S_DOUBLE_TY]]*
// CHECK-NOT: getelementptr inbounds [[PRIVATES_MAIN_TY]], [[PRIVATES_MAIN_TY]]* [[PRIVATES]], i{{.+}} 0, i{{.+}} 2
// CHECK-NOT: getelementptr inbounds [[PRIVATES_MAIN_TY]], [[PRIVATES_MAIN_TY]]* [[PRIVATES]], i{{.+}} 0, i{{.+}} 3
// CHECK: ret
//
// CHECK: define internal void [[PRIVATES_MAP_FN:@.+]]([[PRIVATES_MAIN_TY]]* noalias %0, [[S_DOUBLE_TY]]** noalias %1, i32** noalias %2, [2 x [[S_DOUBLE_TY]]]** noalias %3, [2 x i32]** noalias %4, i32** noalias %5)
// CHECK: [[PRIVATES:%.+]] = load [[PRIVATES_MAIN_TY]]*, [[PRIVATES_MAIN_TY]]**
// CHECK: [[PRIV_S_VAR:%.+]] = getelementptr inbounds [[PRIVATES_MAIN_TY]], [[PRIVATES_MAIN_TY]]* [[PRIVATES]], i32 0, i32 0
// CHECK: [[ARG3:%.+]] = load [2 x [[S_DOUBLE_TY]]]**, [2 x [[S_DOUBLE_TY]]]*** %{{.+}},
// CHECK: store [2 x [[S_DOUBLE_TY]]]* [[PRIV_S_VAR]], [2 x [[S_DOUBLE_TY]]]** [[ARG3]],
// CHECK: [[PRIV_VAR:%.+]] = getelementptr inbounds [[PRIVATES_MAIN_TY]], [[PRIVATES_MAIN_TY]]* [[PRIVATES]], i32 0, i32 1
// CHECK: [[ARG1:%.+]] = load [[S_DOUBLE_TY]]**, [[S_DOUBLE_TY]]*** {{.+}},
// CHECK: store [[S_DOUBLE_TY]]* [[PRIV_VAR]], [[S_DOUBLE_TY]]** [[ARG1]],
// CHECK: [[PRIV_T_VAR:%.+]] = getelementptr inbounds [[PRIVATES_MAIN_TY]], [[PRIVATES_MAIN_TY]]* [[PRIVATES]], i32 0, i32 2
// CHECK: [[ARG2:%.+]] = load i32**, i32*** %{{.+}},
// CHECK: store i32* [[PRIV_T_VAR]], i32** [[ARG2]],
// CHECK: [[PRIV_VEC:%.+]] = getelementptr inbounds [[PRIVATES_MAIN_TY]], [[PRIVATES_MAIN_TY]]* [[PRIVATES]], i32 0, i32 3
// CHECK: [[ARG4:%.+]] = load [2 x i32]**, [2 x i32]*** %{{.+}},
// CHECK: store [2 x i32]* [[PRIV_VEC]], [2 x i32]** [[ARG4]],
// CHECK: [[PRIV_SIVAR:%.+]] = getelementptr inbounds [[PRIVATES_MAIN_TY]], [[PRIVATES_MAIN_TY]]* [[PRIVATES]], i32 0, i32 4
// CHECK: [[ARG5:%.+]] = load i{{[0-9]+}}**, i{{[0-9]+}}*** %{{.+}},
// CHECK: store i{{[0-9]+}}* [[PRIV_SIVAR]], i{{[0-9]+}}** [[ARG5]],
// CHECK: ret void
// CHECK: define internal i32 [[TASK_ENTRY]](i32 %0, [[KMP_TASK_MAIN_TY]]* noalias %1)
// CHECK: [[PRIV_VAR_ADDR:%.+]] = alloca [[S_DOUBLE_TY]]*,
// CHECK: [[PRIV_T_VAR_ADDR:%.+]] = alloca i32*,
// CHECK: [[PRIV_S_ARR_ADDR:%.+]] = alloca [2 x [[S_DOUBLE_TY]]]*,
// CHECK: [[PRIV_VEC_ADDR:%.+]] = alloca [2 x i32]*,
// CHECK: [[PRIV_SIVAR_ADDR:%.+]] = alloca i32*,
// CHECK: store void (i8*, ...)* bitcast (void ([[PRIVATES_MAIN_TY]]*, [[S_DOUBLE_TY]]**, i32**, [2 x [[S_DOUBLE_TY]]]**, [2 x i32]**, i32**)* [[PRIVATES_MAP_FN]] to void (i8*, ...)*), void (i8*, ...)** [[MAP_FN_ADDR:%.+]],
// CHECK: [[MAP_FN:%.+]] = load void (i8*, ...)*, void (i8*, ...)** [[MAP_FN_ADDR]],
// CHECK: call void (i8*, ...) [[MAP_FN]](i8* %{{.+}}, [[S_DOUBLE_TY]]** [[PRIV_VAR_ADDR]], i32** [[PRIV_T_VAR_ADDR]], [2 x [[S_DOUBLE_TY]]]** [[PRIV_S_ARR_ADDR]], [2 x i32]** [[PRIV_VEC_ADDR]], i32** [[PRIV_SIVAR_ADDR]])
// CHECK: [[PRIV_VAR:%.+]] = load [[S_DOUBLE_TY]]*, [[S_DOUBLE_TY]]** [[PRIV_VAR_ADDR]],
// CHECK: [[PRIV_T_VAR:%.+]] = load i32*, i32** [[PRIV_T_VAR_ADDR]],
// CHECK: [[PRIV_S_ARR:%.+]] = load [2 x [[S_DOUBLE_TY]]]*, [2 x [[S_DOUBLE_TY]]]** [[PRIV_S_ARR_ADDR]],
// CHECK: [[PRIV_VEC:%.+]] = load [2 x i32]*, [2 x i32]** [[PRIV_VEC_ADDR]],
// CHECK: [[PRIV_SIVAR:%.+]] = load i32*, i32** [[PRIV_SIVAR_ADDR]],
// Privates actually are used.
// CHECK-DAG: [[PRIV_VAR]]
// CHECK-DAG: [[PRIV_T_VAR]]
// CHECK-DAG: [[PRIV_S_ARR]]
// CHECK-DAG: [[PRIV_VEC]]
// CHECK-DAG: [[PRIV_SIVAR]]
// CHECK: ret
// CHECK: define internal void [[MAIN_DUP]]([[KMP_TASK_MAIN_TY]]* %0, [[KMP_TASK_MAIN_TY]]* %1, i32 %2)
// CHECK: getelementptr inbounds [[KMP_TASK_MAIN_TY]], [[KMP_TASK_MAIN_TY]]* %{{.+}}, i32 0, i32 1
// CHECK: getelementptr inbounds [[PRIVATES_MAIN_TY]], [[PRIVATES_MAIN_TY]]* %{{.+}}, i32 0, i32 0
// CHECK: getelementptr inbounds [2 x [[S_DOUBLE_TY]]], [2 x [[S_DOUBLE_TY]]]* %{{.+}}, i32 0, i32 0
// CHECK: getelementptr [[S_DOUBLE_TY]], [[S_DOUBLE_TY]]* %{{.+}}, i64 2
// CHECK: br i1 %
// CHECK: phi [[S_DOUBLE_TY]]*
// CHECK: call {{.*}} [[S_DOUBLE_TY_COPY_CONSTR]]([[S_DOUBLE_TY]]*
// CHECK: getelementptr [[S_DOUBLE_TY]], [[S_DOUBLE_TY]]* %{{.+}}, i32 1
// CHECK: icmp eq [[S_DOUBLE_TY]]* %
// CHECK: br i1 %
// CHECK: getelementptr inbounds [[PRIVATES_MAIN_TY]], [[PRIVATES_MAIN_TY]]* %{{.+}}, i32 0, i32 1
// CHECK: call {{.*}} [[S_DOUBLE_TY_COPY_CONSTR]]([[S_DOUBLE_TY]]*
// CHECK: ret void
// CHECK: define internal i32 [[DESTRUCTORS]](i32 %0, [[KMP_TASK_MAIN_TY]]* noalias %1)
// CHECK: [[PRIVATES:%.+]] = getelementptr inbounds [[KMP_TASK_MAIN_TY]], [[KMP_TASK_MAIN_TY]]* [[RES_KMP_TASK:%.+]], i{{[0-9]+}} 0, i{{[0-9]+}} 1
// CHECK: [[PRIVATE_S_ARR_REF:%.+]] = getelementptr inbounds [[PRIVATES_MAIN_TY]], [[PRIVATES_MAIN_TY]]* [[PRIVATES]], i{{.+}} 0, i{{.+}} 0
// CHECK: [[PRIVATE_VAR_REF:%.+]] = getelementptr inbounds [[PRIVATES_MAIN_TY]], [[PRIVATES_MAIN_TY]]* [[PRIVATES]], i{{.+}} 0, i{{.+}} 1
// CHECK: call void [[S_DOUBLE_TY_DESTR]]([[S_DOUBLE_TY]]* [[PRIVATE_VAR_REF]])
// CHECK: getelementptr inbounds [2 x [[S_DOUBLE_TY]]], [2 x [[S_DOUBLE_TY]]]* [[PRIVATE_S_ARR_REF]], i{{.+}} 0, i{{.+}} 0
// CHECK: getelementptr inbounds [[S_DOUBLE_TY]], [[S_DOUBLE_TY]]* %{{.+}}, i{{.+}} 2
// CHECK: [[PRIVATE_S_ARR_ELEM_REF:%.+]] = getelementptr inbounds [[S_DOUBLE_TY]], [[S_DOUBLE_TY]]* %{{.+}}, i{{.+}} -1
// CHECK: call void [[S_DOUBLE_TY_DESTR]]([[S_DOUBLE_TY]]* [[PRIVATE_S_ARR_ELEM_REF]])
// CHECK: icmp eq
// CHECK: br i1
// CHECK: ret i32
// CHECK: define {{.*}} i{{[0-9]+}} [[TMAIN_INT]]()
// CHECK: alloca [[S_INT_TY]],
// CHECK: [[TEST:%.+]] = alloca [[S_INT_TY]],
// CHECK: [[T_VAR_ADDR:%.+]] = alloca i32, align 128
// CHECK: [[VEC_ADDR:%.+]] = alloca [2 x i32],
// CHECK: [[S_ARR_ADDR:%.+]] = alloca [2 x [[S_INT_TY]]],
// CHECK: [[VAR_ADDR:%.+]] = alloca [[S_INT_TY]],
// CHECK: [[GTID:%.+]] = call i32 @__kmpc_global_thread_num([[LOC:%.+]])
// CHECK: call {{.*}} [[S_INT_TY_COPY_CONSTR:@.+]]([[S_INT_TY]]* [[TEST]],
// Store original variables in capture struct.
// CHECK: [[VEC_REF:%.+]] = getelementptr inbounds [[CAP_TMAIN_TY]], [[CAP_TMAIN_TY]]* %{{.+}}, i{{[0-9]+}} 0, i{{[0-9]+}} 0
// CHECK: store [2 x i32]* [[VEC_ADDR]], [2 x i32]** [[VEC_REF]],
// CHECK: [[T_VAR_REF:%.+]] = getelementptr inbounds [[CAP_TMAIN_TY]], [[CAP_TMAIN_TY]]* %{{.+}}, i{{[0-9]+}} 0, i{{[0-9]+}} 1
// CHECK: store i32* [[T_VAR_ADDR]], i32** [[T_VAR_REF]],
// CHECK: [[S_ARR_REF:%.+]] = getelementptr inbounds [[CAP_TMAIN_TY]], [[CAP_TMAIN_TY]]* %{{.+}}, i{{[0-9]+}} 0, i{{[0-9]+}} 2
// CHECK: store [2 x [[S_INT_TY]]]* [[S_ARR_ADDR]], [2 x [[S_INT_TY]]]** [[S_ARR_REF]],
// CHECK: [[VAR_REF:%.+]] = getelementptr inbounds [[CAP_TMAIN_TY]], [[CAP_TMAIN_TY]]* %{{.+}}, i{{[0-9]+}} 0, i{{[0-9]+}} 3
// CHECK: store [[S_INT_TY]]* [[VAR_ADDR]], [[S_INT_TY]]** [[VAR_REF]],
// Allocate task.
// Returns struct kmp_task_t {
// [[KMP_TASK_T_TY]] task_data;
// [[KMP_TASK_TMAIN_TY]] privates;
// };
// CHECK: [[RES:%.+]] = call i8* @__kmpc_omp_task_alloc([[LOC]], i32 [[GTID]], i32 9, i64 256, i64 32, i32 (i32, i8*)* bitcast (i32 (i32, [[KMP_TASK_TMAIN_TY]]*)* [[TASK_ENTRY:@[^ ]+]] to i32 (i32, i8*)*))
// CHECK: [[RES_KMP_TASK:%.+]] = bitcast i8* [[RES]] to [[KMP_TASK_TMAIN_TY]]*
// Fill kmp_task_t->shareds by copying from original capture argument.
// CHECK: [[TASK:%.+]] = getelementptr inbounds [[KMP_TASK_TMAIN_TY]], [[KMP_TASK_TMAIN_TY]]* [[RES_KMP_TASK]], i{{[0-9]+}} 0, i{{[0-9]+}} 0
// CHECK: [[SHAREDS_REF_ADDR:%.+]] = getelementptr inbounds [[KMP_TASK_T_TY]], [[KMP_TASK_T_TY]]* [[TASK]], i{{[0-9]+}} 0, i{{[0-9]+}} 0
// CHECK: [[SHAREDS_REF:%.+]] = load i8*, i8** [[SHAREDS_REF_ADDR]],
// CHECK: [[CAPTURES_ADDR:%.+]] = bitcast [[CAP_TMAIN_TY]]* %{{.+}} to i8*
// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 8 [[SHAREDS_REF]], i8* align 8 [[CAPTURES_ADDR]], i64 32, i1 false)
// Initialize kmp_task_t->privates with default values (no init for simple types, default constructors for classes).
// CHECK: [[PRIVATES:%.+]] = getelementptr inbounds [[KMP_TASK_TMAIN_TY]], [[KMP_TASK_TMAIN_TY]]* [[RES_KMP_TASK]], i{{[0-9]+}} 0, i{{[0-9]+}} 2
// CHECK: [[SHAREDS:%.+]] = bitcast i8* [[SHAREDS_REF]] to [[CAP_TMAIN_TY]]*
// t_var;
// CHECK: [[PRIVATE_T_VAR_REF:%.+]] = getelementptr inbounds [[PRIVATES_TMAIN_TY]], [[PRIVATES_TMAIN_TY]]* [[PRIVATES]], i{{.+}} 0, i{{.+}} 0
// CHECK: [[T_VAR_ADDR_REF:%.+]] = getelementptr inbounds [[CAP_TMAIN_TY]], [[CAP_TMAIN_TY]]* [[SHAREDS]], i{{.+}} 0, i{{.+}} 1
// CHECK: [[T_VAR_REF:%.+]] = load i{{.+}}*, i{{.+}}** [[T_VAR_ADDR_REF]],
// CHECK: [[T_VAR:%.+]] = load i{{.+}}, i{{.+}}* [[T_VAR_REF]], align 128
// CHECK: store i32 [[T_VAR]], i32* [[PRIVATE_T_VAR_REF]], align 128
// vec;
// CHECK: [[PRIVATE_VEC_REF:%.+]] = getelementptr inbounds [[PRIVATES_TMAIN_TY]], [[PRIVATES_TMAIN_TY]]* [[PRIVATES]], i{{.+}} 0, i{{.+}} 1
// CHECK: [[VEC_ADDR_REF:%.+]] = getelementptr inbounds [[CAP_TMAIN_TY]], [[CAP_TMAIN_TY]]* [[SHAREDS]], i{{.+}} 0, i{{.+}} 0
// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(
// Constructors for s_arr and var.
// a_arr;
// CHECK: [[PRIVATE_S_ARR_REF:%.+]] = getelementptr inbounds [[PRIVATES_TMAIN_TY]], [[PRIVATES_TMAIN_TY]]* [[PRIVATES]], i{{[0-9]+}} 0, i{{[0-9]+}} 2
// CHECK: [[S_ARR_ADDR_REF:%.+]] = getelementptr inbounds [[CAP_TMAIN_TY]], [[CAP_TMAIN_TY]]* [[SHAREDS]], i{{.+}} 0, i{{.+}} 2
// CHECK: getelementptr inbounds [2 x [[S_INT_TY]]], [2 x [[S_INT_TY]]]* [[PRIVATE_S_ARR_REF]], i{{.+}} 0, i{{.+}} 0
// CHECK: getelementptr [[S_INT_TY]], [[S_INT_TY]]* %{{.+}}, i{{.+}} 2
// CHECK: call void [[S_INT_TY_COPY_CONSTR]]([[S_INT_TY]]* [[S_ARR_CUR:%[^,]+]],
// CHECK: getelementptr [[S_INT_TY]], [[S_INT_TY]]* [[S_ARR_CUR]], i{{.+}} 1
// CHECK: icmp eq
// CHECK: br i1
// var;
// CHECK: [[PRIVATE_VAR_REF:%.+]] = getelementptr inbounds [[PRIVATES_TMAIN_TY]], [[PRIVATES_TMAIN_TY]]* [[PRIVATES]], i{{.+}} 0, i{{.+}} 3
// CHECK: [[VAR_ADDR_REF:%.+]] = getelementptr inbounds [[CAP_TMAIN_TY]], [[CAP_TMAIN_TY]]* [[SHAREDS]], i{{.+}} 0, i{{.+}} 3
// CHECK: call void [[S_INT_TY_COPY_CONSTR]]([[S_INT_TY]]* [[PRIVATE_VAR_REF]],
// Provide pointer to destructor function, which will destroy private variables at the end of the task.
// CHECK: [[DESTRUCTORS_REF:%.+]] = getelementptr inbounds [[KMP_TASK_T_TY]], [[KMP_TASK_T_TY]]* [[TASK]], i{{.+}} 0, i{{.+}} 3
// CHECK: [[DESTRUCTORS_PTR:%.+]] = bitcast %union{{.+}}* [[DESTRUCTORS_REF]] to i32 (i32, i8*)**
// CHECK: store i32 (i32, i8*)* bitcast (i32 (i32, [[KMP_TASK_TMAIN_TY]]*)* [[DESTRUCTORS:@.+]] to i32 (i32, i8*)*), i32 (i32, i8*)** [[DESTRUCTORS_PTR]],
// Start task.
// CHECK: call void @__kmpc_taskloop([[LOC]], i32 [[GTID]], i8* [[RES]], i32 1, i64* %{{.+}}, i64* %{{.+}}, i64 %{{.+}}, i32 1, i32 0, i64 0, i8* bitcast (void ([[KMP_TASK_TMAIN_TY]]*, [[KMP_TASK_TMAIN_TY]]*, i32)* [[TMAIN_DUP:@.+]] to i8*))
// No destructors must be called for private copies of s_arr and var.
// CHECK-NOT: getelementptr inbounds [[PRIVATES_TMAIN_TY]], [[PRIVATES_TMAIN_TY]]* [[PRIVATES]], i{{.+}} 0, i{{.+}} 2
// CHECK-NOT: getelementptr inbounds [[PRIVATES_TMAIN_TY]], [[PRIVATES_TMAIN_TY]]* [[PRIVATES]], i{{.+}} 0, i{{.+}} 3
// CHECK: call void [[S_INT_TY_DESTR:@.+]]([[S_INT_TY]]*
// CHECK-NOT: getelementptr inbounds [[PRIVATES_TMAIN_TY]], [[PRIVATES_TMAIN_TY]]* [[PRIVATES]], i{{.+}} 0, i{{.+}} 2
// CHECK-NOT: getelementptr inbounds [[PRIVATES_TMAIN_TY]], [[PRIVATES_TMAIN_TY]]* [[PRIVATES]], i{{.+}} 0, i{{.+}} 3
// CHECK: ret
//
// CHECK: define internal void [[PRIVATES_MAP_FN:@.+]]([[PRIVATES_TMAIN_TY]]* noalias %0, i32** noalias %1, [2 x i32]** noalias %2, [2 x [[S_INT_TY]]]** noalias %3, [[S_INT_TY]]** noalias %4)
// CHECK: [[PRIVATES:%.+]] = load [[PRIVATES_TMAIN_TY]]*, [[PRIVATES_TMAIN_TY]]**
// CHECK: [[PRIV_T_VAR:%.+]] = getelementptr inbounds [[PRIVATES_TMAIN_TY]], [[PRIVATES_TMAIN_TY]]* [[PRIVATES]], i32 0, i32 0
// CHECK: [[ARG1:%.+]] = load i32**, i32*** %{{.+}},
// CHECK: store i32* [[PRIV_T_VAR]], i32** [[ARG1]],
// CHECK: [[PRIV_VEC:%.+]] = getelementptr inbounds [[PRIVATES_TMAIN_TY]], [[PRIVATES_TMAIN_TY]]* [[PRIVATES]], i32 0, i32 1
// CHECK: [[ARG2:%.+]] = load [2 x i32]**, [2 x i32]*** %{{.+}},
// CHECK: store [2 x i32]* [[PRIV_VEC]], [2 x i32]** [[ARG2]],
// CHECK: [[PRIV_S_VAR:%.+]] = getelementptr inbounds [[PRIVATES_TMAIN_TY]], [[PRIVATES_TMAIN_TY]]* [[PRIVATES]], i32 0, i32 2
// CHECK: [[ARG3:%.+]] = load [2 x [[S_INT_TY]]]**, [2 x [[S_INT_TY]]]*** %{{.+}},
// CHECK: store [2 x [[S_INT_TY]]]* [[PRIV_S_VAR]], [2 x [[S_INT_TY]]]** [[ARG3]],
// CHECK: [[PRIV_VAR:%.+]] = getelementptr inbounds [[PRIVATES_TMAIN_TY]], [[PRIVATES_TMAIN_TY]]* [[PRIVATES]], i32 0, i32 3
// CHECK: [[ARG4:%.+]] = load [[S_INT_TY]]**, [[S_INT_TY]]*** {{.+}},
// CHECK: store [[S_INT_TY]]* [[PRIV_VAR]], [[S_INT_TY]]** [[ARG4]],
// CHECK: ret void
// CHECK: define internal i32 [[TASK_ENTRY]](i32 %0, [[KMP_TASK_TMAIN_TY]]* noalias %1)
// CHECK: alloca i32*,
// CHECK-DAG: [[PRIV_T_VAR_ADDR:%.+]] = alloca i32*,
// CHECK-DAG: [[PRIV_VEC_ADDR:%.+]] = alloca [2 x i32]*,
// CHECK-DAG: [[PRIV_S_ARR_ADDR:%.+]] = alloca [2 x [[S_INT_TY]]]*,
// CHECK-DAG: [[PRIV_VAR_ADDR:%.+]] = alloca [[S_INT_TY]]*,
// CHECK: store void (i8*, ...)* bitcast (void ([[PRIVATES_TMAIN_TY]]*, i32**, [2 x i32]**, [2 x [[S_INT_TY]]]**, [[S_INT_TY]]**)* [[PRIVATES_MAP_FN]] to void (i8*, ...)*), void (i8*, ...)** [[MAP_FN_ADDR:%.+]],
// CHECK: [[MAP_FN:%.+]] = load void (i8*, ...)*, void (i8*, ...)** [[MAP_FN_ADDR]],
// CHECK: call void (i8*, ...) [[MAP_FN]](i8* %{{.+}}, i32** [[PRIV_T_VAR_ADDR]], [2 x i32]** [[PRIV_VEC_ADDR]], [2 x [[S_INT_TY]]]** [[PRIV_S_ARR_ADDR]], [[S_INT_TY]]** [[PRIV_VAR_ADDR]])
// CHECK: [[PRIV_T_VAR:%.+]] = load i32*, i32** [[PRIV_T_VAR_ADDR]],
// CHECK: [[PRIV_VEC:%.+]] = load [2 x i32]*, [2 x i32]** [[PRIV_VEC_ADDR]],
// CHECK: [[PRIV_S_ARR:%.+]] = load [2 x [[S_INT_TY]]]*, [2 x [[S_INT_TY]]]** [[PRIV_S_ARR_ADDR]],
// CHECK: [[PRIV_VAR:%.+]] = load [[S_INT_TY]]*, [[S_INT_TY]]** [[PRIV_VAR_ADDR]],
// Privates actually are used.
// CHECK-DAG: [[PRIV_VAR]]
// CHECK-DAG: [[PRIV_T_VAR]]
// CHECK-DAG: [[PRIV_S_ARR]]
// CHECK-DAG: [[PRIV_VEC]]
// CHECK: ret
// CHECK: define internal void [[TMAIN_DUP]]([[KMP_TASK_TMAIN_TY]]* %0, [[KMP_TASK_TMAIN_TY]]* %1, i32 %2)
// CHECK: getelementptr inbounds [[KMP_TASK_TMAIN_TY]], [[KMP_TASK_TMAIN_TY]]* %{{.+}}, i32 0, i32 2
// CHECK: getelementptr inbounds [[PRIVATES_TMAIN_TY]], [[PRIVATES_TMAIN_TY]]* %{{.+}}, i32 0, i32 2
// CHECK: getelementptr inbounds [2 x [[S_INT_TY]]], [2 x [[S_INT_TY]]]* %{{.+}}, i32 0, i32 0
// CHECK: getelementptr [[S_INT_TY]], [[S_INT_TY]]* %{{.+}}, i64 2
// CHECK: br i1 %
// CHECK: phi [[S_INT_TY]]*
// CHECK: call {{.*}} [[S_INT_TY_COPY_CONSTR]]([[S_INT_TY]]*
// CHECK: getelementptr [[S_INT_TY]], [[S_INT_TY]]* %{{.+}}, i32 1
// CHECK: icmp eq [[S_INT_TY]]* %
// CHECK: br i1 %
// CHECK: getelementptr inbounds [[PRIVATES_TMAIN_TY]], [[PRIVATES_TMAIN_TY]]* %{{.+}}, i32 0, i32 3
// CHECK: call {{.*}} [[S_INT_TY_COPY_CONSTR]]([[S_INT_TY]]*
// CHECK: ret void
// CHECK: define internal i32 [[DESTRUCTORS]](i32 %0, [[KMP_TASK_TMAIN_TY]]* noalias %1)
// CHECK: [[PRIVATES:%.+]] = getelementptr inbounds [[KMP_TASK_TMAIN_TY]], [[KMP_TASK_TMAIN_TY]]* [[RES_KMP_TASK:%.+]], i{{[0-9]+}} 0, i{{[0-9]+}} 2
// CHECK: [[PRIVATE_S_ARR_REF:%.+]] = getelementptr inbounds [[PRIVATES_TMAIN_TY]], [[PRIVATES_TMAIN_TY]]* [[PRIVATES]], i{{.+}} 0, i{{.+}} 2
// CHECK: [[PRIVATE_VAR_REF:%.+]] = getelementptr inbounds [[PRIVATES_TMAIN_TY]], [[PRIVATES_TMAIN_TY]]* [[PRIVATES]], i{{.+}} 0, i{{.+}} 3
// CHECK: call void [[S_INT_TY_DESTR]]([[S_INT_TY]]* [[PRIVATE_VAR_REF]])
// CHECK: getelementptr inbounds [2 x [[S_INT_TY]]], [2 x [[S_INT_TY]]]* [[PRIVATE_S_ARR_REF]], i{{.+}} 0, i{{.+}} 0
// CHECK: getelementptr inbounds [[S_INT_TY]], [[S_INT_TY]]* %{{.+}}, i{{.+}} 2
// CHECK: [[PRIVATE_S_ARR_ELEM_REF:%.+]] = getelementptr inbounds [[S_INT_TY]], [[S_INT_TY]]* %{{.+}}, i{{.+}} -1
// CHECK: call void [[S_INT_TY_DESTR]]([[S_INT_TY]]* [[PRIVATE_S_ARR_ELEM_REF]])
// CHECK: icmp eq
// CHECK: br i1
// CHECK: ret i32
#endif
#else
// ARRAY-LABEL: array_func
struct St {
int a, b;
St() : a(0), b(0) {}
St(const St &) {}
~St() {}
};
void array_func(int n, float a[n], St s[2]) {
// ARRAY: call i8* @__kmpc_omp_task_alloc(
// ARRAY: call void @__kmpc_taskloop(
// ARRAY: store float** %{{.+}}, float*** %{{.+}},
// ARRAY: store %struct.St** %{{.+}}, %struct.St*** %{{.+}},
#pragma omp taskloop firstprivate(a, s)
for (int i = 0; i < 10; ++i)
;
}
#endif
| bsd-2-clause |
sjackman/homebrew-core | Formula/devdash.rb | 1317 | class Devdash < Formula
desc "Highly Configurable Terminal Dashboard for Developers"
homepage "https://thedevdash.com"
url "https://github.com/Phantas0s/devdash/archive/v0.5.0.tar.gz"
sha256 "633a0a599a230a93b7c4eeacdf79a91a2bb672058ef3d5aacce5121167df8d28"
license "Apache-2.0"
bottle do
sha256 cellar: :any_skip_relocation, arm64_monterey: "f4e13f2e58d6e125a578aca41e192b4e655d8daf706e8c1fc154b77c4d884984"
sha256 cellar: :any_skip_relocation, arm64_big_sur: "688199921a304a5ba1c0ac78096d29c86c63076eafd6288085664a32b7e70056"
sha256 cellar: :any_skip_relocation, monterey: "8049a6d438b7a088de9e71cc0356feb1f7576d678b6aa69932b97fdd84c00596"
sha256 cellar: :any_skip_relocation, big_sur: "e71157c4ff045c0e9330fc916b473b38983af56bef7aefd3cdbfd833d9467c18"
sha256 cellar: :any_skip_relocation, catalina: "5589478caf3652ea9a8ba5dd95ead4a927f5a2d4436abb394113e027b0fea805"
sha256 cellar: :any_skip_relocation, mojave: "a247529d915f53e3d43ea23b017373a905b11a51e8f2f18dc19a8eb90c5e9f96"
sha256 cellar: :any_skip_relocation, x86_64_linux: "c8fdb550ff66a46af75552afcc69dd71a93e08097a6e7f94b4e7bc382584c9b0"
end
depends_on "go" => :build
def install
system "go", "build", *std_go_args
end
test do
system bin/"devdash", "-h"
end
end
| bsd-2-clause |
zhengw1985/Update-Installer | external/win32cpp/WCE samples/Simple/SimpleApp.cpp | 146 | #include "SimpleApp.h"
CSimpleApp::CSimpleApp()
{
}
BOOL CSimpleApp::InitInstance()
{
//Create the Window
m_View.Create();
return TRUE;
} | bsd-2-clause |
Pluto-tv/chromium-crosswalk | chrome/android/javatests/src/org/chromium/chrome/browser/infobar/InfoBarTest2.java | 19019 | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.infobar;
import android.graphics.Rect;
import android.graphics.Region;
import android.test.FlakyTest;
import android.test.suitebuilder.annotation.MediumTest;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import org.chromium.base.ThreadUtils;
import org.chromium.base.test.util.Feature;
import org.chromium.chrome.browser.ChromeActivity;
import org.chromium.chrome.browser.preferences.NetworkPredictionOptions;
import org.chromium.chrome.browser.preferences.PrefServiceBridge;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.chrome.test.ChromeActivityTestCaseBase;
import org.chromium.chrome.test.util.InfoBarTestAnimationListener;
import org.chromium.chrome.test.util.InfoBarUtil;
import org.chromium.chrome.test.util.TestHttpServerClient;
import org.chromium.content.browser.test.util.Criteria;
import org.chromium.content.browser.test.util.CriteriaHelper;
import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Tests for InfoBars.
*
* TODO(newt): merge this with InfoBarTest after upstreaming.
*/
public class InfoBarTest2 extends ChromeActivityTestCaseBase<ChromeActivity> {
static class MutableBoolean {
public boolean mValue = false;
}
private InfoBarTestAnimationListener mListener;
public InfoBarTest2() {
super(ChromeActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
// Register for animation notifications
InfoBarContainer container =
getActivity().getActivityTab().getInfoBarContainer();
mListener = new InfoBarTestAnimationListener();
container.setAnimationListener(mListener);
}
// Adds an infobar to the currrent tab. Blocks until the infobar has been added.
protected void addInfoBarToCurrentTab(final InfoBar infoBar) throws InterruptedException {
getInstrumentation().runOnMainSync(new Runnable() {
@Override
public void run() {
Tab tab = getActivity().getActivityTab();
assertTrue("Failed to find tab.", tab != null);
tab.getInfoBarContainer().addInfoBar(infoBar);
}
});
assertTrue("InfoBar not added.", mListener.addInfoBarAnimationFinished());
getInstrumentation().waitForIdleSync();
}
// Removes an infobar from the currrent tab. Blocks until the infobar has been removed.
protected void removeInfoBarFromCurrentTab(final InfoBar infoBar) throws InterruptedException {
getInstrumentation().runOnMainSync(new Runnable() {
@Override
public void run() {
Tab tab = getActivity().getActivityTab();
assertTrue("Failed to find tab.", tab != null);
tab.getInfoBarContainer().removeInfoBar(infoBar);
}
});
assertTrue("InfoBar not removed.", mListener.removeInfoBarAnimationFinished());
getInstrumentation().waitForIdleSync();
}
// Dismisses the passed infobar. Blocks until the bar has been removed.
protected void dismissInfoBar(final InfoBar infoBar) throws InterruptedException {
getInstrumentation().runOnMainSync(new Runnable() {
@Override
public void run() {
infoBar.dismissJavaOnlyInfoBar();
}
});
assertTrue("InfoBar not removed.", mListener.removeInfoBarAnimationFinished());
getInstrumentation().waitForIdleSync();
}
protected ArrayList<Integer> getInfoBarIdsForCurrentTab() {
final ArrayList<Integer> infoBarIds = new ArrayList<Integer>();
getInstrumentation().runOnMainSync(new Runnable() {
@Override
public void run() {
Tab tab = getActivity().getActivityTab();
assertTrue("Failed to find tab.", tab != null);
for (InfoBar infoBar : tab.getInfoBarContainer().getInfoBars()) {
infoBarIds.add(infoBar.getId());
}
}
});
return infoBarIds;
}
/**
* Verifies that infobars added from Java expire or not as expected.
*/
@MediumTest
@Feature({"Browser"})
public void testInfoBarExpiration() throws InterruptedException {
// First add an infobar that expires.
final MutableBoolean dismissed = new MutableBoolean();
MessageInfoBar expiringInfoBar = new MessageInfoBar("Hello!");
expiringInfoBar.setDismissedListener(new InfoBarListeners.Dismiss() {
@Override
public void onInfoBarDismissed(InfoBar infoBar) {
dismissed.mValue = true;
}
});
expiringInfoBar.setExpireOnNavigation(true);
addInfoBarToCurrentTab(expiringInfoBar);
// Verify it's really there.
ArrayList<Integer> infoBarIds = getInfoBarIdsForCurrentTab();
assertEquals(1, infoBarIds.size());
assertEquals(expiringInfoBar.getId(), infoBarIds.get(0).intValue());
// Now navigate, it should expire.
loadUrl(TestHttpServerClient.getUrl("chrome/test/data/android/google.html"));
assertTrue("InfoBar not removed.", mListener.removeInfoBarAnimationFinished());
assertTrue("InfoBar did not expire on navigation.", dismissed.mValue);
infoBarIds = getInfoBarIdsForCurrentTab();
assertTrue(infoBarIds.isEmpty());
// Now test a non-expiring infobar.
MessageInfoBar persistentInfoBar = new MessageInfoBar("Hello!");
persistentInfoBar.setDismissedListener(new InfoBarListeners.Dismiss() {
@Override
public void onInfoBarDismissed(InfoBar infoBar) {
dismissed.mValue = true;
}
});
dismissed.mValue = false;
persistentInfoBar.setExpireOnNavigation(false);
addInfoBarToCurrentTab(persistentInfoBar);
// Navigate, it should still be there.
loadUrl(TestHttpServerClient.getUrl("chrome/test/data/android/google.html"));
assertFalse("InfoBar did expire on navigation.", dismissed.mValue);
infoBarIds = getInfoBarIdsForCurrentTab();
assertEquals(1, infoBarIds.size());
assertEquals(persistentInfoBar.getId(), infoBarIds.get(0).intValue());
// Close the infobar.
dismissInfoBar(persistentInfoBar);
}
// Define function to pass parameter to Runnable to be used in testInfoBarExpirationNoPrerender.
private Runnable setNetworkPredictionOptions(
final NetworkPredictionOptions networkPredictionOptions) {
return new Runnable() {
@Override
public void run() {
PrefServiceBridge.getInstance().setNetworkPredictionOptions(
networkPredictionOptions);
}
};
};
/**
* Same as testInfoBarExpiration but with prerender turned-off.
* The behavior when prerender is on/off is different as in the prerender case the infobars are
* added when we swap tabs.
* @throws InterruptedException
*/
@MediumTest
@Feature({"Browser"})
public void testInfoBarExpirationNoPrerender() throws InterruptedException, ExecutionException {
// Save prediction preference.
NetworkPredictionOptions networkPredictionOption =
ThreadUtils.runOnUiThreadBlocking(new Callable<NetworkPredictionOptions>() {
@Override
public NetworkPredictionOptions call() {
return PrefServiceBridge.getInstance().getNetworkPredictionOptions();
}
});
try {
ThreadUtils.runOnUiThreadBlocking(setNetworkPredictionOptions(
NetworkPredictionOptions.NETWORK_PREDICTION_NEVER));
testInfoBarExpiration();
} finally {
// Make sure we restore prediction preference.
ThreadUtils.runOnUiThreadBlocking(setNetworkPredictionOptions(networkPredictionOption));
}
}
/**
* Tests that adding and then immediately removing an infobar works as expected (and does not
* assert).
*/
@MediumTest
@Feature({"Browser"})
public void testQuickAddOneAndRemove() throws InterruptedException {
final InfoBar infoBar = new MessageInfoBar("Hello");
addInfoBarToCurrentTab(infoBar);
removeInfoBarFromCurrentTab(infoBar);
assertTrue(getInfoBarIdsForCurrentTab().isEmpty());
}
/**
* Tests that adding and then immediately dismissing an infobar works as expected (and does not
* assert).
*/
@MediumTest
@Feature({"Browser"})
public void testQuickAddOneAndDismiss() throws InterruptedException {
final InfoBar infoBar = new MessageInfoBar("Hello");
addInfoBarToCurrentTab(infoBar);
dismissInfoBar(infoBar);
assertTrue(getInfoBarIdsForCurrentTab().isEmpty());
}
/**
* Tests that adding 2 infobars and then immediately removing the last one works as expected.
* This scenario is special as the 2nd infobar does not even get added to the view hierarchy.
*/
@MediumTest
@Feature({"Browser"})
public void testAddTwoAndRemoveOneQuick() throws InterruptedException {
final InfoBar infoBar1 = new MessageInfoBar("One");
final InfoBar infoBar2 = new MessageInfoBar("Two");
getInstrumentation().runOnMainSync(new Runnable() {
@Override
public void run() {
Tab tab = getActivity().getActivityTab();
assertTrue("Failed to find tab.", tab != null);
tab.getInfoBarContainer().addInfoBar(infoBar1);
tab.getInfoBarContainer().addInfoBar(infoBar2);
tab.getInfoBarContainer().removeInfoBar(infoBar2);
}
});
// We should get an infobar added event for the first infobar.
assertTrue("InfoBar not added.", mListener.addInfoBarAnimationFinished());
// But no infobar removed event as the 2nd infobar was removed before it got added.
assertFalse("InfoBar not removed.", mListener.removeInfoBarAnimationFinished());
ArrayList<Integer> infoBarIds = getInfoBarIdsForCurrentTab();
assertEquals(1, infoBarIds.size());
assertEquals(infoBar1.getId(), infoBarIds.get(0).intValue());
}
/**
* Tests that adding 2 infobars and then immediately dismissing the last one works as expected
* This scenario is special as the 2nd infobar does not even get added to the view hierarchy.
*/
@MediumTest
@Feature({"Browser"})
public void testAddTwoAndDismissOneQuick() throws InterruptedException {
final InfoBar infoBar1 = new MessageInfoBar("One");
final InfoBar infoBar2 = new MessageInfoBar("Two");
getInstrumentation().runOnMainSync(new Runnable() {
@Override
public void run() {
Tab tab = getActivity().getActivityTab();
assertTrue("Failed to find tab.", tab != null);
tab.getInfoBarContainer().addInfoBar(infoBar1);
tab.getInfoBarContainer().addInfoBar(infoBar2);
infoBar2.dismissJavaOnlyInfoBar();
}
});
// We should get an infobar added event for the first infobar.
assertTrue("InfoBar not added.", mListener.addInfoBarAnimationFinished());
// But no infobar removed event as the 2nd infobar was removed before it got added.
assertFalse("InfoBar not removed.", mListener.removeInfoBarAnimationFinished());
ArrayList<Integer> infoBarIds = getInfoBarIdsForCurrentTab();
assertEquals(1, infoBarIds.size());
assertEquals(infoBar1.getId(), infoBarIds.get(0).intValue());
}
/**
* Tests that we don't assert when a tab is getting closed while an infobar is being shown and
* had been removed.
*/
@MediumTest
@Feature({"Browser"})
public void testCloseTabOnAdd() throws InterruptedException {
loadUrl(TestHttpServerClient.getUrl(
"chrome/test/data/android/google.html"));
final InfoBar infoBar = new MessageInfoBar("Hello");
addInfoBarToCurrentTab(infoBar);
getInstrumentation().runOnMainSync(new Runnable() {
@Override
public void run() {
Tab tab = getActivity().getActivityTab();
assertTrue("Failed to find tab.", tab != null);
tab.getInfoBarContainer().removeInfoBar(infoBar);
getActivity().getTabModelSelector().closeTab(tab);
}
});
}
/**
* Tests that the x button in the infobar does close the infobar and that the event is not
* propagated to the ContentView.
* @MediumTest
* @Feature({"Browser"})
* Bug: http://crbug.com/172427
*/
@FlakyTest
public void testCloseButton() throws InterruptedException, TimeoutException {
loadUrl(TestHttpServerClient.getUrl(
"chrome/test/data/android/click_listener.html"));
final InfoBar infoBar = new MessageInfoBar("Hello");
getInstrumentation().runOnMainSync(new Runnable() {
@Override
public void run() {
Tab tab = getActivity().getActivityTab();
assertTrue("Failed to find tab.", tab != null);
tab.getInfoBarContainer().addInfoBar(infoBar);
}
});
assertTrue("InfoBar not added", mListener.addInfoBarAnimationFinished());
// Now press the close button.
assertTrue("Close button wasn't found", InfoBarUtil.clickCloseButton(infoBar));
assertTrue("Infobar not removed.", mListener.removeInfoBarAnimationFinished());
// The page should not have received the click.
assertTrue("The page recieved the click.",
!Boolean.parseBoolean(runJavaScriptCodeInCurrentTab("wasClicked")));
}
/**
* Tests that adding and removing correctly manages the transparent region, which allows for
* optimizations in SurfaceFlinger (less overlays).
*/
@MediumTest
@Feature({"Browser"})
public void testAddAndDismissSurfaceFlingerOverlays() throws InterruptedException {
final ViewGroup decorView = (ViewGroup) getActivity().getWindow().getDecorView();
final InfoBarContainer infoBarContainer =
getActivity().getActivityTab().getInfoBarContainer();
// Detect layouts. Note this doesn't actually need to be atomic (just final).
final AtomicInteger layoutCount = new AtomicInteger();
getInstrumentation().runOnMainSync(new Runnable() {
@Override
public void run() {
decorView.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
layoutCount.incrementAndGet();
}
});
}
});
// First add an infobar.
final InfoBar infoBar = new MessageInfoBar("Hello");
addInfoBarToCurrentTab(infoBar);
// A layout must occur to recalculate the transparent region.
boolean layoutOccured = CriteriaHelper.pollForUIThreadCriteria(
new Criteria() {
@Override
public boolean isSatisfied() {
return layoutCount.get() > 0;
}
});
assertTrue(layoutOccured);
final Rect fullDisplayFrame = new Rect();
final Rect fullDisplayFrameMinusContainer = new Rect();
final Rect containerDisplayFrame = new Rect();
getInstrumentation().runOnMainSync(new Runnable() {
@Override
public void run() {
decorView.getWindowVisibleDisplayFrame(fullDisplayFrame);
decorView.getWindowVisibleDisplayFrame(fullDisplayFrameMinusContainer);
fullDisplayFrameMinusContainer.bottom -= infoBarContainer.getHeight();
int windowLocation[] = new int[2];
infoBarContainer.getLocationInWindow(windowLocation);
containerDisplayFrame.set(
windowLocation[0],
windowLocation[1],
windowLocation[0] + infoBarContainer.getWidth(),
windowLocation[1] + infoBarContainer.getHeight());
// The InfoBarContainer subtracts itself from the transparent region.
Region transparentRegion = new Region(fullDisplayFrame);
infoBarContainer.gatherTransparentRegion(transparentRegion);
assertEquals(transparentRegion.getBounds(), fullDisplayFrameMinusContainer);
}
});
// Now remove the infobar.
layoutCount.set(0);
dismissInfoBar(infoBar);
// A layout must occur to recalculate the transparent region.
layoutOccured = CriteriaHelper.pollForUIThreadCriteria(
new Criteria() {
@Override
public boolean isSatisfied() {
return layoutCount.get() > 0;
}
});
assertTrue(layoutOccured);
getInstrumentation().runOnMainSync(new Runnable() {
@Override
public void run() {
// The InfoBarContainer should no longer be subtracted from the transparent region.
// We really want assertTrue(transparentRegion.contains(containerDisplayFrame)),
// but region doesn't have 'contains(Rect)', so we invert the test. So, the old
// container rect can't touch the bounding rect of the non-transparent region).
Region transparentRegion = new Region();
decorView.gatherTransparentRegion(transparentRegion);
Region opaqueRegion = new Region(fullDisplayFrame);
opaqueRegion.op(transparentRegion, Region.Op.DIFFERENCE);
assertFalse(opaqueRegion.getBounds().intersect(containerDisplayFrame));
}
});
// Additional manual test that this is working:
// - adb shell dumpsys SurfaceFlinger
// - Observe that Clank's overlay size changes (or disappears if URLbar is also gone).
}
@Override
public void startMainActivity() throws InterruptedException {
startMainActivityOnBlankPage();
}
}
| bsd-3-clause |
manikkang/soligem | core/app/models/spree/stock/splitter/shipping_category.rb | 848 | module Spree
module Stock
module Splitter
class ShippingCategory < Spree::Stock::Splitter::Base
def split(packages)
split_packages = []
packages.each do |package|
split_packages += split_by_category(package)
end
return_next split_packages
end
private
def split_by_category(package)
categories = Hash.new { |hash, key| hash[key] = [] }
package.contents.each do |item|
categories[item.variant.shipping_category_id] << item
end
hash_to_packages(categories)
end
def hash_to_packages(categories)
packages = []
categories.each do |_id, contents|
packages << build_package(contents)
end
packages
end
end
end
end
end
| bsd-3-clause |
nwjs/chromium.src | chrome/browser/notifications/popups_only_ui_controller.cc | 2041 | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/notifications/popups_only_ui_controller.h"
#include "ui/message_center/message_center.h"
#include "ui/message_center/views/desktop_message_popup_collection.h"
PopupsOnlyUiController::PopupsOnlyUiController()
: message_center_(message_center::MessageCenter::Get()) {
message_center_->AddObserver(this);
message_center_->SetHasMessageCenterView(false);
// Initialize collection after calling message_center_->AddObserver to ensure
// the correct order of observers. (PopupsOnlyUiController has to be called
// before MessagePopupCollection, see crbug.com/901350)
popup_collection_ =
std::make_unique<message_center::DesktopMessagePopupCollection>();
}
PopupsOnlyUiController::~PopupsOnlyUiController() {
message_center_->RemoveObserver(this);
}
void PopupsOnlyUiController::OnNotificationAdded(
const std::string& notification_id) {
ShowOrHidePopupBubbles();
}
void PopupsOnlyUiController::OnNotificationRemoved(
const std::string& notification_id,
bool by_user) {
ShowOrHidePopupBubbles();
}
void PopupsOnlyUiController::OnNotificationUpdated(
const std::string& notification_id) {
ShowOrHidePopupBubbles();
}
void PopupsOnlyUiController::OnNotificationClicked(
const std::string& notification_id,
const absl::optional<int>& button_index,
const absl::optional<std::u16string>& reply) {
if (popups_visible_)
ShowOrHidePopupBubbles();
}
void PopupsOnlyUiController::OnBlockingStateChanged(
message_center::NotificationBlocker* blocker) {
ShowOrHidePopupBubbles();
}
void PopupsOnlyUiController::ShowOrHidePopupBubbles() {
if (popups_visible_ && !message_center_->HasPopupNotifications()) {
popups_visible_ = false;
} else if (!popups_visible_ && message_center_->HasPopupNotifications()) {
popup_collection_->StartObserving();
popups_visible_ = true;
}
}
| bsd-3-clause |
yang1fan2/nematus | mosesdecoder-master/moses/WordLattice.cpp | 8744 | #include <map>
#include "StaticData.h"
#include "WordLattice.h"
#include "PCNTools.h"
#include "Util.h"
#include "FloydWarshall.h"
#include "TranslationOptionCollectionLattice.h"
#include "TranslationOptionCollectionConfusionNet.h"
#include "moses/FF/InputFeature.h"
#include "moses/TranslationTask.h"
namespace Moses
{
WordLattice::WordLattice(AllOptions::ptr const& opts) : ConfusionNet(opts)
{
UTIL_THROW_IF2(InputFeature::InstancePtr() == NULL,
"Input feature must be specified");
}
size_t WordLattice::GetColumnIncrement(size_t i, size_t j) const
{
return next_nodes[i][j];
}
void WordLattice::Print(std::ostream& out) const
{
out<<"word lattice: "<<data.size()<<"\n";
for(size_t i=0; i<data.size(); ++i) {
out<<i<<" -- ";
for(size_t j=0; j<data[i].size(); ++j) {
out<<"("<<data[i][j].first.ToString()<<", ";
// dense
std::vector<float>::const_iterator iterDense;
for(iterDense = data[i][j].second.denseScores.begin(); iterDense < data[i][j].second.denseScores.end(); ++iterDense) {
out<<", "<<*iterDense;
}
// sparse
std::map<StringPiece, float>::const_iterator iterSparse;
for(iterSparse = data[i][j].second.sparseScores.begin(); iterSparse != data[i][j].second.sparseScores.end(); ++iterSparse) {
out << ", " << iterSparse->first << "=" << iterSparse->second;
}
out << GetColumnIncrement(i,j) << ") ";
}
out<<"\n";
}
out<<"\n\n";
}
int
WordLattice::
InitializeFromPCNDataType(const PCN::CN& cn, const std::string& debug_line)
{
const std::vector<FactorType>& factorOrder = m_options->input.factor_order;
size_t const maxPhraseLength = m_options->search.max_phrase_length;
const InputFeature *inputFeature = InputFeature::InstancePtr();
size_t numInputScores = inputFeature->GetNumInputScores();
size_t numRealWordCount = inputFeature->GetNumRealWordsInInput();
bool addRealWordCount = (numRealWordCount > 0);
//when we have one more weight than params, we add a word count feature
data.resize(cn.size());
next_nodes.resize(cn.size());
for(size_t i=0; i<cn.size(); ++i) {
const PCN::CNCol& col = cn[i];
if (col.empty()) return false;
data[i].resize(col.size());
next_nodes[i].resize(col.size());
for (size_t j=0; j<col.size(); ++j) {
const PCN::CNAlt& alt = col[j];
//check for correct number of link parameters
if (alt.m_denseFeatures.size() != numInputScores) {
TRACE_ERR("ERROR: need " << numInputScores
<< " link parameters, found "
<< alt.m_denseFeatures.size()
<< " while reading column " << i
<< " from " << debug_line << "\n");
return false;
}
//check each element for bounds
std::vector<float>::const_iterator probsIterator;
data[i][j].second = std::vector<float>(0);
for(probsIterator = alt.m_denseFeatures.begin();
probsIterator < alt.m_denseFeatures.end();
probsIterator++) {
IFVERBOSE(1) {
if (*probsIterator < 0.0f) {
TRACE_ERR("WARN: neg probability: " << *probsIterator << "\n");
//*probsIterator = 0.0f;
}
if (*probsIterator > 1.0f) {
TRACE_ERR("WARN: probability > 1: " << *probsIterator << "\n");
//*probsIterator = 1.0f;
}
}
float score = std::max(static_cast<float>(log(*probsIterator)), LOWEST_SCORE);
ScorePair &scorePair = data[i][j].second;
scorePair.denseScores.push_back(score);
}
//store 'real' word count in last feature if we have one more weight than we do arc scores and not epsilon
if (addRealWordCount) {
//only add count if not epsilon
float value = (alt.m_word=="" || alt.m_word==EPSILON) ? 0.0f : -1.0f;
data[i][j].second.denseScores.push_back(value);
}
Word& w = data[i][j].first;
w.CreateFromString(Input,factorOrder,StringPiece(alt.m_word),false);
// String2Word(alt.m_word, data[i][j]. first, factorOrder);
next_nodes[i][j] = alt.m_next;
if(next_nodes[i][j] > maxPhraseLength) {
TRACE_ERR("ERROR: Jump length " << next_nodes[i][j] << " in word lattice exceeds maximum phrase length " << maxPhraseLength << ".\n");
TRACE_ERR("ERROR: Increase max-phrase-length to process this lattice.\n");
return false;
}
}
}
if (!cn.empty()) {
std::vector<std::vector<bool> > edges(0);
this->GetAsEdgeMatrix(edges);
floyd_warshall(edges,distances);
IFVERBOSE(2) {
TRACE_ERR("Shortest paths:\n");
for (size_t i=0; i<edges.size(); ++i) {
for (size_t j=0; j<edges.size(); ++j) {
int d = distances[i][j];
if (d > 99999) {
d=-1;
}
TRACE_ERR("\t" << d);
}
TRACE_ERR("\n");
}
}
}
return !cn.empty();
}
int
WordLattice::
Read(std::istream& in)
{
Clear();
std::string line;
if(!getline(in,line)) return 0;
std::map<std::string, std::string> meta=ProcessAndStripSGML(line);
if (meta.find("id") != meta.end()) {
this->SetTranslationId(atol(meta["id"].c_str()));
}
PCN::CN cn = PCN::parsePCN(line);
return InitializeFromPCNDataType(cn, line);
}
void WordLattice::GetAsEdgeMatrix(std::vector<std::vector<bool> >& edges) const
{
edges.resize(data.size()+1,std::vector<bool>(data.size()+1, false));
for (size_t i=0; i<data.size(); ++i) {
for (size_t j=0; j<data[i].size(); ++j) {
edges[i][i+next_nodes[i][j]] = true;
}
}
}
int WordLattice::ComputeDistortionDistance(const Range& prev, const Range& current) const
{
int result;
if (prev.GetStartPos() == NOT_FOUND && current.GetStartPos() == 0) {
result = 0;
VERBOSE(4, "Word lattice distortion: monotonic initial step\n");
} else if (prev.GetEndPos()+1 == current.GetStartPos()) {
result = 0;
VERBOSE(4, "Word lattice distortion: monotonic step from " << prev.GetEndPos() << " to " << current.GetStartPos() << "\n");
} else if (prev.GetStartPos() == NOT_FOUND) {
result = distances[0][current.GetStartPos()];
VERBOSE(4, "Word lattice distortion: initial step from 0 to " << current.GetStartPos() << " of length " << result << "\n");
if (result < 0 || result > 99999) {
TRACE_ERR("prev: " << prev << "\ncurrent: " << current << "\n");
TRACE_ERR("A: got a weird distance from 0 to " << (current.GetStartPos()+1) << " of " << result << "\n");
}
} else if (prev.GetEndPos() > current.GetStartPos()) {
result = distances[current.GetStartPos()][prev.GetEndPos() + 1];
VERBOSE(4, "Word lattice distortion: backward step from " << (prev.GetEndPos()+1) << " to " << current.GetStartPos() << " of length " << result << "\n");
if (result < 0 || result > 99999) {
TRACE_ERR("prev: " << prev << "\ncurrent: " << current << "\n");
TRACE_ERR("B: got a weird distance from "<< current.GetStartPos() << " to " << prev.GetEndPos()+1 << " of " << result << "\n");
}
} else {
result = distances[prev.GetEndPos() + 1][current.GetStartPos()];
VERBOSE(4, "Word lattice distortion: forward step from " << (prev.GetEndPos()+1) << " to " << current.GetStartPos() << " of length " << result << "\n");
if (result < 0 || result > 99999) {
TRACE_ERR("prev: " << prev << "\ncurrent: " << current << "\n");
TRACE_ERR("C: got a weird distance from "<< prev.GetEndPos()+1 << " to " << current.GetStartPos() << " of " << result << "\n");
}
}
return result;
}
bool WordLattice::CanIGetFromAToB(size_t start, size_t end) const
{
// std::cerr << "CanIgetFromAToB(" << start << "," << end << ")=" << distances[start][end] << std::endl;
return distances[start][end] < 100000;
}
TranslationOptionCollection*
WordLattice::
CreateTranslationOptionCollection(ttasksptr const& ttask) const
{
TranslationOptionCollection *rv = NULL;
if (StaticData::Instance().GetUseLegacyPT()) {
rv = new TranslationOptionCollectionConfusionNet(ttask, *this);
} else {
rv = new TranslationOptionCollectionLattice(ttask, *this);
}
assert(rv);
return rv;
}
std::ostream& operator<<(std::ostream &out, const WordLattice &obj)
{
out << "next_nodes=";
for (size_t i = 0; i < obj.next_nodes.size(); ++i) {
out << i << ":";
const std::vector<size_t> &inner = obj.next_nodes[i];
for (size_t j = 0; j < inner.size(); ++j) {
out << inner[j] << " ";
}
}
out << "distances=";
for (size_t i = 0; i < obj.distances.size(); ++i) {
out << i << ":";
const std::vector<int> &inner = obj.distances[i];
for (size_t j = 0; j < inner.size(); ++j) {
out << inner[j] << " ";
}
}
return out;
}
} // namespace
| bsd-3-clause |
endlessm/chromium-browser | third_party/swiftshader/third_party/llvm-7.0/llvm/lib/Target/Nios2/Nios2MachineFunction.cpp | 436 | //===-- Nios2MachineFunctionInfo.cpp - Private data used for Nios2 --------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Nios2MachineFunction.h"
using namespace llvm;
void Nios2FunctionInfo::anchor() {}
| bsd-3-clause |
chromium/chromium | content/browser/web_package/web_bundle_reader.cc | 14986 | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/web_package/web_bundle_reader.h"
#include <limits>
#include "base/check_op.h"
#include "base/numerics/safe_math.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "content/browser/web_package/web_bundle_blob_data_source.h"
#include "content/browser/web_package/web_bundle_source.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/system/data_pipe_producer.h"
#include "mojo/public/cpp/system/file_data_source.h"
#include "mojo/public/cpp/system/platform_handle.h"
#include "net/base/url_util.h"
#include "services/network/public/cpp/resource_request.h"
#include "third_party/blink/public/common/web_package/web_package_request_matcher.h"
namespace content {
WebBundleReader::SharedFile::SharedFile(
std::unique_ptr<WebBundleSource> source) {
base::ThreadPool::PostTaskAndReplyWithResult(
FROM_HERE, {base::MayBlock()},
base::BindOnce(
[](std::unique_ptr<WebBundleSource> source)
-> std::unique_ptr<base::File> { return source->OpenFile(); },
std::move(source)),
base::BindOnce(&SharedFile::SetFile, base::RetainedRef(this)));
}
void WebBundleReader::SharedFile::DuplicateFile(
base::OnceCallback<void(base::File)> callback) {
// Basically this interface expects this method is called at most once. Have
// a DCHECK for the case that does not work for a clear reason, just in case.
// The call site also have another DCHECK for external callers not to cause
// such problematic cases.
DCHECK(duplicate_callback_.is_null());
duplicate_callback_ = std::move(callback);
if (file_)
SetFile(std::move(file_));
}
base::File* WebBundleReader::SharedFile::operator->() {
DCHECK(file_);
return file_.get();
}
WebBundleReader::SharedFile::~SharedFile() {
// Move the last reference to |file_| that leads an internal blocking call
// that is not permitted here.
base::ThreadPool::PostTask(
FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()},
base::BindOnce([](std::unique_ptr<base::File> file) {},
std::move(file_)));
}
void WebBundleReader::SharedFile::SetFile(std::unique_ptr<base::File> file) {
file_ = std::move(file);
if (duplicate_callback_.is_null())
return;
base::ThreadPool::PostTaskAndReplyWithResult(
FROM_HERE, {base::MayBlock()},
base::BindOnce(
[](base::File* file) -> base::File { return file->Duplicate(); },
file_.get()),
std::move(duplicate_callback_));
}
class WebBundleReader::SharedFileDataSource final
: public mojo::DataPipeProducer::DataSource {
public:
SharedFileDataSource(scoped_refptr<WebBundleReader::SharedFile> file,
uint64_t offset,
uint64_t length)
: file_(std::move(file)), offset_(offset), length_(length) {
error_ = mojo::FileDataSource::ConvertFileErrorToMojoResult(
(*file_)->error_details());
// base::File::Read takes int64_t as an offset. So, offset + length should
// not overflow in int64_t.
uint64_t max_offset;
if (!base::CheckAdd(offset, length).AssignIfValid(&max_offset) ||
(std::numeric_limits<int64_t>::max() < max_offset)) {
error_ = MOJO_RESULT_INVALID_ARGUMENT;
}
}
SharedFileDataSource(const SharedFileDataSource&) = delete;
SharedFileDataSource& operator=(const SharedFileDataSource&) = delete;
private:
// Implements mojo::DataPipeProducer::DataSource. Following methods are called
// on a blockable sequenced task runner.
uint64_t GetLength() const override { return length_; }
ReadResult Read(uint64_t offset, base::span<char> buffer) override {
ReadResult result;
result.result = error_;
if (length_ < offset)
result.result = MOJO_RESULT_INVALID_ARGUMENT;
if (result.result != MOJO_RESULT_OK)
return result;
uint64_t readable_size = length_ - offset;
uint64_t writable_size = buffer.size();
uint64_t copyable_size =
std::min(std::min(readable_size, writable_size),
static_cast<uint64_t>(std::numeric_limits<int>::max()));
int bytes_read =
(*file_)->Read(offset_ + offset, buffer.data(), copyable_size);
if (bytes_read < 0) {
result.result = mojo::FileDataSource::ConvertFileErrorToMojoResult(
(*file_)->GetLastFileError());
} else {
result.bytes_read = bytes_read;
}
return result;
}
scoped_refptr<WebBundleReader::SharedFile> file_;
MojoResult error_;
const uint64_t offset_;
const uint64_t length_;
};
WebBundleReader::WebBundleReader(std::unique_ptr<WebBundleSource> source)
: source_(std::move(source)),
parser_(std::make_unique<data_decoder::SafeWebBundleParser>()),
file_(base::MakeRefCounted<SharedFile>(source_->Clone())) {
DCHECK(source_->is_trusted_file() || source_->is_file());
}
WebBundleReader::WebBundleReader(
std::unique_ptr<WebBundleSource> source,
int64_t content_length,
mojo::ScopedDataPipeConsumerHandle outer_response_body,
network::mojom::URLLoaderClientEndpointsPtr endpoints,
BrowserContext::BlobContextGetter blob_context_getter)
: source_(std::move(source)),
parser_(std::make_unique<data_decoder::SafeWebBundleParser>()) {
DCHECK(source_->is_network());
mojo::PendingRemote<web_package::mojom::BundleDataSource> pending_remote;
blob_data_source_ = std::make_unique<WebBundleBlobDataSource>(
content_length, std::move(outer_response_body), std::move(endpoints),
std::move(blob_context_getter));
blob_data_source_->AddReceiver(
pending_remote.InitWithNewPipeAndPassReceiver());
parser_->OpenDataSource(std::move(pending_remote));
}
WebBundleReader::~WebBundleReader() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
}
void WebBundleReader::ReadMetadata(MetadataCallback callback) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK_EQ(state_, State::kInitial);
if (!blob_data_source_) {
DCHECK(source_->is_trusted_file() || source_->is_file());
file_->DuplicateFile(base::BindOnce(&WebBundleReader::ReadMetadataInternal,
this, std::move(callback)));
return;
}
DCHECK(source_->is_network());
parser_->ParseMetadata(base::BindOnce(&WebBundleReader::OnMetadataParsed,
base::Unretained(this),
std::move(callback)));
}
void WebBundleReader::ReadResponse(
const network::ResourceRequest& resource_request,
const std::string& accept_langs,
ResponseCallback callback) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK_NE(state_, State::kInitial);
auto it = entries_.find(net::SimplifyUrlForRequest(resource_request.url));
if (it == entries_.end() || it->second->response_locations.empty()) {
base::ThreadPool::PostTask(
FROM_HERE,
base::BindOnce(
std::move(callback), nullptr,
web_package::mojom::BundleResponseParseError::New(
web_package::mojom::BundleParseErrorType::kParserInternalError,
"Not found in Web Bundle file.")));
return;
}
const web_package::mojom::BundleIndexValuePtr& entry = it->second;
size_t response_index = 0;
if (!entry->variants_value.empty()) {
// Select the best variant for the request.
blink::WebPackageRequestMatcher matcher(resource_request.headers,
accept_langs);
auto found = matcher.FindBestMatchingIndex(entry->variants_value);
if (!found || *found >= entry->response_locations.size()) {
base::ThreadPool::PostTask(
FROM_HERE,
base::BindOnce(
std::move(callback), nullptr,
web_package::mojom::BundleResponseParseError::New(
web_package::mojom::BundleParseErrorType::
kParserInternalError,
"Cannot find a response that matches request headers.")));
return;
}
response_index = *found;
}
auto response_location = entry->response_locations[response_index].Clone();
if (state_ == State::kDisconnected) {
// Try reconnecting, if not attempted yet.
if (pending_read_responses_.empty())
Reconnect();
pending_read_responses_.emplace_back(std::move(response_location),
std::move(callback));
return;
}
ReadResponseInternal(std::move(response_location), std::move(callback));
}
void WebBundleReader::ReadResponseInternal(
web_package::mojom::BundleResponseLocationPtr location,
ResponseCallback callback) {
parser_->ParseResponse(
location->offset, location->length,
base::BindOnce(&WebBundleReader::OnResponseParsed, base::Unretained(this),
std::move(callback)));
}
void WebBundleReader::Reconnect() {
DCHECK(!parser_);
parser_ = std::make_unique<data_decoder::SafeWebBundleParser>();
if (!blob_data_source_) {
DCHECK(source_->is_trusted_file() || source_->is_file());
file_->DuplicateFile(
base::BindOnce(&WebBundleReader::ReconnectForFile, this));
return;
}
DCHECK(source_->is_network());
mojo::PendingRemote<web_package::mojom::BundleDataSource> pending_remote;
blob_data_source_->AddReceiver(
pending_remote.InitWithNewPipeAndPassReceiver());
parser_->OpenDataSource(std::move(pending_remote));
GetUIThreadTaskRunner({})->PostTask(
FROM_HERE, base::BindOnce(&WebBundleReader::DidReconnect, this,
absl::nullopt /* error */));
}
void WebBundleReader::ReconnectForFile(base::File file) {
base::File::Error file_error = parser_->OpenFile(std::move(file));
absl::optional<std::string> error;
if (file_error != base::File::FILE_OK)
error = base::File::ErrorToString(file_error);
GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(&WebBundleReader::DidReconnect, this, std::move(error)));
}
void WebBundleReader::DidReconnect(absl::optional<std::string> error) {
DCHECK_EQ(state_, State::kDisconnected);
DCHECK(parser_);
auto read_tasks = std::move(pending_read_responses_);
if (error) {
for (auto& pair : read_tasks) {
base::ThreadPool::PostTask(
FROM_HERE,
base::BindOnce(std::move(pair.second), nullptr,
web_package::mojom::BundleResponseParseError::New(
web_package::mojom::BundleParseErrorType::
kParserInternalError,
*error)));
}
return;
}
state_ = State::kMetadataReady;
parser_->SetDisconnectCallback(base::BindOnce(
&WebBundleReader::OnParserDisconnected, base::Unretained(this)));
for (auto& pair : read_tasks)
ReadResponseInternal(std::move(pair.first), std::move(pair.second));
}
void WebBundleReader::ReadResponseBody(
web_package::mojom::BundleResponsePtr response,
mojo::ScopedDataPipeProducerHandle producer_handle,
BodyCompletionCallback callback) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK_NE(state_, State::kInitial);
if (!blob_data_source_) {
DCHECK(source_->is_trusted_file() || source_->is_file());
auto data_producer =
std::make_unique<mojo::DataPipeProducer>(std::move(producer_handle));
mojo::DataPipeProducer* raw_producer = data_producer.get();
raw_producer->Write(
std::make_unique<SharedFileDataSource>(file_, response->payload_offset,
response->payload_length),
base::BindOnce(
[](std::unique_ptr<mojo::DataPipeProducer> producer,
BodyCompletionCallback callback, MojoResult result) {
std::move(callback).Run(
result == MOJO_RESULT_OK ? net::OK : net::ERR_UNEXPECTED);
},
std::move(data_producer), std::move(callback)));
return;
}
DCHECK(source_->is_network());
blob_data_source_->ReadToDataPipe(
response->payload_offset, response->payload_length,
std::move(producer_handle), std::move(callback));
}
bool WebBundleReader::HasEntry(const GURL& url) const {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK_NE(state_, State::kInitial);
return entries_.contains(net::SimplifyUrlForRequest(url));
}
const GURL& WebBundleReader::GetPrimaryURL() const {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK_NE(state_, State::kInitial);
return primary_url_;
}
const WebBundleSource& WebBundleReader::source() const {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return *source_;
}
void WebBundleReader::ReadMetadataInternal(MetadataCallback callback,
base::File file) {
DCHECK(source_->is_trusted_file() || source_->is_file());
base::File::Error error = parser_->OpenFile(std::move(file));
if (base::File::FILE_OK != error) {
GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(
std::move(callback),
web_package::mojom::BundleMetadataParseError::New(
web_package::mojom::BundleParseErrorType::kParserInternalError,
GURL() /* fallback_url */, base::File::ErrorToString(error))));
} else {
parser_->ParseMetadata(base::BindOnce(&WebBundleReader::OnMetadataParsed,
base::Unretained(this),
std::move(callback)));
}
}
void WebBundleReader::OnMetadataParsed(
MetadataCallback callback,
web_package::mojom::BundleMetadataPtr metadata,
web_package::mojom::BundleMetadataParseErrorPtr error) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK_EQ(state_, State::kInitial);
state_ = State::kMetadataReady;
parser_->SetDisconnectCallback(base::BindOnce(
&WebBundleReader::OnParserDisconnected, base::Unretained(this)));
if (metadata) {
primary_url_ = metadata->primary_url;
entries_ = std::move(metadata->requests);
}
std::move(callback).Run(std::move(error));
}
void WebBundleReader::OnResponseParsed(
ResponseCallback callback,
web_package::mojom::BundleResponsePtr response,
web_package::mojom::BundleResponseParseErrorPtr error) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK_NE(state_, State::kInitial);
std::move(callback).Run(std::move(response), std::move(error));
}
void WebBundleReader::OnParserDisconnected() {
DCHECK_EQ(state_, State::kMetadataReady);
state_ = State::kDisconnected;
parser_ = nullptr;
// Reconnection will be attempted on next ReadResponse() call.
}
} // namespace content
| bsd-3-clause |
chromium/chromium | chrome/utility/safe_browsing/mac/hfs_unittest.cc | 7086 | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/utility/safe_browsing/mac/hfs.h"
#include <stddef.h>
#include <stdint.h>
#include <memory>
#include "base/cxx17_backports.h"
#include "base/files/file.h"
#include "base/logging.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/utility/safe_browsing/mac/dmg_test_utils.h"
#include "chrome/utility/safe_browsing/mac/read_stream.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace safe_browsing {
namespace dmg {
namespace {
class HFSIteratorTest : public testing::Test {
public:
void GetTargetFiles(bool case_sensitive,
std::set<std::u16string>* files,
std::set<std::u16string>* dirs) {
const char16_t* const kBaseFiles[] = {
u"first/second/third/fourth/fifth/random",
u"first/second/third/fourth/Hello World",
u"first/second/third/symlink-random",
u"first/second/goat-output.txt",
u"first/unicode_name",
u"README.txt",
u".metadata_never_index",
};
const char16_t* const kBaseDirs[] = {
u"first/second/third/fourth/fifth",
u"first/second/third/fourth",
u"first/second/third",
u"first/second",
u"first",
u".Trashes",
};
const std::u16string dmg_name = u"SafeBrowsingDMG/";
for (size_t i = 0; i < base::size(kBaseFiles); ++i)
files->insert(dmg_name + kBaseFiles[i]);
files->insert(dmg_name + u"first/second/" + u"Tĕsẗ 🐐 ");
dirs->insert(dmg_name.substr(0, dmg_name.size() - 1));
for (size_t i = 0; i < base::size(kBaseDirs); ++i)
dirs->insert(dmg_name + kBaseDirs[i]);
if (case_sensitive) {
files->insert(u"SafeBrowsingDMG/first/second/third/fourth/hEllo wOrld");
}
}
void TestTargetFiles(safe_browsing::dmg::HFSIterator* hfs_reader,
bool case_sensitive) {
std::set<std::u16string> files, dirs;
GetTargetFiles(case_sensitive, &files, &dirs);
ASSERT_TRUE(hfs_reader->Open());
while (hfs_reader->Next()) {
std::u16string path = hfs_reader->GetPath();
// Skip over .fseventsd files.
if (path.find(u"SafeBrowsingDMG/.fseventsd") != std::u16string::npos) {
continue;
}
if (hfs_reader->IsDirectory())
EXPECT_TRUE(dirs.erase(path)) << path;
else
EXPECT_TRUE(files.erase(path)) << path;
}
EXPECT_EQ(0u, files.size());
for (const auto& file : files) {
ADD_FAILURE() << "Unexpected missing file " << file;
}
}
};
TEST_F(HFSIteratorTest, HFSPlus) {
base::File file;
ASSERT_NO_FATAL_FAILURE(test::GetTestFile("hfs_plus.img", &file));
FileReadStream stream(file.GetPlatformFile());
HFSIterator hfs_reader(&stream);
TestTargetFiles(&hfs_reader, false);
}
TEST_F(HFSIteratorTest, HFSXCaseSensitive) {
base::File file;
ASSERT_NO_FATAL_FAILURE(test::GetTestFile("hfsx_case_sensitive.img", &file));
FileReadStream stream(file.GetPlatformFile());
HFSIterator hfs_reader(&stream);
TestTargetFiles(&hfs_reader, true);
}
class HFSFileReadTest : public testing::TestWithParam<const char*> {
protected:
void SetUp() override {
ASSERT_NO_FATAL_FAILURE(test::GetTestFile(GetParam(), &hfs_file_));
hfs_stream_ = std::make_unique<FileReadStream>(hfs_file_.GetPlatformFile());
hfs_reader_ = std::make_unique<HFSIterator>(hfs_stream_.get());
ASSERT_TRUE(hfs_reader_->Open());
}
bool GoToFile(const char16_t* name) {
while (hfs_reader_->Next()) {
if (EndsWith(hfs_reader_->GetPath(), name,
base::CompareCase::SENSITIVE)) {
return true;
}
}
return false;
}
HFSIterator* hfs_reader() { return hfs_reader_.get(); }
private:
base::File hfs_file_;
std::unique_ptr<FileReadStream> hfs_stream_;
std::unique_ptr<HFSIterator> hfs_reader_;
};
TEST_P(HFSFileReadTest, ReadReadme) {
ASSERT_TRUE(GoToFile(u"README.txt"));
std::unique_ptr<ReadStream> stream = hfs_reader()->GetReadStream();
ASSERT_TRUE(stream.get());
EXPECT_FALSE(hfs_reader()->IsSymbolicLink());
EXPECT_FALSE(hfs_reader()->IsHardLink());
EXPECT_FALSE(hfs_reader()->IsDecmpfsCompressed());
std::vector<uint8_t> buffer(4, 0);
// Read the first four bytes.
EXPECT_TRUE(stream->ReadExact(&buffer[0], buffer.size()));
const uint8_t expected[] = { 'T', 'h', 'i', 's' };
EXPECT_EQ(0, memcmp(expected, &buffer[0], sizeof(expected)));
buffer.clear();
// Rewind back to the start.
EXPECT_EQ(0, stream->Seek(0, SEEK_SET));
// Read the entire file now.
EXPECT_TRUE(ReadEntireStream(stream.get(), &buffer));
EXPECT_EQ("This is a test HFS+ filesystem generated by "
"chrome/test/data/safe_browsing/dmg/make_hfs.sh.\n",
base::StringPiece(reinterpret_cast<const char*>(&buffer[0]),
buffer.size()));
EXPECT_EQ(92u, buffer.size());
}
TEST_P(HFSFileReadTest, ReadRandom) {
ASSERT_TRUE(GoToFile(u"fifth/random"));
std::unique_ptr<ReadStream> stream = hfs_reader()->GetReadStream();
ASSERT_TRUE(stream.get());
EXPECT_FALSE(hfs_reader()->IsSymbolicLink());
EXPECT_FALSE(hfs_reader()->IsHardLink());
EXPECT_FALSE(hfs_reader()->IsDecmpfsCompressed());
std::vector<uint8_t> buffer;
EXPECT_TRUE(ReadEntireStream(stream.get(), &buffer));
EXPECT_EQ(768u, buffer.size());
}
TEST_P(HFSFileReadTest, Symlink) {
ASSERT_TRUE(GoToFile(u"symlink-random"));
std::unique_ptr<ReadStream> stream = hfs_reader()->GetReadStream();
ASSERT_TRUE(stream.get());
EXPECT_TRUE(hfs_reader()->IsSymbolicLink());
EXPECT_FALSE(hfs_reader()->IsHardLink());
EXPECT_FALSE(hfs_reader()->IsDecmpfsCompressed());
std::vector<uint8_t> buffer;
EXPECT_TRUE(ReadEntireStream(stream.get(), &buffer));
EXPECT_EQ("fourth/fifth/random",
base::StringPiece(reinterpret_cast<const char*>(&buffer[0]),
buffer.size()));
}
TEST_P(HFSFileReadTest, HardLink) {
ASSERT_TRUE(GoToFile(u"unicode_name"));
EXPECT_FALSE(hfs_reader()->IsSymbolicLink());
EXPECT_TRUE(hfs_reader()->IsHardLink());
EXPECT_FALSE(hfs_reader()->IsDecmpfsCompressed());
}
TEST_P(HFSFileReadTest, DecmpfsFile) {
ASSERT_TRUE(GoToFile(u"first/second/goat-output.txt"));
std::unique_ptr<ReadStream> stream = hfs_reader()->GetReadStream();
ASSERT_TRUE(stream.get());
EXPECT_FALSE(hfs_reader()->IsSymbolicLink());
EXPECT_FALSE(hfs_reader()->IsHardLink());
EXPECT_TRUE(hfs_reader()->IsDecmpfsCompressed());
std::vector<uint8_t> buffer;
EXPECT_TRUE(ReadEntireStream(stream.get(), &buffer));
EXPECT_EQ(0u, buffer.size());
}
INSTANTIATE_TEST_SUITE_P(HFSIteratorTest,
HFSFileReadTest,
testing::Values("hfs_plus.img",
"hfsx_case_sensitive.img"));
} // namespace
} // namespace dmg
} // namespace safe_browsing
| bsd-3-clause |
lecaoquochung/ddnb.django | django/utils/formats.py | 8251 | from __future__ import absolute_import # Avoid importing `importlib` from this package.
import decimal
import datetime
from importlib import import_module
import unicodedata
from django.conf import settings
from django.utils import dateformat, numberformat, datetime_safe
from django.utils.encoding import force_str
from django.utils.functional import lazy
from django.utils.safestring import mark_safe
from django.utils import six
from django.utils.translation import get_language, to_locale, check_for_language
# format_cache is a mapping from (format_type, lang) to the format string.
# By using the cache, it is possible to avoid running get_format_modules
# repeatedly.
_format_cache = {}
_format_modules_cache = {}
ISO_INPUT_FORMATS = {
'DATE_INPUT_FORMATS': ('%Y-%m-%d',),
'TIME_INPUT_FORMATS': ('%H:%M:%S', '%H:%M:%S.%f', '%H:%M'),
'DATETIME_INPUT_FORMATS': (
'%Y-%m-%d %H:%M:%S',
'%Y-%m-%d %H:%M:%S.%f',
'%Y-%m-%d %H:%M',
'%Y-%m-%d'
),
}
def reset_format_cache():
"""Clear any cached formats.
This method is provided primarily for testing purposes,
so that the effects of cached formats can be removed.
"""
global _format_cache, _format_modules_cache
_format_cache = {}
_format_modules_cache = {}
def iter_format_modules(lang, format_module_path=None):
"""
Does the heavy lifting of finding format modules.
"""
if not check_for_language(lang):
return
if format_module_path is None:
format_module_path = settings.FORMAT_MODULE_PATH
format_locations = []
if format_module_path:
if isinstance(format_module_path, six.string_types):
format_module_path = [format_module_path]
for path in format_module_path:
format_locations.append(path + '.%s')
format_locations.append('django.conf.locale.%s')
locale = to_locale(lang)
locales = [locale]
if '_' in locale:
locales.append(locale.split('_')[0])
for location in format_locations:
for loc in locales:
try:
yield import_module('%s.formats' % (location % loc))
except ImportError:
pass
def get_format_modules(lang=None, reverse=False):
"""
Returns a list of the format modules found
"""
if lang is None:
lang = get_language()
modules = _format_modules_cache.setdefault(lang, list(iter_format_modules(lang, settings.FORMAT_MODULE_PATH)))
if reverse:
return list(reversed(modules))
return modules
def get_format(format_type, lang=None, use_l10n=None):
"""
For a specific format type, returns the format for the current
language (locale), defaults to the format in the settings.
format_type is the name of the format, e.g. 'DATE_FORMAT'
If use_l10n is provided and is not None, that will force the value to
be localized (or not), overriding the value of settings.USE_L10N.
"""
format_type = force_str(format_type)
if use_l10n or (use_l10n is None and settings.USE_L10N):
if lang is None:
lang = get_language()
cache_key = (format_type, lang)
try:
cached = _format_cache[cache_key]
if cached is not None:
return cached
else:
# Return the general setting by default
return getattr(settings, format_type)
except KeyError:
for module in get_format_modules(lang):
try:
val = getattr(module, format_type)
for iso_input in ISO_INPUT_FORMATS.get(format_type, ()):
if iso_input not in val:
if isinstance(val, tuple):
val = list(val)
val.append(iso_input)
_format_cache[cache_key] = val
return val
except AttributeError:
pass
_format_cache[cache_key] = None
return getattr(settings, format_type)
get_format_lazy = lazy(get_format, six.text_type, list, tuple)
def date_format(value, format=None, use_l10n=None):
"""
Formats a datetime.date or datetime.datetime object using a
localizable format
If use_l10n is provided and is not None, that will force the value to
be localized (or not), overriding the value of settings.USE_L10N.
"""
return dateformat.format(value, get_format(format or 'DATE_FORMAT', use_l10n=use_l10n))
def time_format(value, format=None, use_l10n=None):
"""
Formats a datetime.time object using a localizable format
If use_l10n is provided and is not None, that will force the value to
be localized (or not), overriding the value of settings.USE_L10N.
"""
return dateformat.time_format(value, get_format(format or 'TIME_FORMAT', use_l10n=use_l10n))
def number_format(value, decimal_pos=None, use_l10n=None, force_grouping=False):
"""
Formats a numeric value using localization settings
If use_l10n is provided and is not None, that will force the value to
be localized (or not), overriding the value of settings.USE_L10N.
"""
if use_l10n or (use_l10n is None and settings.USE_L10N):
lang = get_language()
else:
lang = None
return numberformat.format(
value,
get_format('DECIMAL_SEPARATOR', lang, use_l10n=use_l10n),
decimal_pos,
get_format('NUMBER_GROUPING', lang, use_l10n=use_l10n),
get_format('THOUSAND_SEPARATOR', lang, use_l10n=use_l10n),
force_grouping=force_grouping
)
def localize(value, use_l10n=None):
"""
Checks if value is a localizable type (date, number...) and returns it
formatted as a string using current locale format.
If use_l10n is provided and is not None, that will force the value to
be localized (or not), overriding the value of settings.USE_L10N.
"""
if isinstance(value, bool):
return mark_safe(six.text_type(value))
elif isinstance(value, (decimal.Decimal, float) + six.integer_types):
return number_format(value, use_l10n=use_l10n)
elif isinstance(value, datetime.datetime):
return date_format(value, 'DATETIME_FORMAT', use_l10n=use_l10n)
elif isinstance(value, datetime.date):
return date_format(value, use_l10n=use_l10n)
elif isinstance(value, datetime.time):
return time_format(value, 'TIME_FORMAT', use_l10n=use_l10n)
else:
return value
def localize_input(value, default=None):
"""
Checks if an input value is a localizable type and returns it
formatted with the appropriate formatting string of the current locale.
"""
if isinstance(value, (decimal.Decimal, float) + six.integer_types):
return number_format(value)
elif isinstance(value, datetime.datetime):
value = datetime_safe.new_datetime(value)
format = force_str(default or get_format('DATETIME_INPUT_FORMATS')[0])
return value.strftime(format)
elif isinstance(value, datetime.date):
value = datetime_safe.new_date(value)
format = force_str(default or get_format('DATE_INPUT_FORMATS')[0])
return value.strftime(format)
elif isinstance(value, datetime.time):
format = force_str(default or get_format('TIME_INPUT_FORMATS')[0])
return value.strftime(format)
return value
def sanitize_separators(value):
"""
Sanitizes a value according to the current decimal and
thousand separator setting. Used with form field input.
"""
if settings.USE_L10N and isinstance(value, six.string_types):
parts = []
decimal_separator = get_format('DECIMAL_SEPARATOR')
if decimal_separator in value:
value, decimals = value.split(decimal_separator, 1)
parts.append(decimals)
if settings.USE_THOUSAND_SEPARATOR:
thousand_sep = get_format('THOUSAND_SEPARATOR')
for replacement in set([
thousand_sep, unicodedata.normalize('NFKD', thousand_sep)]):
value = value.replace(replacement, '')
parts.append(value)
value = '.'.join(reversed(parts))
return value
| bsd-3-clause |
Instrument/react | npm-react-codemod/transforms/class.js | 13414 | /*eslint-disable no-comma-dangle*/
'use strict';
function updateReactCreateClassToES6(file, api, options) {
const j = api.jscodeshift;
require('./utils/array-polyfills');
const ReactUtils = require('./utils/ReactUtils')(j);
const printOptions = options.printOptions || {quote: 'single'};
const root = j(file.source);
const AUTOBIND_IGNORE_KEYS = {
componentDidMount: true,
componentDidUpdate: true,
componentWillReceiveProps: true,
componentWillMount: true,
componentWillUpdate: true,
componentWillUnmount: true,
getDefaultProps: true,
getInitialState: true,
render: true,
shouldComponentUpdate: true,
};
const BASE_COMPONENT_METHODS = ['setState', 'forceUpdate'];
const DEFAULT_PROPS_FIELD = 'getDefaultProps';
const DEFAULT_PROPS_KEY = 'defaultProps';
const GET_INITIAL_STATE_FIELD = 'getInitialState';
const DEPRECATED_APIS = [
'getDOMNode',
'isMounted',
'replaceProps',
'replaceState',
'setProps',
];
const STATIC_KEYS = {
childContextTypes: true,
contextTypes: true,
displayName: true,
propTypes: true,
};
// ---------------------------------------------------------------------------
// Checks if the module uses mixins or accesses deprecated APIs.
const checkDeprecatedAPICalls = classPath =>
DEPRECATED_APIS.reduce(
(acc, name) =>
acc + j(classPath)
.find(j.Identifier, {name})
.size(),
0
) > 0;
const callsDeprecatedAPIs = classPath => {
if (checkDeprecatedAPICalls(classPath)) {
console.log(
file.path + ': "' + ReactUtils.getComponentName(classPath) + '" ' +
'skipped because of deprecated API calls. Remove calls to ' +
DEPRECATED_APIS.join(', ') + ' in your React component and re-run ' +
'this script.'
);
return false;
}
return true;
};
const hasMixins = classPath => {
if (ReactUtils.hasMixins(classPath)) {
console.log(
file.path + ': "' + ReactUtils.getComponentName(classPath) + '" ' +
' skipped because of mixins.'
);
return false;
}
return true;
};
// ---------------------------------------------------------------------------
// Helpers
const createFindPropFn = prop => property => (
property.key &&
property.key.type === 'Identifier' &&
property.key.name === prop
);
const filterDefaultPropsField = node =>
createFindPropFn(DEFAULT_PROPS_FIELD)(node);
const filterGetInitialStateField = node =>
createFindPropFn(GET_INITIAL_STATE_FIELD)(node);
const findGetDefaultProps = specPath =>
specPath.properties.find(createFindPropFn(DEFAULT_PROPS_FIELD));
const findGetInitialState = specPath =>
specPath.properties.find(createFindPropFn(GET_INITIAL_STATE_FIELD));
// This is conservative; only check for `setState` and `forceUpdate` literals
// instead of also checking which objects they are called on.
const shouldExtendReactComponent = classPath =>
BASE_COMPONENT_METHODS.some(name => (
j(classPath)
.find(j.Identifier, {name})
.size() > 0
));
const withComments = (to, from) => {
to.comments = from.comments;
return to;
};
// ---------------------------------------------------------------------------
// Collectors
const isFunctionExpression = node => (
node.key &&
node.key.type === 'Identifier' &&
node.value &&
node.value.type === 'FunctionExpression'
);
const collectStatics = specPath => {
const statics = specPath.properties.find(createFindPropFn('statics'));
const staticsObject =
(statics && statics.value && statics.value.properties) || [];
const getDefaultProps = findGetDefaultProps(specPath);
if (getDefaultProps) {
staticsObject.push(createDefaultProps(getDefaultProps));
}
return (
staticsObject.concat(specPath.properties.filter(property =>
property.key && STATIC_KEYS[property.key.name]
))
.sort((a, b) => a.key.name < b.key.name)
);
};
const collectFunctions = specPath => specPath.properties
.filter(prop =>
!(filterDefaultPropsField(prop) || filterGetInitialStateField(prop))
)
.filter(isFunctionExpression);
const findAutobindNamesFor = (root, fnNames, literalOrIdentifier) => {
const node = literalOrIdentifier;
const autobindNames = {};
j(root)
.find(j.MemberExpression, {
object: node.name ? {
type: node.type,
name: node.name,
} : {type: node.type},
property: {
type: 'Identifier',
},
})
.filter(path => path.value.property && fnNames[path.value.property.name])
.filter(path => {
const call = path.parent.value;
return !(
call &&
call.type === 'CallExpression' &&
call.callee.type === 'MemberExpression' &&
call.callee.object.type === node.type &&
call.callee.object.name === node.name &&
call.callee.property.type === 'Identifier' &&
call.callee.property.name === path.value.property.name
);
})
.forEach(path => autobindNames[path.value.property.name] = true);
return Object.keys(autobindNames);
};
const collectAutoBindFunctions = (functions, classPath) => {
const fnNames = {};
functions
.filter(fn => !AUTOBIND_IGNORE_KEYS[fn.key.name])
.forEach(fn => fnNames[fn.key.name] = true);
const autobindNames = {};
const add = name => autobindNames[name] = true;
// Find `this.<foo>`
findAutobindNamesFor(classPath, fnNames, j.thisExpression()).forEach(add);
// Find `self.<foo>` if `self = this`
j(classPath)
.findVariableDeclarators()
.filter(path => (
path.value.id.type === 'Identifier' &&
path.value.init &&
path.value.init.type === 'ThisExpression'
))
.forEach(path =>
findAutobindNamesFor(
j(path).closest(j.FunctionExpression).get(),
fnNames,
path.value.id
).forEach(add)
);
return Object.keys(autobindNames).sort();
};
// ---------------------------------------------------------------------------
// Boom!
const createMethodDefinition = fn =>
withComments(j.methodDefinition(
'',
fn.key,
fn.value
), fn);
const createBindAssignment = name =>
j.expressionStatement(
j.assignmentExpression(
'=',
j.memberExpression(
j.thisExpression(),
j.identifier(name),
false
),
j.callExpression(
j.memberExpression(
j.memberExpression(
j.thisExpression(),
j.identifier(name),
false
),
j.identifier('bind'),
false
),
[j.thisExpression()]
)
)
);
const createSuperCall = shouldAddSuperCall =>
!shouldAddSuperCall ?
[] :
[j.expressionStatement(
j.callExpression(
j.identifier('super'),
[j.identifier('props'), j.identifier('context')]
)
)];
const updatePropsAccess = getInitialState =>
getInitialState ?
j(getInitialState)
.find(j.MemberExpression, {
object: {
type: 'ThisExpression',
},
property: {
type: 'Identifier',
name: 'props',
},
})
.forEach(path => j(path).replaceWith(j.identifier('props')))
.size() > 0 :
false;
const inlineGetInitialState = getInitialState => {
if (!getInitialState) {
return [];
}
return getInitialState.value.body.body.map(statement => {
if (statement.type === 'ReturnStatement') {
return j.expressionStatement(
j.assignmentExpression(
'=',
j.memberExpression(
j.thisExpression(),
j.identifier('state'),
false
),
statement.argument
)
);
}
return statement;
});
};
const createConstructorArgs = (shouldAddSuperClass, hasPropsAccess) => {
if (shouldAddSuperClass) {
return [j.identifier('props'), j.identifier('context')];
} else if (hasPropsAccess) {
return [j.identifier('props')];
} else {
return [];
}
};
const createConstructor = (
getInitialState,
autobindFunctions,
shouldAddSuperClass
) => {
if (!getInitialState && !autobindFunctions.length) {
return [];
}
const hasPropsAccess = updatePropsAccess(getInitialState);
return [createMethodDefinition({
key: j.identifier('constructor'),
value: j.functionExpression(
null,
createConstructorArgs(shouldAddSuperClass, hasPropsAccess),
j.blockStatement(
[].concat(
createSuperCall(shouldAddSuperClass),
autobindFunctions.map(createBindAssignment),
inlineGetInitialState(getInitialState)
)
)
),
})];
};
const createES6Class = (
name,
functions,
getInitialState,
autobindFunctions,
comments,
shouldAddSuperClass
) =>
withComments(j.classDeclaration(
name ? j.identifier(name) : null,
j.classBody(
[].concat(
createConstructor(
getInitialState,
autobindFunctions,
shouldAddSuperClass
),
functions.map(createMethodDefinition)
)
),
shouldAddSuperClass ? j.memberExpression(
j.identifier('React'),
j.identifier('Component'),
false
) : null
), {comments});
const createStaticAssignment = (name, staticProperty) =>
withComments(j.expressionStatement(
j.assignmentExpression(
'=',
j.memberExpression(
name,
j.identifier(staticProperty.key.name),
false
),
staticProperty.value
)
), staticProperty);
const createStaticAssignmentExpressions = (name, statics) =>
statics.map(staticProperty => createStaticAssignment(name, staticProperty));
const hasSingleReturnStatement = value => (
value.type === 'FunctionExpression' &&
value.body &&
value.body.type === 'BlockStatement' &&
value.body.body &&
value.body.body.length === 1 &&
value.body.body[0].type === 'ReturnStatement' &&
value.body.body[0].argument &&
value.body.body[0].argument.type === 'ObjectExpression'
);
const createDefaultPropsValue = value => {
if (hasSingleReturnStatement(value)) {
return value.body.body[0].argument;
} else {
return j.callExpression(
value,
[]
);
}
};
const createDefaultProps = prop =>
withComments(
j.property(
'init',
j.identifier(DEFAULT_PROPS_KEY),
createDefaultPropsValue(prop.value)
),
prop
);
const getComments = classPath => {
if (classPath.value.comments) {
return classPath.value.comments;
}
const declaration = j(classPath).closest(j.VariableDeclaration);
if (declaration.size()) {
return declaration.get().value.comments;
}
return null;
};
const createModuleExportsMemberExpression = () =>
j.memberExpression(
j.identifier('module'),
j.identifier('exports'),
false
);
const updateToES6Class = (classPath, shouldExtend, isModuleExports) => {
const specPath = ReactUtils.getReactCreateClassSpec(classPath);
const name = ReactUtils.getComponentName(classPath);
const statics = collectStatics(specPath);
const functions = collectFunctions(specPath);
const comments = getComments(classPath);
const autobindFunctions = collectAutoBindFunctions(functions, classPath);
const getInitialState = findGetInitialState(specPath);
const staticName =
name ? j.identifier(name) : createModuleExportsMemberExpression();
var path;
if (isModuleExports) {
path = ReactUtils.findReactCreateClassCallExpression(classPath);
} else {
path = j(classPath).closest(j.VariableDeclaration);
}
path.replaceWith(
createES6Class(
name,
functions,
getInitialState,
autobindFunctions,
comments,
shouldExtend || shouldExtendReactComponent(classPath)
)
);
const staticAssignments =
createStaticAssignmentExpressions(staticName, statics);
if (isModuleExports) {
const body = root.get().value.body;
body.push.apply(body, staticAssignments);
} else {
staticAssignments
.forEach(expression => path = path.insertAfter(expression));
}
};
if (
options['no-explicit-require'] || ReactUtils.hasReact(root)
) {
const apply = (path, isModuleExports) =>
path
.filter(hasMixins)
.filter(callsDeprecatedAPIs)
.forEach(classPath => updateToES6Class(
classPath,
!options['no-super-class'],
isModuleExports
));
const didTransform = (
apply(ReactUtils.findReactCreateClass(root), false).size() +
apply(ReactUtils.findReactCreateClassModuleExports(root), true).size()
) > 0;
if (didTransform) {
return root.toSource(printOptions) + '\n';
}
}
return null;
}
module.exports = updateReactCreateClassToES6;
| bsd-3-clause |
ladams1776/zend_first | vendor/symfony/console/Helper/Table.php | 19777 | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Console\Helper;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Exception\InvalidArgumentException;
/**
* Provides helpers to display a table.
*
* @author Fabien Potencier <[email protected]>
* @author Саша Стаменковић <[email protected]>
* @author Abdellatif Ait boudad <[email protected]>
* @author Max Grigorian <[email protected]>
*/
class Table
{
/**
* Table headers.
*
* @var array
*/
private $headers = array();
/**
* Table rows.
*
* @var array
*/
private $rows = array();
/**
* Column widths cache.
*
* @var array
*/
private $effectiveColumnWidths = array();
/**
* Number of columns cache.
*
* @var array
*/
private $numberOfColumns;
/**
* @var OutputInterface
*/
private $output;
/**
* @var TableStyle
*/
private $style;
/**
* @var array
*/
private $columnStyles = array();
/**
* User set column widths.
*
* @var array
*/
private $columnWidths = array();
private static $styles;
public function __construct(OutputInterface $output)
{
$this->output = $output;
if (!self::$styles) {
self::$styles = self::initStyles();
}
$this->setStyle('default');
}
/**
* Sets a style definition.
*
* @param string $name The style name
* @param TableStyle $style A TableStyle instance
*/
public static function setStyleDefinition($name, TableStyle $style)
{
if (!self::$styles) {
self::$styles = self::initStyles();
}
self::$styles[$name] = $style;
}
/**
* Gets a style definition by name.
*
* @param string $name The style name
*
* @return TableStyle A TableStyle instance
*/
public static function getStyleDefinition($name)
{
if (!self::$styles) {
self::$styles = self::initStyles();
}
if (!self::$styles[$name]) {
throw new InvalidArgumentException(sprintf('Style "%s" is not defined.', $name));
}
return self::$styles[$name];
}
/**
* Sets table style.
*
* @param TableStyle|string $name The style name or a TableStyle instance
*
* @return Table
*/
public function setStyle($name)
{
if ($name instanceof TableStyle) {
$this->style = $name;
} elseif (isset(self::$styles[$name])) {
$this->style = self::$styles[$name];
} else {
throw new InvalidArgumentException(sprintf('Style "%s" is not defined.', $name));
}
return $this;
}
/**
* Gets the current table style.
*
* @return TableStyle
*/
public function getStyle()
{
return $this->style;
}
/**
* Sets table column style.
*
* @param int $columnIndex Column index
* @param TableStyle|string $name The style name or a TableStyle instance
*
* @return Table
*/
public function setColumnStyle($columnIndex, $name)
{
$columnIndex = intval($columnIndex);
if ($name instanceof TableStyle) {
$this->columnStyles[$columnIndex] = $name;
} elseif (isset(self::$styles[$name])) {
$this->columnStyles[$columnIndex] = self::$styles[$name];
} else {
throw new InvalidArgumentException(sprintf('Style "%s" is not defined.', $name));
}
return $this;
}
/**
* Gets the current style for a column.
*
* If style was not set, it returns the global table style.
*
* @param int $columnIndex Column index
*
* @return TableStyle
*/
public function getColumnStyle($columnIndex)
{
if (isset($this->columnStyles[$columnIndex])) {
return $this->columnStyles[$columnIndex];
}
return $this->getStyle();
}
/**
* Sets the minimum width of a column.
*
* @param int $columnIndex Column index
* @param int $width Minimum column width in characters
*
* @return Table
*/
public function setColumnWidth($columnIndex, $width)
{
$this->columnWidths[intval($columnIndex)] = intval($width);
return $this;
}
/**
* Sets the minimum width of all columns.
*
* @param array $widths
*
* @return Table
*/
public function setColumnWidths(array $widths)
{
$this->columnWidths = array();
foreach ($widths as $index => $width) {
$this->setColumnWidth($index, $width);
}
return $this;
}
public function setHeaders(array $headers)
{
$headers = array_values($headers);
if (!empty($headers) && !is_array($headers[0])) {
$headers = array($headers);
}
$this->headers = $headers;
return $this;
}
public function setRows(array $rows)
{
$this->rows = array();
return $this->addRows($rows);
}
public function addRows(array $rows)
{
foreach ($rows as $row) {
$this->addRow($row);
}
return $this;
}
public function addRow($row)
{
if ($row instanceof TableSeparator) {
$this->rows[] = $row;
return $this;
}
if (!is_array($row)) {
throw new InvalidArgumentException('A row must be an array or a TableSeparator instance.');
}
$this->rows[] = array_values($row);
return $this;
}
public function setRow($column, array $row)
{
$this->rows[$column] = $row;
return $this;
}
/**
* Renders table to output.
*
* Example:
* +---------------+-----------------------+------------------+
* | ISBN | Title | Author |
* +---------------+-----------------------+------------------+
* | 99921-58-10-7 | Divine Comedy | Dante Alighieri |
* | 9971-5-0210-0 | A Tale of Two Cities | Charles Dickens |
* | 960-425-059-0 | The Lord of the Rings | J. R. R. Tolkien |
* +---------------+-----------------------+------------------+
*/
public function render()
{
$this->calculateNumberOfColumns();
$rows = $this->buildTableRows($this->rows);
$headers = $this->buildTableRows($this->headers);
$this->calculateColumnsWidth(array_merge($headers, $rows));
$this->renderRowSeparator();
if (!empty($headers)) {
foreach ($headers as $header) {
$this->renderRow($header, $this->style->getCellHeaderFormat());
$this->renderRowSeparator();
}
}
foreach ($rows as $row) {
if ($row instanceof TableSeparator) {
$this->renderRowSeparator();
} else {
$this->renderRow($row, $this->style->getCellRowFormat());
}
}
if (!empty($rows)) {
$this->renderRowSeparator();
}
$this->cleanup();
}
/**
* Renders horizontal header separator.
*
* Example: +-----+-----------+-------+
*/
private function renderRowSeparator()
{
if (0 === $count = $this->numberOfColumns) {
return;
}
if (!$this->style->getHorizontalBorderChar() && !$this->style->getCrossingChar()) {
return;
}
$markup = $this->style->getCrossingChar();
for ($column = 0; $column < $count; ++$column) {
$markup .= str_repeat($this->style->getHorizontalBorderChar(), $this->effectiveColumnWidths[$column]).$this->style->getCrossingChar();
}
$this->output->writeln(sprintf($this->style->getBorderFormat(), $markup));
}
/**
* Renders vertical column separator.
*/
private function renderColumnSeparator()
{
$this->output->write(sprintf($this->style->getBorderFormat(), $this->style->getVerticalBorderChar()));
}
/**
* Renders table row.
*
* Example: | 9971-5-0210-0 | A Tale of Two Cities | Charles Dickens |
*
* @param array $row
* @param string $cellFormat
*/
private function renderRow(array $row, $cellFormat)
{
if (empty($row)) {
return;
}
$this->renderColumnSeparator();
foreach ($this->getRowColumns($row) as $column) {
$this->renderCell($row, $column, $cellFormat);
$this->renderColumnSeparator();
}
$this->output->writeln('');
}
/**
* Renders table cell with padding.
*
* @param array $row
* @param int $column
* @param string $cellFormat
*/
private function renderCell(array $row, $column, $cellFormat)
{
$cell = isset($row[$column]) ? $row[$column] : '';
$width = $this->effectiveColumnWidths[$column];
if ($cell instanceof TableCell && $cell->getColspan() > 1) {
// add the width of the following columns(numbers of colspan).
foreach (range($column + 1, $column + $cell->getColspan() - 1) as $nextColumn) {
$width += $this->getColumnSeparatorWidth() + $this->effectiveColumnWidths[$nextColumn];
}
}
// str_pad won't work properly with multi-byte strings, we need to fix the padding
if (false !== $encoding = mb_detect_encoding($cell, null, true)) {
$width += strlen($cell) - mb_strwidth($cell, $encoding);
}
$style = $this->getColumnStyle($column);
if ($cell instanceof TableSeparator) {
$this->output->write(sprintf($style->getBorderFormat(), str_repeat($style->getHorizontalBorderChar(), $width)));
} else {
$width += Helper::strlen($cell) - Helper::strlenWithoutDecoration($this->output->getFormatter(), $cell);
$content = sprintf($style->getCellRowContentFormat(), $cell);
$this->output->write(sprintf($cellFormat, str_pad($content, $width, $style->getPaddingChar(), $style->getPadType())));
}
}
/**
* Calculate number of columns for this table.
*/
private function calculateNumberOfColumns()
{
if (null !== $this->numberOfColumns) {
return;
}
$columns = array(0);
foreach (array_merge($this->headers, $this->rows) as $row) {
if ($row instanceof TableSeparator) {
continue;
}
$columns[] = $this->getNumberOfColumns($row);
}
$this->numberOfColumns = max($columns);
}
private function buildTableRows($rows)
{
$unmergedRows = array();
for ($rowKey = 0; $rowKey < count($rows); ++$rowKey) {
$rows = $this->fillNextRows($rows, $rowKey);
// Remove any new line breaks and replace it with a new line
foreach ($rows[$rowKey] as $column => $cell) {
if (!strstr($cell, "\n")) {
continue;
}
$lines = explode("\n", $cell);
foreach ($lines as $lineKey => $line) {
if ($cell instanceof TableCell) {
$line = new TableCell($line, array('colspan' => $cell->getColspan()));
}
if (0 === $lineKey) {
$rows[$rowKey][$column] = $line;
} else {
$unmergedRows[$rowKey][$lineKey][$column] = $line;
}
}
}
}
$tableRows = array();
foreach ($rows as $rowKey => $row) {
$tableRows[] = $this->fillCells($row);
if (isset($unmergedRows[$rowKey])) {
$tableRows = array_merge($tableRows, $unmergedRows[$rowKey]);
}
}
return $tableRows;
}
/**
* fill rows that contains rowspan > 1.
*
* @param array $rows
* @param int $line
*
* @return array
*/
private function fillNextRows($rows, $line)
{
$unmergedRows = array();
foreach ($rows[$line] as $column => $cell) {
if ($cell instanceof TableCell && $cell->getRowspan() > 1) {
$nbLines = $cell->getRowspan() - 1;
$lines = array($cell);
if (strstr($cell, "\n")) {
$lines = explode("\n", $cell);
$nbLines = count($lines) > $nbLines ? substr_count($cell, "\n") : $nbLines;
$rows[$line][$column] = new TableCell($lines[0], array('colspan' => $cell->getColspan()));
unset($lines[0]);
}
// create a two dimensional array (rowspan x colspan)
$unmergedRows = array_replace_recursive(array_fill($line + 1, $nbLines, ''), $unmergedRows);
foreach ($unmergedRows as $unmergedRowKey => $unmergedRow) {
$value = isset($lines[$unmergedRowKey - $line]) ? $lines[$unmergedRowKey - $line] : '';
$unmergedRows[$unmergedRowKey][$column] = new TableCell($value, array('colspan' => $cell->getColspan()));
}
}
}
foreach ($unmergedRows as $unmergedRowKey => $unmergedRow) {
// we need to know if $unmergedRow will be merged or inserted into $rows
if (isset($rows[$unmergedRowKey]) && is_array($rows[$unmergedRowKey]) && ($this->getNumberOfColumns($rows[$unmergedRowKey]) + $this->getNumberOfColumns($unmergedRows[$unmergedRowKey]) <= $this->numberOfColumns)) {
foreach ($unmergedRow as $cellKey => $cell) {
// insert cell into row at cellKey position
array_splice($rows[$unmergedRowKey], $cellKey, 0, array($cell));
}
} else {
$row = $this->copyRow($rows, $unmergedRowKey - 1);
foreach ($unmergedRow as $column => $cell) {
if (!empty($cell)) {
$row[$column] = $unmergedRow[$column];
}
}
array_splice($rows, $unmergedRowKey, 0, array($row));
}
}
return $rows;
}
/**
* fill cells for a row that contains colspan > 1.
*
* @param array $row
*
* @return array
*/
private function fillCells($row)
{
$newRow = array();
foreach ($row as $column => $cell) {
$newRow[] = $cell;
if ($cell instanceof TableCell && $cell->getColspan() > 1) {
foreach (range($column + 1, $column + $cell->getColspan() - 1) as $position) {
// insert empty value at column position
$newRow[] = '';
}
}
}
return $newRow ?: $row;
}
/**
* @param array $rows
* @param int $line
*
* @return array
*/
private function copyRow($rows, $line)
{
$row = $rows[$line];
foreach ($row as $cellKey => $cellValue) {
$row[$cellKey] = '';
if ($cellValue instanceof TableCell) {
$row[$cellKey] = new TableCell('', array('colspan' => $cellValue->getColspan()));
}
}
return $row;
}
/**
* Gets number of columns by row.
*
* @param array $row
*
* @return int
*/
private function getNumberOfColumns(array $row)
{
$columns = count($row);
foreach ($row as $column) {
$columns += $column instanceof TableCell ? ($column->getColspan() - 1) : 0;
}
return $columns;
}
/**
* Gets list of columns for the given row.
*
* @param array $row
*
* @return array
*/
private function getRowColumns($row)
{
$columns = range(0, $this->numberOfColumns - 1);
foreach ($row as $cellKey => $cell) {
if ($cell instanceof TableCell && $cell->getColspan() > 1) {
// exclude grouped columns.
$columns = array_diff($columns, range($cellKey + 1, $cellKey + $cell->getColspan() - 1));
}
}
return $columns;
}
/**
* Calculates columns widths.
*
* @param array $rows
*/
private function calculateColumnsWidth($rows)
{
for ($column = 0; $column < $this->numberOfColumns; ++$column) {
$lengths = array();
foreach ($rows as $row) {
if ($row instanceof TableSeparator) {
continue;
}
foreach ($row as $i => $cell) {
if ($cell instanceof TableCell) {
$textLength = strlen($cell);
if ($textLength > 0) {
$contentColumns = str_split($cell, ceil($textLength / $cell->getColspan()));
foreach ($contentColumns as $position => $content) {
$row[$i + $position] = $content;
}
}
}
}
$lengths[] = $this->getCellWidth($row, $column);
}
$this->effectiveColumnWidths[$column] = max($lengths) + strlen($this->style->getCellRowContentFormat()) - 2;
}
}
/**
* Gets column width.
*
* @return int
*/
private function getColumnSeparatorWidth()
{
return strlen(sprintf($this->style->getBorderFormat(), $this->style->getVerticalBorderChar()));
}
/**
* Gets cell width.
*
* @param array $row
* @param int $column
*
* @return int
*/
private function getCellWidth(array $row, $column)
{
$cellWidth = 0;
if (isset($row[$column])) {
$cell = $row[$column];
$cellWidth = Helper::strlenWithoutDecoration($this->output->getFormatter(), $cell);
}
$columnWidth = isset($this->columnWidths[$column]) ? $this->columnWidths[$column] : 0;
return max($cellWidth, $columnWidth);
}
/**
* Called after rendering to cleanup cache data.
*/
private function cleanup()
{
$this->effectiveColumnWidths = array();
$this->numberOfColumns = null;
}
private static function initStyles()
{
$borderless = new TableStyle();
$borderless
->setHorizontalBorderChar('=')
->setVerticalBorderChar(' ')
->setCrossingChar(' ')
;
$compact = new TableStyle();
$compact
->setHorizontalBorderChar('')
->setVerticalBorderChar(' ')
->setCrossingChar('')
->setCellRowContentFormat('%s')
;
$styleGuide = new TableStyle();
$styleGuide
->setHorizontalBorderChar('-')
->setVerticalBorderChar(' ')
->setCrossingChar(' ')
->setCellHeaderFormat('%s')
;
return array(
'default' => new TableStyle(),
'borderless' => $borderless,
'compact' => $compact,
'symfony-style-guide' => $styleGuide,
);
}
}
| bsd-3-clause |
vinayvinsol/spree | core/app/models/spree/stock_movement.rb | 894 | module Spree
class StockMovement < Spree::Base
QUANTITY_LIMITS = {
max: 2**31 - 1,
min: -2**31
}.freeze
belongs_to :stock_item, class_name: 'Spree::StockItem', inverse_of: :stock_movements
belongs_to :originator, polymorphic: true
after_create :update_stock_item_quantity
with_options presence: true do
validates :stock_item
validates :quantity, numericality: {
greater_than_or_equal_to: QUANTITY_LIMITS[:min],
less_than_or_equal_to: QUANTITY_LIMITS[:max],
only_integer: true
}
end
scope :recent, -> { order(created_at: :desc) }
self.whitelisted_ransackable_attributes = ['quantity']
def readonly?
persisted?
end
private
def update_stock_item_quantity
return unless stock_item.should_track_inventory?
stock_item.adjust_count_on_hand quantity
end
end
end
| bsd-3-clause |
zhangfangyan/devide | modules/readers/dicomRDR.py | 10649 | # Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
import gen_utils
from module_kits.misc_kit import misc_utils
import os
from module_base import ModuleBase
from module_mixins import \
IntrospectModuleMixin, FileOpenDialogModuleMixin
import module_utils
import stat
import wx
import vtk
import vtkdevide
import module_utils
class dicomRDR(ModuleBase,
IntrospectModuleMixin,
FileOpenDialogModuleMixin):
def __init__(self, module_manager):
# call the constructor in the "base"
ModuleBase.__init__(self, module_manager)
# setup necessary VTK objects
self._reader = vtkdevide.vtkDICOMVolumeReader()
module_utils.setup_vtk_object_progress(self, self._reader,
'Reading DICOM data')
self._viewFrame = None
self._fileDialog = None
# setup some defaults
self._config.dicomFilenames = []
self._config.seriesInstanceIdx = 0
self._config.estimateSliceThickness = 1
# do the normal thang (down to logic, up again)
self.sync_module_logic_with_config()
def close(self):
if self._fileDialog is not None:
del self._fileDialog
# this will take care of all the vtkPipeline windows
IntrospectModuleMixin.close(self)
if self._viewFrame is not None:
# take care of our own window
self._viewFrame.Destroy()
# also remove the binding we have to our reader
del self._reader
def get_input_descriptions(self):
return ()
def set_input(self, idx, input_stream):
raise Exception
def get_output_descriptions(self):
return ('DICOM data (vtkStructuredPoints)',)
def get_output(self, idx):
return self._reader.GetOutput()
def logic_to_config(self):
self._config.seriesInstanceIdx = self._reader.GetSeriesInstanceIdx()
# refresh our list of dicomFilenames
del self._config.dicomFilenames[:]
for i in range(self._reader.get_number_of_dicom_filenames()):
self._config.dicomFilenames.append(
self._reader.get_dicom_filename(i))
self._config.estimateSliceThickness = self._reader.\
GetEstimateSliceThickness()
def config_to_logic(self):
self._reader.SetSeriesInstanceIdx(self._config.seriesInstanceIdx)
# this will clear only the dicom_filenames_buffer without setting
# mtime of the vtkDICOMVolumeReader
self._reader.clear_dicom_filenames()
for fullname in self._config.dicomFilenames:
# this will simply add a file to the buffer list of the
# vtkDICOMVolumeReader (will not set mtime)
self._reader.add_dicom_filename(fullname)
# if we've added the same list as we added at the previous exec
# of apply_config(), the dicomreader is clever enough to know that
# it doesn't require an update. Yay me.
self._reader.SetEstimateSliceThickness(
self._config.estimateSliceThickness)
def view_to_config(self):
self._config.seriesInstanceIdx = self._viewFrame.si_idx_spin.GetValue()
lb = self._viewFrame.dicomFilesListBox
count = lb.GetCount()
filenames_init = []
for n in range(count):
filenames_init.append(lb.GetString(n))
# go through list of files in directory, perform trivial tests
# and create a new list of files
del self._config.dicomFilenames[:]
for filename in filenames_init:
# at the moment, we check that it's a regular file
if stat.S_ISREG(os.stat(filename)[stat.ST_MODE]):
self._config.dicomFilenames.append(filename)
if len(self._config.dicomFilenames) == 0:
wx.LogError('Empty directory specified, not attempting '
'change in config.')
self._config.estimateSliceThickness = self._viewFrame.\
estimateSliceThicknessCheckBox.\
GetValue()
def config_to_view(self):
# first transfer list of files to listbox
lb = self._viewFrame.dicomFilesListBox
lb.Clear()
for fn in self._config.dicomFilenames:
lb.Append(fn)
# at this stage, we can always assume that the logic is current
# with the config struct...
self._viewFrame.si_idx_spin.SetValue(self._config.seriesInstanceIdx)
# some information in the view does NOT form part of the config,
# but comes directly from the logic:
# we're going to be reading some information from the _reader which
# is only up to date after this call
self._reader.UpdateInformation()
# get current SeriesInstanceIdx from the DICOMReader
# FIXME: the frikking SpinCtrl does not want to update when we call
# SetValue()... we've now hard-coded it in wxGlade (still doesn't work)
self._viewFrame.si_idx_spin.SetValue(
int(self._reader.GetSeriesInstanceIdx()))
# try to get current SeriesInstanceIdx (this will run at least
# UpdateInfo)
si_uid = self._reader.GetSeriesInstanceUID()
if si_uid == None:
si_uid = "NONE"
self._viewFrame.si_uid_text.SetValue(si_uid)
msii = self._reader.GetMaximumSeriesInstanceIdx()
self._viewFrame.seriesInstancesText.SetValue(str(msii))
# also limit the spin-control
self._viewFrame.si_idx_spin.SetRange(0, msii)
sd = self._reader.GetStudyDescription()
if sd == None:
self._viewFrame.study_description_text.SetValue("NONE");
else:
self._viewFrame.study_description_text.SetValue(sd);
rp = self._reader.GetReferringPhysician()
if rp == None:
self._viewFrame.referring_physician_text.SetValue("NONE");
else:
self._viewFrame.referring_physician_text.SetValue(rp);
dd = self._reader.GetDataDimensions()
ds = self._reader.GetDataSpacing()
self._viewFrame.dimensions_text.SetValue(
'%d x %d x %d at %.2f x %.2f x %.2f mm / voxel' % tuple(dd + ds))
self._viewFrame.estimateSliceThicknessCheckBox.SetValue(
self._config.estimateSliceThickness)
def execute_module(self):
# get the vtkDICOMVolumeReader to try and execute
self._reader.Update()
# now get some metadata out and insert it in our output stream
# first determine axis labels based on IOP ####################
iop = self._reader.GetImageOrientationPatient()
row = iop[0:3]
col = iop[3:6]
# the cross product (plane normal) based on the row and col will
# also be in the LPH coordinate system
norm = [0,0,0]
vtk.vtkMath.Cross(row, col, norm)
xl = misc_utils.major_axis_from_iop_cosine(row)
yl = misc_utils.major_axis_from_iop_cosine(col)
zl = misc_utils.major_axis_from_iop_cosine(norm)
lut = {'L' : 0, 'R' : 1, 'P' : 2, 'A' : 3, 'F' : 4, 'H' : 5}
if xl and yl and zl:
# add this data as a vtkFieldData
fd = self._reader.GetOutput().GetFieldData()
axis_labels_array = vtk.vtkIntArray()
axis_labels_array.SetName('axis_labels_array')
for l in xl + yl + zl:
axis_labels_array.InsertNextValue(lut[l])
fd.AddArray(axis_labels_array)
# window/level ###############################################
def _createViewFrame(self):
import modules.readers.resources.python.dicomRDRViewFrame
reload(modules.readers.resources.python.dicomRDRViewFrame)
self._viewFrame = module_utils.instantiate_module_view_frame(
self, self._module_manager,
modules.readers.resources.python.dicomRDRViewFrame.\
dicomRDRViewFrame)
# make sure the listbox is empty
self._viewFrame.dicomFilesListBox.Clear()
objectDict = {'dicom reader' : self._reader}
module_utils.create_standard_object_introspection(
self, self._viewFrame, self._viewFrame.viewFramePanel,
objectDict, None)
module_utils.create_eoca_buttons(self, self._viewFrame,
self._viewFrame.viewFramePanel)
wx.EVT_BUTTON(self._viewFrame, self._viewFrame.addButton.GetId(),
self._handlerAddButton)
wx.EVT_BUTTON(self._viewFrame, self._viewFrame.removeButton.GetId(),
self._handlerRemoveButton)
# follow ModuleBase convention to indicate that we now have
# a view
self.view_initialised = True
def view(self, parent_window=None):
if self._viewFrame is None:
self._createViewFrame()
self.sync_module_view_with_logic()
self._viewFrame.Show(True)
self._viewFrame.Raise()
def _handlerAddButton(self, event):
if not self._fileDialog:
self._fileDialog = wx.FileDialog(
self._module_manager.get_module_view_parent_window(),
'Select files to add to the list', "", "",
"DICOM files (*.dcm)|*.dcm|DICOM files (*.img)|*.img|All files (*)|*",
wx.OPEN | wx.MULTIPLE)
if self._fileDialog.ShowModal() == wx.ID_OK:
newFilenames = self._fileDialog.GetPaths()
# first check for duplicates in the listbox
lb = self._viewFrame.dicomFilesListBox
count = lb.GetCount()
oldFilenames = []
for n in range(count):
oldFilenames.append(lb.GetString(n))
filenamesToAdd = [fn for fn in newFilenames
if fn not in oldFilenames]
for fn in filenamesToAdd:
lb.Append(fn)
def _handlerRemoveButton(self, event):
"""Remove all selected filenames from the internal list.
"""
lb = self._viewFrame.dicomFilesListBox
sels = list(lb.GetSelections())
# we have to delete from the back to the front
sels.sort()
sels.reverse()
# build list
for sel in sels:
lb.Delete(sel)
| bsd-3-clause |
rainlike/justshop | vendor/sylius/sylius/src/Sylius/Bundle/ResourceBundle/Controller/ResourceUpdateHandlerInterface.php | 827 | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Bundle\ResourceBundle\Controller;
use Doctrine\Common\Persistence\ObjectManager;
use Sylius\Component\Resource\Model\ResourceInterface;
/**
* @author Grzegorz Sadowski <[email protected]>
*/
interface ResourceUpdateHandlerInterface
{
/**
* @param ResourceInterface $resource
* @param RequestConfiguration $requestConfiguration
* @param ObjectManager $manager
*/
public function handle(
ResourceInterface $resource,
RequestConfiguration $requestConfiguration,
ObjectManager $manager
): void;
}
| mit |
wikimedia/mediawiki-vagrant | puppet/modules/stdlib/lib/puppet/parser/functions/is_ipv6_address.rb | 797 | #
# is_ipv6_address.rb
#
module Puppet::Parser::Functions
newfunction(:is_ipv6_address, :type => :rvalue, :doc => <<-EOS
Returns true if the string passed to this function is a valid IPv6 address.
EOS
) do |arguments|
function_deprecation([:is_ipv6_address, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Ipv6. There is further documentation for validate_legacy function in the README.'])
require 'ipaddr'
if (arguments.size != 1) then
raise(Puppet::ParseError, "is_ipv6_address(): Wrong number of arguments "+
"given #{arguments.size} for 1")
end
begin
ip = IPAddr.new(arguments[0])
rescue ArgumentError
return false
end
return ip.ipv6?
end
end
# vim: set ts=2 sw=2 et :
| mit |
Sharjeel-Khan/Portfolio | js/ngmap/directives/map.js | 2471 | /**
* @ngdoc directive
* @memberof ngMap
* @name ng-map
* @param Attr2Options {service}
* convert html attribute to Google map api options
* @description
* Implementation of {@link __MapController}
* Initialize a Google map within a `<div>` tag
* with given options and register events
*
* @attr {Expression} map-initialized
* callback function when map is initialized
* e.g., map-initialized="mycallback(map)"
* @attr {Expression} geo-callback if center is an address or current location,
* the expression is will be executed when geo-lookup is successful.
* e.g., geo-callback="showMyStoreInfo()"
* @attr {Array} geo-fallback-center
* The center of map incase geolocation failed. i.e. [0,0]
* @attr {Object} geo-location-options
* The navigator geolocation options.
* e.g., { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }.
* If none specified, { timeout: 5000 }.
* If timeout not specified, timeout: 5000 added
* @attr {Boolean} zoom-to-include-markers
* When true, map boundary will be changed automatially
* to include all markers when initialized
* @attr {Boolean} default-style
* When false, the default styling,
* `display:block;height:300px`, will be ignored.
* @attr {String} <MapOption> Any Google map options,
* https://developers.google.com/maps/documentation/javascript/reference?csw=1#MapOptions
* @attr {String} <MapEvent> Any Google map events,
* https://rawgit.com/allenhwkim/angularjs-google-maps/master/build/map_events.html
* @attr {Boolean} single-info-window
* When true the map will only display one info window at the time,
* if not set or false,
* everytime an info window is open it will be displayed with the othe one.
* @attr {Boolean} trigger-resize
* Default to false. Set to true to trigger resize of the map. Needs to be done anytime you resize the map
* @example
* Usage:
* <map MAP_OPTIONS_OR_MAP_EVENTS ..>
* ... Any children directives
* </map>
*
* Example:
* <map center="[40.74, -74.18]" on-click="doThat()">
* </map>
*
* <map geo-fallback-center="[40.74, -74.18]" zoom-to-inlude-markers="true">
* </map>
*/
(function () {
'use strict';
var mapDirective = function () {
return {
restrict: 'AE',
controller: '__MapController',
controllerAs: 'ngmap'
};
};
angular.module('ngMap').directive('map', [mapDirective]);
angular.module('ngMap').directive('ngMap', [mapDirective]);
})();
| mit |
tomgazit/University-Material-Manager | filters/FilterASCIIHexDecode.php | 1498 | <?php
//
// FPDI - Version 1.5.2
//
// Copyright 2004-2014 Setasign - Jan Slabon
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/**
* Class FilterASCIIHexDecode
*/
class FilterASCIIHexDecode
{
/**
* Converts an ASCII hexadecimal encoded string into it's binary representation.
*
* @param string $data The input string
* @return string
*/
public function decode($data)
{
$data = preg_replace('/[^0-9A-Fa-f]/', '', rtrim($data, '>'));
if ((strlen($data) % 2) == 1) {
$data .= '0';
}
return pack('H*', $data);
}
/**
* Converts a string into ASCII hexadecimal representation.
*
* @param string $data The input string
* @param boolean $leaveEOD
* @return string
*/
public function encode($data, $leaveEOD = false)
{
return current(unpack('H*', $data)) . ($leaveEOD ? '' : '>');
}
} | mit |
gnat42/symfony | src/Symfony/Component/Config/Resource/ClassExistenceResource.php | 4708 | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Config\Resource;
/**
* ClassExistenceResource represents a class existence.
* Freshness is only evaluated against resource existence.
*
* The resource must be a fully-qualified class name.
*
* @author Fabien Potencier <[email protected]>
*
* @final since Symfony 4.3
*/
class ClassExistenceResource implements SelfCheckingResourceInterface
{
private $resource;
private $exists;
private static $autoloadLevel = 0;
private static $autoloadedClass;
private static $existsCache = [];
/**
* @param string $resource The fully-qualified class name
* @param bool|null $exists Boolean when the existency check has already been done
*/
public function __construct(string $resource, bool $exists = null)
{
$this->resource = $resource;
$this->exists = $exists;
}
/**
* {@inheritdoc}
*/
public function __toString()
{
return $this->resource;
}
/**
* @return string The file path to the resource
*/
public function getResource()
{
return $this->resource;
}
/**
* {@inheritdoc}
*
* @throws \ReflectionException when a parent class/interface/trait is not found
*/
public function isFresh($timestamp)
{
$loaded = class_exists($this->resource, false) || interface_exists($this->resource, false) || trait_exists($this->resource, false);
if (null !== $exists = &self::$existsCache[(int) (0 >= $timestamp)][$this->resource]) {
$exists = $exists || $loaded;
} elseif (!$exists = $loaded) {
if (!self::$autoloadLevel++) {
spl_autoload_register(__CLASS__.'::throwOnRequiredClass');
}
$autoloadedClass = self::$autoloadedClass;
self::$autoloadedClass = $this->resource;
try {
$exists = class_exists($this->resource) || interface_exists($this->resource, false) || trait_exists($this->resource, false);
} catch (\ReflectionException $e) {
if (0 >= $timestamp) {
unset(self::$existsCache[1][$this->resource]);
throw $e;
}
} finally {
self::$autoloadedClass = $autoloadedClass;
if (!--self::$autoloadLevel) {
spl_autoload_unregister(__CLASS__.'::throwOnRequiredClass');
}
}
}
if (null === $this->exists) {
$this->exists = $exists;
}
return $this->exists xor !$exists;
}
/**
* @internal
*/
public function __sleep(): array
{
if (null === $this->exists) {
$this->isFresh(0);
}
return ['resource', 'exists'];
}
/**
* @throws \ReflectionException When $class is not found and is required
*
* @internal
*/
public static function throwOnRequiredClass($class)
{
if (self::$autoloadedClass === $class) {
return;
}
$e = new \ReflectionException("Class $class not found");
$trace = $e->getTrace();
$autoloadFrame = [
'function' => 'spl_autoload_call',
'args' => [$class],
];
$i = 1 + array_search($autoloadFrame, $trace, true);
if (isset($trace[$i]['function']) && !isset($trace[$i]['class'])) {
switch ($trace[$i]['function']) {
case 'get_class_methods':
case 'get_class_vars':
case 'get_parent_class':
case 'is_a':
case 'is_subclass_of':
case 'class_exists':
case 'class_implements':
case 'class_parents':
case 'trait_exists':
case 'defined':
case 'interface_exists':
case 'method_exists':
case 'property_exists':
case 'is_callable':
return;
}
$props = [
'file' => $trace[$i]['file'],
'line' => $trace[$i]['line'],
'trace' => \array_slice($trace, 1 + $i),
];
foreach ($props as $p => $v) {
$r = new \ReflectionProperty('Exception', $p);
$r->setAccessible(true);
$r->setValue($e, $v);
}
}
throw $e;
}
}
| mit |
davehorton/drachtio-server | deps/boost_1_77_0/boost/math/distributions/beta.hpp | 19087 | // boost\math\distributions\beta.hpp
// Copyright John Maddock 2006.
// Copyright Paul A. Bristow 2006.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)
// http://en.wikipedia.org/wiki/Beta_distribution
// http://www.itl.nist.gov/div898/handbook/eda/section3/eda366h.htm
// http://mathworld.wolfram.com/BetaDistribution.html
// The Beta Distribution is a continuous probability distribution.
// The beta distribution is used to model events which are constrained to take place
// within an interval defined by maxima and minima,
// so is used extensively in PERT and other project management systems
// to describe the time to completion.
// The cdf of the beta distribution is used as a convenient way
// of obtaining the sum over a set of binomial outcomes.
// The beta distribution is also used in Bayesian statistics.
#ifndef BOOST_MATH_DIST_BETA_HPP
#define BOOST_MATH_DIST_BETA_HPP
#include <boost/math/distributions/fwd.hpp>
#include <boost/math/special_functions/beta.hpp> // for beta.
#include <boost/math/distributions/complement.hpp> // complements.
#include <boost/math/distributions/detail/common_error_handling.hpp> // error checks
#include <boost/math/special_functions/fpclassify.hpp> // isnan.
#include <boost/math/tools/roots.hpp> // for root finding.
#if defined (BOOST_MSVC)
# pragma warning(push)
# pragma warning(disable: 4702) // unreachable code
// in domain_error_imp in error_handling
#endif
#include <utility>
namespace boost
{
namespace math
{
namespace beta_detail
{
// Common error checking routines for beta distribution functions:
template <class RealType, class Policy>
inline bool check_alpha(const char* function, const RealType& alpha, RealType* result, const Policy& pol)
{
if(!(boost::math::isfinite)(alpha) || (alpha <= 0))
{
*result = policies::raise_domain_error<RealType>(
function,
"Alpha argument is %1%, but must be > 0 !", alpha, pol);
return false;
}
return true;
} // bool check_alpha
template <class RealType, class Policy>
inline bool check_beta(const char* function, const RealType& beta, RealType* result, const Policy& pol)
{
if(!(boost::math::isfinite)(beta) || (beta <= 0))
{
*result = policies::raise_domain_error<RealType>(
function,
"Beta argument is %1%, but must be > 0 !", beta, pol);
return false;
}
return true;
} // bool check_beta
template <class RealType, class Policy>
inline bool check_prob(const char* function, const RealType& p, RealType* result, const Policy& pol)
{
if((p < 0) || (p > 1) || !(boost::math::isfinite)(p))
{
*result = policies::raise_domain_error<RealType>(
function,
"Probability argument is %1%, but must be >= 0 and <= 1 !", p, pol);
return false;
}
return true;
} // bool check_prob
template <class RealType, class Policy>
inline bool check_x(const char* function, const RealType& x, RealType* result, const Policy& pol)
{
if(!(boost::math::isfinite)(x) || (x < 0) || (x > 1))
{
*result = policies::raise_domain_error<RealType>(
function,
"x argument is %1%, but must be >= 0 and <= 1 !", x, pol);
return false;
}
return true;
} // bool check_x
template <class RealType, class Policy>
inline bool check_dist(const char* function, const RealType& alpha, const RealType& beta, RealType* result, const Policy& pol)
{ // Check both alpha and beta.
return check_alpha(function, alpha, result, pol)
&& check_beta(function, beta, result, pol);
} // bool check_dist
template <class RealType, class Policy>
inline bool check_dist_and_x(const char* function, const RealType& alpha, const RealType& beta, RealType x, RealType* result, const Policy& pol)
{
return check_dist(function, alpha, beta, result, pol)
&& beta_detail::check_x(function, x, result, pol);
} // bool check_dist_and_x
template <class RealType, class Policy>
inline bool check_dist_and_prob(const char* function, const RealType& alpha, const RealType& beta, RealType p, RealType* result, const Policy& pol)
{
return check_dist(function, alpha, beta, result, pol)
&& check_prob(function, p, result, pol);
} // bool check_dist_and_prob
template <class RealType, class Policy>
inline bool check_mean(const char* function, const RealType& mean, RealType* result, const Policy& pol)
{
if(!(boost::math::isfinite)(mean) || (mean <= 0))
{
*result = policies::raise_domain_error<RealType>(
function,
"mean argument is %1%, but must be > 0 !", mean, pol);
return false;
}
return true;
} // bool check_mean
template <class RealType, class Policy>
inline bool check_variance(const char* function, const RealType& variance, RealType* result, const Policy& pol)
{
if(!(boost::math::isfinite)(variance) || (variance <= 0))
{
*result = policies::raise_domain_error<RealType>(
function,
"variance argument is %1%, but must be > 0 !", variance, pol);
return false;
}
return true;
} // bool check_variance
} // namespace beta_detail
// typedef beta_distribution<double> beta;
// is deliberately NOT included to avoid a name clash with the beta function.
// Use beta_distribution<> mybeta(...) to construct type double.
template <class RealType = double, class Policy = policies::policy<> >
class beta_distribution
{
public:
typedef RealType value_type;
typedef Policy policy_type;
beta_distribution(RealType l_alpha = 1, RealType l_beta = 1) : m_alpha(l_alpha), m_beta(l_beta)
{
RealType result;
beta_detail::check_dist(
"boost::math::beta_distribution<%1%>::beta_distribution",
m_alpha,
m_beta,
&result, Policy());
} // beta_distribution constructor.
// Accessor functions:
RealType alpha() const
{
return m_alpha;
}
RealType beta() const
{ // .
return m_beta;
}
// Estimation of the alpha & beta parameters.
// http://en.wikipedia.org/wiki/Beta_distribution
// gives formulae in section on parameter estimation.
// Also NIST EDA page 3 & 4 give the same.
// http://www.itl.nist.gov/div898/handbook/eda/section3/eda366h.htm
// http://www.epi.ucdavis.edu/diagnostictests/betabuster.html
static RealType find_alpha(
RealType mean, // Expected value of mean.
RealType variance) // Expected value of variance.
{
static const char* function = "boost::math::beta_distribution<%1%>::find_alpha";
RealType result = 0; // of error checks.
if(false ==
(
beta_detail::check_mean(function, mean, &result, Policy())
&& beta_detail::check_variance(function, variance, &result, Policy())
)
)
{
return result;
}
return mean * (( (mean * (1 - mean)) / variance)- 1);
} // RealType find_alpha
static RealType find_beta(
RealType mean, // Expected value of mean.
RealType variance) // Expected value of variance.
{
static const char* function = "boost::math::beta_distribution<%1%>::find_beta";
RealType result = 0; // of error checks.
if(false ==
(
beta_detail::check_mean(function, mean, &result, Policy())
&&
beta_detail::check_variance(function, variance, &result, Policy())
)
)
{
return result;
}
return (1 - mean) * (((mean * (1 - mean)) /variance)-1);
} // RealType find_beta
// Estimate alpha & beta from either alpha or beta, and x and probability.
// Uses for these parameter estimators are unclear.
static RealType find_alpha(
RealType beta, // from beta.
RealType x, // x.
RealType probability) // cdf
{
static const char* function = "boost::math::beta_distribution<%1%>::find_alpha";
RealType result = 0; // of error checks.
if(false ==
(
beta_detail::check_prob(function, probability, &result, Policy())
&&
beta_detail::check_beta(function, beta, &result, Policy())
&&
beta_detail::check_x(function, x, &result, Policy())
)
)
{
return result;
}
return ibeta_inva(beta, x, probability, Policy());
} // RealType find_alpha(beta, a, probability)
static RealType find_beta(
// ibeta_invb(T b, T x, T p); (alpha, x, cdf,)
RealType alpha, // alpha.
RealType x, // probability x.
RealType probability) // probability cdf.
{
static const char* function = "boost::math::beta_distribution<%1%>::find_beta";
RealType result = 0; // of error checks.
if(false ==
(
beta_detail::check_prob(function, probability, &result, Policy())
&&
beta_detail::check_alpha(function, alpha, &result, Policy())
&&
beta_detail::check_x(function, x, &result, Policy())
)
)
{
return result;
}
return ibeta_invb(alpha, x, probability, Policy());
} // RealType find_beta(alpha, x, probability)
private:
RealType m_alpha; // Two parameters of the beta distribution.
RealType m_beta;
}; // template <class RealType, class Policy> class beta_distribution
template <class RealType, class Policy>
inline const std::pair<RealType, RealType> range(const beta_distribution<RealType, Policy>& /* dist */)
{ // Range of permissible values for random variable x.
using boost::math::tools::max_value;
return std::pair<RealType, RealType>(static_cast<RealType>(0), static_cast<RealType>(1));
}
template <class RealType, class Policy>
inline const std::pair<RealType, RealType> support(const beta_distribution<RealType, Policy>& /* dist */)
{ // Range of supported values for random variable x.
// This is range where cdf rises from 0 to 1, and outside it, the pdf is zero.
return std::pair<RealType, RealType>(static_cast<RealType>(0), static_cast<RealType>(1));
}
template <class RealType, class Policy>
inline RealType mean(const beta_distribution<RealType, Policy>& dist)
{ // Mean of beta distribution = np.
return dist.alpha() / (dist.alpha() + dist.beta());
} // mean
template <class RealType, class Policy>
inline RealType variance(const beta_distribution<RealType, Policy>& dist)
{ // Variance of beta distribution = np(1-p).
RealType a = dist.alpha();
RealType b = dist.beta();
return (a * b) / ((a + b ) * (a + b) * (a + b + 1));
} // variance
template <class RealType, class Policy>
inline RealType mode(const beta_distribution<RealType, Policy>& dist)
{
static const char* function = "boost::math::mode(beta_distribution<%1%> const&)";
RealType result;
if ((dist.alpha() <= 1))
{
result = policies::raise_domain_error<RealType>(
function,
"mode undefined for alpha = %1%, must be > 1!", dist.alpha(), Policy());
return result;
}
if ((dist.beta() <= 1))
{
result = policies::raise_domain_error<RealType>(
function,
"mode undefined for beta = %1%, must be > 1!", dist.beta(), Policy());
return result;
}
RealType a = dist.alpha();
RealType b = dist.beta();
return (a-1) / (a + b - 2);
} // mode
//template <class RealType, class Policy>
//inline RealType median(const beta_distribution<RealType, Policy>& dist)
//{ // Median of beta distribution is not defined.
// return tools::domain_error<RealType>(function, "Median is not implemented, result is %1%!", std::numeric_limits<RealType>::quiet_NaN());
//} // median
//But WILL be provided by the derived accessor as quantile(0.5).
template <class RealType, class Policy>
inline RealType skewness(const beta_distribution<RealType, Policy>& dist)
{
BOOST_MATH_STD_USING // ADL of std functions.
RealType a = dist.alpha();
RealType b = dist.beta();
return (2 * (b-a) * sqrt(a + b + 1)) / ((a + b + 2) * sqrt(a * b));
} // skewness
template <class RealType, class Policy>
inline RealType kurtosis_excess(const beta_distribution<RealType, Policy>& dist)
{
RealType a = dist.alpha();
RealType b = dist.beta();
RealType a_2 = a * a;
RealType n = 6 * (a_2 * a - a_2 * (2 * b - 1) + b * b * (b + 1) - 2 * a * b * (b + 2));
RealType d = a * b * (a + b + 2) * (a + b + 3);
return n / d;
} // kurtosis_excess
template <class RealType, class Policy>
inline RealType kurtosis(const beta_distribution<RealType, Policy>& dist)
{
return 3 + kurtosis_excess(dist);
} // kurtosis
template <class RealType, class Policy>
inline RealType pdf(const beta_distribution<RealType, Policy>& dist, const RealType& x)
{ // Probability Density/Mass Function.
BOOST_FPU_EXCEPTION_GUARD
static const char* function = "boost::math::pdf(beta_distribution<%1%> const&, %1%)";
BOOST_MATH_STD_USING // for ADL of std functions
RealType a = dist.alpha();
RealType b = dist.beta();
// Argument checks:
RealType result = 0;
if(false == beta_detail::check_dist_and_x(
function,
a, b, x,
&result, Policy()))
{
return result;
}
using boost::math::beta;
// Corner case: check_x ensures x element of [0, 1], but PDF is 0 for x = 0 and x = 1. PDF EQN:
// https://wikimedia.org/api/rest_v1/media/math/render/svg/125fdaa41844a8703d1a8610ac00fbf3edacc8e7
if(x == 0 || x == 1)
{
return RealType(0);
}
return ibeta_derivative(a, b, x, Policy());
} // pdf
template <class RealType, class Policy>
inline RealType cdf(const beta_distribution<RealType, Policy>& dist, const RealType& x)
{ // Cumulative Distribution Function beta.
BOOST_MATH_STD_USING // for ADL of std functions
static const char* function = "boost::math::cdf(beta_distribution<%1%> const&, %1%)";
RealType a = dist.alpha();
RealType b = dist.beta();
// Argument checks:
RealType result = 0;
if(false == beta_detail::check_dist_and_x(
function,
a, b, x,
&result, Policy()))
{
return result;
}
// Special cases:
if (x == 0)
{
return 0;
}
else if (x == 1)
{
return 1;
}
return ibeta(a, b, x, Policy());
} // beta cdf
template <class RealType, class Policy>
inline RealType cdf(const complemented2_type<beta_distribution<RealType, Policy>, RealType>& c)
{ // Complemented Cumulative Distribution Function beta.
BOOST_MATH_STD_USING // for ADL of std functions
static const char* function = "boost::math::cdf(beta_distribution<%1%> const&, %1%)";
RealType const& x = c.param;
beta_distribution<RealType, Policy> const& dist = c.dist;
RealType a = dist.alpha();
RealType b = dist.beta();
// Argument checks:
RealType result = 0;
if(false == beta_detail::check_dist_and_x(
function,
a, b, x,
&result, Policy()))
{
return result;
}
if (x == 0)
{
return 1;
}
else if (x == 1)
{
return 0;
}
// Calculate cdf beta using the incomplete beta function.
// Use of ibeta here prevents cancellation errors in calculating
// 1 - x if x is very small, perhaps smaller than machine epsilon.
return ibetac(a, b, x, Policy());
} // beta cdf
template <class RealType, class Policy>
inline RealType quantile(const beta_distribution<RealType, Policy>& dist, const RealType& p)
{ // Quantile or Percent Point beta function or
// Inverse Cumulative probability distribution function CDF.
// Return x (0 <= x <= 1),
// for a given probability p (0 <= p <= 1).
// These functions take a probability as an argument
// and return a value such that the probability that a random variable x
// will be less than or equal to that value
// is whatever probability you supplied as an argument.
static const char* function = "boost::math::quantile(beta_distribution<%1%> const&, %1%)";
RealType result = 0; // of argument checks:
RealType a = dist.alpha();
RealType b = dist.beta();
if(false == beta_detail::check_dist_and_prob(
function,
a, b, p,
&result, Policy()))
{
return result;
}
// Special cases:
if (p == 0)
{
return 0;
}
if (p == 1)
{
return 1;
}
return ibeta_inv(a, b, p, static_cast<RealType*>(0), Policy());
} // quantile
template <class RealType, class Policy>
inline RealType quantile(const complemented2_type<beta_distribution<RealType, Policy>, RealType>& c)
{ // Complement Quantile or Percent Point beta function .
// Return the number of expected x for a given
// complement of the probability q.
static const char* function = "boost::math::quantile(beta_distribution<%1%> const&, %1%)";
//
// Error checks:
RealType q = c.param;
const beta_distribution<RealType, Policy>& dist = c.dist;
RealType result = 0;
RealType a = dist.alpha();
RealType b = dist.beta();
if(false == beta_detail::check_dist_and_prob(
function,
a,
b,
q,
&result, Policy()))
{
return result;
}
// Special cases:
if(q == 1)
{
return 0;
}
if(q == 0)
{
return 1;
}
return ibetac_inv(a, b, q, static_cast<RealType*>(0), Policy());
} // Quantile Complement
} // namespace math
} // namespace boost
// This include must be at the end, *after* the accessors
// for this distribution have been defined, in order to
// keep compilers that support two-phase lookup happy.
#include <boost/math/distributions/detail/derived_accessors.hpp>
#if defined (BOOST_MSVC)
# pragma warning(pop)
#endif
#endif // BOOST_MATH_DIST_BETA_HPP
| mit |
JSMike/angular | modules/@angular/core/test/application_ref_spec.ts | 15130 | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {APP_BOOTSTRAP_LISTENER, APP_INITIALIZER, CompilerFactory, Component, NgModule, PlatformRef, TemplateRef, Type, ViewChild, ViewContainerRef} from '@angular/core';
import {ApplicationRef, ApplicationRef_} from '@angular/core/src/application_ref';
import {ErrorHandler} from '@angular/core/src/error_handler';
import {ComponentRef} from '@angular/core/src/linker/component_factory';
import {BrowserModule} from '@angular/platform-browser';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {DOCUMENT} from '@angular/platform-browser/src/dom/dom_tokens';
import {expect} from '@angular/platform-browser/testing/matchers';
import {ServerModule} from '@angular/platform-server';
import {ComponentFixtureNoNgZone, TestBed, async, inject, withModule} from '../testing';
@Component({selector: 'comp', template: 'hello'})
class SomeComponent {
}
export function main() {
describe('bootstrap', () => {
let mockConsole: MockConsole;
let fakeDoc: Document;
beforeEach(() => {
fakeDoc = getDOM().createHtmlDocument();
const el = getDOM().createElement('comp', fakeDoc);
getDOM().appendChild(fakeDoc.body, el);
mockConsole = new MockConsole();
});
type CreateModuleOptions = {providers?: any[], ngDoBootstrap?: any, bootstrap?: any[]};
function createModule(providers?: any[]): Type<any>;
function createModule(options: CreateModuleOptions): Type<any>;
function createModule(providersOrOptions: any[] | CreateModuleOptions): Type<any> {
let options: CreateModuleOptions = {};
if (providersOrOptions instanceof Array) {
options = {providers: providersOrOptions};
} else {
options = providersOrOptions || {};
}
const errorHandler = new ErrorHandler(false);
errorHandler._console = mockConsole as any;
const platformModule = getDOM().supportsDOMEvents() ? BrowserModule : ServerModule;
@NgModule({
providers: [
{provide: ErrorHandler, useValue: errorHandler}, {provide: DOCUMENT, useValue: fakeDoc},
options.providers || []
],
imports: [platformModule],
declarations: [SomeComponent],
entryComponents: [SomeComponent],
bootstrap: options.bootstrap || []
})
class MyModule {
}
if (options.ngDoBootstrap !== false) {
(<any>MyModule.prototype).ngDoBootstrap = options.ngDoBootstrap || (() => {});
}
return MyModule;
}
describe('ApplicationRef', () => {
beforeEach(() => { TestBed.configureTestingModule({imports: [createModule()]}); });
it('should throw when reentering tick', inject([ApplicationRef], (ref: ApplicationRef_) => {
const view = jasmine.createSpyObj('view', ['detach', 'attachToAppRef']);
const viewRef = jasmine.createSpyObj('viewRef', ['detectChanges']);
viewRef.internalView = view;
view.ref = viewRef;
try {
ref.attachView(viewRef);
viewRef.detectChanges.and.callFake(() => ref.tick());
expect(() => ref.tick()).toThrowError('ApplicationRef.tick is called recursively');
} finally {
ref.detachView(viewRef);
}
}));
describe('APP_BOOTSTRAP_LISTENER', () => {
let capturedCompRefs: ComponentRef<any>[];
beforeEach(() => {
capturedCompRefs = [];
TestBed.configureTestingModule({
providers: [{
provide: APP_BOOTSTRAP_LISTENER,
multi: true,
useValue: (compRef: any) => { capturedCompRefs.push(compRef); }
}]
});
});
it('should be called when a component is bootstrapped',
inject([ApplicationRef], (ref: ApplicationRef_) => {
const compRef = ref.bootstrap(SomeComponent);
expect(capturedCompRefs).toEqual([compRef]);
}));
});
describe('bootstrap', () => {
beforeEach(
() => {
});
it('should throw if an APP_INITIIALIZER is not yet resolved',
withModule(
{
providers: [
{provide: APP_INITIALIZER, useValue: () => new Promise(() => {}), multi: true}
]
},
inject([ApplicationRef], (ref: ApplicationRef_) => {
expect(() => ref.bootstrap(SomeComponent))
.toThrowError(
'Cannot bootstrap as there are still asynchronous initializers running. Bootstrap components in the `ngDoBootstrap` method of the root module.');
})));
});
});
describe('bootstrapModule', () => {
let defaultPlatform: PlatformRef;
beforeEach(
inject([PlatformRef], (_platform: PlatformRef) => { defaultPlatform = _platform; }));
it('should wait for asynchronous app initializers', async(() => {
let resolve: (result: any) => void;
const promise: Promise<any> = new Promise((res) => { resolve = res; });
let initializerDone = false;
setTimeout(() => {
resolve(true);
initializerDone = true;
}, 1);
defaultPlatform
.bootstrapModule(
createModule([{provide: APP_INITIALIZER, useValue: () => promise, multi: true}]))
.then(_ => { expect(initializerDone).toBe(true); });
}));
it('should rethrow sync errors even if the exceptionHandler is not rethrowing', async(() => {
defaultPlatform
.bootstrapModule(createModule(
[{provide: APP_INITIALIZER, useValue: () => { throw 'Test'; }, multi: true}]))
.then(() => expect(false).toBe(true), (e) => {
expect(e).toBe('Test');
// Note: if the modules throws an error during construction,
// we don't have an injector and therefore no way of
// getting the exception handler. So
// the error is only rethrown but not logged via the exception handler.
expect(mockConsole.res).toEqual([]);
});
}));
it('should rethrow promise errors even if the exceptionHandler is not rethrowing',
async(() => {
defaultPlatform
.bootstrapModule(createModule([
{provide: APP_INITIALIZER, useValue: () => Promise.reject('Test'), multi: true}
]))
.then(() => expect(false).toBe(true), (e) => {
expect(e).toBe('Test');
expect(mockConsole.res).toEqual(['EXCEPTION: Test']);
});
}));
it('should throw useful error when ApplicationRef is not configured', async(() => {
@NgModule()
class EmptyModule {
}
return defaultPlatform.bootstrapModule(EmptyModule)
.then(() => fail('expecting error'), (error) => {
expect(error.message)
.toEqual('No ErrorHandler. Is platform module (BrowserModule) included?');
});
}));
it('should call the `ngDoBootstrap` method with `ApplicationRef` on the main module',
async(() => {
const ngDoBootstrap = jasmine.createSpy('ngDoBootstrap');
defaultPlatform.bootstrapModule(createModule({ngDoBootstrap: ngDoBootstrap}))
.then((moduleRef) => {
const appRef = moduleRef.injector.get(ApplicationRef);
expect(ngDoBootstrap).toHaveBeenCalledWith(appRef);
});
}));
it('should auto bootstrap components listed in @NgModule.bootstrap', async(() => {
defaultPlatform.bootstrapModule(createModule({bootstrap: [SomeComponent]}))
.then((moduleRef) => {
const appRef: ApplicationRef = moduleRef.injector.get(ApplicationRef);
expect(appRef.componentTypes).toEqual([SomeComponent]);
});
}));
it('should error if neither `ngDoBootstrap` nor @NgModule.bootstrap was specified',
async(() => {
defaultPlatform.bootstrapModule(createModule({ngDoBootstrap: false}))
.then(() => expect(false).toBe(true), (e) => {
const expectedErrMsg =
`The module MyModule was bootstrapped, but it does not declare "@NgModule.bootstrap" components nor a "ngDoBootstrap" method. Please define one of these.`;
expect(e.message).toEqual(expectedErrMsg);
expect(mockConsole.res[0]).toEqual('EXCEPTION: ' + expectedErrMsg);
});
}));
});
describe('bootstrapModuleFactory', () => {
let defaultPlatform: PlatformRef;
beforeEach(
inject([PlatformRef], (_platform: PlatformRef) => { defaultPlatform = _platform; }));
it('should wait for asynchronous app initializers', async(() => {
let resolve: (result: any) => void;
const promise: Promise<any> = new Promise((res) => { resolve = res; });
let initializerDone = false;
setTimeout(() => {
resolve(true);
initializerDone = true;
}, 1);
const compilerFactory: CompilerFactory =
defaultPlatform.injector.get(CompilerFactory, null);
const moduleFactory = compilerFactory.createCompiler().compileModuleSync(
createModule([{provide: APP_INITIALIZER, useValue: () => promise, multi: true}]));
defaultPlatform.bootstrapModuleFactory(moduleFactory).then(_ => {
expect(initializerDone).toBe(true);
});
}));
it('should rethrow sync errors even if the exceptionHandler is not rethrowing', async(() => {
const compilerFactory: CompilerFactory =
defaultPlatform.injector.get(CompilerFactory, null);
const moduleFactory = compilerFactory.createCompiler().compileModuleSync(createModule(
[{provide: APP_INITIALIZER, useValue: () => { throw 'Test'; }, multi: true}]));
expect(() => defaultPlatform.bootstrapModuleFactory(moduleFactory)).toThrow('Test');
// Note: if the modules throws an error during construction,
// we don't have an injector and therefore no way of
// getting the exception handler. So
// the error is only rethrown but not logged via the exception handler.
expect(mockConsole.res).toEqual([]);
}));
it('should rethrow promise errors even if the exceptionHandler is not rethrowing',
async(() => {
const compilerFactory: CompilerFactory =
defaultPlatform.injector.get(CompilerFactory, null);
const moduleFactory = compilerFactory.createCompiler().compileModuleSync(createModule(
[{provide: APP_INITIALIZER, useValue: () => Promise.reject('Test'), multi: true}]));
defaultPlatform.bootstrapModuleFactory(moduleFactory)
.then(() => expect(false).toBe(true), (e) => {
expect(e).toBe('Test');
expect(mockConsole.res).toEqual(['EXCEPTION: Test']);
});
}));
});
describe('attachView / detachView', () => {
@Component({template: '{{name}}'})
class MyComp {
name = 'Initial';
}
@Component({template: '<ng-container #vc></ng-container>'})
class ContainerComp {
@ViewChild('vc', {read: ViewContainerRef})
vc: ViewContainerRef;
}
@Component({template: '<template #t>Dynamic content</template>'})
class EmbeddedViewComp {
@ViewChild(TemplateRef)
tplRef: TemplateRef<Object>;
}
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [MyComp, ContainerComp, EmbeddedViewComp],
providers: [{provide: ComponentFixtureNoNgZone, useValue: true}]
});
});
it('should dirty check attached views', () => {
const comp = TestBed.createComponent(MyComp);
const appRef: ApplicationRef = TestBed.get(ApplicationRef);
expect(appRef.viewCount).toBe(0);
appRef.tick();
expect(comp.nativeElement).toHaveText('');
appRef.attachView(comp.componentRef.hostView);
appRef.tick();
expect(appRef.viewCount).toBe(1);
expect(comp.nativeElement).toHaveText('Initial');
});
it('should not dirty check detached views', () => {
const comp = TestBed.createComponent(MyComp);
const appRef: ApplicationRef = TestBed.get(ApplicationRef);
appRef.attachView(comp.componentRef.hostView);
appRef.tick();
expect(comp.nativeElement).toHaveText('Initial');
appRef.detachView(comp.componentRef.hostView);
comp.componentInstance.name = 'New';
appRef.tick();
expect(appRef.viewCount).toBe(0);
expect(comp.nativeElement).toHaveText('Initial');
});
it('should detach attached views if they are destroyed', () => {
const comp = TestBed.createComponent(MyComp);
const appRef: ApplicationRef = TestBed.get(ApplicationRef);
appRef.attachView(comp.componentRef.hostView);
comp.destroy();
expect(appRef.viewCount).toBe(0);
});
it('should detach attached embedded views if they are destroyed', () => {
const comp = TestBed.createComponent(EmbeddedViewComp);
const appRef: ApplicationRef = TestBed.get(ApplicationRef);
const embeddedViewRef = comp.componentInstance.tplRef.createEmbeddedView({});
appRef.attachView(embeddedViewRef);
embeddedViewRef.destroy();
expect(appRef.viewCount).toBe(0);
});
it('should not allow to attach a view to both, a view container and the ApplicationRef',
() => {
const comp = TestBed.createComponent(MyComp);
const hostView = comp.componentRef.hostView;
const containerComp = TestBed.createComponent(ContainerComp);
containerComp.detectChanges();
const vc = containerComp.componentInstance.vc;
const appRef: ApplicationRef = TestBed.get(ApplicationRef);
vc.insert(hostView);
expect(() => appRef.attachView(hostView))
.toThrowError('This view is already attached to a ViewContainer!');
vc.detach(0);
appRef.attachView(hostView);
expect(() => vc.insert(hostView))
.toThrowError('This view is already attached directly to the ApplicationRef!');
});
});
});
}
@Component({selector: 'my-comp', template: ''})
class MyComp6 {
}
class MockConsole {
res: any[] = [];
log(s: any): void { this.res.push(s); }
error(s: any): void { this.res.push(s); }
}
| mit |
mlsnyder/developer-dot | public/code/blog/avatax-connector-app/AvaTaxConnector/Controllers/HomeController.cs | 1045 | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AvaTaxConnector.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
//ViewBag.Message = "AvaTax API V2";
return View();
}
public ActionResult Settings(string txtAccountNumber, string txtAPIKey)
{
if (string.IsNullOrEmpty(txtAccountNumber) || string.IsNullOrEmpty(txtAPIKey))
{
txtAccountNumber = ConfigurationManager.AppSettings["AccountNumber"];
txtAPIKey = ConfigurationManager.AppSettings["APIKey"];
}
else
{
ConfigurationManager.AppSettings["AccountNumber"] = txtAccountNumber;
ConfigurationManager.AppSettings["APIKey"] = txtAPIKey;
ViewBag.Message = "Settings saved.";
}
return View();
}
}
}
| mit |
tuka217/Sylius | src/Sylius/Bundle/ThemeBundle/Collector/ThemeCollector.php | 2528 | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Bundle\ThemeBundle\Collector;
use Sylius\Bundle\ThemeBundle\Context\ThemeContextInterface;
use Sylius\Bundle\ThemeBundle\HierarchyProvider\ThemeHierarchyProviderInterface;
use Sylius\Bundle\ThemeBundle\Model\ThemeInterface;
use Sylius\Bundle\ThemeBundle\Repository\ThemeRepositoryInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\DataCollector\DataCollector;
/**
* @author Kamil Kokot <[email protected]>
*/
class ThemeCollector extends DataCollector
{
/**
* @var ThemeRepositoryInterface
*/
private $themeRepository;
/**
* @var ThemeContextInterface
*/
private $themeContext;
/**
* @var ThemeHierarchyProviderInterface
*/
private $themeHierarchyProvider;
/**
* @param ThemeRepositoryInterface $themeRepository
* @param ThemeContextInterface $themeContext
* @param ThemeHierarchyProviderInterface $themeHierarchyProvider
*/
public function __construct(
ThemeRepositoryInterface $themeRepository,
ThemeContextInterface $themeContext,
ThemeHierarchyProviderInterface $themeHierarchyProvider
) {
$this->themeRepository = $themeRepository;
$this->themeContext = $themeContext;
$this->themeHierarchyProvider = $themeHierarchyProvider;
}
/**
* @return ThemeInterface
*/
public function getUsedTheme()
{
return $this->data['used_theme'];
}
/**
* @return ThemeInterface[]
*/
public function getUsedThemes()
{
return $this->data['used_themes'];
}
/**
* @return ThemeInterface[]
*/
public function getThemes()
{
return $this->data['themes'];
}
/**
* {@inheritdoc}
*/
public function collect(Request $request, Response $response, \Exception $exception = null)
{
$this->data['used_theme'] = $this->themeContext->getTheme();
$this->data['used_themes'] = $this->themeHierarchyProvider->getThemeHierarchy($this->themeContext->getTheme());
$this->data['themes'] = $this->themeRepository->findAll();
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'sylius_theme';
}
}
| mit |
Amritesh/three.js | src/textures/DataTexture2DArray.js | 714 | /**
* @author Takahiro https://github.com/takahirox
*/
import { Texture } from './Texture.js';
import { ClampToEdgeWrapping, NearestFilter } from '../constants.js';
function DataTexture2DArray( data, width, height, depth ) {
Texture.call( this, null );
this.image = { data: data, width: width, height: height, depth: depth };
this.magFilter = NearestFilter;
this.minFilter = NearestFilter;
this.wrapR = ClampToEdgeWrapping;
this.generateMipmaps = false;
this.flipY = false;
}
DataTexture2DArray.prototype = Object.create( Texture.prototype );
DataTexture2DArray.prototype.constructor = DataTexture2DArray;
DataTexture2DArray.prototype.isDataTexture2DArray = true;
export { DataTexture2DArray };
| mit |
Duoxilian/home-assistant | tests/components/tts/test_voicerss.py | 7340 | """The tests for the VoiceRSS speech platform."""
import asyncio
import os
import shutil
import homeassistant.components.tts as tts
from homeassistant.components.media_player import (
SERVICE_PLAY_MEDIA, ATTR_MEDIA_CONTENT_ID, DOMAIN as DOMAIN_MP)
from homeassistant.bootstrap import setup_component
from tests.common import (
get_test_home_assistant, assert_setup_component, mock_service)
class TestTTSVoiceRSSPlatform(object):
"""Test the voicerss speech component."""
def setup_method(self):
"""Setup things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.url = "https://api.voicerss.org/"
self.form_data = {
'key': '1234567xx',
'hl': 'en-us',
'c': 'MP3',
'f': '8khz_8bit_mono',
'src': "I person is on front of your door.",
}
def teardown_method(self):
"""Stop everything that was started."""
default_tts = self.hass.config.path(tts.DEFAULT_CACHE_DIR)
if os.path.isdir(default_tts):
shutil.rmtree(default_tts)
self.hass.stop()
def test_setup_component(self):
"""Test setup component."""
config = {
tts.DOMAIN: {
'platform': 'voicerss',
'api_key': '1234567xx'
}
}
with assert_setup_component(1, tts.DOMAIN):
setup_component(self.hass, tts.DOMAIN, config)
def test_setup_component_without_api_key(self):
"""Test setup component without api key."""
config = {
tts.DOMAIN: {
'platform': 'voicerss',
}
}
with assert_setup_component(0, tts.DOMAIN):
setup_component(self.hass, tts.DOMAIN, config)
def test_service_say(self, aioclient_mock):
"""Test service call say."""
calls = mock_service(self.hass, DOMAIN_MP, SERVICE_PLAY_MEDIA)
aioclient_mock.post(
self.url, data=self.form_data, status=200, content=b'test')
config = {
tts.DOMAIN: {
'platform': 'voicerss',
'api_key': '1234567xx',
}
}
with assert_setup_component(1, tts.DOMAIN):
setup_component(self.hass, tts.DOMAIN, config)
self.hass.services.call(tts.DOMAIN, 'voicerss_say', {
tts.ATTR_MESSAGE: "I person is on front of your door.",
})
self.hass.block_till_done()
assert len(calls) == 1
assert len(aioclient_mock.mock_calls) == 1
assert aioclient_mock.mock_calls[0][2] == self.form_data
assert calls[0].data[ATTR_MEDIA_CONTENT_ID].find(".mp3") != -1
def test_service_say_german_config(self, aioclient_mock):
"""Test service call say with german code in the config."""
calls = mock_service(self.hass, DOMAIN_MP, SERVICE_PLAY_MEDIA)
self.form_data['hl'] = 'de-de'
aioclient_mock.post(
self.url, data=self.form_data, status=200, content=b'test')
config = {
tts.DOMAIN: {
'platform': 'voicerss',
'api_key': '1234567xx',
'language': 'de-de',
}
}
with assert_setup_component(1, tts.DOMAIN):
setup_component(self.hass, tts.DOMAIN, config)
self.hass.services.call(tts.DOMAIN, 'voicerss_say', {
tts.ATTR_MESSAGE: "I person is on front of your door.",
})
self.hass.block_till_done()
assert len(calls) == 1
assert len(aioclient_mock.mock_calls) == 1
assert aioclient_mock.mock_calls[0][2] == self.form_data
def test_service_say_german_service(self, aioclient_mock):
"""Test service call say with german code in the service."""
calls = mock_service(self.hass, DOMAIN_MP, SERVICE_PLAY_MEDIA)
self.form_data['hl'] = 'de-de'
aioclient_mock.post(
self.url, data=self.form_data, status=200, content=b'test')
config = {
tts.DOMAIN: {
'platform': 'voicerss',
'api_key': '1234567xx',
}
}
with assert_setup_component(1, tts.DOMAIN):
setup_component(self.hass, tts.DOMAIN, config)
self.hass.services.call(tts.DOMAIN, 'voicerss_say', {
tts.ATTR_MESSAGE: "I person is on front of your door.",
tts.ATTR_LANGUAGE: "de-de"
})
self.hass.block_till_done()
assert len(calls) == 1
assert len(aioclient_mock.mock_calls) == 1
assert aioclient_mock.mock_calls[0][2] == self.form_data
def test_service_say_error(self, aioclient_mock):
"""Test service call say with http response 400."""
calls = mock_service(self.hass, DOMAIN_MP, SERVICE_PLAY_MEDIA)
aioclient_mock.post(
self.url, data=self.form_data, status=400, content=b'test')
config = {
tts.DOMAIN: {
'platform': 'voicerss',
'api_key': '1234567xx',
}
}
with assert_setup_component(1, tts.DOMAIN):
setup_component(self.hass, tts.DOMAIN, config)
self.hass.services.call(tts.DOMAIN, 'voicerss_say', {
tts.ATTR_MESSAGE: "I person is on front of your door.",
})
self.hass.block_till_done()
assert len(calls) == 0
assert len(aioclient_mock.mock_calls) == 1
assert aioclient_mock.mock_calls[0][2] == self.form_data
def test_service_say_timeout(self, aioclient_mock):
"""Test service call say with http timeout."""
calls = mock_service(self.hass, DOMAIN_MP, SERVICE_PLAY_MEDIA)
aioclient_mock.post(
self.url, data=self.form_data, exc=asyncio.TimeoutError())
config = {
tts.DOMAIN: {
'platform': 'voicerss',
'api_key': '1234567xx',
}
}
with assert_setup_component(1, tts.DOMAIN):
setup_component(self.hass, tts.DOMAIN, config)
self.hass.services.call(tts.DOMAIN, 'voicerss_say', {
tts.ATTR_MESSAGE: "I person is on front of your door.",
})
self.hass.block_till_done()
assert len(calls) == 0
assert len(aioclient_mock.mock_calls) == 1
assert aioclient_mock.mock_calls[0][2] == self.form_data
def test_service_say_error_msg(self, aioclient_mock):
"""Test service call say with http error api message."""
calls = mock_service(self.hass, DOMAIN_MP, SERVICE_PLAY_MEDIA)
aioclient_mock.post(
self.url, data=self.form_data, status=200,
content=b'The subscription does not support SSML!'
)
config = {
tts.DOMAIN: {
'platform': 'voicerss',
'api_key': '1234567xx',
}
}
with assert_setup_component(1, tts.DOMAIN):
setup_component(self.hass, tts.DOMAIN, config)
self.hass.services.call(tts.DOMAIN, 'voicerss_say', {
tts.ATTR_MESSAGE: "I person is on front of your door.",
})
self.hass.block_till_done()
assert len(calls) == 0
assert len(aioclient_mock.mock_calls) == 1
assert aioclient_mock.mock_calls[0][2] == self.form_data
| mit |
r22016/azure-sdk-for-net | src/Batch/Client/Tests/ObjectModel/Azure.Batch.Unit.Tests/OptionsUnitTests.cs | 3223 | // Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Azure.Batch.Unit.Tests
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BatchTestCommon;
using Xunit;
using Protocol=Microsoft.Azure.Batch.Protocol;
public class OptionsUnitTests
{
[Fact]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.VeryShortDuration)]
public void TestOptionsDontMissODataParameters()
{
Type selectedModelType = typeof (Protocol.Models.CertificateAddOptions);
IEnumerable<Type> optionsTypes = selectedModelType.Assembly.GetTypes().Where(t =>
t.Namespace == selectedModelType.Namespace &&
t.Name.EndsWith("Options") &&
!t.Name.Equals("ExitOptions"));
Assert.NotEmpty(optionsTypes);
int filterCount = 0;
int selectCount = 0;
int expandCount = 0;
int timeoutCount = 0;
foreach (Type optionsType in optionsTypes)
{
Assert.True(typeof(Protocol.Models.IOptions).IsAssignableFrom(optionsType), string.Format("type {0} missing IOptions", optionsType));
if (optionsType.GetProperty("Filter") != null)
{
++filterCount;
Assert.True(typeof(Protocol.Models.IODataFilter).IsAssignableFrom(optionsType), string.Format("type {0} missing filter", optionsType));
}
if (optionsType.GetProperty("Select") != null)
{
++selectCount;
Assert.True(typeof(Protocol.Models.IODataSelect).IsAssignableFrom(optionsType), string.Format("type {0} missing select", optionsType));
}
if (optionsType.GetProperty("Expand") != null)
{
++expandCount;
Assert.True(typeof(Protocol.Models.IODataExpand).IsAssignableFrom(optionsType), string.Format("type {0} missing expand", optionsType));
}
if (optionsType.GetProperty("Timeout") != null)
{
++timeoutCount;
Assert.True(typeof(Protocol.Models.ITimeoutOptions).IsAssignableFrom(optionsType), string.Format("type {0} missing timeout", optionsType));
}
}
Assert.NotEqual(0, filterCount);
Assert.NotEqual(0, selectCount);
Assert.NotEqual(0, expandCount);
Assert.NotEqual(0, timeoutCount);
}
}
}
| mit |
beanworks/doctrine2 | tests/Doctrine/Tests/ORM/Functional/Ticket/DDC425Test.php | 1017 | <?php
namespace Doctrine\Tests\ORM\Functional\Ticket;
use DateTime, Doctrine\DBAL\Types\Type;
class DDC425Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp()
{
parent::setUp();
$this->_schemaTool->createSchema(
[
$this->_em->getClassMetadata(DDC425Entity::class),
]
);
}
/**
* @group DDC-425
*/
public function testIssue()
{
//$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger);
$num = $this->_em->createQuery('DELETE '.__NAMESPACE__.'\DDC425Entity e WHERE e.someDatetimeField > ?1')
->setParameter(1, new DateTime, Type::DATETIME)
->getResult();
$this->assertEquals(0, $num);
}
}
/** @Entity */
class DDC425Entity {
/**
* @Id @Column(type="integer")
* @GeneratedValue
*/
public $id;
/** @Column(type="datetime") */
public $someDatetimeField;
}
| mit |
symfony/symfony | src/Symfony/Bridge/Twig/Translation/TwigExtractor.php | 2615 | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bridge\Twig\Translation;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Translation\Extractor\AbstractFileExtractor;
use Symfony\Component\Translation\Extractor\ExtractorInterface;
use Symfony\Component\Translation\MessageCatalogue;
use Twig\Environment;
use Twig\Error\Error;
use Twig\Source;
/**
* TwigExtractor extracts translation messages from a twig template.
*
* @author Michel Salib <[email protected]>
* @author Fabien Potencier <[email protected]>
*/
class TwigExtractor extends AbstractFileExtractor implements ExtractorInterface
{
/**
* Default domain for found messages.
*/
private string $defaultDomain = 'messages';
/**
* Prefix for found message.
*/
private string $prefix = '';
private Environment $twig;
public function __construct(Environment $twig)
{
$this->twig = $twig;
}
/**
* {@inheritdoc}
*/
public function extract($resource, MessageCatalogue $catalogue)
{
foreach ($this->extractFiles($resource) as $file) {
try {
$this->extractTemplate(file_get_contents($file->getPathname()), $catalogue);
} catch (Error $e) {
// ignore errors, these should be fixed by using the linter
}
}
}
/**
* {@inheritdoc}
*/
public function setPrefix(string $prefix)
{
$this->prefix = $prefix;
}
protected function extractTemplate(string $template, MessageCatalogue $catalogue)
{
$visitor = $this->twig->getExtension('Symfony\Bridge\Twig\Extension\TranslationExtension')->getTranslationNodeVisitor();
$visitor->enable();
$this->twig->parse($this->twig->tokenize(new Source($template, '')));
foreach ($visitor->getMessages() as $message) {
$catalogue->set(trim($message[0]), $this->prefix.trim($message[0]), $message[1] ?: $this->defaultDomain);
}
$visitor->disable();
}
protected function canBeExtracted(string $file): bool
{
return $this->isFile($file) && 'twig' === pathinfo($file, \PATHINFO_EXTENSION);
}
/**
* {@inheritdoc}
*/
protected function extractFromDirectory($directory): iterable
{
$finder = new Finder();
return $finder->files()->name('*.twig')->in($directory);
}
}
| mit |
redheli/three.js | src/audio/Audio.js | 4420 | /**
* @author mrdoob / http://mrdoob.com/
* @author Reece Aaron Lecrivain / http://reecenotes.com/
*/
THREE.Audio = function ( listener ) {
THREE.Object3D.call( this );
this.type = 'Audio';
this.context = listener.context;
this.source = this.context.createBufferSource();
this.source.onended = this.onEnded.bind( this );
this.gain = this.context.createGain();
this.gain.connect( listener.getInput() );
this.autoplay = false;
this.startTime = 0;
this.playbackRate = 1;
this.isPlaying = false;
this.hasPlaybackControl = true;
this.sourceType = 'empty';
this.filters = [];
};
THREE.Audio.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), {
constructor: THREE.Audio,
getOutput: function () {
return this.gain;
},
setNodeSource: function ( audioNode ) {
this.hasPlaybackControl = false;
this.sourceType = 'audioNode';
this.source = audioNode;
this.connect();
return this;
},
setBuffer: function ( audioBuffer ) {
this.source.buffer = audioBuffer;
this.sourceType = 'buffer';
if ( this.autoplay ) this.play();
return this;
},
play: function () {
if ( this.isPlaying === true ) {
console.warn( 'THREE.Audio: Audio is already playing.' );
return;
}
if ( this.hasPlaybackControl === false ) {
console.warn( 'THREE.Audio: this Audio has no playback control.' );
return;
}
var source = this.context.createBufferSource();
source.buffer = this.source.buffer;
source.loop = this.source.loop;
source.onended = this.source.onended;
source.start( 0, this.startTime );
source.playbackRate.value = this.playbackRate;
this.isPlaying = true;
this.source = source;
return this.connect();
},
pause: function () {
if ( this.hasPlaybackControl === false ) {
console.warn( 'THREE.Audio: this Audio has no playback control.' );
return;
}
this.source.stop();
this.startTime = this.context.currentTime;
return this;
},
stop: function () {
if ( this.hasPlaybackControl === false ) {
console.warn( 'THREE.Audio: this Audio has no playback control.' );
return;
}
this.source.stop();
this.startTime = 0;
return this;
},
connect: function () {
if ( this.filters.length > 0 ) {
this.source.connect( this.filters[ 0 ] );
for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
this.filters[ i - 1 ].connect( this.filters[ i ] );
}
this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
} else {
this.source.connect( this.getOutput() );
}
return this;
},
disconnect: function () {
if ( this.filters.length > 0 ) {
this.source.disconnect( this.filters[ 0 ] );
for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
this.filters[ i - 1 ].disconnect( this.filters[ i ] );
}
this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
} else {
this.source.disconnect( this.getOutput() );
}
return this;
},
getFilters: function () {
return this.filters;
},
setFilters: function ( value ) {
if ( ! value ) value = [];
if ( this.isPlaying === true ) {
this.disconnect();
this.filters = value;
this.connect();
} else {
this.filters = value;
}
return this;
},
getFilter: function () {
return this.getFilters()[ 0 ];
},
setFilter: function ( filter ) {
return this.setFilters( filter ? [ filter ] : [] );
},
setPlaybackRate: function ( value ) {
if ( this.hasPlaybackControl === false ) {
console.warn( 'THREE.Audio: this Audio has no playback control.' );
return;
}
this.playbackRate = value;
if ( this.isPlaying === true ) {
this.source.playbackRate.value = this.playbackRate;
}
return this;
},
getPlaybackRate: function () {
return this.playbackRate;
},
onEnded: function () {
this.isPlaying = false;
},
getLoop: function () {
if ( this.hasPlaybackControl === false ) {
console.warn( 'THREE.Audio: this Audio has no playback control.' );
return false;
}
return this.source.loop;
},
setLoop: function ( value ) {
if ( this.hasPlaybackControl === false ) {
console.warn( 'THREE.Audio: this Audio has no playback control.' );
return;
}
this.source.loop = value;
},
getVolume: function () {
return this.gain.gain.value;
},
setVolume: function ( value ) {
this.gain.gain.value = value;
return this;
}
} );
| mit |
kentcdodds/eslint | tests/lib/config/config-rule.js | 11740 | /**
* @fileoverview Tests for ConfigOps
* @author Ian VanSchooten
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const assert = require("chai").assert,
ConfigRule = require("../../../lib/config/config-rule"),
loadRules = require("../../../lib/load-rules"),
schema = require("../../fixtures/config-rule/schemas");
//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------
const SEVERITY = 2;
describe("ConfigRule", () => {
describe("generateConfigsFromSchema()", () => {
let actualConfigs;
it("should create a config with only severity for an empty schema", () => {
actualConfigs = ConfigRule.generateConfigsFromSchema([]);
assert.deepEqual(actualConfigs, [SEVERITY]);
});
it("should create a config with only severity with no arguments", () => {
actualConfigs = ConfigRule.generateConfigsFromSchema();
assert.deepEqual(actualConfigs, [SEVERITY]);
});
describe("for a single enum schema", () => {
before(() => {
actualConfigs = ConfigRule.generateConfigsFromSchema(schema.enum);
});
it("should create an array of configs", () => {
assert.isArray(actualConfigs);
assert.equal(actualConfigs.length, 3);
});
it("should include the error severity (2) without options as the first config", () => {
assert.equal(actualConfigs[0], SEVERITY);
});
it("should set all configs to error severity (2)", () => {
actualConfigs.forEach(actualConfig => {
if (Array.isArray(actualConfig)) {
assert.equal(actualConfig[0], SEVERITY);
}
});
});
it("should return configs with each enumerated value in the schema", () => {
assert.sameDeepMembers(actualConfigs, [SEVERITY, [SEVERITY, "always"], [SEVERITY, "never"]]);
});
});
describe("for a object schema with a single enum property", () => {
before(() => {
actualConfigs = ConfigRule.generateConfigsFromSchema(schema.objectWithEnum);
});
it("should return configs with option objects", () => {
// Skip first config (severity only)
actualConfigs.slice(1).forEach(actualConfig => {
const actualConfigOption = actualConfig[1]; // severity is first element, option is second
assert.isObject(actualConfigOption);
});
});
it("should use the object property name from the schema", () => {
const propName = "enumProperty";
assert.equal(actualConfigs.length, 3);
actualConfigs.slice(1).forEach(actualConfig => {
const actualConfigOption = actualConfig[1];
assert.property(actualConfigOption, propName);
});
});
it("should have each enum as option object values", () => {
const propName = "enumProperty",
actualValues = [];
actualConfigs.slice(1).forEach(actualConfig => {
const configOption = actualConfig[1];
actualValues.push(configOption[propName]);
});
assert.sameMembers(actualValues, ["always", "never"]);
});
});
describe("for a object schema with a multiple enum properties", () => {
before(() => {
actualConfigs = ConfigRule.generateConfigsFromSchema(schema.objectWithMultipleEnums);
});
it("should create configs for all properties in each config", () => {
const expectedProperties = ["firstEnum", "anotherEnum"];
assert.equal(actualConfigs.length, 7);
actualConfigs.slice(1).forEach(actualConfig => {
const configOption = actualConfig[1];
const actualProperties = Object.keys(configOption);
assert.sameMembers(actualProperties, expectedProperties);
});
});
it("should create configs for every possible combination", () => {
const expectedConfigs = [
{ firstEnum: "always", anotherEnum: "var" },
{ firstEnum: "always", anotherEnum: "let" },
{ firstEnum: "always", anotherEnum: "const" },
{ firstEnum: "never", anotherEnum: "var" },
{ firstEnum: "never", anotherEnum: "let" },
{ firstEnum: "never", anotherEnum: "const" }
];
const actualConfigOptions = actualConfigs.slice(1).map(actualConfig => actualConfig[1]);
assert.sameDeepMembers(actualConfigOptions, expectedConfigs);
});
});
describe("for a object schema with a single boolean property", () => {
before(() => {
actualConfigs = ConfigRule.generateConfigsFromSchema(schema.objectWithBool);
});
it("should return configs with option objects", () => {
assert.equal(actualConfigs.length, 3);
actualConfigs.slice(1).forEach(actualConfig => {
const actualConfigOption = actualConfig[1];
assert.isObject(actualConfigOption);
});
});
it("should use the object property name from the schema", () => {
const propName = "boolProperty";
assert.equal(actualConfigs.length, 3);
actualConfigs.slice(1).forEach(actualConfig => {
const actualConfigOption = actualConfig[1];
assert.property(actualConfigOption, propName);
});
});
it("should include both true and false configs", () => {
const propName = "boolProperty",
actualValues = [];
actualConfigs.slice(1).forEach(actualConfig => {
const configOption = actualConfig[1];
actualValues.push(configOption[propName]);
});
assert.sameMembers(actualValues, [true, false]);
});
});
describe("for a object schema with a multiple bool properties", () => {
before(() => {
actualConfigs = ConfigRule.generateConfigsFromSchema(schema.objectWithMultipleBools);
});
it("should create configs for all properties in each config", () => {
const expectedProperties = ["firstBool", "anotherBool"];
assert.equal(actualConfigs.length, 5);
actualConfigs.slice(1).forEach(config => {
const configOption = config[1];
const actualProperties = Object.keys(configOption);
assert.sameMembers(actualProperties, expectedProperties);
});
});
it("should create configs for every possible combination", () => {
const expectedConfigOptions = [
{ firstBool: true, anotherBool: true },
{ firstBool: true, anotherBool: false },
{ firstBool: false, anotherBool: true },
{ firstBool: false, anotherBool: false }
];
const actualConfigOptions = actualConfigs.slice(1).map(config => config[1]);
assert.sameDeepMembers(actualConfigOptions, expectedConfigOptions);
});
});
describe("for a schema with an enum and an object", () => {
before(() => {
actualConfigs = ConfigRule.generateConfigsFromSchema(schema.mixedEnumObject);
});
it("should create configs with only the enum values", () => {
assert.equal(actualConfigs[1].length, 2);
assert.equal(actualConfigs[2].length, 2);
const actualOptions = [actualConfigs[1][1], actualConfigs[2][1]];
assert.sameMembers(actualOptions, ["always", "never"]);
});
it("should create configs with a string and an object", () => {
assert.equal(actualConfigs.length, 7);
actualConfigs.slice(3).forEach(config => {
assert.isString(config[1]);
assert.isObject(config[2]);
});
});
});
describe("for a schema with an enum followed by an object with no usable properties", () => {
before(() => {
actualConfigs = ConfigRule.generateConfigsFromSchema(schema.mixedEnumObjectWithNothing);
});
it("should create config only for the enum", () => {
const expectedConfigs = [2, [2, "always"], [2, "never"]];
assert.sameDeepMembers(actualConfigs, expectedConfigs);
});
});
describe("for a schema with an enum preceded by an object with no usable properties", () => {
before(() => {
actualConfigs = ConfigRule.generateConfigsFromSchema(schema.mixedObjectWithNothingEnum);
});
it("should not create a config for the enum", () => {
const expectedConfigs = [2];
assert.sameDeepMembers(actualConfigs, expectedConfigs);
});
});
describe("for a schema with an enum preceded by a string", () => {
before(() => {
actualConfigs = ConfigRule.generateConfigsFromSchema(schema.mixedStringEnum);
});
it("should not create a config for the enum", () => {
const expectedConfigs = [2];
assert.sameDeepMembers(actualConfigs, expectedConfigs);
});
});
describe("for a schema with oneOf", () => {
before(() => {
actualConfigs = ConfigRule.generateConfigsFromSchema(schema.oneOf);
});
it("should create a set of configs", () => {
assert.isArray(actualConfigs);
});
});
describe("for a schema with nested objects", () => {
before(() => {
actualConfigs = ConfigRule.generateConfigsFromSchema(schema.nestedObjects);
});
it("should create a set of configs", () => {
assert.isArray(actualConfigs);
});
});
});
describe("createCoreRuleConfigs()", () => {
const rulesConfig = ConfigRule.createCoreRuleConfigs();
it("should create a rulesConfig containing all core rules", () => {
const coreRules = loadRules(),
expectedRules = Object.keys(coreRules),
actualRules = Object.keys(rulesConfig);
assert.sameMembers(actualRules, expectedRules);
});
it("should create arrays of configs for rules", () => {
assert.isArray(rulesConfig.quotes);
assert.include(rulesConfig.quotes, 2);
});
it("should create configs for rules with meta", () => {
assert(rulesConfig["accessor-pairs"].length > 1);
});
});
});
| mit |
ro0NL/symfony | src/Symfony/Component/OptionsResolver/Debug/OptionsResolverIntrospector.php | 3183 | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\OptionsResolver\Debug;
use Symfony\Component\OptionsResolver\Exception\NoConfigurationException;
use Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* @author Maxime Steinhausser <[email protected]>
*
* @final
*/
class OptionsResolverIntrospector
{
private $get;
public function __construct(OptionsResolver $optionsResolver)
{
$this->get = \Closure::bind(function ($property, $option, $message) {
/** @var OptionsResolver $this */
if (!$this->isDefined($option)) {
throw new UndefinedOptionsException(sprintf('The option "%s" does not exist.', $option));
}
if (!\array_key_exists($option, $this->{$property})) {
throw new NoConfigurationException($message);
}
return $this->{$property}[$option];
}, $optionsResolver, $optionsResolver);
}
/**
* @throws NoConfigurationException on no configured value
*/
public function getDefault(string $option): mixed
{
return ($this->get)('defaults', $option, sprintf('No default value was set for the "%s" option.', $option));
}
/**
* @return \Closure[]
*
* @throws NoConfigurationException on no configured closures
*/
public function getLazyClosures(string $option): array
{
return ($this->get)('lazy', $option, sprintf('No lazy closures were set for the "%s" option.', $option));
}
/**
* @return string[]
*
* @throws NoConfigurationException on no configured types
*/
public function getAllowedTypes(string $option): array
{
return ($this->get)('allowedTypes', $option, sprintf('No allowed types were set for the "%s" option.', $option));
}
/**
* @return mixed[]
*
* @throws NoConfigurationException on no configured values
*/
public function getAllowedValues(string $option): array
{
return ($this->get)('allowedValues', $option, sprintf('No allowed values were set for the "%s" option.', $option));
}
/**
* @throws NoConfigurationException on no configured normalizer
*/
public function getNormalizer(string $option): \Closure
{
return current($this->getNormalizers($option));
}
/**
* @throws NoConfigurationException when no normalizer is configured
*/
public function getNormalizers(string $option): array
{
return ($this->get)('normalizers', $option, sprintf('No normalizer was set for the "%s" option.', $option));
}
/**
* @throws NoConfigurationException on no configured deprecation
*/
public function getDeprecation(string $option): array
{
return ($this->get)('deprecated', $option, sprintf('No deprecation was set for the "%s" option.', $option));
}
}
| mit |
HasanSa/hackathon | node_modules/eslint-config-airbnb/rules/es6.js | 1697 | module.exports = {
'env': {
'es6': false
},
'ecmaFeatures': {
'arrowFunctions': true,
'blockBindings': true,
'classes': true,
'defaultParams': true,
'destructuring': true,
'forOf': true,
'generators': false,
'modules': true,
'objectLiteralComputedProperties': true,
'objectLiteralDuplicateProperties': false,
'objectLiteralShorthandMethods': true,
'objectLiteralShorthandProperties': true,
'spread': true,
'superInFunctions': true,
'templateStrings': true,
'jsx': true
},
'rules': {
// require parens in arrow function arguments
'arrow-parens': 0,
// require space before/after arrow function's arrow
'arrow-spacing': 0,
// verify super() callings in constructors
'constructor-super': 0,
// enforce the spacing around the * in generator functions
'generator-star-spacing': 0,
// disallow modifying variables of class declarations
'no-class-assign': 0,
// disallow modifying variables that are declared using const
'no-const-assign': 0,
// disallow to use this/super before super() calling in constructors.
'no-this-before-super': 0,
// require let or const instead of var
'no-var': 2,
// require method and property shorthand syntax for object literals
'object-shorthand': 0,
// suggest using of const declaration for variables that are never modified after declared
'prefer-const': 2,
// suggest using the spread operator instead of .apply()
'prefer-spread': 0,
// suggest using Reflect methods where applicable
'prefer-reflect': 0,
// disallow generator functions that do not have yield
'require-yield': 0
}
};
| mit |
snaewe/vboxweb | languages/fr_fr.py | 27370 | """
French / France language file
$Id$
"""
trans = {
# General actions
'File' : 'Fichier',
'Edit' : 'Modifier',
'Save' : 'Enregistrer',
'OK' : 'OK',
'Cancel' : 'Annuler',
'Create' : 'Créer',
'Select' : 'Séléctionner',
'Up' : 'Haut',
'Down' : 'Bas',
'Yes' : 'Oui',
'No' : 'Non',
'Close' : 'Fermer',
'Any' : 'Quelconque',
'New' : 'Créer',
'Delete' : 'Supprimer',
'Keep' : 'Conserver',
'Settings' : 'Configuration',
'Preferences' : 'Préférences',
'Refresh' : 'Actualiser',
'Start' : 'Démarrer',
'Power Off' : 'Extinction',
'Details' : 'Détails',
'Console' : 'Console',
'Description' : 'Description',
'Configuration' : 'Configuration',
'Operating System' : 'Système d\'exploitation',
'Machine' : 'Machine',
'Enabled' : 'Activer',
'Disabled' : 'Désactiver',
'Hosting' : 'Hébergeur',
'Basic' : 'Simple',
'Advanced' : 'Avancé',
'None' : 'Aucun',
'Help' : 'Aide',
'About' : 'A propos',
'Version' : 'Version',
'VirtualBox User Manual' : 'Manuel utilisateur de VirtualBox',
'Operation Canceled' : 'Opération annulée',
'Next' : 'Suivant',
'Back' : 'Précédent',
'Finish' : 'Terminer',
'Select File' : 'Sélectionner un fichier',
'Select Folder' : 'Sélectionner un dossier',
# Power button
'Pause' : 'Pause',
'Reset' : 'Redémarrer',
'Save State' : 'Enregistrer l\'état',
'ACPI Power Button' : 'ACPI Power Boutton',
'ACPI Sleep Button' : 'ACPI Sleep Boutton',
'ACPI event not handled' : 'L\'événement ACPI n\'a pas été traité par la machine virtuelle.',
'Approx X remaining' : '%s restant(es)', """ %s will be replaced with a time. E.g. Approx 2 minutes, 4 seconds remaining """
'X ago' : 'il y as %s', """ %s will be replaced with a time. E.g. 20 hours ago """
'minutes' : 'minutes',
'seconds' : 'secondes',
'hours' : 'heures',
'days' : 'jours',
""" Snapshots """
'Snapshots' : 'Instantanés',
'Snapshot Folder' : 'Dossier des instantanés',
'Current State' : 'État actuel',
'Restore' : 'Restaurer',
'Restore Snapshot' : 'Restaurer un instantané',
'Take Snapshot' : 'Prendre un instantané',
'Delete Snapshot' : 'Supprimer un instantané',
'Snapshot Details' : 'Afficher les détails',
'Snapshot Name' : 'Nom de l\'instantané',
'Snapshot Description' : 'Description de l\'instantané',
'Restore Snapshot Message' : 'Êtes-vous sûr de vouloir restaurer l\'instantané %s? Vous perdrez définitivement l\'état actuel de votre machine.',
'Delete Snapshot Message1' : 'Supprimer cet instantané entrainera la perte de toutes les informations d\'état qui y sont sauvegardées, et la fusion des données de disques virtuels répartis sur plusieurs fichiers en un seul. Ce processus peut durer longtemps et est irréversible.',
'Delete Snapshot Message2' : 'Voulez-vous vraiment effacer l\'instantané %s?',
'Taken' : 'Prise',
'changed' : 'modifier',
""" Discard State """
'Discard' : 'Oublier',
'Discard Message1' : 'Êtes-vous sûr de vouloir oublier l\'état sauvegardé pour la machine virtuelle %s?', # %s willl be replaced with VM name
'Discard Message2' : 'Ceci revient à redémarrer l\'ordinateur virtuel sans que son système d\'exploitation ne s\'éteigne proprement.',
""" Delete or Unregister Inaccessible Machine """
'VM Inaccessible' : 'La VM sélectionnée est inaccessible. Prenez en compte le message d\'erreur ci-dessous et appuyez sur le bouton Actualiser si vous voulez répéter la vérification de l\'accessibilité.',
'Delete VM Message1' : 'Voulez-vous vraiment supprimer la machine virtuelle %s?',
'Delete VM Message2' : 'Cette opération est irréversible.',
'Unregister VM Message1' : 'Êtes-vous sûr de vouloir supprimer la machine virtuelle inaccessible %s?',
'Unregister VM Message2' : 'Vous ne pourrez pas l\'enregistrer à nouveau dans l\'interface graphique.',
'Unregister' : 'Libérer',
""" Error fetching machines """
'Error vmlist 1' : 'Une erreur est survenue lors de la récupération de la liste des machines virtuelles enregistrées à partir de VirtualBox. Assurez-vous que vboxwebsrv est lancé et que les paramètres du fichier config.php sont corrects.',
'Error vmlist 2' : 'La liste des machines virtuelles ne sera plus rafraichi automatiquement jusqu\'à ce que cette page soit rechargée.',
""" Properties """
'host' : 'Hôte VirtualBox',
'Port' : 'Port',
'General' : 'Général',
'Name' : 'Nom',
'OS Type' : 'Type OS',
""" Options in Preferences / Global Settings """
'Default Hard Disk Folder' : 'Dossier par défaut des disques durs',
'Default Machine Folder' : 'Dossiers par défaut des machines',
'VRDP Authentication Library' : 'Authentication VRDP par défaut',
'Add host-only network' : 'Ajouter réseau privé hôte',
'Remove host-only network' : 'Supprimer réseau privé hôte',
'Edit host-only network' : 'Modifier réseau privé hôte',
'Host-only Network Details' : 'Détails réseau privé hôte',
'Host-only Networks' : 'Réseau privé hôte',
'IPv4Mask' : 'Masque réseau IPv4',
'IPv6Mask' : 'Longueur du masque réseau IPv6',
'Server Address' : 'Adresse du serveur',
'Server Mask' : 'Masque du serveur',
'Lower Address Bound' : 'Limite inférieure des addresses',
'Upper Address Bound' : 'Limite supérieure des addresses',
'DHCP Server' : 'Serveur DHCP',
'DHCP enabled' : 'DHCP activée',
'Manually configured' : 'Configuration manuelle',
'Delete Interface Message1' : 'Si vous enlevez ce réseau privé hôte, l\'interface correspondante de la machine hôte sera également enlevée. Voulez-vous vraiment enlever cette interface %s?',
'Delete Interface Message2' : 'Note : cette interface est peut-être utilisée par d\'autres machines virtuelles. Si vous l\'enlevez, ces interfaces ne seront plus utilisables jusqu\'à ce que vous modifiez leur configuration en choisissant un autre réseau privé hôte ou un autre mode d\'accès.',
'System' : 'Système',
'Base Memory' : 'Mémoire vive',
'Memory' : 'Mémoire',
'free' : 'libre', # as in free/available memory
'Enable IO APIC' : 'Activer les IO APIC',
'Enable EFI' : 'Activer EFI (OS spéciaux seulement)',
'Hardware clock in UTC time' : 'Horloge interne en UTC',
'Processors' : 'Processeur(s)',
'Boot Order' : 'Ordre d\'amorçage',
'Removable Media' : 'Média amovible',
'Remember Runtime Changes' : 'Enregistrer les changements pendant l\'éxécution',
'Motherboard' : 'Carte mère',
'Acceleration' : 'Accélération',
'Extended Features' : 'Fonctions avancées',
'CPUs' : 'CPUs',
'VCPU' : 'VT-x/AMD-V',
'Nested Paging' : 'Pagination imbriquée',
'Hardware Virtualization' : 'Virtualisation matérielle',
'Enable VCPU' : 'Activer VT-x/AMD-V',
'Enable Nested Paging' : 'Activer pagination imbriquée',
'Enable PAE/NX' : 'Activer PAE/NX',
'Display' : 'Affichage',
'Video' : 'Vidéo',
'Video 2d' : '2D Accélération',
'Video 3d' : '3D Accélération',
'Video Memory' : 'Mémoire Vidéo',
'Remote Display' : 'Bureau à distance',
'Remote Console' : 'Console à distance (RDP)',
'Ports' : 'Ports',
'Net Address' : 'Adresse réseau',
'Enable Server' : 'Activer serveur',
'Server Port' : 'Port serveur',
'Authentication Timeout' : 'Délai d\'attente d\'authentification',
'Authentication Method' : 'Méthode d\'authentification',
'External' : 'Externe',
'Guest' : 'Invité',
'Storage' : 'Stockage',
'Storage Tree' : 'Arboresence Stockage',
'Attributes' : 'Attribut',
'Type' : 'Type',
'Slot' : 'Emplacement',
'Size' : 'Taille',
'Virtual Size' : 'Taille virtuelle',
'Actual Size' : 'Taille réelle',
'Location' : 'Emplacement',
'Information' : 'Information',
'Use host I/O cache' : 'Utiliser le cache E/S de l\'hôte',
'IDE Controller' : 'Contrôleur IDE',
'Primary Master' : 'Maître primaire',
'Primary Slave' : 'Esclave primaire',
'Secondary Master' : 'Maître secondaire',
'Secondary Slave' : 'Esclave secondaire',
'Floppy Controller' : 'Contrôleur disquettes',
'Floppy Device' : 'Lecteur disquette',
'SCSI Controller' : 'Contrôleur SCSI',
'SCSI Port' : 'Port SCSI',
'SATA Controller' : 'Contrôleur SATA',
'SATA Port' : 'Port SATA',
'SAS Controller' : 'Contrôleur SAS',
'SAS Port' : 'Port SAS',
'HardDisk' : 'Disque dur',
'Floppy' : 'Disquette',
'DVD' : 'CD/DVD',
'Type (Format)' : 'Type (Format)',
'Add Attachment' : 'Ajouter périphérique',
'Remove Attachment' : 'Supprimer périphérique',
'Add Controller' : 'Ajouter contrôleur',
'Remove Controller' : 'Supprimer contrôleur',
'Add CD/DVD Device' : 'Ajouter périphérique CD/DVD',
'Add Hard Disk' : 'Ajouter un disque dur',
'Add Floppy Device' : 'Ajouter périphérique disquette',
'DVD Device' : 'Périphérique CD/DVD',
'Empty' : 'Vide',
'Passthrough' : 'Mode direct',
'Unknown Device' : 'Périphérique inconnu',
'Host Drive' : 'Lecteur hôte',
'Add IDE Controller' : 'Ajouter contrôleur IDE',
'Add Floppy Controller' : 'Ajouter contrôleur disquette',
'Add SCSI Controller' : 'Ajouter contrôleur SCSI',
'Add SATA Controller' : 'Ajouter contrôleur SATA',
'Add SAS Controller' : 'Ajouter contrôleur SAS',
'LsiLogic' : 'LsiLogic',
'BusLogic' : 'BusLogic',
'IntelAhci' : 'AHCI',
'PIIX3' : 'PIIX3',
'PIIX4' : 'PIIX4',
'ICH6' : 'ICH6',
'I82078' : 'I82078',
'LsiLogicSas' : 'LsiLogic SAS',
'Differencing Disks' : 'Disques durs différentiels',
'No unused media message 1' : 'Aucun média non utilisé disponible pour le nouvel attachement.',
'No unused media message 2' : 'Appuyez sur le bouton Créer pour démarrer l\'assistant nouveau disque virtuel et créer un nouveau support, ou appuyez sur Sélectionner si vous souhaitez ouvrir le gestionnaire de médias virtuels.',
'storage attached indirectly' : 'Attachement indirecte en utilisant un disque dur de différenciation.',
'base disk indirectly attached' : 'Ce disque dur de base est connecté indirectement à travers le disque dur différentiel suivant :',
'Attached to' : 'Attaché à',
'Not Attached' : 'Aucune connexion',
'USB' : 'USB',
'USB Controller' : 'USB Contrôler',
'Enable USB Controller' : 'Activer le contrôler USB',
'Enable USB 2.0 Controller' : 'Activer le contrôler USB 2.0 (EHCI)',
'USB Device Filters' : 'Filtre périphérique USB',
'Add Empty Filter' : 'Ajouter un filtre vide',
'Add Filter From Device' : 'Ajouter un filtre depuis un périphérique',
'Edit Filter' : 'Modifier filtre',
'Remove Filter' : 'Supprimer filtre',
'Move Filter Up' : 'Déplacer le filtre vers le haut',
'Move Filter Down' : 'Déplacer le filtre vers le bas',
'Device Filters' : 'Filtres',
'active' : 'active',
'USB Filter' : 'Filtre USB',
'New Filter' : 'Nouveau filtre',
'Vendor ID' : 'ID du vendeur',
'Product ID' : 'ID du produit',
'Revision' : 'Révision',
'Manufacturer' : 'Fabricant',
'Serial No' : 'N° de série',
'Remote' : 'A distance',
'Shared Folders' : 'Dossiers partagés',
'Shared Folder' : 'Dossier partagé',
'Folders List' : 'Liste des dossiers',
'Path' : 'Chemin',
'Access' : 'Accès',
# read only & read/write
'ro' : 'Lecture seule',
'rw' : 'Inscriptible',
'Full Access' : 'Plein',
'Add Shared Folder' : 'Ajouter un dossier partagé',
'Edit Shared Folder' : 'Modifier un dossier partagé',
'Remove Shared Folder' : 'Supprimer un dossier partagé',
'Audio' : 'Son',
'Enable Audio' : 'Activer le son',
'Host Audio Driver' : 'Pilote audio hôte',
'Audio Controller' : 'Controleur audio',
'WinMM' : 'Windows multimedia',
'Null Audio Driver' : 'Null Audio Driver',
'OSS' : 'Open Sound System',
'ALSA' : 'Advanced Linux Sound Architecture',
'DirectSound' : 'Microsoft DirectSound',
'CoreAudio' : 'Core Audio',
'MMPM' : 'Reserved for historical reasons.', """ In API. May never see it in the real world """
'Pulse' : 'Pulse Audio',
'SolAudio' : 'Solaris Audio',
'AC97' : 'ICH AC97',
'SB16' : 'SoundBlaster 16',
'Network' : 'Réseau',
'Adapter' : 'Interface',
'Network Adapter' : 'Carte réseau',
'Enable Network Adapter' : 'Activer la carte réseau',
'Adapter Type' : 'Type de carte',
'adapter' : 'carte',
'Bridged' : 'Pont',
'Bridged Adapter' : 'Accès par pont',
'HostOnly' : 'privé hôte',
'Internal' : 'interne',
'Internal Network' : 'Réseau interne',
'Host-only Adapter' : 'Réseau privé hôte',
'NAT' : 'NAT',
'network' : 'réseau',
'Ethernet' : 'Ethernet',
'PPP' : 'PPP',
'SLIP' : 'SLIP',
'IPv4Addr' : 'Adresse IPv4',
'IPv6Addr' : 'Adresse IPv6',
'Mac Address' : 'Adresse MAC',
'Cable connected' : 'Câble branché',
'netMediumType' : 'Type',
'Guest Network Adapters' : 'Carte réseau invité',
'Am79C970A' : 'AMD PCNet-PCI II network card',
'Am79C973' : 'AMD PCNet-FAST III network card',
'I82540EM' : 'Intel PRO/1000 MT Desktop network card',
'I82543GC' : 'Intel PRO/1000 T Server network card',
'I82545EM' : 'Intel PRO/1000 MT Server network card',
'Virtio' : 'Réseau para-virtuel (virtio-net)',
# Machine states
'PoweredOff' : 'Éteinte',
'Saved' : 'Sauvegardée',
'Teleported' : 'Téléporté',
'Aborted' : 'Avortée',
'Running' : 'En fonction',
'Paused' : 'En pause',
'Stuck' : 'Collé',
'Teleporting' : 'En téléportation',
'LiveSnapshotting' : 'Instantané en direct',
'Starting' : 'Démarrage',
'Stopping' : 'Extinction',
'Saving' : 'Enregistrement',
'Restoring' : 'Restauration',
'TeleportingPausedVM' : 'En pause pour la téléportation',
'TeleportingIn' : 'Téléportation vers',
'RestoringSnapshot' : 'Restauration de l\'instantané',
'DeletingSnapshot' : 'Suppression de l\'instantané',
'SettingUp' : 'Initialisation',
'FirstOnline' : 'First Online',
'LastOnline' : 'Last Online',
'FirstTransient' : 'First Transient',
'LastTransient' : 'Last Transient',
# Mount dialog
'Mount' : 'Insérer',
# list separator
'LIST_SEP' : ', ',
# Sizes
'B' : 'o',
'KB' : 'Kio',
'MB' : 'Mio',
'GB' : 'Gio',
'TB' : 'Tio',
# Virtual Media Manager
'Open Virtual Media Manager' : 'Ouvrir le Gestionnaire de médias virtuels',
'Virtual Media Manager' : 'Gestionnaire de médias',
'Are you sure remove medium' : 'Êtes-vous sûr de vouloir supprimer le média %s de la liste des médias inconnus?',
'Medium remove note' : 'Le conteneur de ce média ne sera pas supprimé et il sera possible de le rajouter à la liste ultérieurement.',
'Are you sure release medium' : 'Êtes-vous sûr de vouloir libérer le média %s?',
'This will detach from' : 'Il sera détaché de (ou des) machines virtuelles suivantes : %s.',
'Please select a medium.' : 'Sélectionnez un média.',
'VMM Remove Media Message1' : 'Voulez-vous supprimer le conteneur du disque dur %s?',
'VMM Remove Media Message2' : 'Si vous choisissez Supprimer le conteneur sera supprimé. <b>Cette opération est irréversible.</b>',
'VMM Remove Media Message3' : 'Si vous choisissez Conserver il sera seulement enlevé de la liste des disques connus, et le conteneur sera laissé tel quel. Il sera donc possible de rajouter le disque dur à la liste ultérieurement.',
'Normal' : 'Normal',
'Writethrough' : 'Hors instantanés',
'Immutable' : 'Immuable',
'Actions' : 'Actions',
'Add' : 'Ajouter',
'Clone' : 'Cloner',
'Remove' : 'Enlever',
'Release' : 'Libérer',
'Hard Disks' : 'Disques durs',
'CD/DVD Images' : 'Images CD/DVD',
'Floppy Images' : 'Images de disquette',
""" New hard disk wizard """
'Create New Virtual Disk' : 'Créer un nouveau disque virtuel',
'newDisk Welcome' : 'Bienvenue dans l\'assistant de création de disque virtuel!',
'newDisk Step1 Message1' : 'Cet assistant vous aidera à créer un nouveau disque dur virtuel pour votre machine.',
'newDisk Step1 Message2' : 'Utilisez le bouton Suivant pour atteindre la page suivante de l\'assistant et le bouton Précédent pour revenir à la page précédente. Vous pouvez également interrompre l\'exécution de l\'assistant avec le bouton Annuler.',
'Hard Disk Storage Type' : 'Type de conteneur pour le disque dur',
'newDisk Step2 Message1' : 'Choisissez le type d\'image qui contiendra le disque dur virtuel que vous voulez créer.',
'newDisk Step2 dynamic' : 'Au début une <b>image de taille variable</b> prend peu de place sur votre vrai disque dur. L\'espace occupé augmentera en fonction des besoins du système d\'exploitation invité, jusqu\'à la taille limite spécifiée.',
'newDisk Step2 fixed' : 'Une <b>image de taille fixe</b> occupe un espace constant. La taille du fichier image correspond approximativement à l\'espace du disque virtuel. La création d\'une image de taille fixe peut prendre un certain temps, qui dépend de la taille choisie et des performances en écriture de votre vrai disque dur.',
'Storage Type' : 'Type de l\'image',
'Dynamically expanding storage' : 'Image de taille variable',
'Fixed-size storage' : 'Image de taille fixe',
'Virtual Disk Location and Size' : 'Emplacement et taille du disque virtuel',
'newDisk Step3 Message1' : 'Entrez le chemin du fichier qui contiendra les données du disque dur ou cliquez sur le bouton pour choisir son emplacement.',
'newDisk Step3 Message2' : 'Choisissez la taille maximale du disque dur virtuel. Le système d\'exploitation invité verra cette taille comme taille maximale de ce disque dur.',
'Summary' : 'Récapitulatif',
'newDisk Step4 Message1' : 'Vous êtes sur le point de créer un disque dur virtuel avec les paramètres suivants :',
'newDisk Step4 Message2' : 'Si ces paramètres vous conviennent cliquez sur Terminer pour créer le nouveau disque dur.',
""" New virtual machine wizard """
'Create New Virtual Machine' : 'Créer une nouvelle machine virtuelle',
'New Virtual Machine Wizard' : 'Assistant de création d\'une nouvelle machine virtuelle',
'newVM Welcome' : 'Bienvenue dans l\'assistant de création de machine virtuelle!',
'newVM Step1 Message1' : 'Cet assistant aidera à créer une nouvelle machine virtuelle pour VirtualBox.',
'newVM Step1 Message2' : 'Utilisez le bouton Suivant pour atteindre la page suivante de l\'assistant et le bouton Précédent pour revenir à la page précédente. Vous pouvez également interrompre l\'exécution de l\'assistant avec le bouton Annuler.',
'VM Name and OS Type' : 'Nom et système d\'exploitation',
'newVM Step2 Message1' : 'Choisissez un nom pour la nouvelle machine virtuelle et le type du système d\'exploitation invité que vous désirez installer sur cette machine.',
'newVM Step2 Message2' : 'Le nom de la machine virtuelle peut servir à indiquer la configuration matérielle et logicielle. Il sera utilisé par tous les composants de VirtualBox pour l\'identifier.',
'newVM Step3 Message1' : 'Choisissez la quantité de la mémoire vive (RAM) à allouer à la machine virtuelle, en mégaoctets.',
'newVM Step3 Message2' : 'La quantité recommandée est de %s Mio.', """ %s will be replaced with the recommended memory size at run time """
'Virtual Hard Disk' : 'Disque dur virtuel',
'Boot Hard Disk' : 'Disque dur d\'amorçage',
'Create new hard disk' : 'Créer un nouveau disque dur',
'Use existing hard disk' : 'Utiliser un disque dur existant',
'newVM Step4 Message1' : 'Choisissez une image de disque dur à utiliser pour l\'amorçage de la machine virtuelle. Vous pouvez soit créer une nouvelle image en cliquant sur Nouveau soit choisir une image existante dans le Gestionnaire de médias virtuels avec le bouton Existant.',
'newVM Step4 Message2' : 'Si vous avez besoin d\'une configuration de disques plus complexe, vous pouvez sauter cette étape et allouer des disques plus tard dans la Configuration de la machine.',
'newVM Step4 Message3' : 'La taille recommandée pour le disque dur d\'amorçage est de %s Mio.', """ %s will be replaced with the recommended memory size at run time """
'newVM Step5 Message1' : 'Vous êtes sur le point de créer une nouvelle machine virtuelle avec les paramètres suivants :',
'newVM Step5 Message2' : 'Si cette configuration vous convient cliquez sur Terminer pour créer la nouvelle machine virtuelle.',
'newVM Step5 Message3' : 'Vous pourrez modifier ces paramètres ainsi que d\'autres à tout moment avec la fenêtre Configuration du menu de la fenêtre principale.',
""" VM Log files """
'Show Log' : 'Afficher le journal',
'Logs' : 'Journaux',
'No logs found.' : 'Aucun journal trouvé.',
""" Import / Export Appliances """
'Export Appliance' : 'Exporter application virtuelle',
'Appliance Export Wizard' : 'Assistant d\'exportation d\'application virtuelle',
'Appliance Export Wizard Welcome' : 'Bienvenue dans l\'assistant d\'exportation d\'application virtuelle!',
'appExport Step1 Message1' : 'Cet assistant va vous aider à exporter une application virtuelle.',
'appExport Step1 Message2' : 'Utilisez le bouton Suivant pour atteindre la page suivante de l\'assistant et le bouton Précédent pour revenir à la page précédente. Vous pouvez également interrompre l\'exécution de l\'assistant avec le bouton Annuler.',
'appExport Step1 Message3' : 'Choisissez les machines virtuelles à ajouter à l\'application virtuelle. Vous pouvez en choisir plusieurs, mais elles doivent être éteintes avant d\'être exportées.',
'Appliance Export Settings' : 'Paramètre d\'exportation d\'application virtuelle',
'appExport Step2 Message1' : 'Vous pouvez effectuer des modifications sur les configurations des machines virtuelles sélectionnées. La plupart des propriétés affichées peuvent être changées en cliquant dessus.',
'appExport Step3 Message1' : 'Choisisez un nom de fichier pour l\'OVF.',
'Import Appliance' : 'Importer application virtuelle',
'Appliance Import Wizard' : 'Assistant d\'importation d\'application virtuelle',
'Appliance Import Wizard Welcome' : 'Bienvenue dans l\'assistant d\'importation d\'application virtuelle!',
'appImport Step1 Message1' : 'Cet assistant va vous aider à importer une application virtuelle.',
'appImport Step1 Message2' : 'Utilisez le bouton Suivant pour atteindre la page suivante de l\'assistant et le bouton Précédent pour revenir à la page précédente. Vous pouvez également interrompre l\'exécution de l\'assistant avec le bouton Annuler.',
'appImport Step1 Message3' : 'VirtualBox supporte actuellement l\'importation d\'applications enregistrées dans le format Open Virtualization Format (OVF). Avant de continuer, choisissez ci-dessous le fichier à importer :',
'Appliance Import Settings' : 'Paramètre d\'importation d\'application virtuelle',
'appImport Step2 Message1' : 'Voici les machines virtuelles décrites dans l\'application virtuelle et les paramètres suggérés pour les machines importées. Vous pouvez en changer certains en double-cliquant dessus et désactiver les autres avec les cases à cocher.',
'appImport Step3 Message1' : 'Choisisez un nom de fichier pour l\'OVF.',
'Write legacy OVF' : 'Utiliser l\'ancien format OVF 0.9',
'Virtual System X' : 'Système virtuel %s', # %s will be replaced with the virtual system number
'Product' : 'Produit',
'Product-URL' : 'URL du produit',
'Vendor' : 'Vendeur',
'Vendor-URL' : 'URL du vendeur',
'License' : 'Licence',
'Hard Disk Controller' : 'Hard Disk Controller',
'Virtual Disk Image' : 'Virtual Disk Image',
'Warnings' : 'Avertissements',
""" Operation in progress onUnLoad warning message """
'Operation in progress' : 'Attention: une opération interne VirtualBox est en cours. La fermeture de cette fenêtre ou le lancement de nouvelles opérations peut entraîner des résultats indésirables. Veuillez attendre la fin de l\'opération.',
'Loading ...' : 'Chargement ...', # "loading ..." screen
""" Versions """
'Unsupported version' : 'Vous utilisez une version non testée de VirtualBox (%s) avec phpVirtualbox. Cela peut engendrer des résultats indésirables.',
'Do not show message again' : 'Ne plus afficher ce message.',
""" Fatal connection error """
'Fatal error' : 'Une erreur est survenue lors de la communication avec vboxwebsrv. Plus aucune requête ne sera envoyée par VirtualBox Web Console jusqu\'à ce que l\'erreur soit corrigée et que cette page soit actualisée. Les détails de cette erreur de connexion doivent être affiché dans une boîte de dialogue annexe.',
""" Guest properties error """
'Unable to retrieve guest properties' : 'Impossible de récupérer les propriétés de l\'invité. Assurez-vous que la machine virtuelle est en marche et que les additions invités soit installées.',
"""RDP """
'User name' : 'Utilisateur',
'Password' : 'Mot de passe',
'Connecting to' : 'Connexion à',
'Connected to' : 'Connecter à',
'Requested desktop size' : 'Taille du bureau',
'Connect' : 'Connecter',
'Detach' : 'Détacher',
'Disconnect' : 'Déconnecter',
"Ctrl-Alt-Del" : "Insérer Ctrl-Alt-Del",
'Disconnect reason' : 'Raison de la déconnexion',
"Redirection by" : "Rediriger par",
'Virtual machine is not running or RDP configured.' : 'La machine virtuelle n\'est pas démarrée ou n\'est pas configurée pour accepter les connexions RDP.',
""" Operating Systems """
'Other' : 'Autres/Inconnus',
'Windows31' : 'Windows 3.1',
'Windows95' : 'Windows 95',
'Windows98' : 'Windows 98',
'WindowsMe' : 'Windows Me',
'WindowsNT4' : 'Windows NT 4',
'Windows2000' : 'Windows 2000',
'WindowsXP' : 'Windows XP',
'WindowsXP_64' : 'Windows XP (64 bit)',
'Windows2003' : 'Windows 2003',
'Windows2003_64' : 'Windows 2003 (64 bit)',
'WindowsVista' : 'Windows Vista',
'WindowsVista_64' : 'Windows Vista (64 bit)',
'Windows2008' : 'Windows 2008',
'Windows2008_64' : 'Windows 2008 (64 bit)',
'Windows7' : 'Windows 7',
'Windows7_64' : 'Windows 7 (64 bit)',
'WindowsNT' : 'Autres Windows',
'Linux22' : 'Linux 2.2',
'Linux24' : 'Linux 2.4',
'Linux24_64' : 'Linux 2.4 (64 bit)',
'Linux26' : 'Linux 2.6',
'Linux26_64' : 'Linux 2.6 (64 bit)',
'ArchLinux' : 'Arch Linux',
'ArchLinux_64' : 'Arch Linux (64 bit)',
'Debian' : 'Debian',
'Debian_64' : 'Debian (64 bit)',
'OpenSUSE' : 'openSUSE',
'OpenSUSE_64' : 'openSUSE (64 bit)',
'Fedora' : 'Fedora',
'Fedora_64' : 'Fedora (64 bit)',
'Gentoo' : 'Gentoo',
'Gentoo_64' : 'Gentoo (64 bit)',
'Mandriva' : 'Mandriva',
'Mandriva_64' : 'Mandriva (64 bit)',
'RedHat' : 'Red Hat',
'RedHat_64' : 'Red Hat (64 bit)',
'Turbolinux' : 'Turbolinux',
'Ubuntu' : 'Ubuntu',
'Ubuntu_64' : 'Ubuntu (64 bit)',
'Xandros' : 'Xandros',
'Xandros_64' : 'Xandros (64 bit)',
'Linux' : 'Autres Linux',
'Solaris' : 'Solaris',
'Solaris_64' : 'Solaris (64 bit)',
'OpenSolaris' : 'OpenSolaris',
'OpenSolaris_64' : 'OpenSolaris (64 bit)',
'FreeBSD' : 'FreeBSD',
'FreeBSD_64' : 'FreeBSD (64 bit)',
'OpenBSD' : 'OpenBSD',
'OpenBSD_64' : 'OpenBSD (64 bit)',
'NetBSD' : 'NetBSD',
'NetBSD_64' : 'NetBSD (64 bit)',
'OS2Warp3' : 'OS/2 Warp 3',
'OS2Warp4' : 'OS/2 Warp 4',
'OS2Warp45' : 'OS/2 Warp 4.5',
'OS2eCS' : 'eComStation',
'OS2' : 'Other OS/2',
'DOS' : 'DOS',
'Netware' : 'Netware',
'MacOS' : 'Mac OS X Server',
'MacOS_64' : 'Mac OS X Server (64 bit)',
}
| mit |
pingjiang/imba | test/lib/syntax/selectors.js | 521 | (function(){
function check(sel,query){
return this.eq(sel.query(),query);
};
describe("Syntax - Selectors",function() {
return test("variations",function() {
var a = 1;
var s = "ok";
check(q$('ul li .item'),"ul li .item");
check(q$('ul ._custom.hello'),"ul ._custom.hello");
check(q$('ul>li div[name="'+s+'"]'),'ul>li div[name="ok"]');
check(q$('ul>li div[tabindex="'+a+'"]'),'ul>li div[tabindex="1"]');
return check(q$('._mycanvas,._other'),'._mycanvas,._other');
});
});
})() | mit |
darly/photobooth | typings/browser/ambient/yargs/index.d.ts | 4480 | // Generated by typings
// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/6a287502dab374e7d4cbf18ea1ac5dff7f74726a/yargs/yargs.d.ts
// Type definitions for yargs
// Project: https://github.com/chevex/yargs
// Definitions by: Martin Poelstra <https://github.com/poelstra>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "yargs" {
module yargs {
interface Argv {
argv: any;
(...args: any[]): any;
parse(...args: any[]): any;
reset(): Argv;
locale(): string;
locale(loc:string): Argv;
detectLocale(detect:boolean): Argv;
alias(shortName: string, longName: string): Argv;
alias(aliases: { [shortName: string]: string }): Argv;
alias(aliases: { [shortName: string]: string[] }): Argv;
default(key: string, value: any): Argv;
default(defaults: { [key: string]: any}): Argv;
demand(key: string, msg: string): Argv;
demand(key: string, required?: boolean): Argv;
demand(keys: string[], msg: string): Argv;
demand(keys: string[], required?: boolean): Argv;
demand(positionals: number, required?: boolean): Argv;
demand(positionals: number, msg: string): Argv;
require(key: string, msg: string): Argv;
require(key: string, required: boolean): Argv;
require(keys: number[], msg: string): Argv;
require(keys: number[], required: boolean): Argv;
require(positionals: number, required: boolean): Argv;
require(positionals: number, msg: string): Argv;
required(key: string, msg: string): Argv;
required(key: string, required: boolean): Argv;
required(keys: number[], msg: string): Argv;
required(keys: number[], required: boolean): Argv;
required(positionals: number, required: boolean): Argv;
required(positionals: number, msg: string): Argv;
requiresArg(key: string): Argv;
requiresArg(keys: string[]): Argv;
describe(key: string, description: string): Argv;
describe(descriptions: { [key: string]: string }): Argv;
option(key: string, options: Options): Argv;
option(options: { [key: string]: Options }): Argv;
options(key: string, options: Options): Argv;
options(options: { [key: string]: Options }): Argv;
usage(message: string, options?: { [key: string]: Options }): Argv;
usage(options?: { [key: string]: Options }): Argv;
command(command: string, description: string): Argv;
command(command: string, description: string, fn: (args: Argv) => void): Argv;
completion(cmd: string, fn?: SyncCompletionFunction): Argv;
completion(cmd: string, description?: string, fn?: SyncCompletionFunction): Argv;
completion(cmd: string, fn?: AsyncCompletionFunction): Argv;
completion(cmd: string, description?: string, fn?: AsyncCompletionFunction): Argv;
example(command: string, description: string): Argv;
check(func: (argv: any, aliases: { [alias: string]: string }) => any): Argv;
boolean(key: string): Argv;
boolean(keys: string[]): Argv;
string(key: string): Argv;
string(keys: string[]): Argv;
choices(choices: Object): Argv;
choices(key: string, values:any[]): Argv;
config(key: string): Argv;
config(keys: string[]): Argv;
wrap(columns: number): Argv;
strict(): Argv;
help(): string;
help(option: string, description?: string): Argv;
epilog(msg: string): Argv;
epilogue(msg: string): Argv;
version(version: string, option?: string, description?: string): Argv;
version(version: () => string, option?: string, description?: string): Argv;
showHelpOnFail(enable: boolean, message?: string): Argv;
showHelp(func?: (message: string) => any): Argv;
exitProcess(enabled:boolean): Argv;
/* Undocumented */
normalize(key: string): Argv;
normalize(keys: string[]): Argv;
implies(key: string, value: string): Argv;
implies(implies: { [key: string]: string }): Argv;
count(key: string): Argv;
count(keys: string[]): Argv;
fail(func: (msg: string) => any): void;
}
interface Options {
type?: string;
alias?: any;
demand?: any;
required?: any;
require?: any;
default?: any;
boolean?: any;
string?: any;
count?: any;
describe?: any;
description?: any;
desc?: any;
requiresArg?: any;
choices?:string[];
}
type SyncCompletionFunction = (current: string, argv: any) => string[];
type AsyncCompletionFunction = (current: string, argv: any, done: (completion: string[]) => void) => void;
}
var yargs: yargs.Argv;
export = yargs;
} | mit |
SonarSystems/Cocos-Helper | External Cocos Helper Android Frameworks/Libs/MoPub/mopub-sdk/src/main/java/com/mopub/nativeads/ViewBinder.java | 2511 | package com.mopub.nativeads;
import android.support.annotation.NonNull;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class ViewBinder {
public final static class Builder {
private final int layoutId;
private int titleId;
private int textId;
private int callToActionId;
private int mainImageId;
private int iconImageId;
@NonNull private Map<String, Integer> extras = Collections.emptyMap();
public Builder(final int layoutId) {
this.layoutId = layoutId;
this.extras = new HashMap<String, Integer>();
}
@NonNull
public final Builder titleId(final int titleId) {
this.titleId = titleId;
return this;
}
@NonNull
public final Builder textId(final int textId) {
this.textId = textId;
return this;
}
@NonNull
public final Builder callToActionId(final int callToActionId) {
this.callToActionId = callToActionId;
return this;
}
@NonNull
public final Builder mainImageId(final int mainImageId) {
this.mainImageId = mainImageId;
return this;
}
@NonNull
public final Builder iconImageId(final int iconImageId) {
this.iconImageId = iconImageId;
return this;
}
@NonNull
public final Builder addExtras(final Map<String, Integer> resourceIds) {
this.extras = new HashMap<String, Integer>(resourceIds);
return this;
}
@NonNull
public final Builder addExtra(final String key, final int resourceId) {
this.extras.put(key, resourceId);
return this;
}
@NonNull
public final ViewBinder build() {
return new ViewBinder(this);
}
}
final int layoutId;
final int titleId;
final int textId;
final int callToActionId;
final int mainImageId;
final int iconImageId;
@NonNull final Map<String, Integer> extras;
private ViewBinder(@NonNull final Builder builder) {
this.layoutId = builder.layoutId;
this.titleId = builder.titleId;
this.textId = builder.textId;
this.callToActionId = builder.callToActionId;
this.mainImageId = builder.mainImageId;
this.iconImageId = builder.iconImageId;
this.extras = builder.extras;
}
}
| mit |
gabrielstuff/fusejs | test/unit/src/fixtures/json.js | 112 | var attackTarget;
var Fixtures = {
'mixed_dont_enum': { 'a':'A', 'b':'B', 'toString':'bar', 'valueOf':'' }
}; | mit |
dhairyagabha/opinion_base | db/migrate/20171118164047_add_attachment_avatar_to_users.rb | 215 | class AddAttachmentAvatarToUsers < ActiveRecord::Migration[5.1]
def self.up
change_table :users do |t|
t.attachment :avatar
end
end
def self.down
remove_attachment :users, :avatar
end
end
| mit |
ScottHolden/azure-sdk-for-net | src/SDKs/ApiManagement/Management.ApiManagement/Generated/IRegionsOperations.cs | 2053 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ApiManagement
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// RegionsOperations operations.
/// </summary>
public partial interface IRegionsOperations
{
/// <summary>
/// Lists all azure regions in which the service exists.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IEnumerable<RegionContract>>> ListByServiceWithHttpMessagesAsync(string resourceGroupName, string serviceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| mit |
georgemarshall/DefinitelyTyped | types/honeybadger/index.d.ts | 1945 | // Type definitions for honeybadger 1.4
// Project: https://github.com/honeybadger-io/honeybadger-node
// Definitions by: Ryan Skrzypek <https://github.com/rskrz>
// Levi Bostian <https://github.com/levibostian>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.9
import { RequestHandler, ErrorRequestHandler } from 'express';
import { EventEmitter } from 'events';
declare namespace honeybadger {
interface ConfigureOptions {
apiKey: string;
endpoint?: string;
hostname?: string;
environment?: string;
projectRoot?: string;
logger?: Console;
developmentEnvironments?: ReadonlyArray<string>;
filters?: ReadonlyArray<string>;
}
interface metadata {
name?: string;
message?: string;
context?: object;
session?: object;
headers?: object;
params?: object;
cgiData?: object;
url?: string;
component?: string;
action?: string;
fingerprint?: string;
}
type CallbackFunction = (err: Error | null, notice: object | null) => void;
type LambdaHandler = (event: object, context: object) => void;
interface HoneyBadgerInstance extends EventEmitter {
context: any;
configure: (options: ConfigureOptions) => void;
notify: (err?: any, name?: any, extra?: CallbackFunction | metadata, callback?: CallbackFunction) => void;
setContext: (context: object) => void;
resetContext: (context?: object) => void;
factory: (options?: ConfigureOptions) => HoneyBadgerInstance;
errorHandler: ErrorRequestHandler;
requestHandler: RequestHandler;
lambdaHandler: (handler: LambdaHandler) => LambdaHandler;
onUncaughtException: (func: (error: Error) => void) => void;
}
}
declare const honeybadger: honeybadger.HoneyBadgerInstance;
export = honeybadger;
| mit |
YousefED/DefinitelyTyped | types/react-icons/md/brightness-6.d.ts | 164 | import * as React from 'react';
import { IconBaseProps } from 'react-icon-base';
export default class MdBrightness6 extends React.Component<IconBaseProps, any> { }
| mit |
gaow/pfar | src/include/armadillo_bits/fn_median.hpp | 1689 | // Copyright (C) 2009-2016 National ICT Australia (NICTA)
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
// -------------------------------------------------------------------
//
// Written by Conrad Sanderson - http://conradsanderson.id.au
//! \addtogroup fn_median
//! @{
template<typename T1>
arma_warn_unused
arma_inline
const Op<T1, op_median>
median
(
const T1& X,
const uword dim = 0,
const typename enable_if< is_arma_type<T1>::value == true >::result* junk1 = 0,
const typename enable_if< resolves_to_vector<T1>::value == false >::result* junk2 = 0
)
{
arma_extra_debug_sigprint();
arma_ignore(junk1);
arma_ignore(junk2);
return Op<T1, op_median>(X, dim, 0);
}
template<typename T1>
arma_warn_unused
arma_inline
const Op<T1, op_median>
median
(
const T1& X,
const uword dim,
const typename enable_if<resolves_to_vector<T1>::value == true>::result* junk = 0
)
{
arma_extra_debug_sigprint();
arma_ignore(junk);
return Op<T1, op_median>(X, dim, 0);
}
template<typename T1>
arma_warn_unused
inline
typename T1::elem_type
median
(
const T1& X,
const arma_empty_class junk1 = arma_empty_class(),
const typename enable_if<resolves_to_vector<T1>::value == true>::result* junk2 = 0
)
{
arma_extra_debug_sigprint();
arma_ignore(junk1);
arma_ignore(junk2);
return op_median::median_vec(X);
}
template<typename T>
arma_warn_unused
arma_inline
const typename arma_scalar_only<T>::result &
median(const T& x)
{
return x;
}
//! @}
| mit |
mcrawshaw/DefinitelyTyped | types/navigation-react/index.d.ts | 2333 | // Type definitions for NavigationReact 2.0
// Project: http://grahammendick.github.io/navigation/
// Definitions by: Graham Mendick <https://github.com/grahammendick>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
import { StateNavigator } from 'navigation';
import { Component, HTMLProps } from 'react';
/**
* Defines the Link Props contract
*/
export interface LinkProps extends HTMLProps<HTMLAnchorElement> {
/**
* Indicates whether Links listen for navigate events
*/
lazy?: boolean;
/**
* Determines the effect on browser history
*/
historyAction?: 'add' | 'replace' | 'none';
/**
* Handles Link click events
*/
navigating?(e: MouseEvent, domId: string, link: string): boolean;
/**
* The State Navigator
*/
stateNavigator?: StateNavigator;
}
/**
* Defines the Refresh Link Props contract
*/
export interface RefreshLinkProps extends LinkProps {
/**
* The NavigationData to pass
*/
navigationData?: any;
/**
* Indicates whether to include all the current NavigationData
*/
includeCurrentData?: boolean;
/**
* The data to add from the current NavigationData
*/
currentDataKeys?: string;
/**
* The Css Class to display when the Link is active
*/
activeCssClass?: string;
/**
* Indicates whether the Link is disabled when active
*/
disableActive?: boolean;
}
/**
* Hyperlink Component the navigates to the current State
*/
export class RefreshLink extends Component<RefreshLinkProps, any> { }
/**
* Defines the Navigation Link Props contract
*/
export interface NavigationLinkProps extends RefreshLinkProps {
/**
* The key of the State to navigate to
*/
stateKey: string;
}
/**
* Hyperlink Component the navigates to a State
*/
export class NavigationLink extends Component<NavigationLinkProps, any> { }
/**
* Defines the Navigation Back Link Props contract
*/
export interface NavigationBackLinkProps extends RefreshLinkProps {
/**
* Starting at 1, The number of Crumb steps to go back
*/
distance: number;
}
/**
* Hyperlink Component the navigates back along the crumb trail
*/
export class NavigationBackLink extends Component<NavigationBackLinkProps, any> { }
| mit |
cdnjs/cdnjs | ajax/libs/jQuery.mmenu/9.0.4/addons/navbars/navbar.title.min.js | 302 | import*as DOM from"../../_modules/dom";export default function(e){let a=DOM.create("a.mm-navbar__title");e.append(a),this.bind("openPanel:before",e=>{if(!e.parentElement.matches(".mm-listitem--vertical")){const t=e.querySelector(".mm-navbar__title");t&&(e=t.cloneNode(!0),a.after(e),a.remove(),a=e)}})} | mit |
rajul/Pydev | plugins/org.python.pydev.refactoring/tests/python/coderefactoring/extractmethod/testExtractMethod1.py | 423 | class A:
def test(self):
##|print "Initializing A"##|
attribute = "hello"
def my_method(self):
print self.attribute
a = A()
a.test()
##r
class A:
def extracted_method(self):
print "Initializing A"
def test(self):
self.extracted_method()
attribute = "hello"
def my_method(self):
print self.attribute
a = A()
a.test() | epl-1.0 |
kolo1477/kalista | Viktor/Properties/AssemblyInfo.cs | 1396 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Viktor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Viktor")]
[assembly: AssemblyCopyright("Copyright © Hellsing 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e87f9574-36e7-4b76-bd4e-f0a8b69cf7fb")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.2")]
[assembly: AssemblyFileVersion("1.0.0.2")]
| gpl-2.0 |
sbamamoto/contro | grails-app/assets/javascripts/src-noconflict/snippets/text.js | 330 |
; (function() {
ace.require(["ace/snippets/text"], function(m) {
if (typeof module == "object" && typeof exports == "object" && module) {
module.exports = m;
}
});
})();
| gpl-2.0 |
m-kuhn/QGIS | python/plugins/processing/algs/qgis/AddTableField.py | 4301 | # -*- coding: utf-8 -*-
"""
***************************************************************************
AddTableField.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
***************************************************************************
* *
* 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. *
* *
***************************************************************************
"""
__author__ = 'Victor Olaya'
__date__ = 'August 2012'
__copyright__ = '(C) 2012, Victor Olaya'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
from qgis.PyQt.QtCore import QVariant
from qgis.core import (QgsField,
QgsProcessing,
QgsProcessingAlgorithm,
QgsProcessingParameterString,
QgsProcessingParameterNumber,
QgsProcessingParameterEnum,
QgsProcessingFeatureSource)
from processing.algs.qgis.QgisAlgorithm import QgisFeatureBasedAlgorithm
class AddTableField(QgisFeatureBasedAlgorithm):
FIELD_NAME = 'FIELD_NAME'
FIELD_TYPE = 'FIELD_TYPE'
FIELD_LENGTH = 'FIELD_LENGTH'
FIELD_PRECISION = 'FIELD_PRECISION'
TYPES = [QVariant.Int, QVariant.Double, QVariant.String]
def group(self):
return self.tr('Vector table')
def groupId(self):
return 'vectortable'
def __init__(self):
super().__init__()
self.type_names = [self.tr('Integer'),
self.tr('Float'),
self.tr('String')]
self.field = None
def flags(self):
return super().flags() & ~QgsProcessingAlgorithm.FlagSupportsInPlaceEdits
def initParameters(self, config=None):
self.addParameter(QgsProcessingParameterString(self.FIELD_NAME,
self.tr('Field name')))
self.addParameter(QgsProcessingParameterEnum(self.FIELD_TYPE,
self.tr('Field type'), self.type_names))
self.addParameter(QgsProcessingParameterNumber(self.FIELD_LENGTH,
self.tr('Field length'), QgsProcessingParameterNumber.Integer,
10, False, 1, 255))
self.addParameter(QgsProcessingParameterNumber(self.FIELD_PRECISION,
self.tr('Field precision'), QgsProcessingParameterNumber.Integer, 0, False, 0, 10))
def name(self):
return 'addfieldtoattributestable'
def displayName(self):
return self.tr('Add field to attributes table')
def outputName(self):
return self.tr('Added')
def inputLayerTypes(self):
return [QgsProcessing.TypeVector]
def prepareAlgorithm(self, parameters, context, feedback):
field_type = self.parameterAsEnum(parameters, self.FIELD_TYPE, context)
field_name = self.parameterAsString(parameters, self.FIELD_NAME, context)
field_length = self.parameterAsInt(parameters, self.FIELD_LENGTH, context)
field_precision = self.parameterAsInt(parameters, self.FIELD_PRECISION, context)
self.field = QgsField(field_name, self.TYPES[field_type], '',
field_length, field_precision)
return True
def outputFields(self, inputFields):
inputFields.append(self.field)
return inputFields
def sourceFlags(self):
return QgsProcessingFeatureSource.FlagSkipGeometryValidityChecks
def processFeature(self, feature, context, feedback):
attributes = feature.attributes()
attributes.append(None)
feature.setAttributes(attributes)
return [feature]
| gpl-2.0 |
isauragalafate/drupal8 | vendor/drupal/console/src/Command/Module/DownloadCommand.php | 7533 | <?php
/**
* @file
* Contains \Drupal\Console\Command\Module\DownloadCommand.
*/
namespace Drupal\Console\Command\Module;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Drupal\Console\Core\Command\Command;
use Drupal\Console\Command\Shared\ProjectDownloadTrait;
use Drupal\Console\Utils\DrupalApi;
use GuzzleHttp\Client;
use Drupal\Console\Extension\Manager;
use Drupal\Console\Utils\Validator;
use Drupal\Console\Utils\Site;
use Drupal\Console\Core\Utils\ConfigurationManager;
use Drupal\Console\Core\Utils\ShellProcess;
class DownloadCommand extends Command
{
use ProjectDownloadTrait;
/**
* @var DrupalApi
*/
protected $drupalApi;
/**
* @var Client
*/
protected $httpClient;
/**
* @var string
*/
protected $appRoot;
/**
* @var Manager
*/
protected $extensionManager;
/**
* @var Validator
*/
protected $validator;
/**
* @var ConfigurationManager
*/
protected $configurationManager;
/**
* @var ShellProcess
*/
protected $shellProcess;
/**
* @var string
*/
protected $root;
/**
* DownloadCommand constructor.
*
* @param DrupalApi $drupalApi
* @param Client $httpClient
* @param $appRoot
* @param Manager $extensionManager
* @param Validator $validator
* @param Site $site
* @param ConfigurationManager $configurationManager
* @param ShellProcess $shellProcess
* @param $root
*/
public function __construct(
DrupalApi $drupalApi,
Client $httpClient,
$appRoot,
Manager $extensionManager,
Validator $validator,
Site $site,
ConfigurationManager $configurationManager,
ShellProcess $shellProcess,
$root
) {
$this->drupalApi = $drupalApi;
$this->httpClient = $httpClient;
$this->appRoot = $appRoot;
$this->extensionManager = $extensionManager;
$this->validator = $validator;
$this->site = $site;
$this->configurationManager = $configurationManager;
$this->shellProcess = $shellProcess;
$this->root = $root;
parent::__construct();
}
protected function configure()
{
$this
->setName('module:download')
->setDescription($this->trans('commands.module.download.description'))
->addArgument(
'module',
InputArgument::IS_ARRAY,
$this->trans('commands.module.download.arguments.module')
)
->addOption(
'path',
null,
InputOption::VALUE_OPTIONAL,
$this->trans('commands.module.download.options.path')
)
->addOption(
'latest',
null,
InputOption::VALUE_NONE,
$this->trans('commands.module.download.options.latest')
)
->addOption(
'composer',
null,
InputOption::VALUE_NONE,
$this->trans('commands.module.install.options.composer')
)
->addOption(
'unstable',
null,
InputOption::VALUE_NONE,
$this->trans('commands.module.download.options.unstable')
)
->setAliases(['mod']);
}
/**
* {@inheritdoc}
*/
protected function interact(InputInterface $input, OutputInterface $output)
{
$composer = $input->getOption('composer');
$module = $input->getArgument('module');
if (!$module) {
$module = $this->modulesQuestion();
$input->setArgument('module', $module);
}
if (!$composer) {
$path = $input->getOption('path');
if (!$path) {
$path = $this->getIo()->ask(
$this->trans('commands.module.download.questions.path'),
'modules/contrib'
);
$input->setOption('path', $path);
}
}
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$modules = $input->getArgument('module');
$latest = $input->getOption('latest');
$path = $input->getOption('path');
$composer = $input->getOption('composer');
$unstable = true;
if ($composer) {
foreach ($modules as $module) {
if (!$latest) {
$versions = $this->drupalApi
->getPackagistModuleReleases($module, 10, $unstable);
if (!$versions) {
$this->getIo()->error(
sprintf(
$this->trans(
'commands.module.download.messages.no-releases'
),
$module
)
);
return 1;
} else {
$version = $this->getIo()->choice(
sprintf(
$this->trans(
'commands.site.new.questions.composer-release'
),
$module
),
$versions
);
}
} else {
$versions = $this->drupalApi
->getPackagistModuleReleases($module, 10, $unstable);
if (!$versions) {
$this->getIo()->error(
sprintf(
$this->trans(
'commands.module.download.messages.no-releases'
),
$module
)
);
return 1;
} else {
$version = current(
$this->drupalApi
->getPackagistModuleReleases($module, 1, $unstable)
);
}
}
// Register composer repository
$command = "composer config repositories.drupal composer https://packages.drupal.org/8";
$this->shellProcess->exec($command, $this->root);
$command = sprintf(
'composer require drupal/%s:%s --prefer-dist --optimize-autoloader --sort-packages --update-no-dev',
$module,
$version
);
if ($this->shellProcess->exec($command, $this->root)) {
$this->getIo()->success(
sprintf(
$this->trans('commands.module.download.messages.composer'),
$module
)
);
}
}
} else {
$this->downloadModules($modules, $latest, $path);
}
return true;
}
}
| gpl-2.0 |
openjdk/jdk7u | jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/api/server/WebServiceContextDelegate.java | 5870 | /*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.xml.internal.ws.api.server;
import com.sun.istack.internal.NotNull;
import com.sun.istack.internal.Nullable;
import com.sun.xml.internal.ws.api.message.Packet;
import com.sun.xml.internal.ws.api.pipe.Pipe;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.WebServiceException;
import java.security.Principal;
/**
* This object is set to {@link Packet#webServiceContextDelegate}
* to serve {@link WebServiceContext} methods for a {@link Packet}.
*
* <p>
* When the user application calls a method on {@link WebServiceContext},
* the JAX-WS RI goes to the {@link Packet} that represents the request,
* then check {@link Packet#webServiceContextDelegate}, and forwards
* the method calls to {@link WebServiceContextDelegate}.
*
* <p>
* All the methods defined on this interface takes {@link Packet}
* (whose {@link Packet#webServiceContextDelegate} points to
* this object), so that a single stateless {@link WebServiceContextDelegate}
* can be used to serve multiple concurrent {@link Packet}s,
* if the implementation wishes to do so.
*
* <p>
* (It is also allowed to create one instance of
* {@link WebServiceContextDelegate} for each packet,
* and thus effectively ignore the packet parameter.)
*
* <p>
* Attaching this on a {@link Packet} allows {@link Pipe}s to
* intercept and replace them, if they wish.
*
*
* @author Kohsuke Kawaguchi
*/
public interface WebServiceContextDelegate {
/**
* Implements {@link WebServiceContext#getUserPrincipal()}
* for the given packet.
*
* @param request
* Always non-null. See class javadoc.
* @see WebServiceContext#getUserPrincipal()
*/
Principal getUserPrincipal(@NotNull Packet request);
/**
* Implements {@link WebServiceContext#isUserInRole(String)}
* for the given packet.
*
* @param request
* Always non-null. See class javadoc.
* @see WebServiceContext#isUserInRole(String)
*/
boolean isUserInRole(@NotNull Packet request,String role);
/**
* Gets the address of the endpoint.
*
* <p>
* The "address" of endpoints is always affected by a particular
* client being served, hence it's up to transport to provide this
* information.
*
* @param request
* Always non-null. See class javadoc.
* @param endpoint
* The endpoint whose address will be returned.
*
* @throws WebServiceException
* if this method could not compute the address for some reason.
* @return
* Absolute URL of the endpoint. This shold be an address that the client
* can use to talk back to this same service later.
*
* @see WebServiceContext#getEndpointReference
*/
@NotNull String getEPRAddress(@NotNull Packet request, @NotNull WSEndpoint endpoint);
/**
* Gets the address of the primary WSDL.
*
* <p>
* If a transport supports publishing of WSDL by itself (instead/in addition to MEX),
* then it should implement this method so that the rest of the JAX-WS RI can
* use that information.
*
* For example, HTTP transports often use the convention {@code getEPRAddress()+"?wsdl"}
* for publishing WSDL on HTTP.
*
* <p>
* Some transports may not have such WSDL publishing mechanism on its own.
* Those transports may choose to return null, indicating that WSDL
* is not published. If such transports are always used in conjunction with
* other transports that support WSDL publishing (such as SOAP/TCP used
* with Servlet transport), then such transport may
* choose to find the corresponding servlet endpoint by {@link Module#getBoundEndpoints()}
* and try to obtain the address from there.
*
* <p>
* This information is used to put a metadata reference inside an EPR,
* among other things. Clients that do not support MEX rely on this
* WSDL URL to retrieve metadata, it is desirable for transports to support
* this, but not mandatory.
*
* <p>
* This method will be never invoked if the {@link WSEndpoint}
* does not have a corresponding WSDL to begin with
* (IOW {@link WSEndpoint#getServiceDefinition() returning null}.
*
* @param request
* Always non-null. See class javadoc.
* @param endpoint
* The endpoint whose address will be returned.
*
* @return
* null if the implementation does not support the notion of
* WSDL publishing.
*/
@Nullable String getWSDLAddress(@NotNull Packet request, @NotNull WSEndpoint endpoint);
}
| gpl-2.0 |
cw196/tiwal | zh/wp-content/plugins/so-widgets-bundle/widgets/so-google-map-widget/so-google-map-widget.php | 21451 | <?php
/*
Widget Name: Google Maps widget
Description: A highly customisable Google Maps widget. Help your site find its place and give it some direction.
Author: SiteOrigin
Author URI: http://siteorigin.com
*/
class SiteOrigin_Widget_GoogleMap_Widget extends SiteOrigin_Widget {
function __construct() {
parent::__construct(
'sow-google-map',
__( 'SiteOrigin Google Maps', 'siteorigin-widgets' ),
array(
'description' => __( 'A Google Maps widget.', 'siteorigin-widgets' ),
'help' => 'https://siteorigin.com/widgets-bundle/google-maps-widget/'
),
array(),
array(
'map_center' => array(
'type' => 'textarea',
'rows' => 2,
'label' => __( 'Map center', 'siteorigin-widgets' ),
'description' => __( 'The name of a place, town, city, or even a country. Can be an exact address too.', 'siteorigin-widgets' )
),
'settings' => array(
'type' => 'section',
'label' => __( 'Settings', 'siteorigin-widgets' ),
'hide' => false,
'description' => __( 'Set map display options.', 'siteorigin-widgets' ),
'fields' => array(
'map_type' => array(
'type' => 'radio',
'default' => 'interactive',
'label' => __( 'Map type', 'siteorigin-widgets' ),
'state_emitter' => array(
'callback' => 'select',
'args' => array( 'map_type' )
),
'options' => array(
'interactive' => __( 'Interactive', 'siteorigin-widgets' ),
'static' => __( 'Static image', 'siteorigin-widgets' ),
)
),
'width' => array(
'type' => 'text',
'default' => 640,
'hidden' => true,
'state_handler' => array(
'map_type[static]' => array('show'),
'_else[map_type]' => array('hide'),
),
'label' => __( 'Width', 'siteorigin-widgets' )
),
'height' => array(
'type' => 'text',
'default' => 480,
'label' => __( 'Height', 'siteorigin-widgets' )
),
'zoom' => array(
'type' => 'slider',
'label' => __( 'Zoom level', 'siteorigin-widgets' ),
'description' => __( 'A value from 0 (the world) to 21 (street level).', 'siteorigin-widgets' ),
'min' => 0,
'max' => 21,
'default' => 12,
'integer' => true,
),
'scroll_zoom' => array(
'type' => 'checkbox',
'default' => true,
'state_handler' => array(
'map_type[interactive]' => array('show'),
'_else[map_type]' => array('hide'),
),
'label' => __( 'Scroll to zoom', 'siteorigin-widgets' ),
'description' => __( 'Allow scrolling over the map to zoom in or out.', 'siteorigin-widgets' )
),
'draggable' => array(
'type' => 'checkbox',
'default' => true,
'state_handler' => array(
'map_type[interactive]' => array('show'),
'_else[map_type]' => array('hide'),
),
'label' => __( 'Draggable', 'siteorigin-widgets' ),
'description' => __( 'Allow dragging the map to move it around.', 'siteorigin-widgets' )
),
'disable_default_ui' => array(
'type' => 'checkbox',
'default' => false,
'state_handler' => array(
'map_type[interactive]' => array('show'),
'_else[map_type]' => array('hide'),
),
'label' => __( 'Disable default UI', 'siteorigin-widgets' ),
'description' => __( 'Hides the default Google Maps controls.', 'siteorigin-widgets' )
),
'keep_centered' => array(
'type' => 'checkbox',
'default' => false,
'state_handler' => array(
'map_type[interactive]' => array('show'),
'_else[map_type]' => array('hide'),
),
'label' => __( 'Keep map centered', 'siteorigin-widgets' ),
'description' => __( 'Keeps the map centered when it\'s container is resized.', 'siteorigin-widgets' )
)
)
),
'markers' => array(
'type' => 'section',
'label' => __( 'Markers', 'siteorigin-widgets' ),
'hide' => true,
'description' => __( 'Use markers to identify points of interest on the map.', 'siteorigin-widgets' ),
'fields' => array(
'marker_at_center' => array(
'type' => 'checkbox',
'default' => true,
'label' => __( 'Show marker at map center', 'siteorigin-widgets' )
),
'marker_icon' => array(
'type' => 'media',
'default' => '',
'label' => __( 'Marker icon', 'siteorigin-widgets' ),
'description' => __( 'Replaces the default map marker with your own image.', 'siteorigin-widgets' )
),
'markers_draggable' => array(
'type' => 'checkbox',
'default' => false,
'state_handler' => array(
'map_type[interactive]' => array('show'),
'_else[map_type]' => array('hide'),
),
'label' => __( 'Draggable markers', 'siteorigin-widgets' )
),
'marker_positions' => array(
'type' => 'repeater',
'label' => __( 'Marker positions', 'siteorigin-widgets' ),
'description' => __( 'Please be aware that adding more than 10 markers may cause a slight delay before they appear, due to Google Geocoding API rate limits.', 'siteorigin-widgets' ),
'item_name' => __( 'Marker', 'siteorigin-widgets' ),
'item_label' => array(
'selector' => "[id*='marker_positions-place']",
'update_event' => 'change',
'value_method' => 'val'
),
'fields' => array(
'place' => array(
'type' => 'textarea',
'rows' => 2,
'label' => __( 'Place', 'siteorigin-widgets' )
),
'info' => array(
'type' => 'tinymce',
'rows' => 10,
'label' => __( 'Info Window Content', 'siteorigin-widgets' )
),
'info_max_width' => array(
'type' => 'text',
'label' => __( 'Info Window max width', 'siteorigin-widgets' )
),
)
),
'info_display' => array(
'type' => 'radio',
'label' => __( 'When should Info Windows be displayed?' ),
'default' => 'click',
'options' => array(
'click' => __( 'Click', 'siteorigin-widgets' ),
'mouseover' => __( 'Mouse over', 'siteorigin-widgets' ),
'always' => __( 'Always', 'siteorigin-widgets' ),
)
),
)
),
'styles' => array(
'type' => 'section',
'label' => __( 'Styles', 'siteorigin-widgets' ),
'hide' => true,
'description' => __( 'Apply custom colors to map features, or hide them completely.', 'siteorigin-widgets' ),
'fields' => array(
'style_method' => array(
'type' => 'radio',
'default' => 'normal',
'label' => __( 'Map styles', 'siteorigin-widgets' ),
'state_emitter' => array(
'callback' => 'select',
'args' => array( 'style_method' )
),
'options' => array(
'normal' => __( 'Default', 'siteorigin-widgets' ),
'custom' => __( 'Custom', 'siteorigin-widgets' ),
'raw_json' => __( 'Predefined Styles', 'siteorigin-widgets' ),
)
),
'styled_map_name' => array(
'type' => 'text',
'state_handler' => array(
'style_method[default]' => array('hide'),
'_else[style_method]' => array('show'),
),
'label' => __( 'Styled map name', 'siteorigin-widgets' )
),
'raw_json_map_styles' => array(
'type' => 'textarea',
'state_handler' => array(
'style_method[raw_json]' => array('show'),
'_else[style_method]' => array('hide'),
),
'rows' => 5,
'hidden' => true,
'label' => __( 'Raw JSON styles', 'siteorigin-widgets' ),
'description' => __( 'Copy and paste predefined styles here from <a href="http://snazzymaps.com/" target="_blank">Snazzy Maps</a>.', 'siteorigin-widgets' )
),
'custom_map_styles' => array(
'type' => 'repeater',
'state_handler' => array(
'style_method[custom]' => array('show'),
'_else[style_method]' => array('hide'),
),
'label' => __( 'Custom map styles', 'siteorigin-widgets' ),
'item_name' => __( 'Style', 'siteorigin-widgets' ),
'item_label' => array(
'selector' => "[id*='custom_map_styles-map_feature'] :selected",
'update_event' => 'change',
'value_method' => 'text'
),
'fields' => array(
'map_feature' => array(
'type' => 'select',
'label' => '',
'prompt' => __( 'Select map feature to style', 'siteorigin-widgets' ),
'options' => array(
'water' => __( 'Water', 'siteorigin-widgets' ),
'road_highway' => __( 'Highways', 'siteorigin-widgets' ),
'road_arterial' => __( 'Arterial roads', 'siteorigin-widgets' ),
'road_local' => __( 'Local roads', 'siteorigin-widgets' ),
'transit_line' => __( 'Transit lines', 'siteorigin-widgets' ),
'transit_station' => __( 'Transit stations', 'siteorigin-widgets' ),
'landscape_man-made' => __( 'Man-made landscape', 'siteorigin-widgets' ),
'landscape_natural_landcover' => __( 'Natural landscape landcover', 'siteorigin-widgets' ),
'landscape_natural_terrain' => __( 'Natural landscape terrain', 'siteorigin-widgets' ),
'poi_attraction' => __( 'Point of interest - Attractions', 'siteorigin-widgets' ),
'poi_business' => __( 'Point of interest - Business', 'siteorigin-widgets' ),
'poi_government' => __( 'Point of interest - Government', 'siteorigin-widgets' ),
'poi_medical' => __( 'Point of interest - Medical', 'siteorigin-widgets' ),
'poi_park' => __( 'Point of interest - Parks', 'siteorigin-widgets' ),
'poi_place-of-worship' => __( 'Point of interest - Places of worship', 'siteorigin-widgets' ),
'poi_school' => __( 'Point of interest - Schools', 'siteorigin-widgets' ),
'poi_sports-complex' => __( 'Point of interest - Sports complexes', 'siteorigin-widgets' ),
)
),
'element_type' => array(
'type' => 'select',
'label' => __( 'Select element type to style', 'siteorigin-widgets' ),
'options' => array(
'geometry' => __( 'Geometry', 'siteorigin-widgets' ),
'labels' => __( 'Labels', 'siteorigin-widgets' ),
'all' => __( 'All', 'siteorigin-widgets' ),
)
),
'visibility' => array(
'type' => 'checkbox',
'default' => true,
'label' => __( 'Visible', 'siteorigin-widgets' )
),
'color' => array(
'type' => 'color',
'label' => __( 'Color', 'siteorigin-widgets' )
)
)
)
)
),
'directions' => array(
'type' => 'section',
'label' => __( 'Directions', 'siteorigin-widgets' ),
'state_handler' => array(
'map_type[interactive]' => array('show'),
'_else[map_type]' => array('hide'),
),
'hide' => true,
'description' => __( 'Display a route on your map, with waypoints between your starting point and destination.', 'siteorigin-widgets' ),
'fields' => array(
'origin' => array(
'type' => 'text',
'label' => __( 'Starting point', 'siteorigin-widgets' )
),
'destination' => array(
'type' => 'text',
'label' => __( 'Destination', 'siteorigin-widgets' )
),
'travel_mode' => array(
'type' => 'select',
'label' => __( 'Travel mode', 'siteorigin-widgets' ),
'default' => 'driving',
'options' => array(
'driving' => __( 'Driving', 'siteorigin-widgets' ),
'walking' => __( 'Walking', 'siteorigin-widgets' ),
'bicycling' => __( 'Bicycling', 'siteorigin-widgets' ),
'transit' => __( 'Transit', 'siteorigin-widgets' )
)
),
'avoid_highways' => array(
'type' => 'checkbox',
'label' => __( 'Avoid highways', 'siteorigin-widgets' ),
),
'avoid_tolls' => array(
'type' => 'checkbox',
'label' => __( 'Avoid tolls', 'siteorigin-widgets' ),
),
'waypoints' => array(
'type' => 'repeater',
'label' => __( 'Waypoints', 'siteorigin-widgets' ),
'item_name' => __( 'Waypoint', 'siteorigin-widgets' ),
'item_label' => array(
'selector' => "[id*='waypoints-location']",
'update_event' => 'change',
'value_method' => 'val'
),
'fields' => array(
'location' => array(
'type' => 'textarea',
'rows' => 2,
'label' => __( 'Location', 'siteorigin-widgets' )
),
'stopover' => array(
'type' => 'checkbox',
'default' => true,
'label' => __( 'Stopover', 'siteorigin-widgets' ),
'description' => __( 'Whether or not this is a stop on the route or just a route preference.', 'siteorigin-widgets' )
)
)
),
'optimize_waypoints' => array(
'type' => 'checkbox',
'label' => __( 'Optimize waypoints', 'siteorigin-widgets' ),
'default' => false,
'description' => __( 'Allow the Google Maps service to reorder waypoints for the shortest travelling distance.', 'siteorigin-widgets' )
)
)
),
'api_key_section' => array(
'type' => 'section',
'label' => __( 'API key', 'siteorigin-widgets' ),
'hide' => true,
'fields' => array(
'api_key' => array(
'type' => 'text',
'label' => __( 'API key', 'siteorigin-widgets' ),
'description' => __( 'Enter your API key if you have one. This enables you to monitor your Google Maps API usage in the Google APIs Console.', 'siteorigin-widgets' ),
'optional' => true
)
)
)
)
);
}
function initialize() {
$this->register_frontend_scripts(
array(
array(
'sow-google-map',
siteorigin_widget_get_plugin_dir_url( 'google-map' ) . 'js/js-map' . SOW_BUNDLE_JS_SUFFIX . '.js',
array( 'jquery' ),
SOW_BUNDLE_VERSION . mt_rand()
)
)
);
$this->register_frontend_styles(
array(
array(
'sow-google-map',
siteorigin_widget_get_plugin_dir_url( 'google-map' ) . 'css/style.css',
array(),
SOW_BUNDLE_VERSION
)
)
);
}
function get_template_name( $instance ) {
return $instance['settings']['map_type'] == 'static' ? 'static-map' : 'js-map';
}
function get_style_name( $instance ) {
return '';
}
function get_template_variables( $instance, $args ) {
if( empty( $instance ) ) return array();
$settings = $instance['settings'];
$mrkr_src = wp_get_attachment_image_src( $instance['markers']['marker_icon'] );
$styles = $this->get_styles( $instance );
if ( $settings['map_type'] == 'static' ) {
$src_url = $this->get_static_image_src( $instance, $settings['width'], $settings['height'], ! empty( $styles ) ? $styles['styles'] : array() );
return array(
'src_url' => sow_esc_url( $src_url )
);
} else {
$markers = $instance['markers'];
$directions_json = '';
if ( ! empty( $instance['directions']['origin'] ) && ! empty( $instance['directions']['destination'] ) ) {
if ( empty( $instance['directions']['waypoints'] ) ) {
unset( $instance['directions']['waypoints'] );
}
$directions_json = json_encode( siteorigin_widgets_underscores_to_camel_case( $instance['directions'] ) );
}
return array(
'map_id' => md5( $instance['map_center'] ),
'height' => $settings['height'],
'map_data' => array(
'address' => $instance['map_center'],
'zoom' => $settings['zoom'],
'scroll-zoom' => $settings['scroll_zoom'],
'draggable' => $settings['draggable'],
'disable-ui' => $settings['disable_default_ui'],
'keep-centered' => $settings['keep_centered'],
'marker-icon' => ! empty( $mrkr_src ) ? $mrkr_src[0] : '',
'markers-draggable' => isset( $markers['markers_draggable'] ) ? $markers['markers_draggable'] : '',
'marker-at-center' => !empty( $markers['marker_at_center'] ),
'marker-info-display' => $markers['info_display'],
'marker-positions' => isset( $markers['marker_positions'] ) ? json_encode( $markers['marker_positions'] ) : '',
'map-name' => ! empty( $styles ) ? $styles['map_name'] : '',
'map-styles' => ! empty( $styles ) ? json_encode( $styles['styles'] ) : '',
'directions' => $directions_json,
'api-key' => $instance['api_key_section']['api_key']
)
);
}
}
private function get_styles( $instance ) {
$style_config = $instance['styles'];
switch ( $style_config['style_method'] ) {
case 'custom':
if ( empty( $style_config['custom_map_styles'] ) ) {
return array();
} else {
$map_name = ! empty( $style_config['styled_map_name'] ) ? $style_config['styled_map_name'] : 'Custom Map';
$map_styles = $style_config['custom_map_styles'];
$styles = array();
foreach ( $map_styles as $style_item ) {
$map_feature = $style_item['map_feature'];
unset( $style_item['map_feature'] );
$element_type = $style_item['element_type'];
unset( $style_item['element_type'] );
$stylers = array();
foreach ( $style_item as $style_name => $style_value ) {
if ( $style_value !== '' && ! is_null( $style_value ) ) {
$style_value = $style_value === false ? 'off' : $style_value;
array_push( $stylers, array( $style_name => $style_value ) );
}
}
$map_feature = str_replace( '_', '.', $map_feature );
$map_feature = str_replace( '-', '_', $map_feature );
array_push( $styles, array(
'featureType' => $map_feature,
'elementType' => $element_type,
'stylers' => $stylers
) );
}
return array( 'map_name' => $map_name, 'styles' => $styles );
}
case 'raw_json':
if ( empty( $style_config['raw_json_map_styles'] ) ) {
return array();
} else {
$map_name = ! empty( $style_config['styled_map_name'] ) ? $style_config['styled_map_name'] : __( 'Custom Map', 'siteorigin-widgets' );
$styles_string = $style_config['raw_json_map_styles'];
return array( 'map_name' => $map_name, 'styles' => json_decode( $styles_string, true ) );
}
case 'normal':
default:
return array();
}
}
private function get_static_image_src( $instance, $width, $height, $styles ) {
$src_url = "https://maps.googleapis.com/maps/api/staticmap?";
$src_url .= "center=" . $instance['map_center'];
$src_url .= "&zoom=" . $instance['settings']['zoom'];
$src_url .= "&size=" . $width . "x" . $height;
if ( ! empty( $instance['api_key_section']['api_key'] ) ) {
$src_url .= "&key=" . $instance['api_key_section']['api_key'];
}
if ( ! empty( $styles ) ) {
foreach ( $styles as $st ) {
if ( empty( $st ) || ! isset( $st['stylers'] ) || empty( $st['stylers'] ) ) {
continue;
}
$st_string = '';
if ( isset ( $st['featureType'] ) ) {
$st_string .= 'feature:' . $st['featureType'];
}
if ( isset ( $st['elementType'] ) ) {
if ( ! empty( $st_string ) ) {
$st_string .= "|";
}
$st_string .= 'element:' . $st['elementType'];
}
foreach ( $st['stylers'] as $style_prop_arr ) {
foreach ( $style_prop_arr as $prop_name => $prop_val ) {
if ( ! empty( $st_string ) ) {
$st_string .= "|";
}
if ( $prop_val[0] == "#" ) {
$prop_val = "0x" . substr( $prop_val, 1 );
}
if ( is_bool( $prop_val ) ) {
$prop_val = $prop_val ? 'true' : 'false';
}
$st_string .= $prop_name . ":" . $prop_val;
}
}
$st_string = '&style=' . $st_string;
$src_url .= $st_string;
}
}
if ( ! empty( $instance['markers'] ) ) {
$markers = $instance['markers'];
$markers_st = '';
if ( ! empty( $markers['marker_icon'] ) ) {
$mrkr_src = wp_get_attachment_image_src( $markers['marker_icon'] );
if ( ! empty( $mrkr_src ) ) {
$markers_st .= 'icon:' . $mrkr_src[0];
}
}
if ( !empty( $markers['marker_at_center'] ) ) {
if ( ! empty( $markers_st ) ) {
$markers_st .= "|";
}
$markers_st .= $instance['map_center'];
}
if ( ! empty( $markers['marker_positions'] ) ) {
foreach ( $markers['marker_positions'] as $marker ) {
if ( ! empty( $markers_st ) ) {
$markers_st .= "|";
}
$markers_st .= urlencode( $marker['place'] );
}
}
$markers_st = '&markers=' . $markers_st;
$src_url .= $markers_st;
}
return $src_url;
}
}
siteorigin_widget_register( 'google-map', __FILE__ ); | gpl-2.0 |
sivakgm/squid-3.4 | helpers/external_acl/kerberos_ldap_group/support_netbios.cc | 5816 | /*
* -----------------------------------------------------------------------------
*
* Author: Markus Moeller (markus_moeller at compuserve.com)
*
* Copyright (C) 2007 Markus Moeller. All rights reserved.
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*
* -----------------------------------------------------------------------------
*/
#include "squid.h"
#include "util.h"
#ifdef HAVE_LDAP
#include "support.h"
struct ndstruct *init_nd(void);
void free_nd(struct ndstruct *ndsp);
struct ndstruct *
init_nd(void) {
struct ndstruct *ndsp;
ndsp = (struct ndstruct *) xmalloc(sizeof(struct ndstruct));
ndsp->netbios = NULL;
ndsp->domain = NULL;
ndsp->next = NULL;
return ndsp;
}
void
free_nd(struct ndstruct *ndsp)
{
while (ndsp) {
struct ndstruct *ndspn = ndsp->next;
xfree(ndsp->netbios);
xfree(ndsp->domain);
xfree(ndsp);
ndsp = ndspn;
}
}
int
create_nd(struct main_args *margs)
{
char *np, *dp;
char *p;
struct ndstruct *ndsp = NULL, *ndspn = NULL;
/*
* netbios list format:
*
* nlist=Pattern1[:Pattern2]
*
* Pattern=NetbiosName@Domain Netbios Name for a specific Kerberos domain
* ndstruct.domain=Domain, ndstruct.netbios=NetbiosName
*
*
*/
p = margs->nlist;
np = margs->nlist;
debug((char *) "%s| %s: DEBUG: Netbios list %s\n", LogTime(), PROGRAM, margs->nlist ? margs->nlist : "NULL");
dp = NULL;
if (!p) {
debug((char *) "%s| %s: DEBUG: No netbios names defined.\n", LogTime(), PROGRAM);
return (0);
}
while (*p) { /* loop over group list */
if (*p == '\n' || *p == '\r') { /* Ignore CR and LF if exist */
++p;
continue;
}
if (*p == '@') { /* end of group name - start of domain name */
if (p == np) { /* empty group name not allowed */
debug((char *) "%s| %s: DEBUG: No netbios name defined for domain %s\n", LogTime(), PROGRAM, p);
free_nd(ndsp);
return (1);
}
if (dp) { /* end of domain name - twice */
debug((char *) "%s| %s: @ is not allowed in netbios name %s@%s\n",LogTime(), PROGRAM,np,dp);
free_nd(ndsp);
return(1);
}
*p = '\0';
++p;
ndsp = init_nd();
ndsp->netbios = xstrdup(np);
ndsp->next = ndspn;
dp = p; /* after @ starts new domain name */
} else if (*p == ':') { /* end of group name or end of domain name */
if (p == np) { /* empty group name not allowed */
debug((char *) "%s| %s: DEBUG: No netbios name defined for domain %s\n", LogTime(), PROGRAM, p);
free_nd(ndsp);
return (1);
}
*p = '\0';
++p;
if (dp) { /* end of domain name */
ndsp->domain = xstrdup(dp);
dp = NULL;
} else { /* end of group name and no domain name */
ndsp = init_nd();
ndsp->netbios = xstrdup(np);
ndsp->next = ndspn;
}
ndspn = ndsp;
np = p; /* after : starts new group name */
if (!ndsp->domain || !strcmp(ndsp->domain, "")) {
debug((char *) "%s| %s: DEBUG: No domain defined for netbios name %s\n", LogTime(), PROGRAM, ndsp->netbios);
free_nd(ndsp);
return (1);
}
debug((char *) "%s| %s: DEBUG: Netbios name %s Domain %s\n", LogTime(), PROGRAM, ndsp->netbios, ndsp->domain);
} else
++p;
}
if (p == np) { /* empty group name not allowed */
debug((char *) "%s| %s: DEBUG: No netbios name defined for domain %s\n", LogTime(), PROGRAM, p);
free_nd(ndsp);
return (1);
}
if (dp) { /* end of domain name */
ndsp->domain = xstrdup(dp);
} else { /* end of group name and no domain name */
ndsp = init_nd();
ndsp->netbios = xstrdup(np);
ndsp->next = ndspn;
}
if (!ndsp->domain || !strcmp(ndsp->domain, "")) {
debug((char *) "%s| %s: DEBUG: No domain defined for netbios name %s\n", LogTime(), PROGRAM, ndsp->netbios);
free_nd(ndsp);
return (1);
}
debug((char *) "%s| %s: DEBUG: Netbios name %s Domain %s\n", LogTime(), PROGRAM, ndsp->netbios, ndsp->domain);
margs->ndoms = ndsp;
return (0);
}
char *
get_netbios_name(struct main_args *margs, char *netbios)
{
struct ndstruct *nd;
nd = margs->ndoms;
while (nd && netbios) {
debug((char *) "%s| %s: DEBUG: Netbios domain loop: netbios@domain %s@%s\n", LogTime(), PROGRAM, nd->netbios, nd->domain);
if (nd->netbios && !strcasecmp(nd->netbios, netbios)) {
debug((char *) "%s| %s: DEBUG: Found netbios@domain %s@%s\n", LogTime(), PROGRAM, nd->netbios, nd->domain);
return (nd->domain);
}
nd = nd->next;
}
return NULL;
}
#endif
| gpl-2.0 |
maxximino/dpacalc | dependencies/eigen/test/eigen2/eigen2_cwiseop.cpp | 6697 | // This file is part of Eigen, a lightweight C++ template library
// for linear algebra. Eigen itself is part of the KDE project.
//
// Copyright (C) 2008 Gael Guennebaud <[email protected]>
// Copyright (C) 2006-2008 Benoit Jacob <[email protected]>
//
// Eigen 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.
//
// Alternatively, 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.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "main.h"
#include <functional>
#include <Eigen/Array>
using namespace std;
template<typename Scalar> struct AddIfNull {
const Scalar operator() (const Scalar a, const Scalar b) const {return a<=1e-3 ? b : a;}
enum { Cost = NumTraits<Scalar>::AddCost };
};
template<typename MatrixType> void cwiseops(const MatrixType& m)
{
typedef typename MatrixType::Scalar Scalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType;
int rows = m.rows();
int cols = m.cols();
MatrixType m1 = MatrixType::Random(rows, cols),
m2 = MatrixType::Random(rows, cols),
m3(rows, cols),
m4(rows, cols),
mzero = MatrixType::Zero(rows, cols),
mones = MatrixType::Ones(rows, cols),
identity = Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime>
::Identity(rows, rows),
square = Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime>::Random(rows, rows);
VectorType v1 = VectorType::Random(rows),
v2 = VectorType::Random(rows),
vzero = VectorType::Zero(rows),
vones = VectorType::Ones(rows),
v3(rows);
int r = ei_random<int>(0, rows-1),
c = ei_random<int>(0, cols-1);
Scalar s1 = ei_random<Scalar>();
// test Zero, Ones, Constant, and the set* variants
m3 = MatrixType::Constant(rows, cols, s1);
for (int j=0; j<cols; ++j)
for (int i=0; i<rows; ++i)
{
VERIFY_IS_APPROX(mzero(i,j), Scalar(0));
VERIFY_IS_APPROX(mones(i,j), Scalar(1));
VERIFY_IS_APPROX(m3(i,j), s1);
}
VERIFY(mzero.isZero());
VERIFY(mones.isOnes());
VERIFY(m3.isConstant(s1));
VERIFY(identity.isIdentity());
VERIFY_IS_APPROX(m4.setConstant(s1), m3);
VERIFY_IS_APPROX(m4.setConstant(rows,cols,s1), m3);
VERIFY_IS_APPROX(m4.setZero(), mzero);
VERIFY_IS_APPROX(m4.setZero(rows,cols), mzero);
VERIFY_IS_APPROX(m4.setOnes(), mones);
VERIFY_IS_APPROX(m4.setOnes(rows,cols), mones);
m4.fill(s1);
VERIFY_IS_APPROX(m4, m3);
VERIFY_IS_APPROX(v3.setConstant(rows, s1), VectorType::Constant(rows,s1));
VERIFY_IS_APPROX(v3.setZero(rows), vzero);
VERIFY_IS_APPROX(v3.setOnes(rows), vones);
m2 = m2.template binaryExpr<AddIfNull<Scalar> >(mones);
VERIFY_IS_APPROX(m1.cwise().pow(2), m1.cwise().abs2());
VERIFY_IS_APPROX(m1.cwise().pow(2), m1.cwise().square());
VERIFY_IS_APPROX(m1.cwise().pow(3), m1.cwise().cube());
VERIFY_IS_APPROX(m1 + mones, m1.cwise()+Scalar(1));
VERIFY_IS_APPROX(m1 - mones, m1.cwise()-Scalar(1));
m3 = m1; m3.cwise() += 1;
VERIFY_IS_APPROX(m1 + mones, m3);
m3 = m1; m3.cwise() -= 1;
VERIFY_IS_APPROX(m1 - mones, m3);
VERIFY_IS_APPROX(m2, m2.cwise() * mones);
VERIFY_IS_APPROX(m1.cwise() * m2, m2.cwise() * m1);
m3 = m1;
m3.cwise() *= m2;
VERIFY_IS_APPROX(m3, m1.cwise() * m2);
VERIFY_IS_APPROX(mones, m2.cwise()/m2);
if(NumTraits<Scalar>::HasFloatingPoint)
{
VERIFY_IS_APPROX(m1.cwise() / m2, m1.cwise() * (m2.cwise().inverse()));
m3 = m1.cwise().abs().cwise().sqrt();
VERIFY_IS_APPROX(m3.cwise().square(), m1.cwise().abs());
VERIFY_IS_APPROX(m1.cwise().square().cwise().sqrt(), m1.cwise().abs());
VERIFY_IS_APPROX(m1.cwise().abs().cwise().log().cwise().exp() , m1.cwise().abs());
VERIFY_IS_APPROX(m1.cwise().pow(2), m1.cwise().square());
m3 = (m1.cwise().abs().cwise()<=RealScalar(0.01)).select(mones,m1);
VERIFY_IS_APPROX(m3.cwise().pow(-1), m3.cwise().inverse());
m3 = m1.cwise().abs();
VERIFY_IS_APPROX(m3.cwise().pow(RealScalar(0.5)), m3.cwise().sqrt());
// VERIFY_IS_APPROX(m1.cwise().tan(), m1.cwise().sin().cwise() / m1.cwise().cos());
VERIFY_IS_APPROX(mones, m1.cwise().sin().cwise().square() + m1.cwise().cos().cwise().square());
m3 = m1;
m3.cwise() /= m2;
VERIFY_IS_APPROX(m3, m1.cwise() / m2);
}
// check min
VERIFY_IS_APPROX( m1.cwise().min(m2), m2.cwise().min(m1) );
VERIFY_IS_APPROX( m1.cwise().min(m1+mones), m1 );
VERIFY_IS_APPROX( m1.cwise().min(m1-mones), m1-mones );
// check max
VERIFY_IS_APPROX( m1.cwise().max(m2), m2.cwise().max(m1) );
VERIFY_IS_APPROX( m1.cwise().max(m1-mones), m1 );
VERIFY_IS_APPROX( m1.cwise().max(m1+mones), m1+mones );
VERIFY( (m1.cwise() == m1).all() );
VERIFY( (m1.cwise() != m2).any() );
VERIFY(!(m1.cwise() == (m1+mones)).any() );
if (rows*cols>1)
{
m3 = m1;
m3(r,c) += 1;
VERIFY( (m1.cwise() == m3).any() );
VERIFY( !(m1.cwise() == m3).all() );
}
VERIFY( (m1.cwise().min(m2).cwise() <= m2).all() );
VERIFY( (m1.cwise().max(m2).cwise() >= m2).all() );
VERIFY( (m1.cwise().min(m2).cwise() < (m1+mones)).all() );
VERIFY( (m1.cwise().max(m2).cwise() > (m1-mones)).all() );
VERIFY( (m1.cwise()<m1.unaryExpr(bind2nd(plus<Scalar>(), Scalar(1)))).all() );
VERIFY( !(m1.cwise()<m1.unaryExpr(bind2nd(minus<Scalar>(), Scalar(1)))).all() );
VERIFY( !(m1.cwise()>m1.unaryExpr(bind2nd(plus<Scalar>(), Scalar(1)))).any() );
}
void test_eigen2_cwiseop()
{
for(int i = 0; i < g_repeat ; i++) {
CALL_SUBTEST_1( cwiseops(Matrix<float, 1, 1>()) );
CALL_SUBTEST_2( cwiseops(Matrix4d()) );
CALL_SUBTEST_3( cwiseops(MatrixXf(3, 3)) );
CALL_SUBTEST_3( cwiseops(MatrixXf(22, 22)) );
CALL_SUBTEST_4( cwiseops(MatrixXi(8, 12)) );
CALL_SUBTEST_5( cwiseops(MatrixXd(20, 20)) );
}
}
| gpl-2.0 |
liuyanghejerry/qtextended | examples/server/plugins/exampletask/exampletask.cpp | 1421 | /****************************************************************************
**
** This file is part of the Qt Extended Opensource Package.
**
** Copyright (C) 2009 Trolltech ASA.
**
** Contact: Qt Extended Information ([email protected])
**
** This file may be used under the terms of the GNU General Public License
** version 2.0 as published by the Free Software Foundation and appearing
** in the file LICENSE.GPL included in the packaging of this file.
**
** Please review the following information to ensure GNU General Public
** Licensing requirements will be met:
** http://www.fsf.org/licensing/licenses/info/GPLv2.html.
**
**
****************************************************************************/
#include "exampletask.h"
#include <qtopiaglobal.h>
#include <QDebug>
class ExampleTask: public QObject
{
public:
ExampleTask( QObject* parent = 0 ) : QObject(parent)
{
//server task code
}
~ExampleTask()
{
}
};
ExampleTaskPlugin::ExampleTaskPlugin(QObject* parent)
: ServerTaskPlugin( parent )
{
}
ExampleTaskPlugin::~ExampleTaskPlugin()
{
}
QByteArray ExampleTaskPlugin::name() const
{
return QByteArray("ExampleTask");
}
QObject* ExampleTaskPlugin::initTask(void* createArg ) const
{
Q_UNUSED( createArg );
return new ExampleTask();
}
bool ExampleTaskPlugin::demand() const
{
return true;
}
QTOPIA_EXPORT_PLUGIN( ExampleTaskPlugin )
| gpl-2.0 |
itsimbal/gcc.cet | libsanitizer/asan/asan_memory_profile.cc | 3060 | //===-- asan_memory_profile.cc.cc -----------------------------------------===//
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of AddressSanitizer, an address sanity checker.
//
// This file implements __sanitizer_print_memory_profile.
//===----------------------------------------------------------------------===//
#include "sanitizer_common/sanitizer_common.h"
#include "sanitizer_common/sanitizer_stackdepot.h"
#include "sanitizer_common/sanitizer_stacktrace.h"
#include "sanitizer_common/sanitizer_stoptheworld.h"
#include "lsan/lsan_common.h"
#include "asan/asan_allocator.h"
#if CAN_SANITIZE_LEAKS
namespace __asan {
struct AllocationSite {
u32 id;
uptr total_size;
uptr count;
};
class HeapProfile {
public:
HeapProfile() : allocations_(1024) {}
void Insert(u32 id, uptr size) {
total_allocated_ += size;
total_count_++;
// Linear lookup will be good enough for most cases (although not all).
for (uptr i = 0; i < allocations_.size(); i++) {
if (allocations_[i].id == id) {
allocations_[i].total_size += size;
allocations_[i].count++;
return;
}
}
allocations_.push_back({id, size, 1});
}
void Print(uptr top_percent) {
InternalSort(&allocations_, allocations_.size(),
[](const AllocationSite &a, const AllocationSite &b) {
return a.total_size > b.total_size;
});
CHECK(total_allocated_);
uptr total_shown = 0;
Printf("Live Heap Allocations: %zd bytes from %zd allocations; "
"showing top %zd%%\n", total_allocated_, total_count_, top_percent);
for (uptr i = 0; i < allocations_.size(); i++) {
auto &a = allocations_[i];
Printf("%zd byte(s) (%zd%%) in %zd allocation(s)\n", a.total_size,
a.total_size * 100 / total_allocated_, a.count);
StackDepotGet(a.id).Print();
total_shown += a.total_size;
if (total_shown * 100 / total_allocated_ > top_percent)
break;
}
}
private:
uptr total_allocated_ = 0;
uptr total_count_ = 0;
InternalMmapVector<AllocationSite> allocations_;
};
static void ChunkCallback(uptr chunk, void *arg) {
HeapProfile *hp = reinterpret_cast<HeapProfile*>(arg);
AsanChunkView cv = FindHeapChunkByAllocBeg(chunk);
if (!cv.IsAllocated()) return;
u32 id = cv.GetAllocStackId();
if (!id) return;
hp->Insert(id, cv.UsedSize());
}
static void MemoryProfileCB(const SuspendedThreadsList &suspended_threads_list,
void *argument) {
HeapProfile hp;
__lsan::ForEachChunk(ChunkCallback, &hp);
hp.Print(reinterpret_cast<uptr>(argument));
}
} // namespace __asan
extern "C" {
SANITIZER_INTERFACE_ATTRIBUTE
void __sanitizer_print_memory_profile(uptr top_percent) {
__sanitizer::StopTheWorld(__asan::MemoryProfileCB, (void*)top_percent);
}
} // extern "C"
#endif // CAN_SANITIZE_LEAKS
| gpl-2.0 |
aglne/pluotsorbet | java/midp/com/sun/j2me/crypto/MessageDigest.java | 2179 | /*
*
*
* Copyright 1990-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, 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 version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package com.sun.j2me.crypto;
/**
* Provides applications the functionality of a message digest algorithm
*/
public class MessageDigest {
/**
* Message digest implementation.
*/
com.sun.midp.crypto.MessageDigest messageDigest;
public MessageDigest(String algorithm) throws NoSuchAlgorithmException {
try {
messageDigest = com.sun.midp.crypto.MessageDigest.getInstance(algorithm);
}
catch (com.sun.midp.crypto.NoSuchAlgorithmException e) {
throw new NoSuchAlgorithmException(e.getMessage());
}
}
public void reset() {
messageDigest.reset();
}
public void update(byte[] input, int offset, int len) {
messageDigest.update(input, offset, len);
}
public void digest(byte[] buf, int offset, int len) throws DigestException {
try {
messageDigest.digest(buf, offset, len);
} catch (com.sun.midp.crypto.DigestException e) {
throw new DigestException(e.getMessage());
}
}
public int getDigestLength() {
return messageDigest.getDigestLength();
}
}
| gpl-2.0 |
adamwinn/Jackett | src/Jackett/Models/IndexerConfig/ConfigurationDataBasicLoginWithRSS.cs | 696 | using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Jackett.Models.IndexerConfig
{
public class ConfigurationDataBasicLoginWithRSS : ConfigurationData
{
public StringItem Username { get; private set; }
public StringItem Password { get; private set; }
public HiddenItem RSSKey { get; private set; }
public ConfigurationDataBasicLoginWithRSS()
{
Username = new StringItem { Name = "Username" };
Password = new StringItem { Name = "Password" };
RSSKey = new HiddenItem { Name = "RSSKey" };
}
}
}
| gpl-2.0 |
draekko/codelite | Plugin/EditDlg.cpp | 1775 | //////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//
// copyright : (C) 2014 The CodeLite Team
// file name : EditDlg.cpp
//
// -------------------------------------------------------------------------
// A
// _____ _ _ _ _
// / __ \ | | | | (_) |
// | / \/ ___ __| | ___| | _| |_ ___
// | | / _ \ / _ |/ _ \ | | | __/ _ )
// | \__/\ (_) | (_| | __/ |___| | || __/
// \____/\___/ \__,_|\___\_____/_|\__\___|
//
// F i l e
//
// 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.
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
#include "EditDlg.h"
#include "lexer_configuration.h"
#include "editor_config.h"
#include "windowattrmanager.h"
EditDlg::EditDlg(wxWindow* parent, const wxString& text)
: EditDlgBase(parent)
{
LexerConf::Ptr_t lex = EditorConfigST::Get()->GetLexer("text");
lex->Apply(m_stc10);
m_stc10->SetText(text);
SetName("EditDlg");
WindowAttrManager::Load(this);
}
EditDlg::~EditDlg() {}
wxString clGetStringFromUser(const wxString& initialValue, wxWindow* parent)
{
EditDlg dlg(parent, initialValue);
if(dlg.ShowModal() == wxID_OK) {
return dlg.GetText();
}
return wxEmptyString;
}
| gpl-2.0 |
ruchong/d8 | core/modules/config_translation/tests/src/Unit/ConfigNamesMapperTest.php | 22110 | <?php
/**
* @file
* Contains \Drupal\Tests\config_translation\Unit\ConfigNamesMapperTest.
*/
namespace Drupal\Tests\config_translation\Unit;
use Drupal\config_translation\ConfigNamesMapper;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\Language\Language;
use Drupal\Core\Url;
use Drupal\Tests\UnitTestCase;
use Symfony\Component\Routing\Route;
use Symfony\Component\HttpFoundation\Request;
/**
* Tests the functionality provided by the configuration names mapper.
*
* @group config_translation
*/
class ConfigNamesMapperTest extends UnitTestCase {
/**
* The plugin definition of the test mapper.
*
* @var array
*/
protected $pluginDefinition;
/**
* The configuration names mapper to test.
*
* @see \Drupal\config_translation\ConfigNamesMapper
*
* @var \Drupal\Tests\config_translation\Unit\TestConfigNamesMapper
*/
protected $configNamesMapper;
/**
* The locale configuration manager.
*
* @var \Drupal\locale\LocaleConfigManager|\PHPUnit_Framework_MockObject_MockObject
*/
protected $localeConfigManager;
/**
* The locale configuration manager.
*
* @var \Drupal\locale\LocaleConfigManager|\PHPUnit_Framework_MockObject_MockObject
*/
protected $typedConfigManager;
/**
* The configuration mapper manager.
*
* @var \Drupal\config_translation\ConfigMapperManagerInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $configMapperManager;
/**
* The base route used for testing.
*
* @var \Symfony\Component\Routing\Route
*/
protected $baseRoute;
/**
* The route provider used for testing.
*
* @var \Drupal\Core\Routing\RouteProviderInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $routeProvider;
/**
* The mocked URL generator.
*
* @var \Drupal\Core\Routing\UrlGeneratorInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $urlGenerator;
/**
* The mocked language manager.
*
* @var \Drupal\Core\Language\LanguageManagerInterface $language_manager|\PHPUnit_Framework_MockObject_MockObject
*/
protected $languageManager;
protected function setUp() {
$this->routeProvider = $this->getMock('Drupal\Core\Routing\RouteProviderInterface');
$this->pluginDefinition = array(
'class' => '\Drupal\config_translation\ConfigNamesMapper',
'base_route_name' => 'system.site_information_settings',
'title' => 'System information',
'names' => array('system.site'),
'weight' => 42,
);
$this->typedConfigManager = $this->getMock('Drupal\Core\Config\TypedConfigManagerInterface');
$this->localeConfigManager = $this->getMockBuilder('Drupal\locale\LocaleConfigManager')
->disableOriginalConstructor()
->getMock();
$this->configMapperManager = $this->getMock('Drupal\config_translation\ConfigMapperManagerInterface');
$this->urlGenerator = $this->getMock('Drupal\Core\Routing\UrlGeneratorInterface');
$container = new ContainerBuilder();
$container->set('url_generator', $this->urlGenerator);
\Drupal::setContainer($container);
$this->baseRoute = new Route('/admin/config/system/site-information');
$this->routeProvider
->expects($this->any())
->method('getRouteByName')
->with('system.site_information_settings')
->will($this->returnValue($this->baseRoute));
$this->languageManager = $this->getMock('Drupal\Core\Language\LanguageManagerInterface');
$this->configNamesMapper = new TestConfigNamesMapper(
'system.site_information_settings',
$this->pluginDefinition,
$this->getConfigFactoryStub(),
$this->typedConfigManager,
$this->localeConfigManager,
$this->configMapperManager,
$this->routeProvider,
$this->getStringTranslationStub(),
$this->languageManager
);
}
/**
* Tests ConfigNamesMapper::getTitle().
*/
public function testGetTitle() {
$result = $this->configNamesMapper->getTitle();
$this->assertSame($this->pluginDefinition['title'], $result);
}
/**
* Tests ConfigNamesMapper::getBaseRouteName().
*/
public function testGetBaseRouteName() {
$result = $this->configNamesMapper->getBaseRouteName();
$this->assertSame($this->pluginDefinition['base_route_name'], $result);
}
/**
* Tests ConfigNamesMapper::getBaseRouteParameters().
*/
public function testGetBaseRouteParameters() {
$result = $this->configNamesMapper->getBaseRouteParameters();
$this->assertSame(array(), $result);
}
/**
* Tests ConfigNamesMapper::getBaseRoute().
*/
public function testGetBaseRoute() {
$result = $this->configNamesMapper->getBaseRoute();
$this->assertSame($this->baseRoute, $result);
}
/**
* Tests ConfigNamesMapper::getBasePath().
*/
public function testGetBasePath() {
$this->urlGenerator->expects($this->once())
->method('getPathFromRoute')
->with('system.site_information_settings', [])
->willReturn('/admin/config/system/site-information');
$result = $this->configNamesMapper->getBasePath();
$this->assertSame('/admin/config/system/site-information', $result);
}
/**
* Tests ConfigNamesMapper::getOverviewRouteName().
*/
public function testGetOverviewRouteName() {
$result = $this->configNamesMapper->getOverviewRouteName();
$expected = 'config_translation.item.overview.' . $this->pluginDefinition['base_route_name'];
$this->assertSame($expected, $result);
}
/**
* Tests ConfigNamesMapper::getOverviewRouteParameters().
*/
public function testGetOverviewRouteParameters() {
$result = $this->configNamesMapper->getOverviewRouteParameters();
$this->assertSame(array(), $result);
}
/**
* Tests ConfigNamesMapper::getOverviewRoute().
*/
public function testGetOverviewRoute() {
$expected = new Route('/admin/config/system/site-information/translate',
array(
'_controller' => '\Drupal\config_translation\Controller\ConfigTranslationController::itemPage',
'plugin_id' => 'system.site_information_settings',
),
array(
'_config_translation_overview_access' => 'TRUE',
)
);
$result = $this->configNamesMapper->getOverviewRoute();
$this->assertSame(serialize($expected), serialize($result));
}
/**
* Tests ConfigNamesMapper::getOverviewPath().
*/
public function testGetOverviewPath() {
$this->urlGenerator->expects($this->once())
->method('getPathFromRoute')
->with('config_translation.item.overview.system.site_information_settings', [])
->willReturn('/admin/config/system/site-information/translate');
$result = $this->configNamesMapper->getOverviewPath();
$this->assertSame('/admin/config/system/site-information/translate', $result);
}
/**
* Tests ConfigNamesMapper::getAddRouteName().
*/
public function testGetAddRouteName() {
$result = $this->configNamesMapper->getAddRouteName();
$expected = 'config_translation.item.add.' . $this->pluginDefinition['base_route_name'];
$this->assertSame($expected, $result);
}
/**
* Tests ConfigNamesMapper::getAddRouteParameters().
*/
public function testGetAddRouteParameters() {
$request = Request::create('');
$request->attributes->set('langcode', 'xx');
$this->configNamesMapper->populateFromRequest($request);
$expected = array('langcode' => 'xx');
$result = $this->configNamesMapper->getAddRouteParameters();
$this->assertSame($expected, $result);
}
/**
* Tests ConfigNamesMapper::getAddRoute().
*/
public function testGetAddRoute() {
$expected = new Route('/admin/config/system/site-information/translate/{langcode}/add',
array(
'_form' => '\Drupal\config_translation\Form\ConfigTranslationAddForm',
'plugin_id' => 'system.site_information_settings',
),
array(
'_config_translation_form_access' => 'TRUE',
)
);
$result = $this->configNamesMapper->getAddRoute();
$this->assertSame(serialize($expected), serialize($result));
}
/**
* Tests ConfigNamesMapper::getEditRouteName().
*/
public function testGetEditRouteName() {
$result = $this->configNamesMapper->getEditRouteName();
$expected = 'config_translation.item.edit.' . $this->pluginDefinition['base_route_name'];
$this->assertSame($expected, $result);
}
/**
* Tests ConfigNamesMapper::getEditRouteParameters().
*/
public function testGetEditRouteParameters() {
$request = Request::create('');
$request->attributes->set('langcode', 'xx');
$this->configNamesMapper->populateFromRequest($request);
$expected = array('langcode' => 'xx');
$result = $this->configNamesMapper->getEditRouteParameters();
$this->assertSame($expected, $result);
}
/**
* Tests ConfigNamesMapper::getEditRoute().
*/
public function testGetEditRoute() {
$expected = new Route('/admin/config/system/site-information/translate/{langcode}/edit',
array(
'_form' => '\Drupal\config_translation\Form\ConfigTranslationEditForm',
'plugin_id' => 'system.site_information_settings',
),
array(
'_config_translation_form_access' => 'TRUE',
)
);
$result = $this->configNamesMapper->getEditRoute();
$this->assertSame(serialize($expected), serialize($result));
}
/**
* Tests ConfigNamesMapper::getDeleteRouteName().
*/
public function testGetDeleteRouteName() {
$result = $this->configNamesMapper->getDeleteRouteName();
$expected = 'config_translation.item.delete.' . $this->pluginDefinition['base_route_name'];
$this->assertSame($expected, $result);
}
/**
* Tests ConfigNamesMapper::getDeleteRouteParameters().
*/
public function testGetDeleteRouteParameters() {
$request = Request::create('');
$request->attributes->set('langcode', 'xx');
$this->configNamesMapper->populateFromRequest($request);
$expected = array('langcode' => 'xx'); $result = $this->configNamesMapper->getDeleteRouteParameters();
$this->assertSame($expected, $result);
}
/**
* Tests ConfigNamesMapper::getRoute().
*/
public function testGetDeleteRoute() {
$expected = new Route('/admin/config/system/site-information/translate/{langcode}/delete',
array(
'_form' => '\Drupal\config_translation\Form\ConfigTranslationDeleteForm',
'plugin_id' => 'system.site_information_settings',
),
array(
'_config_translation_form_access' => 'TRUE',
)
);
$result = $this->configNamesMapper->getDeleteRoute();
$this->assertSame(serialize($expected), serialize($result));
}
/**
* Tests ConfigNamesMapper::getConfigNames().
*/
public function testGetConfigNames() {
$result = $this->configNamesMapper->getConfigNames();
$this->assertSame($this->pluginDefinition['names'], $result);
}
/**
* Tests ConfigNamesMapper::addConfigName().
*/
public function testAddConfigName() {
$names = $this->configNamesMapper->getConfigNames();
$this->configNamesMapper->addConfigName('test');
$names[] = 'test';
$result = $this->configNamesMapper->getConfigNames();
$this->assertSame($names, $result);
}
/**
* Tests ConfigNamesMapper::getWeight().
*/
public function testGetWeight() {
$result = $this->configNamesMapper->getWeight();
$this->assertSame($this->pluginDefinition['weight'], $result);
}
/**
* Tests ConfigNamesMapper::populateFromRequest().
*/
public function testPopulateFromRequest() {
// Make sure the language code is not set initially.
$this->assertSame(NULL, $this->configNamesMapper->getInternalLangcode());
// Test that an empty request does not set the language code.
$request = Request::create('');
$this->configNamesMapper->populateFromRequest($request);
$this->assertSame(NULL, $this->configNamesMapper->getInternalLangcode());
// Test that a request with a 'langcode' attribute sets the language code.
$request->attributes->set('langcode', 'xx');
$this->configNamesMapper->populateFromRequest($request);
$this->assertSame('xx', $this->configNamesMapper->getInternalLangcode());
// Test that the language code gets unset with the wrong request.
$request->attributes->remove('langcode');
$this->configNamesMapper->populateFromRequest($request);
$this->assertSame(NULL, $this->configNamesMapper->getInternalLangcode());
}
/**
* Tests ConfigNamesMapper::getTypeLabel().
*/
public function testGetTypeLabel() {
$result = $this->configNamesMapper->getTypeLabel();
$this->assertSame($this->pluginDefinition['title'], $result);
}
/**
* Tests ConfigNamesMapper::getLangcode().
*/
public function testGetLangcode() {
// Test that the getLangcode() falls back to 'en', if no explicit language
// code is provided.
$config_factory = $this->getConfigFactoryStub(array(
'system.site' => array('key' => 'value'),
));
$this->configNamesMapper->setConfigFactory($config_factory);
$result = $this->configNamesMapper->getLangcode();
$this->assertSame('en', $result);
// Test that getLangcode picks up the language code provided by the
// configuration.
$config_factory = $this->getConfigFactoryStub(array(
'system.site' => array('langcode' => 'xx'),
));
$this->configNamesMapper->setConfigFactory($config_factory);
$result = $this->configNamesMapper->getLangcode();
$this->assertSame('xx', $result);
// Test that getLangcode() works for multiple configuration names.
$this->configNamesMapper->addConfigName('system.maintenance');
$config_factory = $this->getConfigFactoryStub(array(
'system.site' => array('langcode' => 'xx'),
'system.maintenance' => array('langcode' => 'xx'),
));
$this->configNamesMapper->setConfigFactory($config_factory);
$result = $this->configNamesMapper->getLangcode();
$this->assertSame('xx', $result);
// Test that getLangcode() throws an exception when different language codes
// are given.
$config_factory = $this->getConfigFactoryStub(array(
'system.site' => array('langcode' => 'xx'),
'system.maintenance' => array('langcode' => 'yy'),
));
$this->configNamesMapper->setConfigFactory($config_factory);
try {
$this->configNamesMapper->getLangcode();
$this->fail();
}
catch (\RuntimeException $e) {}
}
// @todo Test ConfigNamesMapper::getLanguageWithFallback() once
// https://drupal.org/node/1862202 lands in core, because then we can
// remove the direct language_load() call.
/**
* Tests ConfigNamesMapper::getConfigData().
*/
public function testGetConfigData() {
$configs = array(
'system.site' => array(
'name' => 'Drupal',
'slogan' => 'Come for the software, stay for the community!',
),
'system.maintenance' => array(
'enabled' => FALSE,
'message' => '@site is currently under maintenance.',
),
'system.rss' => array(
'items' => array(
'limit' => 10,
'view_mode' => 'rss',
),
),
);
$this->configNamesMapper->setConfigNames(array_keys($configs));
$config_factory = $this->getConfigFactoryStub($configs);
$this->configNamesMapper->setConfigFactory($config_factory);
$result = $this->configNamesMapper->getConfigData();
$this->assertSame($configs, $result);
}
/**
* Tests ConfigNamesMapper::hasSchema().
*
* @param array $mock_return_values
* An array of values that the mocked locale configuration manager should
* return for hasConfigSchema().
* @param bool $expected
* The expected return value of ConfigNamesMapper::hasSchema().
*
* @dataProvider providerTestHasSchema
*/
public function testHasSchema(array $mock_return_values, $expected) {
// As the configuration names are arbitrary, simply use integers.
$config_names = range(1, count($mock_return_values));
$this->configNamesMapper->setConfigNames($config_names);
$map = array();
foreach ($config_names as $i => $config_name) {
$map[] = array($config_name, $mock_return_values[$i]);
}
$this->typedConfigManager
->expects($this->any())
->method('hasConfigSchema')
->will($this->returnValueMap($map));
$result = $this->configNamesMapper->hasSchema();
$this->assertSame($expected, $result);
}
/**
* Provides data for for ConfigMapperTest::testHasSchema().
*
* @return array
* An array of arrays, where each inner array has an array of values that
* the mocked locale configuration manager should return for
* hasConfigSchema() as the first value and the expected return value of
* ConfigNamesMapper::hasSchema() as the second value.
*/
public function providerTestHasSchema() {
return array(
array(array(TRUE), TRUE),
array(array(FALSE), FALSE),
array(array(TRUE, TRUE, TRUE), TRUE),
array(array(TRUE, FALSE, TRUE), FALSE),
);
}
/**
* Tests ConfigNamesMapper::hasTranslatable().
*
* @param array $mock_return_values
* An array of values that the mocked configuration mapper manager should
* return for hasTranslatable().
* @param bool $expected
* The expected return value of ConfigNamesMapper::hasTranslatable().
*
* @dataProvider providerTestHasTranslatable
*/
public function testHasTranslatable(array $mock_return_values, $expected) {
// As the configuration names are arbitrary, simply use integers.
$config_names = range(1, count($mock_return_values));
$this->configNamesMapper->setConfigNames($config_names);
$map = array();
foreach ($config_names as $i => $config_name) {
$map[] = array($config_name, $mock_return_values[$i]);
}
$this->configMapperManager
->expects($this->any())
->method('hasTranslatable')
->will($this->returnValueMap($map));
$result = $this->configNamesMapper->hasTranslatable();
$this->assertSame($expected, $result);
}
/**
* Provides data for ConfigNamesMapperTest::testHasTranslatable().
*
* @return array
* An array of arrays, where each inner array has an array of values that
* the mocked configuration mapper manager should return for
* hasTranslatable() as the first value and the expected return value of
* ConfigNamesMapper::hasTranslatable() as the second value.
*/
public function providerTestHasTranslatable() {
return array(
array(array(TRUE), TRUE),
array(array(FALSE), FALSE),
array(array(TRUE, TRUE, TRUE), TRUE),
array(array(TRUE, FALSE, TRUE), FALSE),
);
}
/**
* Tests ConfigNamesMapper::hasTranslation().
*
* @param array $mock_return_values
* An array of values that the mocked configuration mapper manager should
* return for hasTranslation().
* @param bool $expected
* The expected return value of ConfigNamesMapper::hasTranslation().
*
* @dataProvider providerTestHasTranslation
*/
public function testHasTranslation(array $mock_return_values, $expected) {
$language = new Language();
// As the configuration names are arbitrary, simply use integers.
$config_names = range(1, count($mock_return_values));
$this->configNamesMapper->setConfigNames($config_names);
$map = array();
foreach ($config_names as $i => $config_name) {
$map[] = array($config_name, $language, $mock_return_values[$i]);
}
$this->localeConfigManager
->expects($this->any())
->method('hasTranslation')
->will($this->returnValueMap($map));
$result = $this->configNamesMapper->hasTranslation($language);
$this->assertSame($expected, $result);
}
/**
* Provides data for for ConfigNamesMapperTest::testHasTranslation().
*
* @return array
* An array of arrays, where each inner array has an array of values that
* the mocked configuration mapper manager should return for
* hasTranslation() as the first value and the expected return value of
* ConfigNamesMapper::hasTranslation() as the second value.
*/
public function providerTestHasTranslation() {
return array(
array(array(TRUE), TRUE),
array(array(FALSE), FALSE),
array(array(TRUE, TRUE, TRUE), TRUE),
array(array(FALSE, FALSE, TRUE), TRUE),
array(array(FALSE, FALSE, FALSE), FALSE),
);
}
/**
* Tests ConfigNamesMapper::getTypeName().
*/
public function testGetTypeName() {
$result = $this->configNamesMapper->getTypeName();
$this->assertSame('Settings', $result);
}
/**
* Tests ConfigNamesMapper::hasTranslation().
*/
public function testGetOperations() {
$expected = array(
'translate' => array(
'title' => 'Translate',
'url' => Url::fromRoute('config_translation.item.overview.system.site_information_settings'),
),
);
$result = $this->configNamesMapper->getOperations();
$this->assertEquals($expected, $result);
}
}
/**
* Defines a test mapper class.
*/
class TestConfigNamesMapper extends ConfigNamesMapper {
/**
* Gets the internal language code of this mapper, if any.
*
* This method is not to be confused with
* ConfigMapperInterface::getLangcode().
*
* @return string|null
* The language code of this mapper if it is set; NULL otherwise.
*/
public function getInternalLangcode() {
return isset($this->langcode) ? $this->langcode : NULL;
}
/**
* Sets the list of configuration names.
*
* @param array $config_names
*/
public function setConfigNames(array $config_names) {
$this->pluginDefinition['names'] = $config_names;
}
/**
* Sets the configuration factory.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The config factory to set.
*/
public function setConfigFactory(ConfigFactoryInterface $config_factory) {
$this->configFactory = $config_factory;
}
}
| gpl-2.0 |
liuyanghejerry/qtextended | qbuild/extensions/runlast.js | 1698 | /****************************************************************************
**
** This file is part of the Qt Extended Opensource Package.
**
** Copyright (C) 2009 Trolltech ASA.
**
** Contact: Qt Extended Information ([email protected])
**
** This file may be used under the terms of the GNU General Public License
** version 2.0 as published by the Free Software Foundation and appearing
** in the file LICENSE.GPL included in the packaging of this file.
**
** Please review the following information to ensure GNU General Public
** Licensing requirements will be met:
** http://www.fsf.org/licensing/licenses/info/GPLv2.html.
**
**
****************************************************************************/
/*!
\extension runlast
This extension allows you run snippets of code "last". That is, after all other extensions have been finalized.
You need to enable it.
\code
CONFIG+=runlast
RUNLAST+="message(hi mom)"
\endcode
*/
/*!
\qbuild_variable RUNLAST
\ingroup runlast_extension
Assign snippets of code to this variable to have them run "last".
Each element of the list is one snippet so quoting is important.
\code
RUNLAST+=\
"message(hi mom)"\
"contains(SOURCES,main.cpp):message(has a main.cpp)"
\endcode
*/
function runlast_init()
{
// There's no way to make something run "last" so this extension is specially handled in qbuild.
###
QMAKE.FINALIZE.runlast.CALL = runlast_finalize
RUNLAST=
###
}
function runlast_finalize()
{
var runlast = project.property("RUNLAST").value();
if ( !runlast || !runlast.length )
return;
for ( var ii in runlast ) {
var snippet = runlast[ii];
project.run(snippet);
}
}
| gpl-2.0 |
anhredweb/togtejendomme.dk | plugins/system/shlib/shl_packages/mvc/layouts/layout.php | 799 | <?php
/**
* Shlib - programming library
*
* @author Yannick Gaultier
* @copyright (c) Yannick Gaultier 2013
* @package shlib
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
* @version 0.2.8.369
* @date 2013-12-21
*/
/** ensure this file is being included by a parent file */
defined('_JEXEC') or die;
/**
* Interface to handle display layout
*
* @package Joomla.Libraries
* @subpackage Layout
* @since 3.0
*/
interface ShlMvcLayout
{
/**
* Method to render the layout.
*
* @param object $displayData Object which properties are used inside the layout file to build displayed output
*
* @return string The rendered layout.
*
* @since 3.0
*/
public function render($displayData);
}
| gpl-2.0 |
yed30/PlatformUIBundle | Tests/js/views/navigation/assets/ez-navigationitemsubtreeview-tests.js | 3530 | /*
* Copyright (C) eZ Systems AS. All rights reserved.
* For full copyright and license information view LICENSE file distributed with this source code.
*/
YUI.add('ez-navigationitemsubtreeview-tests', function (Y) {
var viewTest,
matchTest,
Assert = Y.Assert;
viewTest = new Y.Test.Case({
name: "eZ Navigation Item Subtree View test",
setUp: function () {
this.title = "Title";
this.route = {
name: "viewLocation",
params: {
id: 42,
languageCode: 'eng-GB',
}
};
this.view = new Y.eZ.NavigationItemSubtreeView({
title: this.title,
route: this.route,
});
},
tearDown: function () {
this.view.destroy();
delete this.view;
},
"Should use the navigation item view template": function () {
this.view.render();
Assert.areEqual(
Y.one('#navigationitemview-ez-template').get('text'),
this.view.get('container').get('text')
);
},
});
matchTest = new Y.Test.Case({
name: "eZ Navigation Item View match test",
setUp: function () {
this.routeName = 'viewLocation';
this.locationId = '/2/42/4242';
this.route = {
name: this.routeName,
params: {
id: this.locationId,
languageCode: 'eng-GB',
}
};
this.view = new Y.eZ.NavigationItemSubtreeView({
route: this.route,
});
},
tearDown: function () {
this.view.destroy();
delete this.view;
},
"Should match with the same route": function () {
var route = {
name: this.routeName,
parameters: {
id: this.locationId,
}
};
Assert.isTrue(
this.view.matchRoute(route),
"The navigation item should match"
);
},
"Should not match with a different route": function () {
Assert.isFalse(
this.view.matchRoute({name: this.routeName + 'a different route'}),
"The navigation item should match"
);
},
"Should match with a route pointing to a subitem": function () {
var route = {
name: this.routeName,
parameters: {
id: this.locationId + '/4242424',
},
};
Assert.isTrue(
this.view.matchRoute(route),
"The navigation item should match"
);
},
"Should not match with a route pointing to a different subtree": function () {
var route = {
name: this.routeName,
parameters: {
id: '/2/43/42',
},
};
Assert.isFalse(
this.view.matchRoute(route),
"The navigation item should match"
);
},
});
Y.Test.Runner.setName("eZ Navigation Item View tests");
Y.Test.Runner.add(viewTest);
Y.Test.Runner.add(matchTest);
}, '', {requires: ['test', 'ez-navigationitemsubtreeview']});
| gpl-2.0 |
Lucoms/SkyMist-Core | src/server/scripts/Commands/cs_modify.cpp | 45380 | /*
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.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 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, see <http://www.gnu.org/licenses/>.
*/
/* ScriptData
Name: modify_commandscript
%Complete: 100
Comment: All modify related commands
Category: commandscripts
EndScriptData */
#include "ScriptMgr.h"
#include "ObjectMgr.h"
#include "Chat.h"
#include <stdlib.h>
class modify_commandscript : public CommandScript
{
public:
modify_commandscript() : CommandScript("modify_commandscript") { }
ChatCommand* GetCommands() const
{
static ChatCommand modifyspeedCommandTable[] =
{
{ "fly", SEC_MODERATOR, false, &HandleModifyFlyCommand, "", NULL },
{ "all", SEC_MODERATOR, false, &HandleModifyASpeedCommand, "", NULL },
{ "walk", SEC_MODERATOR, false, &HandleModifySpeedCommand, "", NULL },
{ "backwalk", SEC_MODERATOR, false, &HandleModifyBWalkCommand, "", NULL },
{ "swim", SEC_MODERATOR, false, &HandleModifySwimCommand, "", NULL },
{ "", SEC_MODERATOR, false, &HandleModifyASpeedCommand, "", NULL },
{ NULL, 0, false, NULL, "", NULL }
};
static ChatCommand modifyCommandTable[] =
{
{ "hp", SEC_MODERATOR, false, &HandleModifyHPCommand, "", NULL },
{ "mana", SEC_MODERATOR, false, &HandleModifyManaCommand, "", NULL },
{ "rage", SEC_MODERATOR, false, &HandleModifyRageCommand, "", NULL },
{ "runicpower", SEC_MODERATOR, false, &HandleModifyRunicPowerCommand, "", NULL },
{ "energy", SEC_MODERATOR, false, &HandleModifyEnergyCommand, "", NULL },
{ "money", SEC_MODERATOR, false, &HandleModifyMoneyCommand, "", NULL },
{ "scale", SEC_MODERATOR, false, &HandleModifyScaleCommand, "", NULL },
{ "bit", SEC_MODERATOR, false, &HandleModifyBitCommand, "", NULL },
{ "faction", SEC_MODERATOR, false, &HandleModifyFactionCommand, "", NULL },
{ "spell", SEC_MODERATOR, false, &HandleModifySpellCommand, "", NULL },
{ "talentpoints", SEC_MODERATOR, false, &HandleModifyTalentCommand, "", NULL },
{ "mount", SEC_MODERATOR, false, &HandleModifyMountCommand, "", NULL },
{ "honor", SEC_MODERATOR, false, &HandleModifyHonorCommand, "", NULL },
{ "reputation", SEC_GAMEMASTER, false, &HandleModifyRepCommand, "", NULL },
{ "drunk", SEC_MODERATOR, false, &HandleModifyDrunkCommand, "", NULL },
{ "standstate", SEC_GAMEMASTER, false, &HandleModifyStandStateCommand, "", NULL },
{ "phase", SEC_ADMINISTRATOR, false, &HandleModifyPhaseCommand, "", NULL },
{ "gender", SEC_GAMEMASTER, false, &HandleModifyGenderCommand, "", NULL },
{ "power", SEC_GAMEMASTER, false, &HandleModifyPowerCommand, "", NULL },
{ "currency", SEC_GAMEMASTER, false, &HandleModifyCurrencyCommand, "", NULL },
{ "speed", SEC_MODERATOR, false, NULL, "", modifyspeedCommandTable },
{ NULL, 0, false, NULL, "", NULL }
};
static ChatCommand commandTable[] =
{
{ "morph", SEC_GAMEMASTER, false, &HandleModifyMorphCommand, "", NULL },
{ "demorph", SEC_GAMEMASTER, false, &HandleDeMorphCommand, "", NULL },
{ "modify", SEC_MODERATOR, false, NULL, "", modifyCommandTable },
{ NULL, 0, false, NULL, "", NULL }
};
return commandTable;
}
//Edit Player HP
static bool HandleModifyHPCommand(ChatHandler* handler, const char* args)
{
if (!*args)
return false;
int32 hp = atoi((char*)args);
int32 hpm = atoi((char*)args);
if (hp < 1 || hpm < 1 || hpm < hp)
{
handler->SendSysMessage(LANG_BAD_VALUE);
handler->SetSentErrorMessage(true);
return false;
}
Player* target = handler->getSelectedPlayer();
if (!target)
{
handler->SendSysMessage(LANG_NO_CHAR_SELECTED);
handler->SetSentErrorMessage(true);
return false;
}
if (handler->HasLowerSecurity(target, 0))
return false;
handler->PSendSysMessage(LANG_YOU_CHANGE_HP, handler->GetNameLink(target).c_str(), hp, hpm);
if (handler->needReportToTarget(target))
(ChatHandler(target)).PSendSysMessage(LANG_YOURS_HP_CHANGED, handler->GetNameLink().c_str(), hp, hpm);
target->SetMaxHealth(hpm);
target->SetHealth(hp);
return true;
}
//Edit Player Mana
static bool HandleModifyManaCommand(ChatHandler* handler, const char* args)
{
if (!*args)
return false;
int32 mana = atoi((char*)args);
int32 manam = atoi((char*)args);
if (mana <= 0 || manam <= 0 || manam < mana)
{
handler->SendSysMessage(LANG_BAD_VALUE);
handler->SetSentErrorMessage(true);
return false;
}
Player* target = handler->getSelectedPlayer();
if (!target)
{
handler->SendSysMessage(LANG_NO_CHAR_SELECTED);
handler->SetSentErrorMessage(true);
return false;
}
// check online security
if (handler->HasLowerSecurity(target, 0))
return false;
handler->PSendSysMessage(LANG_YOU_CHANGE_MANA, handler->GetNameLink(target).c_str(), mana, manam);
if (handler->needReportToTarget(target))
(ChatHandler(target)).PSendSysMessage(LANG_YOURS_MANA_CHANGED, handler->GetNameLink().c_str(), mana, manam);
target->SetMaxPower(POWER_MANA, manam);
target->SetPower(POWER_MANA, mana);
return true;
}
//Edit Player Energy
static bool HandleModifyEnergyCommand(ChatHandler* handler, const char* args)
{
if (!*args)
return false;
// char* pmana = strtok((char*)args, " ");
// if (!pmana)
// return false;
// char* pmanaMax = strtok(NULL, " ");
// if (!pmanaMax)
// return false;
// int32 manam = atoi(pmanaMax);
// int32 mana = atoi(pmana);
int32 energy = atoi((char*)args)*10;
int32 energym = atoi((char*)args)*10;
if (energy <= 0 || energym <= 0 || energym < energy)
{
handler->SendSysMessage(LANG_BAD_VALUE);
handler->SetSentErrorMessage(true);
return false;
}
Player* target = handler->getSelectedPlayer();
if (!target)
{
handler->SendSysMessage(LANG_NO_CHAR_SELECTED);
handler->SetSentErrorMessage(true);
return false;
}
// check online security
if (handler->HasLowerSecurity(target, 0))
return false;
handler->PSendSysMessage(LANG_YOU_CHANGE_ENERGY, handler->GetNameLink(target).c_str(), energy/10, energym/10);
if (handler->needReportToTarget(target))
(ChatHandler(target)).PSendSysMessage(LANG_YOURS_ENERGY_CHANGED, handler->GetNameLink().c_str(), energy/10, energym/10);
target->SetMaxPower(POWER_ENERGY, energym);
target->SetPower(POWER_ENERGY, energy);
sLog->outDebug(LOG_FILTER_GENERAL, handler->GetTrinityString(LANG_CURRENT_ENERGY), target->GetMaxPower(POWER_ENERGY));
return true;
}
//Edit Player Rage
static bool HandleModifyRageCommand(ChatHandler* handler, const char* args)
{
if (!*args)
return false;
// char* pmana = strtok((char*)args, " ");
// if (!pmana)
// return false;
// char* pmanaMax = strtok(NULL, " ");
// if (!pmanaMax)
// return false;
// int32 manam = atoi(pmanaMax);
// int32 mana = atoi(pmana);
int32 rage = atoi((char*)args)*10;
int32 ragem = atoi((char*)args)*10;
if (rage <= 0 || ragem <= 0 || ragem < rage)
{
handler->SendSysMessage(LANG_BAD_VALUE);
handler->SetSentErrorMessage(true);
return false;
}
Player* target = handler->getSelectedPlayer();
if (!target)
{
handler->SendSysMessage(LANG_NO_CHAR_SELECTED);
handler->SetSentErrorMessage(true);
return false;
}
// check online security
if (handler->HasLowerSecurity(target, 0))
return false;
handler->PSendSysMessage(LANG_YOU_CHANGE_RAGE, handler->GetNameLink(target).c_str(), rage/10, ragem/10);
if (handler->needReportToTarget(target))
(ChatHandler(target)).PSendSysMessage(LANG_YOURS_RAGE_CHANGED, handler->GetNameLink().c_str(), rage/10, ragem/10);
target->SetMaxPower(POWER_RAGE, ragem);
target->SetPower(POWER_RAGE, rage);
return true;
}
// Edit Player Runic Power
static bool HandleModifyRunicPowerCommand(ChatHandler* handler, const char* args)
{
if (!*args)
return false;
int32 rune = atoi((char*)args)*10;
int32 runem = atoi((char*)args)*10;
if (rune <= 0 || runem <= 0 || runem < rune)
{
handler->SendSysMessage(LANG_BAD_VALUE);
handler->SetSentErrorMessage(true);
return false;
}
Player* target = handler->getSelectedPlayer();
if (!target)
{
handler->SendSysMessage(LANG_NO_CHAR_SELECTED);
handler->SetSentErrorMessage(true);
return false;
}
handler->PSendSysMessage(LANG_YOU_CHANGE_RUNIC_POWER, handler->GetNameLink(target).c_str(), rune/10, runem/10);
if (handler->needReportToTarget(target))
(ChatHandler(target)).PSendSysMessage(LANG_YOURS_RUNIC_POWER_CHANGED, handler->GetNameLink().c_str(), rune/10, runem/10);
target->SetMaxPower(POWER_RUNIC_POWER, runem);
target->SetPower(POWER_RUNIC_POWER, rune);
return true;
}
//Edit Player Faction
static bool HandleModifyFactionCommand(ChatHandler* handler, const char* args)
{
if (!*args)
return false;
char* pfactionid = handler->extractKeyFromLink((char*)args, "Hfaction");
Creature* target = handler->getSelectedCreature();
if (!target)
{
handler->SendSysMessage(LANG_SELECT_CREATURE);
handler->SetSentErrorMessage(true);
return false;
}
if (!pfactionid)
{
if (target)
{
uint32 factionid = target->getFaction();
uint32 flag = target->GetUInt32Value(UNIT_FIELD_FLAGS);
uint32 npcflag = target->GetUInt32Value(UNIT_NPC_FLAGS);
uint32 dyflag = target->GetUInt32Value(OBJECT_FIELD_DYNAMIC_FLAGS);
handler->PSendSysMessage(LANG_CURRENT_FACTION, target->GetGUIDLow(), factionid, flag, npcflag, dyflag);
}
return true;
}
if (!target)
{
handler->SendSysMessage(LANG_NO_CHAR_SELECTED);
handler->SetSentErrorMessage(true);
return false;
}
uint32 factionid = atoi(pfactionid);
uint32 flag;
char *pflag = strtok(NULL, " ");
if (!pflag)
flag = target->GetUInt32Value(UNIT_FIELD_FLAGS);
else
flag = atoi(pflag);
char* pnpcflag = strtok(NULL, " ");
uint32 npcflag;
if (!pnpcflag)
npcflag = target->GetUInt32Value(UNIT_NPC_FLAGS);
else
npcflag = atoi(pnpcflag);
char* pdyflag = strtok(NULL, " ");
uint32 dyflag;
if (!pdyflag)
dyflag = target->GetUInt32Value(OBJECT_FIELD_DYNAMIC_FLAGS);
else
dyflag = atoi(pdyflag);
if (!sFactionTemplateStore.LookupEntry(factionid))
{
handler->PSendSysMessage(LANG_WRONG_FACTION, factionid);
handler->SetSentErrorMessage(true);
return false;
}
handler->PSendSysMessage(LANG_YOU_CHANGE_FACTION, target->GetGUIDLow(), factionid, flag, npcflag, dyflag);
target->setFaction(factionid);
target->SetUInt32Value(UNIT_FIELD_FLAGS, flag);
target->SetUInt32Value(UNIT_NPC_FLAGS, npcflag);
target->SetUInt32Value(OBJECT_FIELD_DYNAMIC_FLAGS, dyflag);
return true;
}
//Edit Player Spell
static bool HandleModifySpellCommand(ChatHandler* handler, const char* args)
{
if (!*args)
return false;
char* pspellflatid = strtok((char*)args, " ");
if (!pspellflatid)
return false;
char* pop = strtok(NULL, " ");
if (!pop)
return false;
char* pval = strtok(NULL, " ");
if (!pval)
return false;
uint16 mark;
char* pmark = strtok(NULL, " ");
uint8 spellflatid = atoi(pspellflatid);
uint8 op = atoi(pop);
uint16 val = atoi(pval);
if (!pmark)
mark = 65535;
else
mark = atoi(pmark);
Player* target = handler->getSelectedPlayer();
if (target == NULL)
{
handler->SendSysMessage(LANG_NO_CHAR_SELECTED);
handler->SetSentErrorMessage(true);
return false;
}
// check online security
if (handler->HasLowerSecurity(target, 0))
return false;
handler->PSendSysMessage(LANG_YOU_CHANGE_SPELLFLATID, spellflatid, val, mark, handler->GetNameLink(target).c_str());
if (handler->needReportToTarget(target))
(ChatHandler(target)).PSendSysMessage(LANG_YOURS_SPELLFLATID_CHANGED, handler->GetNameLink().c_str(), spellflatid, val, mark);
WorldPacket data(SMSG_SET_FLAT_SPELL_MODIFIER, (1+1+2+2));
data << uint8(spellflatid);
data << uint8(op);
data << uint16(val);
data << uint16(mark);
target->GetSession()->SendPacket(&data);
return true;
}
//Edit Player TP
static bool HandleModifyTalentCommand (ChatHandler* handler, const char* args)
{
if (!*args)
return false;
int tp = atoi((char*)args);
if (tp < 0)
return false;
Unit* target = handler->getSelectedUnit();
if (!target)
{
handler->SendSysMessage(LANG_NO_CHAR_SELECTED);
handler->SetSentErrorMessage(true);
return false;
}
if (target->GetTypeId() == TYPEID_PLAYER)
{
// check online security
if (handler->HasLowerSecurity(target->ToPlayer(), 0))
return false;
target->ToPlayer()->SetFreeTalentPoints(tp);
target->ToPlayer()->SendTalentsInfoData(false);
return true;
}
else if (target->ToCreature()->isPet())
{
Unit* owner = target->GetOwner();
if (owner && owner->GetTypeId() == TYPEID_PLAYER && ((Pet*)target)->IsPermanentPetFor(owner->ToPlayer()))
{
// check online security
if (handler->HasLowerSecurity(owner->ToPlayer(), 0))
return false;
owner->ToPlayer()->SendTalentsInfoData(true);
return true;
}
}
handler->SendSysMessage(LANG_NO_CHAR_SELECTED);
handler->SetSentErrorMessage(true);
return false;
}
//Edit Player Aspeed
static bool HandleModifyASpeedCommand(ChatHandler* handler, const char* args)
{
if (!*args)
return false;
float ASpeed = (float)atof((char*)args);
if (ASpeed > 50.0f || ASpeed < 0.1f)
{
handler->SendSysMessage(LANG_BAD_VALUE);
handler->SetSentErrorMessage(true);
return false;
}
Player* target = handler->getSelectedPlayer();
if (!target)
{
handler->SendSysMessage(LANG_NO_CHAR_SELECTED);
handler->SetSentErrorMessage(true);
return false;
}
// check online security
if (handler->HasLowerSecurity(target, 0))
return false;
std::string targetNameLink = handler->GetNameLink(target);
if (target->isInFlight())
{
handler->PSendSysMessage(LANG_CHAR_IN_FLIGHT, targetNameLink.c_str());
handler->SetSentErrorMessage(true);
return false;
}
handler->PSendSysMessage(LANG_YOU_CHANGE_ASPEED, ASpeed, targetNameLink.c_str());
if (handler->needReportToTarget(target))
(ChatHandler(target)).PSendSysMessage(LANG_YOURS_ASPEED_CHANGED, handler->GetNameLink().c_str(), ASpeed);
target->SetSpeed(MOVE_WALK, ASpeed, true);
target->SetSpeed(MOVE_RUN, ASpeed, true);
target->SetSpeed(MOVE_SWIM, ASpeed, true);
//target->SetSpeed(MOVE_TURN, ASpeed, true);
target->SetSpeed(MOVE_FLIGHT, ASpeed, true);
return true;
}
//Edit Player Speed
static bool HandleModifySpeedCommand(ChatHandler* handler, const char* args)
{
if (!*args)
return false;
float Speed = (float)atof((char*)args);
if (Speed > 50.0f || Speed < 0.1f)
{
handler->SendSysMessage(LANG_BAD_VALUE);
handler->SetSentErrorMessage(true);
return false;
}
Player* target = handler->getSelectedPlayer();
if (!target)
{
handler->SendSysMessage(LANG_NO_CHAR_SELECTED);
handler->SetSentErrorMessage(true);
return false;
}
// check online security
if (handler->HasLowerSecurity(target, 0))
return false;
std::string targetNameLink = handler->GetNameLink(target);
if (target->isInFlight())
{
handler->PSendSysMessage(LANG_CHAR_IN_FLIGHT, targetNameLink.c_str());
handler->SetSentErrorMessage(true);
return false;
}
handler->PSendSysMessage(LANG_YOU_CHANGE_SPEED, Speed, targetNameLink.c_str());
if (handler->needReportToTarget(target))
(ChatHandler(target)).PSendSysMessage(LANG_YOURS_SPEED_CHANGED, handler->GetNameLink().c_str(), Speed);
target->SetSpeed(MOVE_RUN, Speed, true);
return true;
}
//Edit Player Swim Speed
static bool HandleModifySwimCommand(ChatHandler* handler, const char* args)
{
if (!*args)
return false;
float Swim = (float)atof((char*)args);
if (Swim > 50.0f || Swim < 0.1f)
{
handler->SendSysMessage(LANG_BAD_VALUE);
handler->SetSentErrorMessage(true);
return false;
}
Player* target = handler->getSelectedPlayer();
if (!target)
{
handler->SendSysMessage(LANG_NO_CHAR_SELECTED);
handler->SetSentErrorMessage(true);
return false;
}
// check online security
if (handler->HasLowerSecurity(target, 0))
return false;
std::string targetNameLink = handler->GetNameLink(target);
if (target->isInFlight())
{
handler->PSendSysMessage(LANG_CHAR_IN_FLIGHT, targetNameLink.c_str());
handler->SetSentErrorMessage(true);
return false;
}
handler->PSendSysMessage(LANG_YOU_CHANGE_SWIM_SPEED, Swim, targetNameLink.c_str());
if (handler->needReportToTarget(target))
(ChatHandler(target)).PSendSysMessage(LANG_YOURS_SWIM_SPEED_CHANGED, handler->GetNameLink().c_str(), Swim);
target->SetSpeed(MOVE_SWIM, Swim, true);
return true;
}
//Edit Player Walk Speed
static bool HandleModifyBWalkCommand(ChatHandler* handler, const char* args)
{
if (!*args)
return false;
float BSpeed = (float)atof((char*)args);
if (BSpeed > 50.0f || BSpeed < 0.1f)
{
handler->SendSysMessage(LANG_BAD_VALUE);
handler->SetSentErrorMessage(true);
return false;
}
Player* target = handler->getSelectedPlayer();
if (!target)
{
handler->SendSysMessage(LANG_NO_CHAR_SELECTED);
handler->SetSentErrorMessage(true);
return false;
}
// check online security
if (handler->HasLowerSecurity(target, 0))
return false;
std::string targetNameLink = handler->GetNameLink(target);
if (target->isInFlight())
{
handler->PSendSysMessage(LANG_CHAR_IN_FLIGHT, targetNameLink.c_str());
handler->SetSentErrorMessage(true);
return false;
}
handler->PSendSysMessage(LANG_YOU_CHANGE_BACK_SPEED, BSpeed, targetNameLink.c_str());
if (handler->needReportToTarget(target))
(ChatHandler(target)).PSendSysMessage(LANG_YOURS_BACK_SPEED_CHANGED, handler->GetNameLink().c_str(), BSpeed);
target->SetSpeed(MOVE_RUN_BACK, BSpeed, true);
return true;
}
//Edit Player Fly
static bool HandleModifyFlyCommand(ChatHandler* handler, const char* args)
{
if (!*args)
return false;
float FSpeed = (float)atof((char*)args);
if (FSpeed > 50.0f || FSpeed < 0.1f)
{
handler->SendSysMessage(LANG_BAD_VALUE);
handler->SetSentErrorMessage(true);
return false;
}
Player* target = handler->getSelectedPlayer();
if (!target)
{
handler->SendSysMessage(LANG_NO_CHAR_SELECTED);
handler->SetSentErrorMessage(true);
return false;
}
// check online security
if (handler->HasLowerSecurity(target, 0))
return false;
handler->PSendSysMessage(LANG_YOU_CHANGE_FLY_SPEED, FSpeed, handler->GetNameLink(target).c_str());
if (handler->needReportToTarget(target))
(ChatHandler(target)).PSendSysMessage(LANG_YOURS_FLY_SPEED_CHANGED, handler->GetNameLink().c_str(), FSpeed);
target->SetSpeed(MOVE_FLIGHT, FSpeed, true);
return true;
}
//Edit Player or Creature Scale
static bool HandleModifyScaleCommand(ChatHandler* handler, const char* args)
{
if (!*args)
return false;
float Scale = (float)atof((char*)args);
if (Scale > 10.0f || Scale < 0.1f)
{
handler->SendSysMessage(LANG_BAD_VALUE);
handler->SetSentErrorMessage(true);
return false;
}
Unit* target = handler->getSelectedUnit();
if (!target)
{
handler->SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE);
handler->SetSentErrorMessage(true);
return false;
}
if (Player* player = target->ToPlayer())
{
// check online security
if (handler->HasLowerSecurity(player, 0))
return false;
handler->PSendSysMessage(LANG_YOU_CHANGE_SIZE, Scale, handler->GetNameLink(player).c_str());
if (handler->needReportToTarget(player))
(ChatHandler(player)).PSendSysMessage(LANG_YOURS_SIZE_CHANGED, handler->GetNameLink().c_str(), Scale);
}
target->SetObjectScale(Scale);
return true;
}
//Enable Player mount
static bool HandleModifyMountCommand(ChatHandler* handler, const char* args)
{
if (!*args)
return false;
uint16 mId = 1147;
float speed = (float)15;
uint32 num = 0;
num = atoi((char*)args);
switch (num)
{
case 1:
mId=14340;
break;
case 2:
mId=4806;
break;
case 3:
mId=6471;
break;
case 4:
mId=12345;
break;
case 5:
mId=6472;
break;
case 6:
mId=6473;
break;
case 7:
mId=10670;
break;
case 8:
mId=10719;
break;
case 9:
mId=10671;
break;
case 10:
mId=10672;
break;
case 11:
mId=10720;
break;
case 12:
mId=14349;
break;
case 13:
mId=11641;
break;
case 14:
mId=12244;
break;
case 15:
mId=12242;
break;
case 16:
mId=14578;
break;
case 17:
mId=14579;
break;
case 18:
mId=14349;
break;
case 19:
mId=12245;
break;
case 20:
mId=14335;
break;
case 21:
mId=207;
break;
case 22:
mId=2328;
break;
case 23:
mId=2327;
break;
case 24:
mId=2326;
break;
case 25:
mId=14573;
break;
case 26:
mId=14574;
break;
case 27:
mId=14575;
break;
case 28:
mId=604;
break;
case 29:
mId=1166;
break;
case 30:
mId=2402;
break;
case 31:
mId=2410;
break;
case 32:
mId=2409;
break;
case 33:
mId=2408;
break;
case 34:
mId=2405;
break;
case 35:
mId=14337;
break;
case 36:
mId=6569;
break;
case 37:
mId=10661;
break;
case 38:
mId=10666;
break;
case 39:
mId=9473;
break;
case 40:
mId=9476;
break;
case 41:
mId=9474;
break;
case 42:
mId=14374;
break;
case 43:
mId=14376;
break;
case 44:
mId=14377;
break;
case 45:
mId=2404;
break;
case 46:
mId=2784;
break;
case 47:
mId=2787;
break;
case 48:
mId=2785;
break;
case 49:
mId=2736;
break;
case 50:
mId=2786;
break;
case 51:
mId=14347;
break;
case 52:
mId=14346;
break;
case 53:
mId=14576;
break;
case 54:
mId=9695;
break;
case 55:
mId=9991;
break;
case 56:
mId=6448;
break;
case 57:
mId=6444;
break;
case 58:
mId=6080;
break;
case 59:
mId=6447;
break;
case 60:
mId=4805;
break;
case 61:
mId=9714;
break;
case 62:
mId=6448;
break;
case 63:
mId=6442;
break;
case 64:
mId=14632;
break;
case 65:
mId=14332;
break;
case 66:
mId=14331;
break;
case 67:
mId=8469;
break;
case 68:
mId=2830;
break;
case 69:
mId=2346;
break;
default:
handler->SendSysMessage(LANG_NO_MOUNT);
handler->SetSentErrorMessage(true);
return false;
}
Player* target = handler->getSelectedPlayer();
if (!target)
{
handler->SendSysMessage(LANG_NO_CHAR_SELECTED);
handler->SetSentErrorMessage(true);
return false;
}
// check online security
if (handler->HasLowerSecurity(target, 0))
return false;
handler->PSendSysMessage(LANG_YOU_GIVE_MOUNT, handler->GetNameLink(target).c_str());
if (handler->needReportToTarget(target))
(ChatHandler(target)).PSendSysMessage(LANG_MOUNT_GIVED, handler->GetNameLink().c_str());
target->SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP);
target->Mount(mId);
WorldPacket data(SMSG_MOVE_SET_RUN_SPEED, (8+4+1+4));
ObjectGuid guid = target->GetGUID();
uint8 bitOrder[8] = {6, 5, 0, 1, 2, 4, 3, 7};
data.WriteBitInOrder(guid, bitOrder);
data.WriteByteSeq(guid[4]);
data.WriteByteSeq(guid[7]);
data.WriteByteSeq(guid[1]);
data.WriteByteSeq(guid[3]);
data << float(speed);
data.WriteByteSeq(guid[0]);
data.WriteByteSeq(guid[5]);
data.WriteByteSeq(guid[2]);
data.WriteByteSeq(guid[6]);
data << uint32(0);
target->SendMessageToSet(&data, true);
data.Initialize(SMSG_MOVE_SET_SWIM_SPEED, (8+4+4));
uint8 bitOrder2[8] = {0, 5, 2, 6, 7, 4, 1, 3};
data.WriteBitInOrder(guid, bitOrder2);
data.WriteByteSeq(guid[4]);
data.WriteByteSeq(guid[5]);
data.WriteByteSeq(guid[3]);
data << uint32(0);
data.WriteByteSeq(guid[0]);
data.WriteByteSeq(guid[6]);
data.WriteByteSeq(guid[2]);
data.WriteByteSeq(guid[1]);
data.WriteByteSeq(guid[7]);
data << float(speed);
target->SendMessageToSet(&data, true);
return true;
}
//Edit Player money
static bool HandleModifyMoneyCommand(ChatHandler* handler, const char* args)
{
if (!*args)
return false;
Player* target = handler->getSelectedPlayer();
if (!target)
{
handler->SendSysMessage(LANG_NO_CHAR_SELECTED);
handler->SetSentErrorMessage(true);
return false;
}
// check online security
if (handler->HasLowerSecurity(target, 0))
return false;
int64 addmoney = 0;
// strtoull doesn't exist on WIN
#if PLATFORM == PLATFORM_WINDOWS
addmoney = _strtoui64((char*)args, NULL, 10);
#else
addmoney = strtoull((char*)args, NULL, 10);
#endif
uint64 moneyuser = target->GetMoney();
if (addmoney < 0)
{
int64 newmoney = int64(moneyuser) + addmoney;
sLog->outDebug(LOG_FILTER_GENERAL, handler->GetTrinityString(LANG_CURRENT_MONEY), moneyuser, addmoney, newmoney);
if (newmoney <= 0)
{
handler->PSendSysMessage(LANG_YOU_TAKE_ALL_MONEY, handler->GetNameLink(target).c_str());
if (handler->needReportToTarget(target))
(ChatHandler(target)).PSendSysMessage(LANG_YOURS_ALL_MONEY_GONE, handler->GetNameLink().c_str());
target->SetMoney(0);
}
else
{
if (newmoney > MAX_MONEY_AMOUNT)
newmoney = MAX_MONEY_AMOUNT;
handler->PSendSysMessage(LANG_YOU_TAKE_MONEY, abs(addmoney), handler->GetNameLink(target).c_str());
if (handler->needReportToTarget(target))
(ChatHandler(target)).PSendSysMessage(LANG_YOURS_MONEY_TAKEN, handler->GetNameLink().c_str(), abs(addmoney));
target->SetMoney(newmoney);
}
}
else
{
handler->PSendSysMessage(LANG_YOU_GIVE_MONEY, uint32(addmoney), handler->GetNameLink(target).c_str());
if (handler->needReportToTarget(target))
(ChatHandler(target)).PSendSysMessage(LANG_YOURS_MONEY_GIVEN, handler->GetNameLink().c_str(), uint32(addmoney));
if (addmoney >=MAX_MONEY_AMOUNT)
target->SetMoney(MAX_MONEY_AMOUNT);
else
target->ModifyMoney(int64(addmoney));
}
sLog->outDebug(LOG_FILTER_GENERAL, handler->GetTrinityString(LANG_NEW_MONEY), moneyuser, uint32(addmoney), target->GetMoney());
return true;
}
//Edit Unit field
static bool HandleModifyBitCommand(ChatHandler* handler, const char* args)
{
if (!*args)
return false;
Unit* target = handler->getSelectedUnit();
if (!target)
{
handler->SendSysMessage(LANG_NO_CHAR_SELECTED);
handler->SetSentErrorMessage(true);
return false;
}
// check online security
if (target->GetTypeId() == TYPEID_PLAYER && handler->HasLowerSecurity(target->ToPlayer(), 0))
return false;
char* pField = strtok((char*)args, " ");
if (!pField)
return false;
char* pBit = strtok(NULL, " ");
if (!pBit)
return false;
uint16 field = atoi(pField);
uint32 bit = atoi(pBit);
if (field < OBJECT_END || field >= target->GetValuesCount())
{
handler->SendSysMessage(LANG_BAD_VALUE);
handler->SetSentErrorMessage(true);
return false;
}
if (bit < 1 || bit > 32)
{
handler->SendSysMessage(LANG_BAD_VALUE);
handler->SetSentErrorMessage(true);
return false;
}
if (target->HasFlag(field, (1<<(bit-1))))
{
target->RemoveFlag(field, (1<<(bit-1)));
handler->PSendSysMessage(LANG_REMOVE_BIT, bit, field);
}
else
{
target->SetFlag(field, (1<<(bit-1)));
handler->PSendSysMessage(LANG_SET_BIT, bit, field);
}
return true;
}
static bool HandleModifyHonorCommand(ChatHandler* handler, const char* args)
{
if (!*args)
return false;
Player* target = handler->getSelectedPlayer();
if (!target)
{
handler->SendSysMessage(LANG_PLAYER_NOT_FOUND);
handler->SetSentErrorMessage(true);
return false;
}
// check online security
if (handler->HasLowerSecurity(target, 0))
return false;
int32 amount = (uint32)atoi(args);
target->ModifyCurrency(CURRENCY_TYPE_HONOR_POINTS, amount, true, true);
handler->PSendSysMessage(LANG_COMMAND_MODIFY_HONOR, handler->GetNameLink(target).c_str(), target->GetCurrency(CURRENCY_TYPE_HONOR_POINTS, false));
return true;
}
static bool HandleModifyDrunkCommand(ChatHandler* handler, const char* args)
{
if (!*args)
return false;
uint8 drunklevel = (uint8)atoi(args);
if (drunklevel > 100)
drunklevel = 100;
if (Player* target = handler->getSelectedPlayer())
target->SetDrunkValue(drunklevel);
return true;
}
static bool HandleModifyRepCommand(ChatHandler* handler, const char* args)
{
if (!*args)
return false;
Player* target = handler->getSelectedPlayer();
if (!target)
{
handler->SendSysMessage(LANG_PLAYER_NOT_FOUND);
handler->SetSentErrorMessage(true);
return false;
}
// check online security
if (handler->HasLowerSecurity(target, 0))
return false;
char* factionTxt = handler->extractKeyFromLink((char*)args, "Hfaction");
if (!factionTxt)
return false;
uint32 factionId = atoi(factionTxt);
int32 amount = 0;
char *rankTxt = strtok(NULL, " ");
if (!factionTxt || !rankTxt)
return false;
amount = atoi(rankTxt);
if ((amount == 0) && (rankTxt[0] != '-') && !isdigit(rankTxt[0]))
{
std::string rankStr = rankTxt;
std::wstring wrankStr;
if (!Utf8toWStr(rankStr, wrankStr))
return false;
wstrToLower(wrankStr);
int r = 0;
amount = -42000;
for (; r < MAX_REPUTATION_RANK; ++r)
{
std::string rank = handler->GetTrinityString(ReputationRankStrIndex[r]);
if (rank.empty())
continue;
std::wstring wrank;
if (!Utf8toWStr(rank, wrank))
continue;
wstrToLower(wrank);
if (wrank.substr(0, wrankStr.size()) == wrankStr)
{
char *deltaTxt = strtok(NULL, " ");
if (deltaTxt)
{
int32 delta = atoi(deltaTxt);
if ((delta < 0) || (delta > ReputationMgr::PointsInRank[r] -1))
{
handler->PSendSysMessage(LANG_COMMAND_FACTION_DELTA, (ReputationMgr::PointsInRank[r]-1));
handler->SetSentErrorMessage(true);
return false;
}
amount += delta;
}
break;
}
amount += ReputationMgr::PointsInRank[r];
}
if (r >= MAX_REPUTATION_RANK)
{
handler->PSendSysMessage(LANG_COMMAND_FACTION_INVPARAM, rankTxt);
handler->SetSentErrorMessage(true);
return false;
}
}
FactionEntry const* factionEntry = sFactionStore.LookupEntry(factionId);
if (!factionEntry)
{
handler->PSendSysMessage(LANG_COMMAND_FACTION_UNKNOWN, factionId);
handler->SetSentErrorMessage(true);
return false;
}
if (factionEntry->reputationListID < 0)
{
handler->PSendSysMessage(LANG_COMMAND_FACTION_NOREP_ERROR, factionEntry->name, factionId);
handler->SetSentErrorMessage(true);
return false;
}
target->GetReputationMgr().SetReputation(factionEntry, amount);
handler->PSendSysMessage(LANG_COMMAND_MODIFY_REP, factionEntry->name, factionId,
handler->GetNameLink(target).c_str(), target->GetReputationMgr().GetReputation(factionEntry));
return true;
}
//morph creature or player
static bool HandleModifyMorphCommand(ChatHandler* handler, const char* args)
{
if (!*args)
return false;
uint16 display_id = (uint16)atoi((char*)args);
Unit* target = handler->getSelectedUnit();
if (!target)
target = handler->GetSession()->GetPlayer();
// check online security
else if (target->GetTypeId() == TYPEID_PLAYER && handler->HasLowerSecurity(target->ToPlayer(), 0))
return false;
target->SetDisplayId(display_id);
return true;
}
//set temporary phase mask for player
static bool HandleModifyPhaseCommand(ChatHandler* handler, const char* args)
{
if (!*args)
return false;
uint32 phasemask = (uint32)atoi((char*)args);
Unit* target = handler->getSelectedUnit();
if (target)
{
if (target->GetTypeId() == TYPEID_PLAYER)
target->ToPlayer()->GetPhaseMgr().SetCustomPhase(phasemask);
else
target->SetPhaseMask(phasemask, true);
}
else
handler->GetSession()->GetPlayer()->GetPhaseMgr().SetCustomPhase(phasemask);
return true;
}
//change standstate
static bool HandleModifyStandStateCommand(ChatHandler* handler, const char* args)
{
if (!*args)
return false;
uint32 anim_id = atoi((char*)args);
handler->GetSession()->GetPlayer()->HandleEmote(anim_id);
return true;
}
static bool HandleModifyGenderCommand(ChatHandler* handler, const char* args)
{
if (!*args)
return false;
Player* target = handler->getSelectedPlayer();
if (!target)
{
handler->PSendSysMessage(LANG_PLAYER_NOT_FOUND);
handler->SetSentErrorMessage(true);
return false;
}
PlayerInfo const* info = sObjectMgr->GetPlayerInfo(target->getRace(), target->getClass());
if (!info)
return false;
char const* gender_str = (char*)args;
int gender_len = strlen(gender_str);
Gender gender;
if (!strncmp(gender_str, "male", gender_len)) // MALE
{
if (target->getGender() == GENDER_MALE)
return true;
gender = GENDER_MALE;
}
else if (!strncmp(gender_str, "female", gender_len)) // FEMALE
{
if (target->getGender() == GENDER_FEMALE)
return true;
gender = GENDER_FEMALE;
}
else
{
handler->SendSysMessage(LANG_MUST_MALE_OR_FEMALE);
handler->SetSentErrorMessage(true);
return false;
}
// Set gender
target->SetByteValue(UNIT_FIELD_BYTES_0, 3, gender);
target->SetByteValue(PLAYER_BYTES_3, 0, gender);
// Change display ID
target->InitDisplayIds();
char const* gender_full = gender ? "female" : "male";
handler->PSendSysMessage(LANG_YOU_CHANGE_GENDER, handler->GetNameLink(target).c_str(), gender_full);
if (handler->needReportToTarget(target))
(ChatHandler(target)).PSendSysMessage(LANG_YOUR_GENDER_CHANGED, gender_full, handler->GetNameLink().c_str());
return true;
}
static bool HandleModifyPowerCommand(ChatHandler* handler, const char* args)
{
if (!*args)
return false;
char* power_str = strtok((char*)args, " ");
char* value_str = strtok(NULL, " ");
if (!power_str || !value_str)
return false;
Player* target = handler->getSelectedPlayer();
if (!target)
{
handler->PSendSysMessage(LANG_PLAYER_NOT_FOUND);
handler->SetSentErrorMessage(true);
return false;
}
uint32 power = (uint32)atoi(power_str);
if (power >= MAX_POWERS)
return false;
uint32 value = (uint32)atoi(value_str);
target->SetPower(Powers(power), value);
return true;
}
static bool HandleDeMorphCommand(ChatHandler* handler, const char* /*args*/)
{
Unit* target = handler->getSelectedUnit();
if (!target)
target = handler->GetSession()->GetPlayer();
// check online security
else if (target->GetTypeId() == TYPEID_PLAYER && handler->HasLowerSecurity(target->ToPlayer(), 0))
return false;
target->DeMorph();
return true;
}
static bool HandleModifyCurrencyCommand(ChatHandler* handler, const char* args)
{
if (!*args)
return false;
Player* target = handler->getSelectedPlayer();
if (!target)
{
handler->PSendSysMessage(LANG_PLAYER_NOT_FOUND);
handler->SetSentErrorMessage(true);
return false;
}
uint32 currencyId = atoi(strtok((char*)args, " "));
const CurrencyTypesEntry* currencyType = sCurrencyTypesStore.LookupEntry(currencyId);
if (!currencyType)
return false;
int32 precision = currencyType->Flags & CURRENCY_FLAG_HIGH_PRECISION ? CURRENCY_PRECISION : 1;
uint32 amount = atoi(strtok(NULL, " "));
if (!amount)
return false;
target->ModifyCurrency(currencyId, amount * precision, true, true);
return true;
}
};
void AddSC_modify_commandscript()
{
new modify_commandscript();
}
| gpl-2.0 |
CntEam/Corek-wlk | src/server/scripts/EasternKingdoms/BlackrockDepths/boss_coren_direbrew.cpp | 42464 | /*######
## BrewFest Event
######*/
#include "ScriptPCH.h"
#include "LFGMgr.h"
/*####
## brewfest_trigger 2
####*/
enum eBrewfestBarkQuests
{
BARK_FOR_THE_THUNDERBREWS = 11294,
BARK_FOR_TCHALIS_VOODOO_BREWERY = 11408,
BARK_FOR_THE_BARLEYBREWS = 11293,
BARK_FOR_DROHNS_DISTILLERY = 11407,
SPELL_RAMSTEIN_SWIFT_WORK_RAM = 43880,
SPELL_BREWFEST_RAM = 43883,
SPELL_RAM_FATIGUE = 43052,
SPELL_SPEED_RAM_GALLOP = 42994,
SPELL_SPEED_RAM_CANTER = 42993,
SPELL_SPEED_RAM_TROT = 42992,
SPELL_SPEED_RAM_NORMAL = 43310,
SPELL_SPEED_RAM_EXHAUSED = 43332,
NPC_SPEED_BUNNY_GREEN = 24263,
NPC_SPEED_BUNNY_YELLOW = 24264,
NPC_SPEED_BUNNY_RED = 24265,
NPC_BARKER_BUNNY_1 = 24202,
NPC_BARKER_BUNNY_2 = 24203,
NPC_BARKER_BUNNY_3 = 24204,
NPC_BARKER_BUNNY_4 = 24205,
};
class npc_brewfest_trigger : public CreatureScript
{
public:
npc_brewfest_trigger() : CreatureScript("npc_brewfest_trigger") { }
CreatureAI *GetAI(Creature *creature) const
{
return new npc_brewfest_triggerAI(creature);
}
struct npc_brewfest_triggerAI : public ScriptedAI
{
npc_brewfest_triggerAI(Creature* c) : ScriptedAI(c) {}
void MoveInLineOfSight(Unit *who)
{
if (!who)
return;
if (who->GetTypeId() == TYPEID_PLAYER)
{
if (!(CAST_PLR(who)->GetAura(SPELL_BREWFEST_RAM)))
return;
if (CAST_PLR(who)->GetQuestStatus(BARK_FOR_THE_THUNDERBREWS) == QUEST_STATUS_INCOMPLETE||
CAST_PLR(who)->GetQuestStatus(BARK_FOR_TCHALIS_VOODOO_BREWERY) == QUEST_STATUS_INCOMPLETE||
CAST_PLR(who)->GetQuestStatus(BARK_FOR_THE_BARLEYBREWS) == QUEST_STATUS_INCOMPLETE||
CAST_PLR(who)->GetQuestStatus(BARK_FOR_DROHNS_DISTILLERY) == QUEST_STATUS_INCOMPLETE)
{
uint32 creditMarkerId = me->GetEntry();
if ((creditMarkerId >= 24202) && (creditMarkerId <= 24205))
{
// 24202: Brewfest Barker Bunny 1, 24203: Brewfest Barker Bunny 2, 24204: Brewfest Barker Bunny 3, 24205: Brewfest Barker Bunny 4
if (!CAST_PLR(who)->GetReqKillOrCastCurrentCount(BARK_FOR_THE_BARLEYBREWS, creditMarkerId)||
!CAST_PLR(who)->GetReqKillOrCastCurrentCount(BARK_FOR_THE_THUNDERBREWS, creditMarkerId)||
!CAST_PLR(who)->GetReqKillOrCastCurrentCount(BARK_FOR_DROHNS_DISTILLERY, creditMarkerId)||
!CAST_PLR(who)->GetReqKillOrCastCurrentCount(BARK_FOR_TCHALIS_VOODOO_BREWERY, creditMarkerId))
CAST_PLR(who)->KilledMonsterCredit(creditMarkerId, me->GetGUID());
// Caso para quest 11293 que no se completa teniendo todas las marcas
if (CAST_PLR(who)->GetReqKillOrCastCurrentCount(BARK_FOR_THE_BARLEYBREWS, NPC_BARKER_BUNNY_1)&&
CAST_PLR(who)->GetReqKillOrCastCurrentCount(BARK_FOR_THE_BARLEYBREWS, NPC_BARKER_BUNNY_2)&&
CAST_PLR(who)->GetReqKillOrCastCurrentCount(BARK_FOR_THE_BARLEYBREWS, NPC_BARKER_BUNNY_3)&&
CAST_PLR(who)->GetReqKillOrCastCurrentCount(BARK_FOR_THE_BARLEYBREWS, NPC_BARKER_BUNNY_4))
CAST_PLR(who)->CompleteQuest(BARK_FOR_THE_BARLEYBREWS);
}
}
}
}
};
};
/*####
## npc_brewfest_apple_trigger
####*/
class npc_brewfest_apple_trigger : public CreatureScript
{
public:
npc_brewfest_apple_trigger() : CreatureScript("npc_brewfest_apple_trigger") { }
struct npc_brewfest_apple_triggerAI : public ScriptedAI
{
npc_brewfest_apple_triggerAI(Creature* c) : ScriptedAI(c) {}
void MoveInLineOfSight(Unit *who)
{
Player *player = who->ToPlayer();
if (!player)
return;
if (player->HasAura(SPELL_RAM_FATIGUE) && me->GetDistance(player->GetPositionX(),player->GetPositionY(),player->GetPositionZ()) <= 7.5f)
player->RemoveAura(SPELL_RAM_FATIGUE);
}
};
CreatureAI *GetAI(Creature *creature) const
{
return new npc_brewfest_apple_triggerAI(creature);
}
};
/*####
## spell_brewfest_speed
####*/
class spell_brewfest_speed : public SpellScriptLoader
{
public:
spell_brewfest_speed() : SpellScriptLoader("spell_brewfest_speed") {}
class spell_brewfest_speed_AuraScript : public AuraScript
{
PrepareAuraScript(spell_brewfest_speed_AuraScript);
bool Validate(SpellInfo const* /*spellInfo*/)
{
if (!sSpellMgr->GetSpellInfo(SPELL_RAM_FATIGUE)) //Усталость барана
return false;
if (!sSpellMgr->GetSpellInfo(SPELL_RAMSTEIN_SWIFT_WORK_RAM)) //Стремительный рабочий баран Рамштайна
return false;
if (!sSpellMgr->GetSpellInfo(SPELL_BREWFEST_RAM)) // Арендованный скаковой баран
return false;
if (!sSpellMgr->GetSpellInfo(SPELL_SPEED_RAM_GALLOP)) //42994
return false;
if (!sSpellMgr->GetSpellInfo(SPELL_SPEED_RAM_CANTER)) // 42993
return false;
if (!sSpellMgr->GetSpellInfo(SPELL_SPEED_RAM_TROT)) // 42992
return false;
if (!sSpellMgr->GetSpellInfo(SPELL_SPEED_RAM_NORMAL)) // 43310
return false;
if (!sSpellMgr->GetSpellInfo(SPELL_SPEED_RAM_GALLOP))
return false;
if (!sSpellMgr->GetSpellInfo(SPELL_SPEED_RAM_EXHAUSED)) // Изнемогший баран
return false;
return true;
}
void HandlePeriodicTick(AuraEffect const* aurEff)
{
if (GetId() == SPELL_SPEED_RAM_EXHAUSED)
return;
Player* pCaster = GetCaster()->ToPlayer();
if (!pCaster)
return;
int i;
switch (GetId())
{
case SPELL_SPEED_RAM_GALLOP:
for (i = 0; i < 5; i++)
pCaster->AddAura(SPELL_RAM_FATIGUE,pCaster);
break;
case SPELL_SPEED_RAM_CANTER:
pCaster->AddAura(SPELL_RAM_FATIGUE,pCaster);
break;
case SPELL_SPEED_RAM_TROT:
if (pCaster->HasAura(SPELL_RAM_FATIGUE))
if (pCaster->GetAura(SPELL_RAM_FATIGUE)->GetStackAmount() <= 2)
pCaster->RemoveAura(SPELL_RAM_FATIGUE);
else
pCaster->GetAura(SPELL_RAM_FATIGUE)->ModStackAmount(-2);
break;
case SPELL_SPEED_RAM_NORMAL:
if (pCaster->HasAura(SPELL_RAM_FATIGUE))
if (pCaster->GetAura(SPELL_RAM_FATIGUE)->GetStackAmount() <= 4)
pCaster->RemoveAura(SPELL_RAM_FATIGUE);
else
pCaster->GetAura(SPELL_RAM_FATIGUE)->ModStackAmount(-4);
break;
}
switch (aurEff->GetId())
{
case SPELL_SPEED_RAM_TROT:
if (aurEff->GetTickNumber() == 4)
pCaster->KilledMonsterCredit(NPC_SPEED_BUNNY_GREEN, 0);
break;
case SPELL_SPEED_RAM_CANTER:
if (aurEff->GetTickNumber() == 8)
pCaster->KilledMonsterCredit(NPC_SPEED_BUNNY_YELLOW, 0);
break;
case SPELL_SPEED_RAM_GALLOP:
if (aurEff->GetTickNumber() == 8)
pCaster->KilledMonsterCredit(NPC_SPEED_BUNNY_RED, 0);
break;
}
if (pCaster->HasAura(SPELL_RAM_FATIGUE))
if (pCaster->GetAura(SPELL_RAM_FATIGUE)->GetStackAmount() >= 100)
pCaster->CastSpell(pCaster,SPELL_SPEED_RAM_EXHAUSED, false);
}
void OnRemove(AuraEffect const * aurEff, AuraEffectHandleModes /*mode*/)
{
Player* pCaster = GetCaster()->ToPlayer();
if (!pCaster)
return;
if (!pCaster->HasAura(SPELL_BREWFEST_RAM) || !pCaster->HasAura(SPELL_RAMSTEIN_SWIFT_WORK_RAM))
return;
if (GetId() == SPELL_SPEED_RAM_EXHAUSED)
{
if (pCaster->HasAura(SPELL_RAM_FATIGUE))
pCaster->GetAura(SPELL_RAM_FATIGUE)->ModStackAmount(-15);
} else if (!pCaster->HasAura(SPELL_RAM_FATIGUE) || pCaster->GetAura(SPELL_RAM_FATIGUE)->GetStackAmount() < 100)
switch (GetId())
{
case SPELL_SPEED_RAM_GALLOP:
if (!pCaster->HasAura(SPELL_SPEED_RAM_EXHAUSED))
pCaster->CastSpell(pCaster,SPELL_SPEED_RAM_CANTER, false);
break;
case SPELL_SPEED_RAM_CANTER:
if (!pCaster->HasAura(SPELL_SPEED_RAM_GALLOP))
pCaster->CastSpell(pCaster,SPELL_SPEED_RAM_TROT, false);
break;
case SPELL_SPEED_RAM_TROT:
if (!pCaster->HasAura(SPELL_SPEED_RAM_CANTER))
pCaster->CastSpell(pCaster,SPELL_SPEED_RAM_NORMAL, false);
break;
}
}
void OnApply(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/)
{
Player* pCaster = GetCaster()->ToPlayer();
if (!pCaster)
return;
switch (GetId())
{
case SPELL_SPEED_RAM_GALLOP:
pCaster->GetAura(SPELL_SPEED_RAM_GALLOP)->SetDuration(4000);
break;
case SPELL_SPEED_RAM_CANTER:
pCaster->GetAura(SPELL_SPEED_RAM_CANTER)->SetDuration(4000);
break;
case SPELL_SPEED_RAM_TROT:
pCaster->GetAura(SPELL_SPEED_RAM_TROT)->SetDuration(4000);
break;
}
}
void Register()
{
OnEffectApply += AuraEffectApplyFn(spell_brewfest_speed_AuraScript::OnApply, EFFECT_0, SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED, AURA_EFFECT_HANDLE_REAL);
OnEffectPeriodic += AuraEffectPeriodicFn(spell_brewfest_speed_AuraScript::HandlePeriodicTick, EFFECT_1, SPELL_AURA_PERIODIC_DUMMY);
OnEffectRemove += AuraEffectRemoveFn(spell_brewfest_speed_AuraScript::OnRemove, EFFECT_2, SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED, AURA_EFFECT_HANDLE_REAL);
}
};
AuraScript* GetAuraScript() const
{
return new spell_brewfest_speed_AuraScript();
}
};
/*######
## Q Пей до дна!
######*/
enum BrewfestQuestChugAndChuck
{
QUEST_CHUG_AND_CHUCK_A = 12022,
QUEST_CHUG_AND_CHUCK_H = 12191,
NPC_BREWFEST_STOUT = 24108
};
class item_brewfest_ChugAndChuck : public ItemScript
{
public:
item_brewfest_ChugAndChuck() : ItemScript("item_brewfest_ChugAndChuck") { }
bool OnUse(Player* player, Item* pItem, const SpellCastTargets & /*pTargets*/)
{
if (player->GetQuestStatus(QUEST_CHUG_AND_CHUCK_A) == QUEST_STATUS_INCOMPLETE
|| player->GetQuestStatus(QUEST_CHUG_AND_CHUCK_H) == QUEST_STATUS_INCOMPLETE)
{
if (Creature* pStout = player->FindNearestCreature(NPC_BREWFEST_STOUT, 10.0f)) // spell range
{
return false;
} else
player->SendEquipError(EQUIP_ERR_OUT_OF_RANGE, pItem, NULL);
} else
player->SendEquipError(EQUIP_ERR_CANT_DO_RIGHT_NOW ,pItem, NULL);
return true;
}
};
class item_brewfest_ram_reins : public ItemScript
{
public:
item_brewfest_ram_reins() : ItemScript("item_brewfest_ram_reins") { }
bool OnUse(Player* player, Item* pItem, const SpellCastTargets & /*pTargets*/)
{
if ((player->HasAura(SPELL_BREWFEST_RAM) || player->HasAura(SPELL_RAMSTEIN_SWIFT_WORK_RAM)) && !player->HasAura(SPELL_SPEED_RAM_EXHAUSED))
{
if (player->HasAura(SPELL_SPEED_RAM_NORMAL))
player->CastSpell(player,SPELL_SPEED_RAM_TROT,false);
else if (player->HasAura(SPELL_SPEED_RAM_TROT))
{
if (player->GetAura(SPELL_SPEED_RAM_TROT)->GetDuration() < 3000)
player->GetAura(SPELL_SPEED_RAM_TROT)->SetDuration(4000);
else
player->CastSpell(player,SPELL_SPEED_RAM_CANTER,false);
} else if (player->HasAura(SPELL_SPEED_RAM_CANTER))
{
if (player->GetAura(SPELL_SPEED_RAM_CANTER)->GetDuration() < 3000)
player->GetAura(SPELL_SPEED_RAM_CANTER)->SetDuration(4000);
else
player->CastSpell(player,SPELL_SPEED_RAM_GALLOP,false);
} else if (player->HasAura(SPELL_SPEED_RAM_GALLOP))
player->GetAura(SPELL_SPEED_RAM_GALLOP)->SetDuration(4000);
}
else
player->SendEquipError(EQUIP_ERR_CANT_DO_RIGHT_NOW ,pItem, NULL);
return true;
}
};
/*####
## npc_brewfest_keg_thrower
####*/
enum BrewfestKegThrower
{
SPELL_THROW_KEG = 43660, // Хмельной фестиваль - брошенный бочонок - DND
ITEM_BREWFEST_KEG = 33797 // Переносной холодильник для пива
};
class npc_brewfest_keg_thrower : public CreatureScript
{
public:
npc_brewfest_keg_thrower() : CreatureScript("npc_brewfest_keg_thrower") { }
struct npc_brewfest_keg_throwerAI : public ScriptedAI
{
npc_brewfest_keg_throwerAI(Creature* c) : ScriptedAI(c) {}
void MoveInLineOfSight(Unit *who)
{
Player *player = who->ToPlayer();
if (!player)
return;
if ((player->HasAura(SPELL_BREWFEST_RAM) || player->HasAura(SPELL_RAMSTEIN_SWIFT_WORK_RAM))
&& me->GetDistance(player->GetPositionX(),player->GetPositionY(),player->GetPositionZ()) <= 25.0f
&& !player->HasItemCount(ITEM_BREWFEST_KEG,1))
{
me->CastSpell(player,SPELL_THROW_KEG,false);
me->CastSpell(player,42414,false);
}
}
};
CreatureAI *GetAI(Creature *creature) const
{
return new npc_brewfest_keg_throwerAI(creature);
}
};
/*####
## Туда и обратно
####*/
enum BrewfestKegReceiver
{
SPELL_CREATE_TICKETS = 44501, // Holiday - Brewfest - Daily - Relay Race - Create Tickets - DND
QUEST_THERE_AND_BACK_AGAIN_A = 11122,
QUEST_THERE_AND_BACK_AGAIN_H = 11412,
NPC_BREWFEST_DELIVERY_BUNNY = 24337 // [DND] Brewfest Delivery Bunny
};
class npc_brewfest_keg_receiver : public CreatureScript
{
public:
npc_brewfest_keg_receiver() : CreatureScript("npc_brewfest_keg_receiver") { }
struct npc_brewfest_keg_receiverAI : public ScriptedAI
{
npc_brewfest_keg_receiverAI(Creature* c) : ScriptedAI(c) {}
void MoveInLineOfSight(Unit *who)
{
Player *player = who->ToPlayer();
if (!player)
return;
if ((player->HasAura(SPELL_BREWFEST_RAM) || player->HasAura(SPELL_RAMSTEIN_SWIFT_WORK_RAM))
&& me->GetDistance(player->GetPositionX(),player->GetPositionY(),player->GetPositionZ()) <= 5.0f
&& player->HasItemCount(ITEM_BREWFEST_KEG,1))
{
player->CastSpell(me,SPELL_THROW_KEG,true);
player->DestroyItemCount(ITEM_BREWFEST_KEG,1,true);
if (player->HasAura(SPELL_BREWFEST_RAM))
player->GetAura(SPELL_BREWFEST_RAM)->SetDuration(player->GetAura(SPELL_BREWFEST_RAM)->GetDuration() + 30000);
if (player->HasAura(SPELL_RAMSTEIN_SWIFT_WORK_RAM))
player->GetAura(SPELL_RAMSTEIN_SWIFT_WORK_RAM)->SetDuration(player->GetAura(SPELL_RAMSTEIN_SWIFT_WORK_RAM)->GetDuration() + 30000);
if (player->GetQuestRewardStatus(QUEST_THERE_AND_BACK_AGAIN_A)
|| player->GetQuestRewardStatus(QUEST_THERE_AND_BACK_AGAIN_H))
{
player->CastSpell(player,SPELL_CREATE_TICKETS,true);
}
else
{
player->KilledMonsterCredit(NPC_BREWFEST_DELIVERY_BUNNY,0);
if (player->GetQuestStatus(QUEST_THERE_AND_BACK_AGAIN_A) == QUEST_STATUS_INCOMPLETE)
player->AreaExploredOrEventHappens(QUEST_THERE_AND_BACK_AGAIN_A);
if (player->GetQuestStatus(QUEST_THERE_AND_BACK_AGAIN_H) == QUEST_STATUS_INCOMPLETE)
player->AreaExploredOrEventHappens(QUEST_THERE_AND_BACK_AGAIN_H);
if (player->GetQuestStatus(QUEST_THERE_AND_BACK_AGAIN_A) == QUEST_STATUS_COMPLETE
|| player->GetQuestStatus(QUEST_THERE_AND_BACK_AGAIN_H) == QUEST_STATUS_COMPLETE)
player->RemoveAura(SPELL_BREWFEST_RAM);
}
}
}
};
CreatureAI *GetAI(Creature *creature) const
{
return new npc_brewfest_keg_receiverAI(creature);
}
};
/*####
## npc_brewfest_ram_master
####*/
#define GOSSIP_ITEM_RAM "Do you have additional work?"
#define GOSSIP_ITEM_RAM_REINS "Give me another Ram Racing Reins"
#define SPELL_BREWFEST_SUMMON_RAM 43720 // Trigger Brewfest Racing Ram - Relay Race - Intro
class npc_brewfest_ram_master : public CreatureScript
{
public:
npc_brewfest_ram_master() : CreatureScript("npc_brewfest_ram_master") { }
bool OnGossipHello(Player *player, Creature *pCreature)
{
if (pCreature->isQuestGiver())
player->PrepareQuestMenu(pCreature->GetGUID());
if (player->HasSpellCooldown(SPELL_BREWFEST_SUMMON_RAM)
&& !player->GetQuestRewardStatus(QUEST_THERE_AND_BACK_AGAIN_A)
&& !player->GetQuestRewardStatus(QUEST_THERE_AND_BACK_AGAIN_H)
&& (player->GetQuestStatus(QUEST_THERE_AND_BACK_AGAIN_A) == QUEST_STATUS_INCOMPLETE
|| player->GetQuestStatus(QUEST_THERE_AND_BACK_AGAIN_H) == QUEST_STATUS_INCOMPLETE))
player->RemoveSpellCooldown(SPELL_BREWFEST_SUMMON_RAM);
if (!player->HasAura(SPELL_BREWFEST_RAM) && ((player->GetQuestStatus(QUEST_THERE_AND_BACK_AGAIN_A) == QUEST_STATUS_INCOMPLETE
|| player->GetQuestStatus(QUEST_THERE_AND_BACK_AGAIN_H) == QUEST_STATUS_INCOMPLETE
|| (!player->HasSpellCooldown(SPELL_BREWFEST_SUMMON_RAM) &&
(player->GetQuestRewardStatus(QUEST_THERE_AND_BACK_AGAIN_A)
|| player->GetQuestRewardStatus(QUEST_THERE_AND_BACK_AGAIN_H))))))
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_RAM, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1);
if ((player->GetQuestRewardStatus(QUEST_THERE_AND_BACK_AGAIN_A)
|| player->GetQuestRewardStatus(QUEST_THERE_AND_BACK_AGAIN_H))
&& !player->HasItemCount(33306,1,true))
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_RAM_REINS, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+2);
player->SEND_GOSSIP_MENU(384, pCreature->GetGUID());
return true;
}
bool OnGossipSelect(Player* player, Creature* pCreature, uint32 /*uiSender*/, uint32 uiAction)
{
if (uiAction == GOSSIP_ACTION_INFO_DEF+1)
{
if (player->HasItemCount(ITEM_BREWFEST_KEG,1))
player->DestroyItemCount(ITEM_BREWFEST_KEG,1,true);
player->CastSpell(player,SPELL_BREWFEST_SUMMON_RAM,true);
player->AddSpellCooldown(SPELL_BREWFEST_SUMMON_RAM,0,time(NULL) + 18*60*60);
}
if (uiAction == GOSSIP_ACTION_INFO_DEF+2)
{
player->CastSpell(player,44371,false);
}
return true;
}
};
// Dark Iron Guzzler in the Brewfest achievement 'Down With The Dark Iron'
enum DarkIronGuzzler
{
NPC_DARK_IRON_GUZZLER = 23709,
NPC_DARK_IRON_HERALD = 24536,
NPC_DARK_IRON_SPAWN_BUNNY = 23894,
NPC_FESTIVE_KEG_1 = 23702, // Thunderbrew Festive Keg
NPC_FESTIVE_KEG_2 = 23700, // Barleybrew Festive Keg
NPC_FESTIVE_KEG_3 = 23706, // Gordok Festive Keg
NPC_FESTIVE_KEG_4 = 24373, // T'chalis's Festive Keg
NPC_FESTIVE_KEG_5 = 24372, // Drohn's Festive Keg
SPELL_GO_TO_NEW_TARGET = 42498,
SPELL_ATTACK_KEG = 42393,
SPELL_RETREAT = 42341,
SPELL_DRINK = 42436,
SAY_RANDOM = 0,
};
class npc_dark_iron_guzzler : public CreatureScript
{
public:
npc_dark_iron_guzzler() : CreatureScript("npc_dark_iron_guzzler") { }
CreatureAI *GetAI(Creature* creature) const
{
return new npc_dark_iron_guzzlerAI(creature);
}
struct npc_dark_iron_guzzlerAI : public ScriptedAI
{
npc_dark_iron_guzzlerAI(Creature* creature) : ScriptedAI(creature) { }
bool atKeg;
bool playersLost;
bool barleyAlive;
bool thunderAlive;
bool gordokAlive;
bool drohnAlive;
bool tchaliAlive;
uint32 AttackKegTimer;
uint32 TalkTimer;
void Reset()
{
AttackKegTimer = 5000;
TalkTimer = (urand(1000, 120000));
me->AddUnitMovementFlag(MOVEMENTFLAG_WALKING);
}
void IsSummonedBy(Unit* summoner)
{
// Only cast the spell on spawn
DoCast(me, SPELL_GO_TO_NEW_TARGET);
}
// These values are set through SAI - when a Festive Keg dies it will set data to all Dark Iron Guzzlers within 3 yards (the killers)
void SetData(uint32 type, uint32 data)
{
if (type == 10 && data == 10)
{
DoCast(me, SPELL_GO_TO_NEW_TARGET);
thunderAlive = false;
}
if (type == 11 && data == 11)
{
DoCast(me, SPELL_GO_TO_NEW_TARGET);
barleyAlive = false;
}
if (type == 12 && data == 12)
{
DoCast(me, SPELL_GO_TO_NEW_TARGET);
gordokAlive = false;
}
if (type == 13 && data == 13)
{
DoCast(me, SPELL_GO_TO_NEW_TARGET);
drohnAlive = false;
}
if (type == 14 && data == 14)
{
DoCast(me, SPELL_GO_TO_NEW_TARGET);
tchaliAlive = false;
}
}
// As you can see here we do not have to use a spellscript for this
void SpellHit(Unit* caster, const SpellInfo* spell)
{
if (spell->Id == SPELL_DRINK)
{
// Fake death - it's only visual!
me->SetUInt32Value(UNIT_FIELD_BYTES_1, UNIT_STAND_STATE_DEAD);
me->StopMoving();
// Time based on information from videos
me->DespawnOrUnsummon(7000);
}
// Retreat - run back
if (spell->Id == SPELL_RETREAT)
{
// Remove walking flag so we start running
me->RemoveUnitMovementFlag(MOVEMENTFLAG_WALKING);
if (me->GetAreaId() == 1296)
{
me->GetMotionMaster()->MovePoint(1, 1197.63f, -4293.571f, 21.243f);
}
else if (me->GetAreaId() == 1)
{
me->GetMotionMaster()->MovePoint(2, -5152.3f, -603.529f, 398.356f);
}
}
if (spell->Id == SPELL_GO_TO_NEW_TARGET)
{
// If we're at Durotar we target different kegs if we are at at Dun Morogh
if (me->GetAreaId() == 1296)
{
if (drohnAlive && gordokAlive && tchaliAlive)
{
switch (urand(0, 2))
{
case 0: // Gordok Festive Keg
me->GetMotionMaster()->MovePoint(4, 1220.86f, -4297.37f, 21.192f);
break;
case 1: // Drohn's Festive Keg
me->GetMotionMaster()->MovePoint(5, 1185.98f, -4312.98f, 21.294f);
break;
case 2: // Ti'chali's Festive Keg
me->GetMotionMaster()->MovePoint(6, 1184.12f, -4275.21f, 21.191f);
break;
}
}
else if (!drohnAlive)
{
switch (urand(0, 1))
{
case 0: // Gordok Festive Keg
me->GetMotionMaster()->MovePoint(4, 1220.86f, -4297.37f, 21.192f);
break;
case 1: // Ti'chali's Festive Keg
me->GetMotionMaster()->MovePoint(6, 1184.12f, -4275.21f, 21.191f);
break;
}
}
else if (!gordokAlive)
{
switch (urand(0, 1))
{
case 0: // Drohn's Festive Keg
me->GetMotionMaster()->MovePoint(5, 1185.98f, -4312.98f, 21.294f);
break;
case 1: // Ti'chali's Festive Keg
me->GetMotionMaster()->MovePoint(6, 1184.12f, -4275.21f, 21.191f);
break;
}
}
else if (!tchaliAlive)
{
switch (urand(0, 1))
{
case 0: // Gordok Festive Keg
me->GetMotionMaster()->MovePoint(4, 1220.86f, -4297.37f, 21.192f);
break;
case 1: // Drohn's Festive Keg
me->GetMotionMaster()->MovePoint(5, 1185.98f, -4312.98f, 21.294f);
break;
}
}
}
// If we're at Dun Morogh we target different kegs if we are at Durotar
else if (me->GetAreaId() == 1)
{
if (barleyAlive && gordokAlive && thunderAlive)
{
switch (urand(0, 2))
{
case 0: // Barleybrew Festive Keg
me->GetMotionMaster()->MovePoint(7, -5183.67f, -599.58f, 397.177f);
break;
case 1: // Thunderbrew Festive Keg
me->GetMotionMaster()->MovePoint(8, -5159.53f, -629.52f, 397.213f);
break;
case 2: // Gordok Festive Keg
me->GetMotionMaster()->MovePoint(9, -5148.01f, -578.34f, 397.177f);
break;
}
}
else if (!barleyAlive)
{
switch (urand(0, 1))
{
case 0: // Thunderbrew Festive Keg
me->GetMotionMaster()->MovePoint(8, -5159.53f, -629.52f, 397.213f);
break;
case 1: // Gordok Festive Keg
me->GetMotionMaster()->MovePoint(9, -5148.01f, -578.34f, 397.177f);
break;
}
}
else if (!gordokAlive)
{
switch (urand(0, 1))
{
case 0: // Barleybrew Festive Keg
me->GetMotionMaster()->MovePoint(7, -5183.67f, -599.58f, 397.177f);
break;
case 1: // Thunderbrew Festive Keg
me->GetMotionMaster()->MovePoint(8, -5159.53f, -629.52f, 397.213f);
break;
}
}
else if (!thunderAlive)
{
switch (urand(0, 1))
{
case 0: // Barleybrew Festive Keg
me->GetMotionMaster()->MovePoint(7, -5183.67f, -599.58f, 397.177f);
break;
case 1: // Gordok Festive Keg
me->GetMotionMaster()->MovePoint(9, -5148.01f, -578.34f, 397.177f);
break;
}
}
}
atKeg = false;
}
}
void MovementInform(uint32 Type, uint32 PointId)
{
if (Type != POINT_MOTION_TYPE)
return;
// Arrived at the retreat spot, we should despawn
if (PointId == 1 || PointId == 2)
me->DespawnOrUnsummon(1000);
// Arrived at the new keg - the spell has conditions in database
if (PointId == 4 || PointId == 5 || PointId == 6 || PointId == 7 || PointId == 8 || PointId == 9)
{
DoCast(SPELL_ATTACK_KEG);
me->SetByteFlag(UNIT_FIELD_BYTES_1, 1, 0x01); // Sit down
atKeg = true;
}
}
void UpdateAI(const uint32 diff)
{
if (!IsHolidayActive(HOLIDAY_BREWFEST))
return;
// If all kegs are dead we should retreat because we have won
if ((!gordokAlive && !thunderAlive && !barleyAlive) || (!gordokAlive && !drohnAlive && !tchaliAlive))
{
DoCast(me, SPELL_RETREAT);
// We are doing this because we'll have to reset our scripts when we won
if (Creature* herald = me->FindNearestCreature(NPC_DARK_IRON_HERALD, 100.0f))
herald->AI()->SetData(20, 20);
// Despawn all summon bunnies so they will stop summoning guzzlers
if (Creature* spawnbunny = me->FindNearestCreature(NPC_DARK_IRON_SPAWN_BUNNY, 100.0f))
spawnbunny->DespawnOrUnsummon();
}
if (TalkTimer <= diff)
{
me->AI()->Talk(SAY_RANDOM);
TalkTimer = (urand(44000, 120000));
} else TalkTimer -= diff;
// Only happens if we're at keg
if (atKeg)
{
if (AttackKegTimer <= diff)
{
DoCast(SPELL_ATTACK_KEG);
AttackKegTimer = 5000;
} else AttackKegTimer -= diff;
}
}
};
};
/*######
## npc_coren direbrew
######*/
enum CorenDirebrew
{
SPELL_DISARM = 47310, // Обезвреживание Зловещего Варева
SPELL_DISARM_PRECAST = 47407, // Обезвреживание Зловещего Варева (без затраты маны)
SPELL_MOLE_MACHINE_EMERGE = 50313, // bad id. Появление буровой установки
NPC_ILSA_DIREBREW = 26764,
NPC_URSULA_DIREBREW = 26822,
NPC_DIREBREW_MINION = 26776,
EQUIP_ID_TANKARD = 48663,
FACTION_HOSTILE = 736
};
#define GOSSIP_TEXT_INSULT "Insult Coren Direbrew's brew."
static Position _pos[]=
{
{890.87f, -133.95f, -48.0f, 1.53f},
{892.47f, -133.26f, -48.0f, 2.16f},
{893.54f, -131.81f, -48.0f, 2.75f}
};
class npc_coren_direbrew : public CreatureScript
{
public:
npc_coren_direbrew() : CreatureScript("npc_coren_direbrew") { }
bool OnGossipHello(Player* player, Creature* creature)
{
if (creature->isQuestGiver())
player->PrepareQuestMenu(creature->GetGUID());
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_TEXT_INSULT, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1);
player->SEND_GOSSIP_MENU(15858, creature->GetGUID());
return true;
}
bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action)
{
player->PlayerTalkClass->ClearMenus();
if (action == GOSSIP_ACTION_INFO_DEF + 1)
{
creature->setFaction(FACTION_HOSTILE);
creature->AI()->AttackStart(player);
creature->AI()->DoZoneInCombat();
player->CLOSE_GOSSIP_MENU();
}
return true;
}
struct npc_coren_direbrewAI : public ScriptedAI
{
npc_coren_direbrewAI(Creature* c) : ScriptedAI(c), _summons(me)
{
}
void Reset()
{
me->RestoreFaction();
me->SetCorpseDelay(90); // 1.5 minutes
_addTimer = 20000;
_disarmTimer = urand(10, 15) *IN_MILLISECONDS;
_spawnedIlsa = false;
_spawnedUrsula = false;
_summons.DespawnAll();
for (uint8 i = 0; i < 3; ++i)
if (Creature* creature = me->SummonCreature(NPC_DIREBREW_MINION, _pos[i], TEMPSUMMON_CORPSE_TIMED_DESPAWN, 15000))
_add[i] = creature->GetGUID();
}
void EnterCombat(Unit* /*who*/)
{
SetEquipmentSlots(false, EQUIP_ID_TANKARD, EQUIP_ID_TANKARD, EQUIP_NO_CHANGE);
for (uint8 i = 0; i < 3; ++i)
{
if (_add[i])
{
Creature* creature = ObjectAccessor::GetCreature((*me), _add[i]);
if (creature && creature->isAlive())
{
creature->setFaction(FACTION_HOSTILE);
creature->SetInCombatWithZone();
}
_add[i] = 0;
}
}
}
void UpdateAI(uint32 const diff)
{
if (!UpdateVictim())
return;
// disarm
if (_disarmTimer <= diff)
{
DoCast(SPELL_DISARM_PRECAST);
DoCastVictim(SPELL_DISARM, false);
_disarmTimer = urand(20, 25) *IN_MILLISECONDS;
}
else
_disarmTimer -= diff;
// spawn non-elite adds
if (_addTimer <= diff)
{
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true))
{
float posX, posY, posZ;
target->GetPosition(posX, posY, posZ);
target->CastSpell(target, SPELL_MOLE_MACHINE_EMERGE, true, 0, 0, me->GetGUID());
me->SummonCreature(NPC_DIREBREW_MINION, posX, posY, posZ, 0, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 15000);
_addTimer = 15000;
if (_spawnedIlsa)
_addTimer -= 3000;
if (_spawnedUrsula)
_addTimer -= 3000;
}
}
else
_addTimer -= diff;
if (!_spawnedIlsa && HealthBelowPct(66))
{
DoSpawnCreature(NPC_ILSA_DIREBREW, 0, 0, 0, 0, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 15000);
_spawnedIlsa = true;
}
if (!_spawnedUrsula && HealthBelowPct(33))
{
DoSpawnCreature(NPC_URSULA_DIREBREW, 0, 0, 0, 0, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 15000);
_spawnedUrsula = true;
}
DoMeleeAttackIfReady();
}
void JustSummoned(Creature* summon)
{
if (me->getFaction() == FACTION_HOSTILE)
{
summon->setFaction(FACTION_HOSTILE);
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true))
summon->AI()->AttackStart(target);
}
_summons.Summon(summon);
}
void JustDied(Unit* /*killer*/)
{
_summons.DespawnAll();
// TODO: unhack
Map* map = me->GetMap();
if (map && map->IsDungeon())
{
Map::PlayerList const& players = map->GetPlayers();
if (!players.isEmpty())
for (Map::PlayerList::const_iterator i = players.begin(); i != players.end(); ++i)
if (Player* player = i->getSource())
if (player->GetDistance(me) < 100.0f)
sLFGMgr->RewardDungeonDoneFor(287, player);
}
}
private:
SummonList _summons;
uint64 _add[3];
uint32 _addTimer;
uint32 _disarmTimer;
bool _spawnedIlsa;
bool _spawnedUrsula;
};
CreatureAI* GetAI(Creature* c) const
{
return new npc_coren_direbrewAI(c);
}
};
/*######
## dark iron brewmaiden
######*/
enum Brewmaiden
{
SPELL_SEND_FIRST_MUG = 47333,
SPELL_SEND_SECOND_MUG = 47339,
//SPELL_CREATE_BREW = 47345,
SPELL_HAS_BREW_BUFF = 47376,
//SPELL_HAS_BREW = 47331,
//SPELL_DARK_BREWMAIDENS_STUN = 47340,
SPELL_CONSUME_BREW = 47377,
SPELL_BARRELED = 47442,
SPELL_CHUCK_MUG = 50276
};
class npc_brewmaiden : public CreatureScript
{
public:
npc_brewmaiden() : CreatureScript("npc_brewmaiden") { }
struct npc_brewmaidenAI : public ScriptedAI
{
npc_brewmaidenAI(Creature* c) : ScriptedAI(c)
{
}
void Reset()
{
_brewTimer = 2000;
_barrelTimer = 5000;
_chuckMugTimer = 10000;
}
void EnterCombat(Unit* /*who*/)
{
me->SetInCombatWithZone();
}
void AttackStart(Unit* who)
{
if (!who)
return;
if (me->Attack(who, true))
{
me->AddThreat(who, 1.0f);
me->SetInCombatWith(who);
who->SetInCombatWith(me);
if (me->GetEntry() == NPC_URSULA_DIREBREW)
me->GetMotionMaster()->MoveFollow(who, 10.0f, 0.0f);
else
me->GetMotionMaster()->MoveChase(who);
}
}
void SpellHitTarget(Unit* target, SpellInfo const* spell)
{
// TODO: move to DB
if (spell->Id == SPELL_SEND_FIRST_MUG)
target->CastSpell(target, SPELL_HAS_BREW_BUFF, true);
if (spell->Id == SPELL_SEND_SECOND_MUG)
target->CastSpell(target, SPELL_CONSUME_BREW, true);
}
void UpdateAI(uint32 const diff)
{
if (!UpdateVictim())
return;
if (_brewTimer <= diff)
{
if (!me->IsNonMeleeSpellCasted(false))
{
Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true);
if (target && me->GetDistance(target) > 5.0f)
{
DoCast(target, SPELL_SEND_FIRST_MUG);
_brewTimer = 12000;
}
}
}
else
_brewTimer -= diff;
if (_chuckMugTimer <= diff)
{
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true))
DoCast(target, SPELL_CHUCK_MUG);
_chuckMugTimer = 15000;
}
else
_chuckMugTimer -= diff;
if (me->GetEntry() == NPC_URSULA_DIREBREW)
{
if (_barrelTimer <= diff)
{
if (!me->IsNonMeleeSpellCasted(false))
{
DoCastVictim(SPELL_BARRELED);
_barrelTimer = urand(15, 18) *IN_MILLISECONDS;
}
}
else
_barrelTimer -= diff;
}
else
DoMeleeAttackIfReady();
}
private:
uint32 _brewTimer;
uint32 _barrelTimer;
uint32 _chuckMugTimer;
};
CreatureAI* GetAI(Creature* c) const
{
return new npc_brewmaidenAI(c);
}
};
/*######
## go_mole_machine_console
######*/
enum MoleMachineConsole
{
SPELL_TELEPORT = 49466 // bad id?
};
#define GOSSIP_ITEM_MOLE_CONSOLE "[PH] Please teleport me."
class go_mole_machine_console : public GameObjectScript
{
public:
go_mole_machine_console() : GameObjectScript("go_mole_machine_console") { }
bool OnGossipHello (Player* player, GameObject* go)
{
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_MOLE_CONSOLE, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1);
player->SEND_GOSSIP_MENU(12709, go->GetGUID());
return true;
}
bool OnGossipSelect(Player* player, GameObject* /*go*/, uint32 /*sender*/, uint32 action)
{
if (action == GOSSIP_ACTION_INFO_DEF + 1)
player->CastSpell(player, SPELL_TELEPORT, true);
return true;
}
};
void AddSC_boss_coren_direbrew()
{
//
new npc_brewfest_trigger;
new spell_brewfest_speed;
new npc_brewfest_apple_trigger;
//
new item_brewfest_ChugAndChuck;
new item_brewfest_ram_reins;
new npc_brewfest_keg_thrower;
new npc_brewfest_keg_receiver;
new npc_brewfest_ram_master;
new npc_dark_iron_guzzler;
//
new npc_coren_direbrew;
new npc_brewmaiden;
new go_mole_machine_console;
}
| gpl-2.0 |
stripjenga/wnpr | wp-content/plugins/dynamic-widgets/dynwid_admin_edit.php | 14029 | <?php
/**
* dynwid_admin_edit.php - Options settings
*
* @version $Id: dynwid_admin_edit.php 939272 2014-06-26 19:44:38Z qurl $
* @copyright 2011 Jacco Drabbe
*/
// Plugins support
DW_BP::detect();
DW_QT::detect();
DW_WPSC::detect();
DW_WPML::detect();
// Sanitizing some stuff
$widget_id = ( isset($_GET['id']) && ! empty($_GET['id']) ) ? esc_attr($_GET['id']) : '';
$return_url = ( isset($_GET['returnurl']) && ! empty($_GET['returnurl']) ) ? esc_url($_GET['returnurl']) : '';
// In some cases $widget_id appears not to be global (anymore)
$GLOBALS['widget_id'] = $widget_id;
if (! array_key_exists($widget_id, $DW->registered_widgets) ) {
wp_die('WidgetID is not valid');
}
?>
<style type="text/css">
label {
cursor : default;
}
.condition-select {
width : 450px;
-moz-border-radius-topleft : 6px;
-moz-border-radius-topright : 6px;
-moz-border-radius-bottomleft : 6px;
-moz-border-radius-bottomright : 6px;
border-style : solid;
border-width : 1px;
border-color : #E3E3E3;
padding : 5px;
padding-right: 15px; /* for RTL? */
}
.infotext {
width : 98%;
display : none;
color : #666666;
font-style : italic;
}
#dynwid h3 {
text-indent : 30px;
cursor: pointer;
}
h4 {
text-indent : 30px;
cursor: pointer;
}
.hasoptions {
color : #ff0000;
}
#dynwid {
font-family : 'Lucida Grande', Verdana, Arial, 'Bitstream Vera Sans', sans-serif;
font-size : 13px;
}
.dynwid_conf {
display: none;
padding: 15px;
padding-left: 30px;
}
.ui-datepicker {
font-size : 10px;
}
div.settingbox {
border-color: #E3E3E3;
border-radius: 6px 6px 6px 6px;
border-style: solid;
border-width: 1px;
padding: 5px;
}
</style>
<script type="text/javascript">
/* <![CDATA[ */
function chkChild(prefix, pid) {
var add = true;
var child = false;
if ( jQuery( '#' + prefix + '_act_' + pid).is( ':checked' ) == false ) {
if ( jQuery( '#' + prefix + '_childs_act_' + pid ).length > 0 ) {
jQuery( '#' + prefix + '_childs_act_' + pid ).attr( 'checked', false );
child = true;
}
add = false;
}
var value = jQuery( 'input[name^="' + prefix + '_act"]' ).val();
console.log( 'prefix: ' + prefix + ', value: ' + value );
var a = value.split(',');
if ( child ) {
var value_child = jQuery( 'input[name^="' + prefix + '_childs_act"]' ).val();
var a_child = value_child.split(',');
}
if ( add ) {
if ( jQuery.inArray(pid, a) == -1 ) {
a.push( pid );
}
} else {
a = jQuery.grep( a, function(v) {
return v != pid;
});
if ( child ) {
a_child = jQuery.grep( a_child, function(v) {
return v != pid;
});
}
}
value = a.join();
jQuery( '#' + prefix + '_act' ).val( value );
if ( child ) {
value_child = a_child.join();
jQuery( '#' + prefix + '_childs_act' ).val( value_child );
}
}
function chkParent(prefix, pid) {
var add = false;
if ( jQuery( '#' + prefix + '_childs_act_' + pid ).is( ':checked' ) == true ) {
jQuery( '#' + prefix + '_act_' + pid ).attr('checked', true);
add = true;
}
// var value = jQuery( '#' + prefix + '_act' ).val();
var value = jQuery( 'input[name^="' + prefix + '_act"]' ).val();
// var value_child = jQuery( '#' + prefix + '_childs_act' ).val();
var value_child = jQuery( 'input[name^="' + prefix + '_childs_act"]' ).val();
var a = value.split(',');
var a_child = value_child.split(',');
if ( add ) {
if ( jQuery.inArray(pid, a) == -1 ) {
a.push( pid );
}
if ( jQuery.inArray(pid, a_child) == -1 ) {
a_child.push( pid );
}
} else {
a_child = jQuery.grep( a_child, function(v) {
return v != pid;
});
}
value = a.join();
value_child = a_child.join();
jQuery( '#' + prefix + '_act' ).val( value );
jQuery( '#' + prefix + '_childs_act' ).val( value_child );
}
/* function chkCPChild(type, pid) {
if ( jQuery('#'+type+'_act_'+pid).is(':checked') == false ) {
jQuery('#'+type+'_childs_act_'+pid).attr('checked', false);
}
}
function chkCPParent(type, pid) {
if ( jQuery('#'+type+'_childs_act_'+pid).is(':checked') == true ) {
jQuery('#'+type+'_act_'+pid).attr('checked', true);
}
} */
function divToggle(div) {
var div = '#'+div;
jQuery(div).slideToggle(400);
}
function swChb(c, s) {
for ( i = 0; i < c.length; i++ ) {
if ( s == true ) {
jQuery('#'+c[i]).attr('checked', false);
}
jQuery('#'+c[i]).attr('disabled', s);
}
}
function saveandreturn() {
var returnurl = '<?php echo trailingslashit(admin_url()) . 'themes.php?page=dynwid-config'; ?>';
jQuery('#returnurl').val(returnurl);
jQuery('#dwsave').submit();
}
function swTxt(c, s) {
for ( i = 0; i < c.length; i++ ) {
if ( s == true ) {
jQuery('#'+c[i]).val('');
}
jQuery('#'+c[i]).attr('disabled', s);
}
}
function setOff() {
jQuery(':radio').each( function() {
if ( jQuery(this).val() == 'no' && jQuery.inArray(jQuery(this).attr('name'), exclOff) == -1 ) {
jQuery(this).attr('checked', true);
};
});
alert('All options set to \'No\'.\nDon\'t forget to make changes, otherwise you\'ll receive an error when saving.');
}
function toggleAll() {
jQuery( 'h4, #dynwid h3' ).each( function() {
var id = this.id;
if ( closed_state ) {
jQuery( '#' + id + '_conf' ).slideDown('slow');
} else {
jQuery( '#' + id + '_conf' ).slideUp('slow');
}
});
if ( closed_state ) {
closed_state = false;
} else {
closed_state = true;
}
}
function term_tree(widget_id, name, id, prefix) {
var display = jQuery( '#child_' + prefix + id ).css( 'display' );
if ( display == 'none' ) {
jQuery.post( ajaxurl, { action: 'term_tree', id: id, name: name, widget_id: widget_id, prefix: prefix }, function(data) {
jQuery( '#tree_' + prefix + id ).html( data );
jQuery( '#child_' + prefix + id ).slideDown('slow');
});
} else {
jQuery( '#child_' + prefix + id ).slideUp('slow');
}
}
jQuery(document).ready( function() {
jQuery( 'h4, #dynwid h3' ).click( function() {
var id = this.id;
jQuery( '#' + id + '_conf' ).slideToggle('slow');
});
jQuery( 'h4, #dynwid h3' ).mouseover( function() {
jQuery(this).addClass('ui-state-hover');
});
jQuery( 'h4, #dynwid h3' ).mouseleave( function() {
jQuery(this).removeClass('ui-state-hover');
});
});
var closed_state = true;
/* ]]> */
</script>
<?php
if ( isset($_POST['dynwid_save']) && $_POST['dynwid_save'] == 'yes' ) {
$lead = __('Widget options saved.', DW_L10N_DOMAIN);
$msg = '<a href="themes.php?page=dynwid-config">' . __('Return', DW_L10N_DOMAIN) . '</a> ' . __('to Dynamic Widgets overview', DW_L10N_DOMAIN);
DWMessageBox::create($lead, $msg);
} else if ( isset($_GET['work']) && $_GET['work'] == 'none' ) {
DWMessageBox::setTypeMsg('error');
$text = __('Dynamic does not mean static hiding of a widget.', DW_L10N_DOMAIN) . ' ' . __('Hint', DW_L10N_DOMAIN) . ': <a href="widgets.php">' . __('Remove', DW_L10N_DOMAIN) . '</a>' . ' ' . __('the widget from the sidebar', DW_L10N_DOMAIN) . '.';
DWMessageBox::setMessage($text);
DWMessageBox::output();
} else if ( isset($_GET['work']) && $_GET['work'] == 'nonedate' ) {
DWMessageBox::setTypeMsg('error');
$text = __('The From date can\'t be later than the To date.', DW_L10N_DOMAIN);
DWMessageBox::setMessage($text);
DWMessageBox::output();
}
?>
<h3><?php _e('Edit options for the widget', DW_L10N_DOMAIN); ?>: <em><?php echo $DW->getName($widget_id); ?></em></h3>
<?php echo ( DW_DEBUG ) ? '<pre>ID = ' . $widget_id . '</pre><br />' : ''; ?>
<div class="settingbox">
<b><?php _e('Quick settings', DW_L10N_DOMAIN); ?></b>
<p>
<a href="#" onclick="setOff(); return false;"><?php _e('Set all options to \'No\'', DW_L10N_DOMAIN); ?></a> (<?php _e('Except overriding options like Role, Date, etc.', DW_L10N_DOMAIN); ?>)
</p>
</div><br />
<form id="dwsave" action="<?php echo trailingslashit(admin_url()) . 'themes.php?page=dynwid-config&action=edit&id=' . $widget_id; ?>" method="post">
<?php wp_nonce_field('plugin-name-action_edit_' . $widget_id); ?>
<input type="hidden" name="dynwid_save" value="yes" />
<input type="hidden" name="widget_id" value="<?php echo $widget_id; ?>" />
<input type="hidden" id="returnurl" name="returnurl" value="<?php echo ( (! empty($return_url)) ? trailingslashit(admin_url()) . $return_url : '' ); ?>" />
<div class="settingbox">
<b><?php _e('Individual Posts, Custom Post Types and Tags', DW_L10N_DOMAIN); ?></b>
<p>
<?php
$opt_individual = $DW->getDWOpt($widget_id, 'individual');
$individual = ( $opt_individual->count > 0 ) ? TRUE : FALSE;
$DW->dumpOpt($opt_individual);
echo '<input type="checkbox" id="individual" name="individual" value="1" ' . ( ($individual) ? 'checked="checked"' : '' ) . ' onclick="chkInPosts()" />';
echo ' <label for="individual">' . __('Make exception rule available to individual posts and tags.', DW_L10N_DOMAIN) . '</label>';
echo '<img src="' . $DW->plugin_url . 'img/info.gif" alt="info" title="' . __('Click to toggle info', DW_L10N_DOMAIN) . '" onclick="divToggle(\'individual_post_tag\')" />';
echo '<div>';
echo '<div id="individual_post_tag" class="infotext">';
_e('When you enable this option, you have the ability to apply an exception rule to tags and individual posts (Posts and Custom Post Types).
You can set the exception rule for tags in the single Edit Tag Panel (go to <a href="edit-tags.php?taxonomy=post_tag">Post Tags</a>,
click a tag), For individual posts in the <em>New</em> or <em>Edit</em> Posts panel.
Exception rules for tags and individual posts in any combination work independantly, but will always be counted as one exception.<br />
Please note when this is enabled, exception rules which are set within Posts for Author and/or Category will be disabled.
', DW_L10N_DOMAIN);
echo '</div></div>';
?>
</p>
</div><br />
<input type="button" value="Toggle sections" onclick="toggleAll();" /><br />
<br />
<div id="dynwid">
<?php
$DW->getModuleName();
$DW->dwoptions = apply_filters('dynwid_admin_modules', $DW->dwoptions);
if ( array_key_exists('role', $DW->dwoptions) ) {
$DW_Role = new DW_Role();
$DW_Role->admin();
}
if ( array_key_exists('date', $DW->dwoptions) ) {
$DW_Date = new DW_Date();
$DW_Date->admin();
}
if ( array_key_exists('day', $DW->dwoptions) ) {
$DW_Day = new DW_Day();
$DW_Day->admin();
}
if ( array_key_exists('week', $DW->dwoptions) ) {
$DW_Week = new DW_Week();
$DW_Week->admin();
}
if ( array_key_exists('wpml', $DW->dwoptions) ) {
$DW_WPML = new DW_WPML();
$DW_WPML->admin();
}
if ( array_key_exists('qt', $DW->dwoptions) ) {
$DW_QT = new DW_QT();
$DW_QT->admin();
}
if ( array_key_exists('browser', $DW->dwoptions) ) {
$DW_Browser = new DW_Browser();
$DW_Browser->admin();
}
if ( array_key_exists('ip', $DW->dwoptions) ) {
$DW_IP = new DW_IP();
$DW_IP->admin();
}
if ( array_key_exists('device', $DW->dwoptions) ) {
$DW_Device = new DW_Device();
$DW_Device->admin();
}
if ( array_key_exists('tpl', $DW->dwoptions) ) {
$DW_Tpl = new DW_Tpl();
$DW_Tpl->admin();
}
if ( array_key_exists('url', $DW->dwoptions) ) {
$DW_URL = new DW_URL();
$DW_URL->admin();
}
if ( array_key_exists('front-page', $DW->dwoptions) ) {
$DW_Front_page = new DW_Front_page();
$DW_Front_page->admin();
}
if ( array_key_exists('single', $DW->dwoptions) ) {
$DW_Single = new DW_Single();
$DW_Single->admin();
}
if ( array_key_exists('attachment', $DW->dwoptions) ) {
$DW_Attachment = new DW_Attachment();
$DW_Attachment->admin();
}
if ( array_key_exists('page', $DW->dwoptions) ) {
$DW_Page = new DW_Page();
$DW_Page->admin();
}
if ( array_key_exists('author', $DW->dwoptions) ) {
$DW_Author = new DW_Author();
$DW_Author->admin();
}
if ( array_key_exists('category', $DW->dwoptions) ) {
$DW_Category = new DW_Category();
$DW_Category->admin();
}
if ( array_key_exists('tag', $DW->dwoptions) ) {
$DW_Tag = new DW_Tag();
$DW_Tag->admin();
}
if ( array_key_exists('archive', $DW->dwoptions) ) {
$DW_Archive = new DW_Archive();
$DW_Archive->admin();
}
if ( array_key_exists('e404', $DW->dwoptions) ) {
$DW_E404 = new DW_E404();
$DW_E404->admin();
}
if ( array_key_exists('search', $DW->dwoptions) ) {
$DW_Search = new DW_Search();
$DW_Search->admin();
}
$DW_CustomPost = new DW_CustomPost();
$DW_CustomPost->admin();
if ( array_key_exists('wpsc', $DW->dwoptions) ) {
$DW_WPSC = new DW_WPSC();
$DW_WPSC->admin();
}
if ( array_key_exists('bp', $DW->dwoptions) ) {
$DW_BP = new DW_BP();
$DW_BP->admin();
}
if ( array_key_exists('bbp_profile', $DW->dwoptions) ) {
$DW_bbPress = new DW_bbPress();
$DW_bbPress->admin();
}
if ( array_key_exists('pods', $DW->dwoptions) ) {
$DW_Pods = new DW_Pods();
$DW_Pods->admin();
}
// For JS exclOff
$excl = array();
foreach ( $DW->overrule_maintype as $m ) {
$excl[ ] = "'" . $m . "'";
}
?>
</div><!-- end dynwid -->
<br /><br />
<!-- <div>
Save as a quick setting <input type="text" name="qsetting" value="" />
</div> //-->
<br />
<div style="float:left">
<input class="button-primary" type="submit" value="<?php _e('Save'); ?>" />
</div>
<?php $url = (! empty($return_url) ) ? trailingslashit(admin_url()) . $return_url : trailingslashit(admin_url()) . 'themes.php?page=dynwid-config'; ?>
<?php if ( empty($return_url) ) { ?>
<div style="float:left">
<input class="button-primary" type="button" value="<?php _e('Save'); ?> & <?php _e('Return', DW_L10N_DOMAIN); ?>" onclick="saveandreturn()" />
</div>
<?php } ?>
<div style="float:left">
<input class="button-secondary" type="button" value="<?php _e('Return', DW_L10N_DOMAIN); ?>" onclick="location.href='<?php echo $url; ?>'" />
</div>
</form>
<script type="text/javascript">
/* <![CDATA[ */
var exclOff = new Array(<?php echo implode(', ', $excl); ?>);
/* ]]> */
</script>
| gpl-2.0 |
NickDaly/GemRB-MultipleConfigs | gemrb/GUIScripts/iwd2/Name.py | 2125 | # GemRB - Infinity Engine Emulator
# Copyright (C) 2003 The GemRB Project
#
# 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.
#
#
#character generation, name (GUICG5)
import GemRB
from GUIDefines import *
NameWindow = 0
NameField = 0
DoneButton = 0
def OnLoad():
global NameWindow, NameField, DoneButton
GemRB.LoadWindowPack("GUICG", 800, 600)
NameWindow = GemRB.LoadWindow(5)
BackButton = NameWindow.GetControl(3)
BackButton.SetText(15416)
BackButton.SetFlags(IE_GUI_BUTTON_CANCEL,OP_OR)
DoneButton = NameWindow.GetControl(0)
DoneButton.SetText(11973)
DoneButton.SetFlags(IE_GUI_BUTTON_DEFAULT,OP_OR)
DoneButton.SetState(IE_GUI_BUTTON_DISABLED)
NameField = NameWindow.GetControl(2)
DoneButton.SetEvent(IE_GUI_BUTTON_ON_PRESS, NextPress)
BackButton.SetEvent(IE_GUI_BUTTON_ON_PRESS, BackPress)
NameField.SetEvent(IE_GUI_EDIT_ON_CHANGE, EditChange)
NameWindow.SetVisible(WINDOW_VISIBLE)
NameField.SetStatus(IE_GUI_CONTROL_FOCUSED)
return
def BackPress():
if NameWindow:
NameWindow.Unload()
GemRB.SetNextScript("CharGen8")
return
def NextPress():
Name = NameField.QueryText()
#check length?
#seems like a good idea to store it here for the time being
GemRB.SetToken("CHARNAME",Name)
if NameWindow:
NameWindow.Unload()
GemRB.SetNextScript("CharGen9")
return
def EditChange():
Name = NameField.QueryText()
if len(Name)==0:
DoneButton.SetState(IE_GUI_BUTTON_DISABLED)
else:
DoneButton.SetState(IE_GUI_BUTTON_ENABLED)
return
| gpl-2.0 |
gildaslemoal/elpi | framework/sql/src/org/ofbiz/sql/ConditionPlan.java | 1864 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.ofbiz.sql;
import java.util.Map;
public final class ConditionPlan<C> extends SQLPlan<ConditionPlan<C>> {
private final ConditionPlanner<C> planner;
private final Condition originalCondition;
private final C condition;
public ConditionPlan(ConditionPlanner<C> planner, Condition originalCondition, C condition) {
this.planner = planner;
this.originalCondition = originalCondition;
this.condition = condition;
}
public C getCondition(Map<String, ? extends Object> params) throws ParameterizedConditionException {
if (originalCondition != null) {
return planner.parse(originalCondition, params);
} else {
return condition;
}
}
@Override
public StringBuilder appendTo(StringBuilder sb) {
sb.append("ConditionPlan[");
if (originalCondition != null) {
sb.append("original=" + originalCondition);
} else {
sb.append("condition=" + condition);
}
return sb.append("]");
}
}
| gpl-2.0 |
crtc-demos/gcc-ia16 | libstdc++-v3/testsuite/experimental/filesystem/operations/create_directories.cc | 1963 | // Copyright (C) 2015-2016 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library 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, 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 General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// { dg-options "-std=gnu++11 -lstdc++fs" }
// { dg-require-filesystem-ts "" }
#include <experimental/filesystem>
#include <testsuite_hooks.h>
#include <testsuite_fs.h>
namespace fs = std::experimental::filesystem;
void
test01()
{
bool test __attribute__((unused)) = false;
std::error_code ec;
// Test empty path.
bool b = fs::create_directories( "", ec );
VERIFY( ec );
VERIFY( !b );
// Test existing path.
b = fs::create_directories( fs::current_path(), ec );
VERIFY( !ec );
VERIFY( !b );
// Test non-existent path.
const auto p = __gnu_test::nonexistent_path();
b = fs::create_directories( p, ec );
VERIFY( !ec );
VERIFY( b );
VERIFY( is_directory(p) );
b = fs::create_directories( p/".", ec );
VERIFY( !ec );
VERIFY( !b );
b = fs::create_directories( p/"..", ec );
VERIFY( !ec );
VERIFY( !b );
b = fs::create_directories( p/"d1/d2/d3", ec );
VERIFY( !ec );
VERIFY( b );
VERIFY( is_directory(p/"d1/d2/d3") );
b = fs::create_directories( p/"./d4/../d5", ec );
VERIFY( !ec );
VERIFY( b );
VERIFY( is_directory(p/"./d4/../d5") );
std::uintmax_t count = remove_all(p, ec);
VERIFY( count == 6 );
}
int
main()
{
test01();
}
| gpl-2.0 |
joshmoore/bioformats | components/forks/poi/src/loci/poi/hssf/record/BoolErrRecord.java | 10801 | /*
* #%L
* Fork of Apache Jakarta POI.
* %%
* Copyright (C) 2008 - 2015 Open Microscopy Environment:
* - Board of Regents of the University of Wisconsin-Madison
* - Glencoe Software, Inc.
* - University of Dundee
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
/*
* BoolErrRecord.java
*
* Created on January 19, 2002, 9:30 AM
*/
package loci.poi.hssf.record;
import loci.poi.util.LittleEndian;
/**
* Creates new BoolErrRecord. <P>
* REFERENCE: PG ??? Microsoft Excel 97 Developer's Kit (ISBN: 1-57231-498-2)<P>
* @author Michael P. Harhen
* @author Jason Height (jheight at chariot dot net dot au)
* @version 2.0-pre
*/
public class BoolErrRecord
extends Record
implements CellValueRecordInterface, Comparable
{
public final static short sid = 0x205;
//private short field_1_row;
private int field_1_row;
private short field_2_column;
private short field_3_xf_index;
private byte field_4_bBoolErr;
private byte field_5_fError;
/** Creates new BoolErrRecord */
public BoolErrRecord()
{
}
/**
* Constructs a BoolErr record and sets its fields appropriately.
*
* @param in the RecordInputstream to read the record from
*/
public BoolErrRecord(RecordInputStream in)
{
super(in);
}
/**
* @param in the RecordInputstream to read the record from
*/
protected void fillFields(RecordInputStream in)
{
//field_1_row = LittleEndian.getShort(data, 0 + offset);
field_1_row = in.readUShort();
field_2_column = in.readShort();
field_3_xf_index = in.readShort();
field_4_bBoolErr = in.readByte();
field_5_fError = in.readByte();
}
//public void setRow(short row)
public void setRow(int row)
{
field_1_row = row;
}
public void setColumn(short col)
{
field_2_column = col;
}
/**
* set the index to the ExtendedFormat
* @see loci.poi.hssf.record.ExtendedFormatRecord
* @param xf index to the XF record
*/
public void setXFIndex(short xf)
{
field_3_xf_index = xf;
}
/**
* set the boolean value for the cell
*
* @param value representing the boolean value
*/
public void setValue(boolean value)
{
field_4_bBoolErr = value ? ( byte ) 1
: ( byte ) 0;
field_5_fError = ( byte ) 0;
}
/**
* set the error value for the cell
*
* @param value error representing the error value
* this value can only be 0,7,15,23,29,36 or 42
* see bugzilla bug 16560 for an explanation
*/
public void setValue(byte value)
{
if ( (value==0)||(value==7)||(value==15)||(value==23)||(value==29)||(value==36)||(value==42)) {
field_4_bBoolErr = value;
field_5_fError = ( byte ) 1;
} else {
throw new RuntimeException("Error Value can only be 0,7,15,23,29,36 or 42. It cannot be "+value);
}
}
//public short getRow()
public int getRow()
{
return field_1_row;
}
public short getColumn()
{
return field_2_column;
}
/**
* get the index to the ExtendedFormat
* @see loci.poi.hssf.record.ExtendedFormatRecord
* @return index to the XF record
*/
public short getXFIndex()
{
return field_3_xf_index;
}
/**
* get the value for the cell
*
* @return boolean representing the boolean value
*/
public boolean getBooleanValue()
{
return (field_4_bBoolErr != 0);
}
/**
* get the error value for the cell
*
* @return byte representing the error value
*/
public byte getErrorValue()
{
return field_4_bBoolErr;
}
/**
* Indicates whether the call holds a boolean value
*
* @return boolean true if the cell holds a boolean value
*/
public boolean isBoolean()
{
return (field_5_fError == ( byte ) 0);
}
/**
* manually indicate this is an error rather than a boolean
*/
public void setError(boolean val) {
field_5_fError = (byte) (val == false ? 0 : 1);
}
/**
* Indicates whether the call holds an error value
*
* @return boolean true if the cell holds an error value
*/
public boolean isError()
{
return (field_5_fError != ( byte ) 0);
}
public String toString()
{
StringBuffer buffer = new StringBuffer();
buffer.append("[BOOLERR]\n");
buffer.append(" .row = ")
.append(Integer.toHexString(getRow())).append("\n");
buffer.append(" .col = ")
.append(Integer.toHexString(getColumn())).append("\n");
buffer.append(" .xfindex = ")
.append(Integer.toHexString(getXFIndex())).append("\n");
if (isBoolean())
{
buffer.append(" .booleanValue = ").append(getBooleanValue())
.append("\n");
}
else
{
buffer.append(" .errorValue = ").append(getErrorValue())
.append("\n");
}
buffer.append("[/BOOLERR]\n");
return buffer.toString();
}
/**
* called by the class that is responsible for writing this sucker.
* Subclasses should implement this so that their data is passed back in a
* byte array.
*
* @return byte array containing instance data
*/
public int serialize(int offset, byte [] data)
{
LittleEndian.putShort(data, 0 + offset, sid);
LittleEndian.putShort(data, 2 + offset, ( short ) 8);
//LittleEndian.putShort(data, 4 + offset, getRow());
LittleEndian.putShort(data, 4 + offset, ( short ) getRow());
LittleEndian.putShort(data, 6 + offset, getColumn());
LittleEndian.putShort(data, 8 + offset, getXFIndex());
data[ 10 + offset ] = field_4_bBoolErr;
data[ 11 + offset ] = field_5_fError;
return getRecordSize();
}
public int getRecordSize()
{
return 12;
}
/**
* called by constructor, should throw runtime exception in the event of a
* record passed with a differing ID.
*
* @param id alleged id for this record
*/
protected void validateSid(short id)
{
if (id != BoolErrRecord.sid)
{
throw new RecordFormatException("Not a valid BoolErrRecord");
}
}
public short getSid()
{
return sid;
}
public boolean isBefore(CellValueRecordInterface i)
{
if (this.getRow() > i.getRow())
{
return false;
}
if ((this.getRow() == i.getRow())
&& (this.getColumn() > i.getColumn()))
{
return false;
}
if ((this.getRow() == i.getRow())
&& (this.getColumn() == i.getColumn()))
{
return false;
}
return true;
}
public boolean isAfter(CellValueRecordInterface i)
{
if (this.getRow() < i.getRow())
{
return false;
}
if ((this.getRow() == i.getRow())
&& (this.getColumn() < i.getColumn()))
{
return false;
}
if ((this.getRow() == i.getRow())
&& (this.getColumn() == i.getColumn()))
{
return false;
}
return true;
}
public boolean isEqual(CellValueRecordInterface i)
{
return ((this.getRow() == i.getRow())
&& (this.getColumn() == i.getColumn()));
}
public boolean isInValueSection()
{
return true;
}
public boolean isValue()
{
return true;
}
public int compareTo(Object obj)
{
CellValueRecordInterface loc = ( CellValueRecordInterface ) obj;
if ((this.getRow() == loc.getRow())
&& (this.getColumn() == loc.getColumn()))
{
return 0;
}
if (this.getRow() < loc.getRow())
{
return -1;
}
if (this.getRow() > loc.getRow())
{
return 1;
}
if (this.getColumn() < loc.getColumn())
{
return -1;
}
if (this.getColumn() > loc.getColumn())
{
return 1;
}
return -1;
}
public boolean equals(Object obj)
{
if (!(obj instanceof CellValueRecordInterface))
{
return false;
}
CellValueRecordInterface loc = ( CellValueRecordInterface ) obj;
if ((this.getRow() == loc.getRow())
&& (this.getColumn() == loc.getColumn()))
{
return true;
}
return false;
}
public Object clone() {
BoolErrRecord rec = new BoolErrRecord();
rec.field_1_row = field_1_row;
rec.field_2_column = field_2_column;
rec.field_3_xf_index = field_3_xf_index;
rec.field_4_bBoolErr = field_4_bBoolErr;
rec.field_5_fError = field_5_fError;
return rec;
}
}
| gpl-2.0 |
krichter722/gcc | libstdc++-v3/testsuite/tr1/5_numerical_facilities/random/subtract_with_carry_01/cons/default.cc | 1330 | // 2006-08-22 Paolo Carlini <[email protected]>
//
// Copyright (C) 2006-2017 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library 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, 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// 5.1.4.4 class template subtract_with_carry_01 [tr.rand.eng.sub1]
// 5.1.1 Table 16 line 1 default ctor
#include <tr1/random>
#include <testsuite_hooks.h>
void
test01()
{
using namespace std::tr1;
subtract_with_carry_01<float, 24, 10, 24> x;
VERIFY( x.min() == 0.0 );
VERIFY( x.max() == 1.0 );
#if _GLIBCXX_USE_C99_MATH_TR1
VERIFY( x() == 15039276 * std::tr1::ldexp(float(1), -24) );
#else
VERIFY( x() == 15039276 * std::pow(float(2), -24) );
#endif
}
int main()
{
test01();
return 0;
}
| gpl-2.0 |
mashuai/OpenJDK-Research | hotspot/my-docs/interpreter/bytecode/invokespecial.java | 3303 | invokespecial 183 invokespecial [0x01cc57a0, 0x01cc58e0] 320 bytes
0x01cc57a0: sub $0x4,%esp
0x01cc57a3: fstps (%esp)
0x01cc57a6: jmp 0x01cc57c4
0x01cc57ab: sub $0x8,%esp
0x01cc57ae: fstpl (%esp)
0x01cc57b1: jmp 0x01cc57c4
0x01cc57b6: push %edx
0x01cc57b7: push %eax
0x01cc57b8: jmp 0x01cc57c4
0x01cc57bd: push %eax
0x01cc57be: jmp 0x01cc57c4
0x01cc57c3: push %eax
0x01cc57c4: mov %esi,-0x1c(%ebp)
0x01cc57c7: movzwl 0x1(%esi),%edx
0x01cc57cb: mov -0x14(%ebp),%ecx
0x01cc57ce: shl $0x2,%edx
0x01cc57d1: mov 0x8(%ecx,%edx,4),%ebx
0x01cc57d5: shr $0x10,%ebx //取ConstantPoolCacheEntry._indices字段中的index
0x01cc57d8: and $0xff,%ebx
0x01cc57de: cmp $0xb7,%ebx
0x01cc57e4: je 0x01cc5897
0x01cc57ea: mov $0xb7,%ebx
0x01cc57ef: call 0x01cc57f9
0x01cc57f4: jmp 0x01cc588d
0x01cc57f9: push %ebx
0x01cc57fa: lea 0x8(%esp),%eax
0x01cc57fe: cmpl $0x0,-0x8(%ebp)
0x01cc5805: je 0x01cc581c
0x01cc580b: push $0x55310188
0x01cc5810: call 0x01cc5815
0x01cc5815: pusha
0x01cc5816: call 0x54dedbf0
0x01cc581b: hlt
0x01cc581c: mov %esi,-0x1c(%ebp)
0x01cc581f: mov %fs:0x0(,%eiz,1),%edi
0x01cc5827: mov -0xc(%edi),%edi
0x01cc582a: push %edi
0x01cc582b: mov %ebp,0x144(%edi)
0x01cc5831: mov %eax,0x13c(%edi)
0x01cc5837: call 0x5505b0b0
0x01cc583c: add $0x8,%esp
0x01cc583f: push %eax
0x01cc5840: mov %fs:0x0(,%eiz,1),%eax
0x01cc5848: mov -0xc(%eax),%eax
0x01cc584b: cmp %eax,%edi
0x01cc584d: je 0x01cc5864
;; MacroAssembler::call_VM_base: rdi not callee saved?
0x01cc5853: push $0x55312af0
0x01cc5858: call 0x01cc585d
0x01cc585d: pusha
0x01cc585e: call 0x54dedbf0
0x01cc5863: hlt
0x01cc5864: pop %eax
0x01cc5865: movl $0x0,0x13c(%edi)
0x01cc586f: movl $0x0,0x144(%edi)
0x01cc5879: cmpl $0x0,0x4(%edi)
0x01cc5880: jne 0x01cb0340
0x01cc5886: mov -0x1c(%ebp),%esi
0x01cc5889: mov -0x18(%ebp),%edi
0x01cc588c: ret
0x01cc588d: movzwl 0x1(%esi),%edx
0x01cc5891: mov -0x14(%ebp),%ecx
0x01cc5894: shl $0x2,%edx
0x01cc5897: mov 0xc(%ecx,%edx,4),%ebx
0x01cc589b: mov 0x14(%ecx,%edx,4),%edx
0x01cc589f: mov %edx,%ecx
0x01cc58a1: and $0xff,%ecx
0x01cc58a7: mov -0x4(%esp,%ecx,4),%ecx //this指针存放在堆栈的位置,总是这第一个参数
0x01cc58ab: shr $0x1c,%edx
0x01cc58ae: mov 0x556277cc(,%edx,4),%edx
0x01cc58b5: push %edx
//最初%eax的值是this指针,但是在TemplateTable::invokespecial的prepare_invoke中改变了eax的值
//这应该是个bug,不过并不影响正确性
0x01cc58b6: cmp (%ecx),%eax //__ null_check(rcx);
0x01cc58b8: lea 0x4(%esp),%esi
0x01cc58bc: mov %esi,-0x8(%ebp)
0x01cc58bf: jmp *0x34(%ebx)
0x01cc58c2: push $0x552fd97c
0x01cc58c7: call 0x01cc58cc
0x01cc58cc: pusha
0x01cc58cd: call 0x54dedbf0
0x01cc58d2: hlt
0x01cc58d3: nop
0x01cc58d4: int3
0x01cc58d5: int3
0x01cc58d6: int3
0x01cc58d7: int3
0x01cc58d8: int3
0x01cc58d9: int3
0x01cc58da: int3
0x01cc58db: int3
0x01cc58dc: int3
0x01cc58dd: int3
0x01cc58de: int3
0x01cc58df: int3
| gpl-2.0 |
dillonjerry/aws | AWS-ElasticBeanstalk-CLI-2.6.2/api/lib/aws/client/v2signaturehelper.rb | 1919 | require 'openssl'
require 'base64'
require 'time'
module AWS
module Client
#
# Performs AWS V2 signatures on QueryStringMap objects.
#
# Copyright:: Copyright (c) 2008, 2012 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
class V2SignatureHelper
def initialize(aws_access_key_id, aws_secret_key)
@aws_access_key_id = aws_access_key_id.to_s
@aws_secret_key = aws_secret_key.to_s
end
def sign(args)
query_string_map = args[:query_string_map]
add_fields(query_string_map, args[:datetime])
request = args[:request]
query_string = canonical_query_string(query_string_map)
request[:query_string] = query_string + "&Signature=" + UrlEncoding.encode(compute_signature(canonicalize(args, query_string)))
end
def canonicalize(args, query_string)
uri = args[:uri]
verb = args[:verb]
host = args[:host].downcase
canonical = "#{verb}\n#{host}\n#{uri}\n" + query_string
return canonical
end
def compute_signature(canonical)
digest = OpenSSL::Digest::Digest.new('sha1')
return Base64.encode64(OpenSSL::HMAC.digest(digest, @aws_secret_key, canonical)).strip
end
def add_fields(query_string_map, time)
query_string_map['AWSAccessKeyId'] = @aws_access_key_id
query_string_map['SignatureVersion'] = '2'
query_string_map['SignatureMethod'] = 'HmacSHA1'
query_string_map['Timestamp'] = time
end
def sort(hash)
hash.sort
end
def canonical_query_string (query_string_map)
query = []
query_string_map.each_pair do |k,v|
query << [k,v] unless k == 'Signature'
end
query = query.sort_by(&:first)
query.map{|k,v| "#{UrlEncoding.encode(k)}=#{UrlEncoding.encode(v)}"}.join('&')
end
end
end
end
| gpl-2.0 |
unofficial-opensource-apple/gccfast | libjava/java/nio/InvalidMarkException.java | 1951 | /* InvalidMarkException.java --
Copyright (C) 2002 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath 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, or (at your option)
any later version.
GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.nio;
/**
* @author Michael Koch
* @since 1.4
*/
public class InvalidMarkException extends IllegalStateException
{
/**
* Creates the exception
*/
public InvalidMarkException ()
{
}
}
| gpl-2.0 |
astrophysicist87/iEBE-Plumberg | EBE-Node/EbeCollector/EbeCollectorShell_pureHydroOldFormat.py | 798 | #!/usr/bin/env python
"""
This is one of the shells to the EbeCollector class. This one
creates a database using data from subfolders containing multiple
pure hydro (with old format) events.
"""
from sys import argv, exit
from os import path
try:
from_folder = path.abspath(argv[1])
except:
print("Usage: shell from_folder [sub_folder_pattern] [database_filename]")
exit()
# get optional parameters
if len(argv)>=3:
subfolder_pattern = argv[2]
else:
subfolder_pattern = "event-(\d*)"
if len(argv)>=4:
database_filename = argv[3]
else:
database_filename = "collected.db"
# call EbeCollector
from EbeCollector import EbeCollector
EbeCollector().createDatabaseFromEventFolders(from_folder, subfolder_pattern, database_filename, collectMode="fromPureHydro")
| gpl-3.0 |
isnnn/Sick-Beard-TPB | lib/guessit/patterns.py | 10117 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# GuessIt - A library for guessing information from filenames
# Copyright (c) 2011 Nicolas Wack <[email protected]>
# Copyright (c) 2011 Ricard Marxer <[email protected]>
#
# GuessIt is free software; you can redistribute it and/or modify it under
# the terms of the Lesser GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# GuessIt is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# Lesser GNU General Public License for more details.
#
# You should have received a copy of the Lesser GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import unicode_literals
import re
subtitle_exts = [ 'srt', 'idx', 'sub', 'ssa' ]
video_exts = ['3g2', '3gp', '3gp2', 'asf', 'avi', 'divx', 'flv', 'm4v', 'mk2',
'mka', 'mkv', 'mov', 'mp4', 'mp4a', 'mpeg', 'mpg', 'ogg', 'ogm',
'ogv', 'qt', 'ra', 'ram', 'rm', 'ts', 'wav', 'webm', 'wma', 'wmv']
group_delimiters = [ '()', '[]', '{}' ]
# separator character regexp
sep = r'[][)(}{+ /\._-]' # regexp art, hehe :D
# character used to represent a deleted char (when matching groups)
deleted = '_'
# format: [ (regexp, confidence, span_adjust) ]
episode_rexps = [ # ... Season 2 ...
(r'season (?P<season>[0-9]+)', 1.0, (0, 0)),
(r'saison (?P<season>[0-9]+)', 1.0, (0, 0)),
# ... s02e13 ...
(r'[Ss](?P<season>[0-9]{1,3})[^0-9]?(?P<episodeNumber>(?:-?[eE-][0-9]{1,3})+)[^0-9]', 1.0, (0, -1)),
# ... s03-x02 ... # FIXME: redundant? remove it?
#(r'[Ss](?P<season>[0-9]{1,3})[^0-9]?(?P<bonusNumber>(?:-?[xX-][0-9]{1,3})+)[^0-9]', 1.0, (0, -1)),
# ... 2x13 ...
(r'[^0-9](?P<season>[0-9]{1,2})[^0-9]?(?P<episodeNumber>(?:-?[xX][0-9]{1,3})+)[^0-9]', 1.0, (1, -1)),
# ... s02 ...
#(sep + r's(?P<season>[0-9]{1,2})' + sep, 0.6, (1, -1)),
(r's(?P<season>[0-9]{1,2})[^0-9]', 0.6, (0, -1)),
# v2 or v3 for some mangas which have multiples rips
(r'(?P<episodeNumber>[0-9]{1,3})v[23]' + sep, 0.6, (0, 0)),
# ... ep 23 ...
('ep' + sep + r'(?P<episodeNumber>[0-9]{1,2})[^0-9]', 0.7, (0, -1)),
# ... e13 ... for a mini-series without a season number
(sep + r'e(?P<episodeNumber>[0-9]{1,2})' + sep, 0.6, (1, -1))
]
weak_episode_rexps = [ # ... 213 or 0106 ...
(sep + r'(?P<episodeNumber>[0-9]{2,4})' + sep, (1, -1))
]
non_episode_title = [ 'extras', 'rip' ]
video_rexps = [ # cd number
(r'cd ?(?P<cdNumber>[0-9])( ?of ?(?P<cdNumberTotal>[0-9]))?', 1.0, (0, 0)),
(r'(?P<cdNumberTotal>[1-9]) cds?', 0.9, (0, 0)),
# special editions
(r'edition' + sep + r'(?P<edition>collector)', 1.0, (0, 0)),
(r'(?P<edition>collector)' + sep + 'edition', 1.0, (0, 0)),
(r'(?P<edition>special)' + sep + 'edition', 1.0, (0, 0)),
(r'(?P<edition>criterion)' + sep + 'edition', 1.0, (0, 0)),
# director's cut
(r"(?P<edition>director'?s?" + sep + "cut)", 1.0, (0, 0)),
# video size
(r'(?P<width>[0-9]{3,4})x(?P<height>[0-9]{3,4})', 0.9, (0, 0)),
# website
(r'(?P<website>www(\.[a-zA-Z0-9]+){2,3})', 0.8, (0, 0)),
# bonusNumber: ... x01 ...
(r'x(?P<bonusNumber>[0-9]{1,2})', 1.0, (0, 0)),
# filmNumber: ... f01 ...
(r'f(?P<filmNumber>[0-9]{1,2})', 1.0, (0, 0))
]
websites = [ 'tvu.org.ru', 'emule-island.com', 'UsaBit.com', 'www.divx-overnet.com',
'sharethefiles.com' ]
unlikely_series = [ 'series' ]
# prop_multi is a dict of { property_name: { canonical_form: [ pattern ] } }
# pattern is a string considered as a regexp, with the addition that dashes are
# replaced with '([ \.-_])?' which matches more types of separators (or none)
# note: simpler patterns need to be at the end of the list to not shadow more
# complete ones, eg: 'AAC' needs to come after 'He-AAC'
# ie: from most specific to less specific
prop_multi = { 'format': { 'DVD': [ 'DVD', 'DVD-Rip', 'VIDEO-TS', 'DVDivX' ],
'HD-DVD': [ 'HD-(?:DVD)?-Rip', 'HD-DVD' ],
'BluRay': [ 'Blu-ray', 'B[DR]Rip' ],
'HDTV': [ 'HD-TV' ],
'DVB': [ 'DVB-Rip', 'DVB', 'PD-TV' ],
'WEBRip': [ 'WEB-Rip' ],
'Screener': [ 'DVD-SCR', 'Screener' ],
'VHS': [ 'VHS' ],
'WEB-DL': [ 'WEB-DL' ] },
'screenSize': { '480p': [ '480[pi]?' ],
'720p': [ '720[pi]?' ],
'1080p': [ '1080[pi]?' ] },
'videoCodec': { 'XviD': [ 'Xvid' ],
'DivX': [ 'DVDivX', 'DivX' ],
'h264': [ '[hx]-264' ],
'Rv10': [ 'Rv10' ],
'Mpeg2': [ 'Mpeg2' ] },
# has nothing to do here (or on filenames for that matter), but some
# releases use it and it helps to identify release groups, so we adapt
'videoApi': { 'DXVA': [ 'DXVA' ] },
'audioCodec': { 'AC3': [ 'AC3' ],
'DTS': [ 'DTS' ],
'AAC': [ 'He-AAC', 'AAC-He', 'AAC' ] },
'audioChannels': { '5.1': [ r'5\.1', 'DD5[\._ ]1', '5ch' ] },
'episodeFormat': { 'Minisode': [ 'Minisodes?' ] }
}
# prop_single dict of { property_name: [ canonical_form ] }
prop_single = { 'releaseGroup': [ 'ESiR', 'WAF', 'SEPTiC', r'\[XCT\]', 'iNT', 'PUKKA',
'CHD', 'ViTE', 'TLF', 'FLAiTE',
'MDX', 'GM4F', 'DVL', 'SVD', 'iLUMiNADOS',
'aXXo', 'KLAXXON', 'NoTV', 'ZeaL', 'LOL',
'CtrlHD', 'POD', 'WiKi','IMMERSE', 'FQM',
'2HD', 'CTU', 'HALCYON', 'EbP', 'SiTV',
'HDBRiSe', 'AlFleNi-TeaM', 'EVOLVE', '0TV',
'TLA', 'NTB', 'ASAP', 'MOMENTUM', 'FoV', 'D-Z0N3',
'TrollHD', 'ECI'
],
# potentially confusing release group names (they are words)
'weakReleaseGroup': [ 'DEiTY', 'FiNaLe', 'UnSeeN', 'KiNGS', 'CLUE', 'DIMENSION',
'SAiNTS', 'ARROW', 'EuReKA', 'SiNNERS', 'DiRTY', 'REWARD',
'REPTiLE',
],
'other': [ 'PROPER', 'REPACK', 'LIMITED', 'DualAudio', 'Audiofixed', 'R5',
'complete', 'classic', # not so sure about these ones, could appear in a title
'ws' ] # widescreen
}
_dash = '-'
_psep = '[-\. _]?'
def _to_rexp(prop):
return re.compile(prop.replace(_dash, _psep), re.IGNORECASE)
# properties_rexps dict of { property_name: { canonical_form: [ rexp ] } }
# containing the rexps compiled from both prop_multi and prop_single
properties_rexps = dict((type, dict((canonical_form,
[ _to_rexp(pattern) for pattern in patterns ])
for canonical_form, patterns in props.items()))
for type, props in prop_multi.items())
properties_rexps.update(dict((type, dict((canonical_form, [ _to_rexp(canonical_form) ])
for canonical_form in props))
for type, props in prop_single.items()))
def find_properties(string):
result = []
for property_name, props in properties_rexps.items():
# FIXME: this should be done in a more flexible way...
if property_name in ['weakReleaseGroup']:
continue
for canonical_form, rexps in props.items():
for value_rexp in rexps:
match = value_rexp.search(string)
if match:
start, end = match.span()
# make sure our word is always surrounded by separators
# note: sep is a regexp, but in this case using it as
# a char sequence achieves the same goal
if ((start > 0 and string[start-1] not in sep) or
(end < len(string) and string[end] not in sep)):
continue
result.append((property_name, canonical_form, start, end))
return result
property_synonyms = { 'Special Edition': [ 'Special' ],
'Collector Edition': [ 'Collector' ],
'Criterion Edition': [ 'Criterion' ]
}
def revert_synonyms():
reverse = {}
for canonical, synonyms in property_synonyms.items():
for synonym in synonyms:
reverse[synonym.lower()] = canonical
return reverse
reverse_synonyms = revert_synonyms()
def canonical_form(string):
return reverse_synonyms.get(string.lower(), string)
def compute_canonical_form(property_name, value):
"""Return the canonical form of a property given its type if it is a valid
one, None otherwise."""
for canonical_form, rexps in properties_rexps[property_name].items():
for rexp in rexps:
if rexp.match(value):
return canonical_form
return None
| gpl-3.0 |
Bugex/SkyFireEMU | src/server/scripts/Northrend/Zones/isle_of_conquest.cpp | 2651 | /*
* Copyright (C) 2011-2012 Project SkyFire <http://www.projectskyfire.org/>
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.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 <http://www.gnu.org/licenses/>.
*/
#include "ScriptPCH.h"
#include "BattlegroundIC.h"
// TO-DO: This should be done with SmartAI, but yet it does not correctly support vehicles's AIs.
// Even adding ReactState Passive we still have issues using SmartAI.
class npc_four_car_garage : public CreatureScript
{
public:
npc_four_car_garage() : CreatureScript("npc_four_car_garage") {}
struct npc_four_car_garageAI : public NullCreatureAI
{
npc_four_car_garageAI(Creature* creature) : NullCreatureAI(creature) { }
void PassengerBoarded(Unit* who, int8 /*seatId*/, bool apply)
{
if (apply)
{
uint32 spellId = 0;
switch (me->GetEntry())
{
case NPC_DEMOLISHER:
spellId = SPELL_DRIVING_CREDIT_DEMOLISHER;
break;
case NPC_GLAIVE_THROWER_A:
case NPC_GLAIVE_THROWER_H:
spellId = SPELL_DRIVING_CREDIT_GLAIVE;
break;
case NPC_SIEGE_ENGINE_H:
case NPC_SIEGE_ENGINE_A:
spellId = SPELL_DRIVING_CREDIT_SIEGE;
break;
case NPC_CATAPULT:
spellId = SPELL_DRIVING_CREDIT_CATAPULT;
break;
default:
return;
}
me->CastSpell(who, spellId, true);
}
}
};
CreatureAI* GetAI(Creature* creature) const
{
return new npc_four_car_garageAI(creature);
}
};
void AddSC_isle_of_conquest()
{
new npc_four_car_garage();
} | gpl-3.0 |
customizablebasicincome/cbi-tokensale | node_modules/zeppelin-solidity/migrations/2_deploy_contracts.js | 132 | //var Ownable = artifacts.require("ownership/Ownable.sol");
module.exports = function(deployer) {
//deployer.deploy(Ownable);
};
| gpl-3.0 |
danmarsden/moodle | course/format/social/version.php | 1194 | <?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Version details
*
* @package format
* @subpackage social
* @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$plugin->version = 2018120300; // The current plugin version (Date: YYYYMMDDXX)
$plugin->requires = 2018112800; // Requires this Moodle version
$plugin->component = 'format_social'; // Full name of the plugin (used for diagnostics)
| gpl-3.0 |
kylethayer/bioladder | wiki/includes/libs/rdbms/defines.php | 770 | <?php
use Wikimedia\Rdbms\ILoadBalancer;
use Wikimedia\Rdbms\IDatabase;
/**@{
* Database related constants
*/
define( 'DBO_DEBUG', IDatabase::DBO_DEBUG );
define( 'DBO_NOBUFFER', IDatabase::DBO_NOBUFFER );
define( 'DBO_IGNORE', IDatabase::DBO_IGNORE );
define( 'DBO_TRX', IDatabase::DBO_TRX );
define( 'DBO_DEFAULT', IDatabase::DBO_DEFAULT );
define( 'DBO_PERSISTENT', IDatabase::DBO_PERSISTENT );
define( 'DBO_SYSDBA', IDatabase::DBO_SYSDBA );
define( 'DBO_DDLMODE', IDatabase::DBO_DDLMODE );
define( 'DBO_SSL', IDatabase::DBO_SSL );
define( 'DBO_COMPRESS', IDatabase::DBO_COMPRESS );
/**@}*/
/**@{
* Valid database indexes
* Operation-based indexes
*/
define( 'DB_REPLICA', ILoadBalancer::DB_REPLICA );
define( 'DB_MASTER', ILoadBalancer::DB_MASTER );
/**@}*/
| gpl-3.0 |
dickeyf/darkstar | scripts/zones/Den_of_Rancor/mobs/Tonberry_Tracker.lua | 633 | -----------------------------------
-- Area: Den of Rancor
-- MOB: Tonberry Tracker
-----------------------------------
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer,ally)
checkGoVregime(ally,mob,798,1);
checkGoVregime(ally,mob,799,2);
checkGoVregime(ally,mob,800,2);
local kills = ally:getVar("EVERYONES_GRUDGE_KILLS");
if (kills < 480) then
ally:setVar("EVERYONES_GRUDGE_KILLS",kills + 1);
end
end; | gpl-3.0 |
elphinkuo/Androidpn | androidpn-code/androidpn-client/tags/androidpn-client-0.3.0/src/org/androidpn/sdk/InvalidFormatException.java | 1051 | /*
* Copyright 2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.androidpn.sdk;
/**
* Class desciption here.
*
* @author Sehwan Noh ([email protected])
*/
public class InvalidFormatException extends RuntimeException {
private static final long serialVersionUID = 4500254309828208737L;
public InvalidFormatException(String message) {
super(message);
}
public InvalidFormatException(String message, Throwable cause) {
super(message, cause);
}
}
| gpl-3.0 |
ChloeG/artoolkit5 | doc/apiref-ARWrapper/html/search/all_75.js | 2897 | var searchData=
[
['uid',['UID',['../class_a_r_marker.html#a574a7dfa20733eb751720425be6cb169',1,'ARMarker']]],
['unityrenderevent',['UnityRenderEvent',['../_a_r_tool_kit_wrapper_exported_a_p_i_8h.html#a8672fab0eadfec7bb97a8a0045033747',1,'UnityRenderEvent(int eventID): ARToolKitWrapperExportedAPI.cpp'],['../_a_r_tool_kit_wrapper_exported_a_p_i_8cpp.html#a8672fab0eadfec7bb97a8a0045033747',1,'UnityRenderEvent(int eventID): ARToolKitWrapperExportedAPI.cpp']]],
['unload',['unload',['../class_a_r_marker_multi.html#a9d0df350967d5736f90c398e04491dd6',1,'ARMarkerMulti::unload()'],['../class_a_r_marker_n_f_t.html#aa045d2d5a06509e7faaeb8035a72f341',1,'ARMarkerNFT::unload()'],['../class_a_r_marker_square.html#af7434e51f5d2465ea6916053f59715c6',1,'ARMarkerSquare::unload()']]],
['update',['update',['../class_a_r_controller.html#ac726b34aac45206f4608e9a15875db82',1,'ARController::update()'],['../class_a_r_marker.html#a4064c104e9231bdf61afe2717fe5456b',1,'ARMarker::update()']]],
['updatedebugtexture',['updateDebugTexture',['../class_a_r_controller.html#a17db1749663c70d876d39fbf19274aed',1,'ARController']]],
['updatedebugtextureb',['updateDebugTextureB',['../class_a_r_controller.html#ae89b3a39075cd393cc30ab1904d24473',1,'ARController']]],
['updatetexture',['updateTexture',['../class_a_r_controller.html#a3a39007194f7a2dd42e81f393cf588d8',1,'ARController::updateTexture()'],['../class_video_source.html#aa2b41d0ac135213d868f4491b33d3e1a',1,'VideoSource::updateTexture()']]],
['updatetexture32',['updateTexture32',['../class_a_r_controller.html#ac580d4ef4f76a38b6dd06322ae645e34',1,'ARController::updateTexture32()'],['../class_video_source.html#a664915a2d8a52c5cfb68a6d6fbf91ab4',1,'VideoSource::updateTexture32()']]],
['updatetexturegl',['updateTextureGL',['../class_a_r_controller.html#a5d6c658c56c5c839a77e03dd85f1e2d6',1,'ARController::updateTextureGL()'],['../class_video_source.html#a3215ae64e2830ee7b6a54f880d4ef863',1,'VideoSource::updateTextureGL()']]],
['updatewithdetectedmarkers',['updateWithDetectedMarkers',['../class_a_r_marker_multi.html#aced390511098f4a4184fa3571e6ed12f',1,'ARMarkerMulti::updateWithDetectedMarkers()'],['../class_a_r_marker_square.html#ab2cecf3ab3e0cd01efa5a21d1244b8c8',1,'ARMarkerSquare::updateWithDetectedMarkers()']]],
['updatewithdetectedmarkersstereo',['updateWithDetectedMarkersStereo',['../class_a_r_marker_multi.html#a41f045386e943be58f9489603c6f9212',1,'ARMarkerMulti::updateWithDetectedMarkersStereo()'],['../class_a_r_marker_square.html#a15a80604d5845526c6870240dafc9f01',1,'ARMarkerSquare::updateWithDetectedMarkersStereo()']]],
['updatewithnftresults',['updateWithNFTResults',['../class_a_r_marker_n_f_t.html#a2cb7d55e4a02bedfdfeefc285ce4bfb7',1,'ARMarkerNFT']]],
['usecontposeestimation',['useContPoseEstimation',['../class_a_r_marker_square.html#a4576cb7a9eccc454861f69f3f94445a5',1,'ARMarkerSquare']]]
];
| gpl-3.0 |
ebukoz/thrive | erpnext/demo/user/manufacturing.py | 4593 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe, random, erpnext
from datetime import timedelta
from frappe.utils.make_random import how_many
from frappe.desk import query_report
from erpnext.manufacturing.doctype.workstation.workstation import WorkstationHolidayError
from erpnext.manufacturing.doctype.work_order.test_work_order import make_wo_order_test_record
def work():
if random.random() < 0.3: return
frappe.set_user(frappe.db.get_global('demo_manufacturing_user'))
if not frappe.get_all('Sales Order'): return
from erpnext.projects.doctype.timesheet.timesheet import OverlapError
ppt = frappe.new_doc("Production Plan")
ppt.company = erpnext.get_default_company()
# ppt.use_multi_level_bom = 1 #refactored
ppt.get_items_from = "Sales Order"
# ppt.purchase_request_for_warehouse = "Stores - WPL" # refactored
ppt.run_method("get_open_sales_orders")
if not ppt.get("sales_orders"): return
ppt.run_method("get_items")
ppt.run_method("raise_material_requests")
ppt.save()
ppt.submit()
ppt.run_method("raise_work_orders")
frappe.db.commit()
# submit work orders
for pro in frappe.db.get_values("Work Order", {"docstatus": 0}, "name"):
b = frappe.get_doc("Work Order", pro[0])
b.wip_warehouse = "Work in Progress - WPL"
b.submit()
frappe.db.commit()
# submit material requests
for pro in frappe.db.get_values("Material Request", {"docstatus": 0}, "name"):
b = frappe.get_doc("Material Request", pro[0])
b.submit()
frappe.db.commit()
# stores -> wip
if random.random() < 0.4:
for pro in query_report.run("Open Work Orders")["result"][:how_many("Stock Entry for WIP")]:
make_stock_entry_from_pro(pro[0], "Material Transfer for Manufacture")
# wip -> fg
if random.random() < 0.4:
for pro in query_report.run("Work Orders in Progress")["result"][:how_many("Stock Entry for FG")]:
make_stock_entry_from_pro(pro[0], "Manufacture")
for bom in frappe.get_all('BOM', fields=['item'], filters = {'with_operations': 1}):
pro_order = make_wo_order_test_record(item=bom.item, qty=2,
source_warehouse="Stores - WPL", wip_warehouse = "Work in Progress - WPL",
fg_warehouse = "Stores - WPL", company = erpnext.get_default_company(),
stock_uom = frappe.db.get_value('Item', bom.item, 'stock_uom'),
planned_start_date = frappe.flags.current_date)
# submit job card
if random.random() < 0.4:
submit_job_cards()
def make_stock_entry_from_pro(pro_id, purpose):
from erpnext.manufacturing.doctype.work_order.work_order import make_stock_entry
from erpnext.stock.stock_ledger import NegativeStockError
from erpnext.stock.doctype.stock_entry.stock_entry import IncorrectValuationRateError, \
DuplicateEntryForWorkOrderError, OperationsNotCompleteError
try:
st = frappe.get_doc(make_stock_entry(pro_id, purpose))
st.posting_date = frappe.flags.current_date
st.fiscal_year = str(frappe.flags.current_date.year)
for d in st.get("items"):
d.cost_center = "Main - " + frappe.get_cached_value('Company', st.company, 'abbr')
st.insert()
frappe.db.commit()
st.submit()
frappe.db.commit()
except (NegativeStockError, IncorrectValuationRateError, DuplicateEntryForWorkOrderError,
OperationsNotCompleteError):
frappe.db.rollback()
def submit_job_cards():
work_orders = frappe.get_all("Work Order", ["name", "creation"], {"docstatus": 1, "status": "Not Started"})
work_order = random.choice(work_orders)
# for work_order in work_orders:
start_date = work_order.creation
work_order = frappe.get_doc("Work Order", work_order.name)
job = frappe.get_all("Job Card", ["name", "operation", "work_order"],
{"docstatus": 0, "work_order": work_order.name})
if not job: return
job_map = {}
for d in job:
job_map[d.operation] = frappe.get_doc("Job Card", d.name)
for operation in work_order.operations:
job = job_map[operation.operation]
job_time_log = frappe.new_doc("Job Card Time Log")
job_time_log.from_time = start_date
minutes = operation.get("time_in_mins")
job_time_log.time_in_mins = random.randint(int(minutes/2), minutes)
job_time_log.to_time = job_time_log.from_time + \
timedelta(minutes=job_time_log.time_in_mins)
job_time_log.parent = job.name
job_time_log.parenttype = 'Job Card'
job_time_log.parentfield = 'time_logs'
job_time_log.completed_qty = work_order.qty
job_time_log.save(ignore_permissions=True)
job.time_logs.append(job_time_log)
job.save(ignore_permissions=True)
job.submit()
start_date = job_time_log.to_time
| gpl-3.0 |
Reflexe/doc_to_pdf | Windows/program/python-core-3.5.0/lib/ast.py | 12001 | """
ast
~~~
The `ast` module helps Python applications to process trees of the Python
abstract syntax grammar. The abstract syntax itself might change with
each Python release; this module helps to find out programmatically what
the current grammar looks like and allows modifications of it.
An abstract syntax tree can be generated by passing `ast.PyCF_ONLY_AST` as
a flag to the `compile()` builtin function or by using the `parse()`
function from this module. The result will be a tree of objects whose
classes all inherit from `ast.AST`.
A modified abstract syntax tree can be compiled into a Python code object
using the built-in `compile()` function.
Additionally various helper functions are provided that make working with
the trees simpler. The main intention of the helper functions and this
module in general is to provide an easy to use interface for libraries
that work tightly with the python syntax (template engines for example).
:copyright: Copyright 2008 by Armin Ronacher.
:license: Python License.
"""
from _ast import *
def parse(source, filename='<unknown>', mode='exec'):
"""
Parse the source into an AST node.
Equivalent to compile(source, filename, mode, PyCF_ONLY_AST).
"""
return compile(source, filename, mode, PyCF_ONLY_AST)
def literal_eval(node_or_string):
"""
Safely evaluate an expression node or a string containing a Python
expression. The string or node provided may only consist of the following
Python literal structures: strings, bytes, numbers, tuples, lists, dicts,
sets, booleans, and None.
"""
if isinstance(node_or_string, str):
node_or_string = parse(node_or_string, mode='eval')
if isinstance(node_or_string, Expression):
node_or_string = node_or_string.body
def _convert(node):
if isinstance(node, (Str, Bytes)):
return node.s
elif isinstance(node, Num):
return node.n
elif isinstance(node, Tuple):
return tuple(map(_convert, node.elts))
elif isinstance(node, List):
return list(map(_convert, node.elts))
elif isinstance(node, Set):
return set(map(_convert, node.elts))
elif isinstance(node, Dict):
return dict((_convert(k), _convert(v)) for k, v
in zip(node.keys, node.values))
elif isinstance(node, NameConstant):
return node.value
elif isinstance(node, UnaryOp) and \
isinstance(node.op, (UAdd, USub)) and \
isinstance(node.operand, (Num, UnaryOp, BinOp)):
operand = _convert(node.operand)
if isinstance(node.op, UAdd):
return + operand
else:
return - operand
elif isinstance(node, BinOp) and \
isinstance(node.op, (Add, Sub)) and \
isinstance(node.right, (Num, UnaryOp, BinOp)) and \
isinstance(node.left, (Num, UnaryOp, BinOp)):
left = _convert(node.left)
right = _convert(node.right)
if isinstance(node.op, Add):
return left + right
else:
return left - right
raise ValueError('malformed node or string: ' + repr(node))
return _convert(node_or_string)
def dump(node, annotate_fields=True, include_attributes=False):
"""
Return a formatted dump of the tree in *node*. This is mainly useful for
debugging purposes. The returned string will show the names and the values
for fields. This makes the code impossible to evaluate, so if evaluation is
wanted *annotate_fields* must be set to False. Attributes such as line
numbers and column offsets are not dumped by default. If this is wanted,
*include_attributes* can be set to True.
"""
def _format(node):
if isinstance(node, AST):
fields = [(a, _format(b)) for a, b in iter_fields(node)]
rv = '%s(%s' % (node.__class__.__name__, ', '.join(
('%s=%s' % field for field in fields)
if annotate_fields else
(b for a, b in fields)
))
if include_attributes and node._attributes:
rv += fields and ', ' or ' '
rv += ', '.join('%s=%s' % (a, _format(getattr(node, a)))
for a in node._attributes)
return rv + ')'
elif isinstance(node, list):
return '[%s]' % ', '.join(_format(x) for x in node)
return repr(node)
if not isinstance(node, AST):
raise TypeError('expected AST, got %r' % node.__class__.__name__)
return _format(node)
def copy_location(new_node, old_node):
"""
Copy source location (`lineno` and `col_offset` attributes) from
*old_node* to *new_node* if possible, and return *new_node*.
"""
for attr in 'lineno', 'col_offset':
if attr in old_node._attributes and attr in new_node._attributes \
and hasattr(old_node, attr):
setattr(new_node, attr, getattr(old_node, attr))
return new_node
def fix_missing_locations(node):
"""
When you compile a node tree with compile(), the compiler expects lineno and
col_offset attributes for every node that supports them. This is rather
tedious to fill in for generated nodes, so this helper adds these attributes
recursively where not already set, by setting them to the values of the
parent node. It works recursively starting at *node*.
"""
def _fix(node, lineno, col_offset):
if 'lineno' in node._attributes:
if not hasattr(node, 'lineno'):
node.lineno = lineno
else:
lineno = node.lineno
if 'col_offset' in node._attributes:
if not hasattr(node, 'col_offset'):
node.col_offset = col_offset
else:
col_offset = node.col_offset
for child in iter_child_nodes(node):
_fix(child, lineno, col_offset)
_fix(node, 1, 0)
return node
def increment_lineno(node, n=1):
"""
Increment the line number of each node in the tree starting at *node* by *n*.
This is useful to "move code" to a different location in a file.
"""
for child in walk(node):
if 'lineno' in child._attributes:
child.lineno = getattr(child, 'lineno', 0) + n
return node
def iter_fields(node):
"""
Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields``
that is present on *node*.
"""
for field in node._fields:
try:
yield field, getattr(node, field)
except AttributeError:
pass
def iter_child_nodes(node):
"""
Yield all direct child nodes of *node*, that is, all fields that are nodes
and all items of fields that are lists of nodes.
"""
for name, field in iter_fields(node):
if isinstance(field, AST):
yield field
elif isinstance(field, list):
for item in field:
if isinstance(item, AST):
yield item
def get_docstring(node, clean=True):
"""
Return the docstring for the given node or None if no docstring can
be found. If the node provided does not have docstrings a TypeError
will be raised.
"""
if not isinstance(node, (AsyncFunctionDef, FunctionDef, ClassDef, Module)):
raise TypeError("%r can't have docstrings" % node.__class__.__name__)
if node.body and isinstance(node.body[0], Expr) and \
isinstance(node.body[0].value, Str):
if clean:
import inspect
return inspect.cleandoc(node.body[0].value.s)
return node.body[0].value.s
def walk(node):
"""
Recursively yield all descendant nodes in the tree starting at *node*
(including *node* itself), in no specified order. This is useful if you
only want to modify nodes in place and don't care about the context.
"""
from collections import deque
todo = deque([node])
while todo:
node = todo.popleft()
todo.extend(iter_child_nodes(node))
yield node
class NodeVisitor(object):
"""
A node visitor base class that walks the abstract syntax tree and calls a
visitor function for every node found. This function may return a value
which is forwarded by the `visit` method.
This class is meant to be subclassed, with the subclass adding visitor
methods.
Per default the visitor functions for the nodes are ``'visit_'`` +
class name of the node. So a `TryFinally` node visit function would
be `visit_TryFinally`. This behavior can be changed by overriding
the `visit` method. If no visitor function exists for a node
(return value `None`) the `generic_visit` visitor is used instead.
Don't use the `NodeVisitor` if you want to apply changes to nodes during
traversing. For this a special visitor exists (`NodeTransformer`) that
allows modifications.
"""
def visit(self, node):
"""Visit a node."""
method = 'visit_' + node.__class__.__name__
visitor = getattr(self, method, self.generic_visit)
return visitor(node)
def generic_visit(self, node):
"""Called if no explicit visitor function exists for a node."""
for field, value in iter_fields(node):
if isinstance(value, list):
for item in value:
if isinstance(item, AST):
self.visit(item)
elif isinstance(value, AST):
self.visit(value)
class NodeTransformer(NodeVisitor):
"""
A :class:`NodeVisitor` subclass that walks the abstract syntax tree and
allows modification of nodes.
The `NodeTransformer` will walk the AST and use the return value of the
visitor methods to replace or remove the old node. If the return value of
the visitor method is ``None``, the node will be removed from its location,
otherwise it is replaced with the return value. The return value may be the
original node in which case no replacement takes place.
Here is an example transformer that rewrites all occurrences of name lookups
(``foo``) to ``data['foo']``::
class RewriteName(NodeTransformer):
def visit_Name(self, node):
return copy_location(Subscript(
value=Name(id='data', ctx=Load()),
slice=Index(value=Str(s=node.id)),
ctx=node.ctx
), node)
Keep in mind that if the node you're operating on has child nodes you must
either transform the child nodes yourself or call the :meth:`generic_visit`
method for the node first.
For nodes that were part of a collection of statements (that applies to all
statement nodes), the visitor may also return a list of nodes rather than
just a single node.
Usually you use the transformer like this::
node = YourTransformer().visit(node)
"""
def generic_visit(self, node):
for field, old_value in iter_fields(node):
if isinstance(old_value, list):
new_values = []
for value in old_value:
if isinstance(value, AST):
value = self.visit(value)
if value is None:
continue
elif not isinstance(value, AST):
new_values.extend(value)
continue
new_values.append(value)
old_value[:] = new_values
elif isinstance(old_value, AST):
new_node = self.visit(old_value)
if new_node is None:
delattr(node, field)
else:
setattr(node, field, new_node)
return node
| mpl-2.0 |
JasonGross/mozjs | js/src/tests/ecma_6/TypedObject/objecttype.js | 971 | // |reftest| skip-if(!this.hasOwnProperty("TypedObject"))
var BUGNUMBER = 917454;
var summary = 'objecttype';
/*
* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/licenses/publicdomain/
*/
var T = TypedObject;
function runTests() {
var Point = T.float32.array(3);
var Line = new T.StructType({from: Point, to: Point});
var Lines = Line.array(3);
var lines = new Lines([
{from: [1, 2, 3], to: [4, 5, 6]},
{from: [7, 8, 9], to: [10, 11, 12]},
{from: [13, 14, 15], to: [16, 17, 18]}
]);
assertEq(T.objectType(lines), Lines);
assertEq(T.objectType(lines[0]), Line);
assertEq(T.objectType(lines[0].from[0]), T.float64);
assertEq(T.objectType(""), T.String);
assertEq(T.objectType({}), T.Object);
assertEq(T.objectType([]), T.Object);
assertEq(T.objectType(function() { }), T.Object);
assertEq(T.objectType(undefined), T.Any);
reportCompare(true, true);
print("Tests complete");
}
runTests();
| mpl-2.0 |
legatoproject/legato-docs | 15_05/ccoding_stds_naming.js | 1987 | var ccoding_stds_naming =
[
[ "Naming Overview", "ccoding_stds_naming.html#cstdsNaming", [
[ "Be Descriptive", "ccoding_stds_naming.html#descript", null ],
[ "Prefixes", "ccoding_stds_naming.html#prefix", null ],
[ "Component Interfaces", "ccoding_stds_naming.html#cstdsInterComponentInterfaces", null ],
[ "Module Interfaces", "ccoding_stds_naming.html#cstdsInterModuleInterfaces", null ]
] ],
[ "Files", "ccoding_stds_naming.html#cstdsFiles", null ],
[ "Macros", "ccoding_stds_naming.html#cstdsMacros", null ],
[ "Types", "ccoding_stds_name_types.html", [
[ "Suffix", "ccoding_stds_name_types.html#cstdsNameSuffix", null ],
[ "Prefix", "ccoding_stds_name_types.html#cstdsNameTypesPrefix", null ],
[ "Name", "ccoding_stds_name_types.html#cstdsNameType", null ],
[ "Cardinal Types", "ccoding_stds_name_types.html#cstdsCardinalTypes", null ],
[ "Enumeration Members", "ccoding_stds_name_types.html#cstdsEnumerationMembers", null ],
[ "Struct and Union Namespaces", "ccoding_stds_name_types.html#cstdsStructandUnionNamespaces", null ],
[ "Struct and Union Members", "ccoding_stds_name_types.html#cstdsStructandUnionMembers", null ]
] ],
[ "Functions", "ccoding_stds_name_funcs.html", [
[ "Prefix", "ccoding_stds_name_funcs.html#cstdsFuncsPrefix", null ],
[ "Camel Case", "ccoding_stds_name_funcs.html#cstdsCamelCaseName", null ],
[ "Verbage", "ccoding_stds_name_funcs.html#cstdsVerbage", null ]
] ],
[ "Variables & Function Parameters", "ccoding_stds_param.html", [
[ "Camel Case", "ccoding_stds_param.html#cstdsparamCamelCase", null ],
[ "Prefix", "ccoding_stds_param.html#cstdsparamPrefix", null ],
[ "Pointers", "ccoding_stds_param.html#cstdsparamPointers", null ],
[ "Static Variables", "ccoding_stds_param.html#cstdsparamStaticVariables", null ],
[ "Abbreviations", "ccoding_stds_param.html#cstdsparamAbbreviations", null ]
] ]
]; | mpl-2.0 |
pgonda/servo | components/script/dom/storage.rs | 7280 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::StorageBinding;
use dom::bindings::codegen::Bindings::StorageBinding::StorageMethods;
use dom::bindings::global::{GlobalRef, GlobalField};
use dom::bindings::js::{Root, RootedReference};
use dom::bindings::refcounted::Trusted;
use dom::bindings::utils::{Reflector, reflect_dom_object};
use dom::bindings::codegen::InheritTypes::{EventCast, EventTargetCast};
use dom::event::{EventHelpers, EventBubbles, EventCancelable};
use dom::storageevent::StorageEvent;
use dom::urlhelper::UrlHelper;
use dom::window::WindowHelpers;
use util::str::DOMString;
use page::IterablePage;
use net_traits::storage_task::{StorageTask, StorageTaskMsg, StorageType};
use std::borrow::ToOwned;
use std::sync::mpsc::channel;
use url::Url;
use script_task::{ScriptTask, ScriptMsg, MainThreadRunnable};
#[dom_struct]
pub struct Storage {
reflector_: Reflector,
global: GlobalField,
storage_type: StorageType
}
impl Storage {
fn new_inherited(global: &GlobalRef, storage_type: StorageType) -> Storage {
Storage {
reflector_: Reflector::new(),
global: GlobalField::from_rooted(global),
storage_type: storage_type
}
}
pub fn new(global: &GlobalRef, storage_type: StorageType) -> Root<Storage> {
reflect_dom_object(box Storage::new_inherited(global, storage_type), *global, StorageBinding::Wrap)
}
fn get_url(&self) -> Url {
let global_root = self.global.root();
let global_ref = global_root.r();
global_ref.get_url()
}
fn get_storage_task(&self) -> StorageTask {
let global_root = self.global.root();
let global_ref = global_root.r();
global_ref.as_window().storage_task()
}
}
impl<'a> StorageMethods for &'a Storage {
fn Length(self) -> u32 {
let (sender, receiver) = channel();
self.get_storage_task().send(StorageTaskMsg::Length(sender, self.get_url(), self.storage_type)).unwrap();
receiver.recv().unwrap() as u32
}
fn Key(self, index: u32) -> Option<DOMString> {
let (sender, receiver) = channel();
self.get_storage_task().send(StorageTaskMsg::Key(sender, self.get_url(), self.storage_type, index)).unwrap();
receiver.recv().unwrap()
}
fn GetItem(self, name: DOMString) -> Option<DOMString> {
let (sender, receiver) = channel();
let msg = StorageTaskMsg::GetItem(sender, self.get_url(), self.storage_type, name);
self.get_storage_task().send(msg).unwrap();
receiver.recv().unwrap()
}
fn NamedGetter(self, name: DOMString, found: &mut bool) -> Option<DOMString> {
let item = self.GetItem(name);
*found = item.is_some();
item
}
fn SetItem(self, name: DOMString, value: DOMString) {
let (sender, receiver) = channel();
let msg = StorageTaskMsg::SetItem(sender, self.get_url(), self.storage_type, name.clone(), value.clone());
self.get_storage_task().send(msg).unwrap();
let (changed, old_value) = receiver.recv().unwrap();
if changed {
self.broadcast_change_notification(Some(name), old_value, Some(value));
}
}
fn NamedSetter(self, name: DOMString, value: DOMString) {
self.SetItem(name, value);
}
fn NamedCreator(self, name: DOMString, value: DOMString) {
self.SetItem(name, value);
}
fn RemoveItem(self, name: DOMString) {
let (sender, receiver) = channel();
let msg = StorageTaskMsg::RemoveItem(sender, self.get_url(), self.storage_type, name.clone());
self.get_storage_task().send(msg).unwrap();
if let Some(old_value) = receiver.recv().unwrap() {
self.broadcast_change_notification(Some(name), Some(old_value), None);
}
}
fn NamedDeleter(self, name: DOMString) {
self.RemoveItem(name);
}
fn Clear(self) {
let (sender, receiver) = channel();
self.get_storage_task().send(StorageTaskMsg::Clear(sender, self.get_url(), self.storage_type)).unwrap();
if receiver.recv().unwrap() {
self.broadcast_change_notification(None, None, None);
}
}
}
trait PrivateStorageHelpers {
fn broadcast_change_notification(self, key: Option<DOMString>, old_value: Option<DOMString>,
new_value: Option<DOMString>);
}
impl<'a> PrivateStorageHelpers for &'a Storage {
/// https://html.spec.whatwg.org/multipage/#send-a-storage-notification
fn broadcast_change_notification(self, key: Option<DOMString>, old_value: Option<DOMString>,
new_value: Option<DOMString>){
let global_root = self.global.root();
let global_ref = global_root.r();
let script_chan = global_ref.script_chan();
let trusted_storage = Trusted::new(global_ref.get_cx(), self,
script_chan.clone());
script_chan.send(ScriptMsg::MainThreadRunnableMsg(
box StorageEventRunnable::new(trusted_storage, key,
old_value, new_value))).unwrap();
}
}
pub struct StorageEventRunnable {
element: Trusted<Storage>,
key: Option<DOMString>,
old_value: Option<DOMString>,
new_value: Option<DOMString>
}
impl StorageEventRunnable {
fn new(storage: Trusted<Storage>, key: Option<DOMString>, old_value: Option<DOMString>,
new_value: Option<DOMString>) -> StorageEventRunnable {
StorageEventRunnable { element: storage, key: key, old_value: old_value, new_value: new_value }
}
}
impl MainThreadRunnable for StorageEventRunnable {
fn handler(self: Box<StorageEventRunnable>, script_task: &ScriptTask) {
let this = *self;
let storage_root = this.element.root();
let storage = storage_root.r();
let global_root = storage.global.root();
let global_ref = global_root.r();
let ev_window = global_ref.as_window();
let ev_url = storage.get_url();
let storage_event = StorageEvent::new(
global_ref,
"storage".to_owned(),
EventBubbles::DoesNotBubble, EventCancelable::NotCancelable,
this.key, this.old_value, this.new_value,
ev_url.to_string(),
Some(storage)
);
let event = EventCast::from_ref(storage_event.r());
let root_page = script_task.root_page();
for it_page in root_page.iter() {
let it_window_root = it_page.window();
let it_window = it_window_root.r();
assert!(UrlHelper::SameOrigin(&ev_url, &it_window.get_url()));
// TODO: Such a Document object is not necessarily fully active, but events fired on such
// objects are ignored by the event loop until the Document becomes fully active again.
if ev_window.pipeline() != it_window.pipeline() {
let target = EventTargetCast::from_ref(it_window);
event.fire(target);
}
}
}
}
| mpl-2.0 |
guojianli/consul | consul/server.go | 19079 | package consul
import (
"crypto/tls"
"errors"
"fmt"
"log"
"net"
"net/rpc"
"os"
"path/filepath"
"reflect"
"strconv"
"sync"
"time"
"github.com/hashicorp/consul/acl"
"github.com/hashicorp/consul/tlsutil"
"github.com/hashicorp/raft"
"github.com/hashicorp/raft-boltdb"
"github.com/hashicorp/serf/serf"
)
// These are the protocol versions that Consul can _understand_. These are
// Consul-level protocol versions, that are used to configure the Serf
// protocol versions.
const (
ProtocolVersionMin uint8 = 1
ProtocolVersionMax = 2
)
const (
serfLANSnapshot = "serf/local.snapshot"
serfWANSnapshot = "serf/remote.snapshot"
raftState = "raft/"
tmpStatePath = "tmp/"
snapshotsRetained = 2
// serverRPCCache controls how long we keep an idle connection
// open to a server
serverRPCCache = 2 * time.Minute
// serverMaxStreams controsl how many idle streams we keep
// open to a server
serverMaxStreams = 64
// raftLogCacheSize is the maximum number of logs to cache in-memory.
// This is used to reduce disk I/O for the recently commited entries.
raftLogCacheSize = 512
// raftRemoveGracePeriod is how long we wait to allow a RemovePeer
// to replicate to gracefully leave the cluster.
raftRemoveGracePeriod = 5 * time.Second
)
// Server is Consul server which manages the service discovery,
// health checking, DC forwarding, Raft, and multiple Serf pools.
type Server struct {
// aclAuthCache is the authoritative ACL cache
aclAuthCache *acl.Cache
// aclCache is the non-authoritative ACL cache.
aclCache *aclCache
// Consul configuration
config *Config
// Connection pool to other consul servers
connPool *ConnPool
// Endpoints holds our RPC endpoints
endpoints endpoints
// eventChLAN is used to receive events from the
// serf cluster in the datacenter
eventChLAN chan serf.Event
// eventChWAN is used to receive events from the
// serf cluster that spans datacenters
eventChWAN chan serf.Event
// fsm is the state machine used with Raft to provide
// strong consistency.
fsm *consulFSM
// Have we attempted to leave the cluster
left bool
// localConsuls is used to track the known consuls
// in the local datacenter. Used to do leader forwarding.
localConsuls map[string]*serverParts
localLock sync.RWMutex
// Logger uses the provided LogOutput
logger *log.Logger
// The raft instance is used among Consul nodes within the
// DC to protect operations that require strong consistency
raft *raft.Raft
raftLayer *RaftLayer
raftPeers raft.PeerStore
raftStore *raftboltdb.BoltStore
raftTransport *raft.NetworkTransport
// reconcileCh is used to pass events from the serf handler
// into the leader manager, so that the strong state can be
// updated
reconcileCh chan serf.Member
// remoteConsuls is used to track the known consuls in
// remote datacenters. Used to do DC forwarding.
remoteConsuls map[string][]*serverParts
remoteLock sync.RWMutex
// rpcListener is used to listen for incoming connections
rpcListener net.Listener
rpcServer *rpc.Server
// rpcTLS is the TLS config for incoming TLS requests
rpcTLS *tls.Config
// serfLAN is the Serf cluster maintained inside the DC
// which contains all the DC nodes
serfLAN *serf.Serf
// serfWAN is the Serf cluster maintained between DC's
// which SHOULD only consist of Consul servers
serfWAN *serf.Serf
// sessionTimers track the expiration time of each Session that has
// a TTL. On expiration, a SessionDestroy event will occur, and
// destroy the session via standard session destory processing
sessionTimers map[string]*time.Timer
sessionTimersLock sync.Mutex
// tombstoneGC is used to track the pending GC invocations
// for the KV tombstones
tombstoneGC *TombstoneGC
shutdown bool
shutdownCh chan struct{}
shutdownLock sync.Mutex
}
// Holds the RPC endpoints
type endpoints struct {
Catalog *Catalog
Health *Health
Status *Status
KVS *KVS
Session *Session
Internal *Internal
ACL *ACL
}
// NewServer is used to construct a new Consul server from the
// configuration, potentially returning an error
func NewServer(config *Config) (*Server, error) {
// Check the protocol version
if err := config.CheckVersion(); err != nil {
return nil, err
}
// Check for a data directory!
if config.DataDir == "" {
return nil, fmt.Errorf("Config must provide a DataDir")
}
// Sanity check the ACLs
if err := config.CheckACL(); err != nil {
return nil, err
}
// Ensure we have a log output
if config.LogOutput == nil {
config.LogOutput = os.Stderr
}
// Create the tls wrapper for outgoing connections
tlsConf := config.tlsConfig()
tlsWrap, err := tlsConf.OutgoingTLSWrapper()
if err != nil {
return nil, err
}
// Get the incoming tls config
incomingTLS, err := tlsConf.IncomingTLSConfig()
if err != nil {
return nil, err
}
// Create a logger
logger := log.New(config.LogOutput, "", log.LstdFlags)
// Create the tombstone GC
gc, err := NewTombstoneGC(config.TombstoneTTL, config.TombstoneTTLGranularity)
if err != nil {
return nil, err
}
// Create server
s := &Server{
config: config,
connPool: NewPool(config.LogOutput, serverRPCCache, serverMaxStreams, tlsWrap),
eventChLAN: make(chan serf.Event, 256),
eventChWAN: make(chan serf.Event, 256),
localConsuls: make(map[string]*serverParts),
logger: logger,
reconcileCh: make(chan serf.Member, 32),
remoteConsuls: make(map[string][]*serverParts),
rpcServer: rpc.NewServer(),
rpcTLS: incomingTLS,
tombstoneGC: gc,
shutdownCh: make(chan struct{}),
}
// Initialize the authoritative ACL cache
s.aclAuthCache, err = acl.NewCache(aclCacheSize, s.aclFault)
if err != nil {
s.Shutdown()
return nil, fmt.Errorf("Failed to create ACL cache: %v", err)
}
// Set up the non-authoritative ACL cache
if s.aclCache, err = newAclCache(config, logger, s.RPC); err != nil {
s.Shutdown()
return nil, err
}
// Initialize the RPC layer
if err := s.setupRPC(tlsWrap); err != nil {
s.Shutdown()
return nil, fmt.Errorf("Failed to start RPC layer: %v", err)
}
// Initialize the Raft server
if err := s.setupRaft(); err != nil {
s.Shutdown()
return nil, fmt.Errorf("Failed to start Raft: %v", err)
}
// Initialize the lan Serf
s.serfLAN, err = s.setupSerf(config.SerfLANConfig,
s.eventChLAN, serfLANSnapshot, false)
if err != nil {
s.Shutdown()
return nil, fmt.Errorf("Failed to start lan serf: %v", err)
}
go s.lanEventHandler()
// Initialize the wan Serf
s.serfWAN, err = s.setupSerf(config.SerfWANConfig,
s.eventChWAN, serfWANSnapshot, true)
if err != nil {
s.Shutdown()
return nil, fmt.Errorf("Failed to start wan serf: %v", err)
}
go s.wanEventHandler()
// Start listening for RPC requests
go s.listen()
// Start the metrics handlers
go s.sessionStats()
return s, nil
}
// setupSerf is used to setup and initialize a Serf
func (s *Server) setupSerf(conf *serf.Config, ch chan serf.Event, path string, wan bool) (*serf.Serf, error) {
addr := s.rpcListener.Addr().(*net.TCPAddr)
conf.Init()
if wan {
conf.NodeName = fmt.Sprintf("%s.%s", s.config.NodeName, s.config.Datacenter)
} else {
conf.NodeName = s.config.NodeName
}
conf.Tags["role"] = "consul"
conf.Tags["dc"] = s.config.Datacenter
conf.Tags["vsn"] = fmt.Sprintf("%d", s.config.ProtocolVersion)
conf.Tags["vsn_min"] = fmt.Sprintf("%d", ProtocolVersionMin)
conf.Tags["vsn_max"] = fmt.Sprintf("%d", ProtocolVersionMax)
conf.Tags["build"] = s.config.Build
conf.Tags["port"] = fmt.Sprintf("%d", addr.Port)
if s.config.Bootstrap {
conf.Tags["bootstrap"] = "1"
}
if s.config.BootstrapExpect != 0 {
conf.Tags["expect"] = fmt.Sprintf("%d", s.config.BootstrapExpect)
}
conf.MemberlistConfig.LogOutput = s.config.LogOutput
conf.LogOutput = s.config.LogOutput
conf.EventCh = ch
conf.SnapshotPath = filepath.Join(s.config.DataDir, path)
conf.ProtocolVersion = protocolVersionMap[s.config.ProtocolVersion]
conf.RejoinAfterLeave = s.config.RejoinAfterLeave
if wan {
conf.Merge = &wanMergeDelegate{}
} else {
conf.Merge = &lanMergeDelegate{dc: s.config.Datacenter}
}
// Until Consul supports this fully, we disable automatic resolution.
// When enabled, the Serf gossip may just turn off if we are the minority
// node which is rather unexpected.
conf.EnableNameConflictResolution = false
if err := ensurePath(conf.SnapshotPath, false); err != nil {
return nil, err
}
return serf.Create(conf)
}
// setupRaft is used to setup and initialize Raft
func (s *Server) setupRaft() error {
// If we are in bootstrap mode, enable a single node cluster
if s.config.Bootstrap {
s.config.RaftConfig.EnableSingleNode = true
}
// Create the base state path
statePath := filepath.Join(s.config.DataDir, tmpStatePath)
if err := os.RemoveAll(statePath); err != nil {
return err
}
if err := ensurePath(statePath, true); err != nil {
return err
}
// Create the FSM
var err error
s.fsm, err = NewFSM(s.tombstoneGC, statePath, s.config.LogOutput)
if err != nil {
return err
}
// Create the base raft path
path := filepath.Join(s.config.DataDir, raftState)
if err := ensurePath(path, true); err != nil {
return err
}
// Create the backend raft store for logs and stable storage
store, err := raftboltdb.NewBoltStore(filepath.Join(path, "raft.db"))
if err != nil {
return err
}
s.raftStore = store
// Wrap the store in a LogCache to improve performance
cacheStore, err := raft.NewLogCache(raftLogCacheSize, store)
if err != nil {
store.Close()
return err
}
// Create the snapshot store
snapshots, err := raft.NewFileSnapshotStore(path, snapshotsRetained, s.config.LogOutput)
if err != nil {
store.Close()
return err
}
// Create a transport layer
trans := raft.NewNetworkTransport(s.raftLayer, 3, 10*time.Second, s.config.LogOutput)
s.raftTransport = trans
// Setup the peer store
s.raftPeers = raft.NewJSONPeers(path, trans)
// Ensure local host is always included if we are in bootstrap mode
if s.config.Bootstrap {
peers, err := s.raftPeers.Peers()
if err != nil {
store.Close()
return err
}
if !raft.PeerContained(peers, trans.LocalAddr()) {
s.raftPeers.SetPeers(raft.AddUniquePeer(peers, trans.LocalAddr()))
}
}
// Make sure we set the LogOutput
s.config.RaftConfig.LogOutput = s.config.LogOutput
// Setup the Raft store
s.raft, err = raft.NewRaft(s.config.RaftConfig, s.fsm, cacheStore, store,
snapshots, s.raftPeers, trans)
if err != nil {
store.Close()
trans.Close()
return err
}
// Start monitoring leadership
go s.monitorLeadership()
return nil
}
// setupRPC is used to setup the RPC listener
func (s *Server) setupRPC(tlsWrap tlsutil.DCWrapper) error {
// Create endpoints
s.endpoints.Status = &Status{s}
s.endpoints.Catalog = &Catalog{s}
s.endpoints.Health = &Health{s}
s.endpoints.KVS = &KVS{s}
s.endpoints.Session = &Session{s}
s.endpoints.Internal = &Internal{s}
s.endpoints.ACL = &ACL{s}
// Register the handlers
s.rpcServer.Register(s.endpoints.Status)
s.rpcServer.Register(s.endpoints.Catalog)
s.rpcServer.Register(s.endpoints.Health)
s.rpcServer.Register(s.endpoints.KVS)
s.rpcServer.Register(s.endpoints.Session)
s.rpcServer.Register(s.endpoints.Internal)
s.rpcServer.Register(s.endpoints.ACL)
list, err := net.ListenTCP("tcp", s.config.RPCAddr)
if err != nil {
return err
}
s.rpcListener = list
var advertise net.Addr
if s.config.RPCAdvertise != nil {
advertise = s.config.RPCAdvertise
} else {
advertise = s.rpcListener.Addr()
}
// Verify that we have a usable advertise address
addr, ok := advertise.(*net.TCPAddr)
if !ok {
list.Close()
return fmt.Errorf("RPC advertise address is not a TCP Address: %v", addr)
}
if addr.IP.IsUnspecified() {
list.Close()
return fmt.Errorf("RPC advertise address is not advertisable: %v", addr)
}
// Provide a DC specific wrapper. Raft replication is only
// ever done in the same datacenter, so we can provide it as a constant.
wrapper := tlsutil.SpecificDC(s.config.Datacenter, tlsWrap)
s.raftLayer = NewRaftLayer(advertise, wrapper)
return nil
}
// Shutdown is used to shutdown the server
func (s *Server) Shutdown() error {
s.logger.Printf("[INFO] consul: shutting down server")
s.shutdownLock.Lock()
defer s.shutdownLock.Unlock()
if s.shutdown {
return nil
}
s.shutdown = true
close(s.shutdownCh)
if s.serfLAN != nil {
s.serfLAN.Shutdown()
}
if s.serfWAN != nil {
s.serfWAN.Shutdown()
}
if s.raft != nil {
s.raftTransport.Close()
s.raftLayer.Close()
future := s.raft.Shutdown()
if err := future.Error(); err != nil {
s.logger.Printf("[WARN] consul: Error shutting down raft: %s", err)
}
s.raftStore.Close()
// Clear the peer set on a graceful leave to avoid
// triggering elections on a rejoin.
if s.left {
s.raftPeers.SetPeers(nil)
}
}
if s.rpcListener != nil {
s.rpcListener.Close()
}
// Close the connection pool
s.connPool.Shutdown()
// Close the fsm
if s.fsm != nil {
s.fsm.Close()
}
return nil
}
// Leave is used to prepare for a graceful shutdown of the server
func (s *Server) Leave() error {
s.logger.Printf("[INFO] consul: server starting leave")
s.left = true
// Check the number of known peers
numPeers, err := s.numOtherPeers()
if err != nil {
s.logger.Printf("[ERR] consul: failed to check raft peers: %v", err)
return err
}
// If we are the current leader, and we have any other peers (cluster has multiple
// servers), we should do a RemovePeer to safely reduce the quorum size. If we are
// not the leader, then we should issue our leave intention and wait to be removed
// for some sane period of time.
isLeader := s.IsLeader()
if isLeader && numPeers > 0 {
future := s.raft.RemovePeer(s.raftTransport.LocalAddr())
if err := future.Error(); err != nil && err != raft.ErrUnknownPeer {
s.logger.Printf("[ERR] consul: failed to remove ourself as raft peer: %v", err)
}
}
// Leave the WAN pool
if s.serfWAN != nil {
if err := s.serfWAN.Leave(); err != nil {
s.logger.Printf("[ERR] consul: failed to leave WAN Serf cluster: %v", err)
}
}
// Leave the LAN pool
if s.serfLAN != nil {
if err := s.serfLAN.Leave(); err != nil {
s.logger.Printf("[ERR] consul: failed to leave LAN Serf cluster: %v", err)
}
}
// If we were not leader, wait to be safely removed from the cluster.
// We must wait to allow the raft replication to take place, otherwise
// an immediate shutdown could cause a loss of quorum.
if !isLeader {
limit := time.Now().Add(raftRemoveGracePeriod)
for numPeers > 0 && time.Now().Before(limit) {
// Update the number of peers
numPeers, err = s.numOtherPeers()
if err != nil {
s.logger.Printf("[ERR] consul: failed to check raft peers: %v", err)
break
}
// Avoid the sleep if we are done
if numPeers == 0 {
break
}
// Sleep a while and check again
time.Sleep(50 * time.Millisecond)
}
if numPeers != 0 {
s.logger.Printf("[WARN] consul: failed to leave raft peer set gracefully, timeout")
}
}
return nil
}
// numOtherPeers is used to check on the number of known peers
// excluding the local ndoe
func (s *Server) numOtherPeers() (int, error) {
peers, err := s.raftPeers.Peers()
if err != nil {
return 0, err
}
otherPeers := raft.ExcludePeer(peers, s.raftTransport.LocalAddr())
return len(otherPeers), nil
}
// JoinLAN is used to have Consul join the inner-DC pool
// The target address should be another node inside the DC
// listening on the Serf LAN address
func (s *Server) JoinLAN(addrs []string) (int, error) {
return s.serfLAN.Join(addrs, true)
}
// JoinWAN is used to have Consul join the cross-WAN Consul ring
// The target address should be another node listening on the
// Serf WAN address
func (s *Server) JoinWAN(addrs []string) (int, error) {
return s.serfWAN.Join(addrs, true)
}
// LocalMember is used to return the local node
func (c *Server) LocalMember() serf.Member {
return c.serfLAN.LocalMember()
}
// LANMembers is used to return the members of the LAN cluster
func (s *Server) LANMembers() []serf.Member {
return s.serfLAN.Members()
}
// WANMembers is used to return the members of the LAN cluster
func (s *Server) WANMembers() []serf.Member {
return s.serfWAN.Members()
}
// RemoveFailedNode is used to remove a failed node from the cluster
func (s *Server) RemoveFailedNode(node string) error {
if err := s.serfLAN.RemoveFailedNode(node); err != nil {
return err
}
if err := s.serfWAN.RemoveFailedNode(node); err != nil {
return err
}
return nil
}
// IsLeader checks if this server is the cluster leader
func (s *Server) IsLeader() bool {
return s.raft.State() == raft.Leader
}
// KeyManagerLAN returns the LAN Serf keyring manager
func (s *Server) KeyManagerLAN() *serf.KeyManager {
return s.serfLAN.KeyManager()
}
// KeyManagerWAN returns the WAN Serf keyring manager
func (s *Server) KeyManagerWAN() *serf.KeyManager {
return s.serfWAN.KeyManager()
}
// Encrypted determines if gossip is encrypted
func (s *Server) Encrypted() bool {
return s.serfLAN.EncryptionEnabled() && s.serfWAN.EncryptionEnabled()
}
// inmemCodec is used to do an RPC call without going over a network
type inmemCodec struct {
method string
args interface{}
reply interface{}
err error
}
func (i *inmemCodec) ReadRequestHeader(req *rpc.Request) error {
req.ServiceMethod = i.method
return nil
}
func (i *inmemCodec) ReadRequestBody(args interface{}) error {
sourceValue := reflect.Indirect(reflect.Indirect(reflect.ValueOf(i.args)))
dst := reflect.Indirect(reflect.Indirect(reflect.ValueOf(args)))
dst.Set(sourceValue)
return nil
}
func (i *inmemCodec) WriteResponse(resp *rpc.Response, reply interface{}) error {
if resp.Error != "" {
i.err = errors.New(resp.Error)
return nil
}
sourceValue := reflect.Indirect(reflect.Indirect(reflect.ValueOf(reply)))
dst := reflect.Indirect(reflect.Indirect(reflect.ValueOf(i.reply)))
dst.Set(sourceValue)
return nil
}
func (i *inmemCodec) Close() error {
return nil
}
// RPC is used to make a local RPC call
func (s *Server) RPC(method string, args interface{}, reply interface{}) error {
codec := &inmemCodec{
method: method,
args: args,
reply: reply,
}
if err := s.rpcServer.ServeRequest(codec); err != nil {
return err
}
return codec.err
}
// Stats is used to return statistics for debugging and insight
// for various sub-systems
func (s *Server) Stats() map[string]map[string]string {
toString := func(v uint64) string {
return strconv.FormatUint(v, 10)
}
stats := map[string]map[string]string{
"consul": map[string]string{
"server": "true",
"leader": fmt.Sprintf("%v", s.IsLeader()),
"bootstrap": fmt.Sprintf("%v", s.config.Bootstrap),
"known_datacenters": toString(uint64(len(s.remoteConsuls))),
},
"raft": s.raft.Stats(),
"serf_lan": s.serfLAN.Stats(),
"serf_wan": s.serfWAN.Stats(),
"runtime": runtimeStats(),
}
return stats
}
| mpl-2.0 |
maljac/odoo-addons | evaluation/__init__.py | 361 | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from . import survey
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
UniversityOfHawaii/kfs | kfs-ar/src/main/java/org/kuali/kfs/module/ar/web/struts/CustomerInvoiceWriteoffLookupSummaryAction.java | 7059 | /*
* The Kuali Financial System, a comprehensive financial management system for higher education.
*
* Copyright 2005-2014 The Kuali Foundation
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.kfs.module.ar.web.struts;
import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.kuali.kfs.module.ar.ArKeyConstants;
import org.kuali.kfs.module.ar.ArPropertyConstants;
import org.kuali.kfs.module.ar.batch.service.CustomerInvoiceWriteoffBatchService;
import org.kuali.kfs.module.ar.businessobject.CustomerInvoiceWriteoffLookupResult;
import org.kuali.kfs.module.ar.businessobject.lookup.CustomerInvoiceWriteoffLookupUtil;
import org.kuali.kfs.module.ar.document.CustomerInvoiceDocument;
import org.kuali.kfs.module.ar.document.service.CustomerInvoiceWriteoffDocumentService;
import org.kuali.kfs.sys.KFSConstants;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.rice.kim.api.identity.Person;
import org.kuali.rice.kns.util.KNSGlobalVariables;
import org.kuali.rice.kns.web.struts.action.KualiAction;
import org.kuali.rice.krad.util.GlobalVariables;
import org.kuali.rice.krad.util.KRADConstants;
public class CustomerInvoiceWriteoffLookupSummaryAction extends KualiAction {
public ActionForward viewSummary(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
CustomerInvoiceWriteoffLookupSummaryForm customerInvoiceWriteoffLookupSummaryForm = (CustomerInvoiceWriteoffLookupSummaryForm) form;
String lookupResultsSequenceNumber = customerInvoiceWriteoffLookupSummaryForm.getLookupResultsSequenceNumber();
if (StringUtils.isNotBlank(lookupResultsSequenceNumber)) {
String personId = GlobalVariables.getUserSession().getPerson().getPrincipalId();
Collection<CustomerInvoiceWriteoffLookupResult> customerInvoiceWriteoffLookupResults = CustomerInvoiceWriteoffLookupUtil.getCustomerInvoiceWriteoffResutlsFromLookupResultsSequenceNumber(lookupResultsSequenceNumber,personId);
customerInvoiceWriteoffLookupSummaryForm.setCustomerInvoiceWriteoffLookupResults(customerInvoiceWriteoffLookupResults);
GlobalVariables.getUserSession().addObject(KRADConstants.LOOKUP_RESULTS_SEQUENCE_NUMBER, lookupResultsSequenceNumber);
}
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
public ActionForward createCustomerInvoiceWriteoffs(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
CustomerInvoiceWriteoffLookupSummaryForm customerInvoiceWriteoffLookupSummaryForm = (CustomerInvoiceWriteoffLookupSummaryForm) form;
Person person = GlobalVariables.getUserSession().getPerson();
CustomerInvoiceWriteoffDocumentService service = SpringContext.getBean(CustomerInvoiceWriteoffDocumentService.class);
Collection<CustomerInvoiceWriteoffLookupResult> lookupResults = customerInvoiceWriteoffLookupSummaryForm.getCustomerInvoiceWriteoffLookupResults();
//TODO Need to check every invoiceNumber submitted and make sure that:
// 1. Invoice exists in the system.
// 2. Invoice doesnt already have a writeoff in progress, either in route or final.
// make sure no null/blank invoiceNumbers get sent
boolean anyFound = false;
boolean customerNoteMissingOrInvalid = false;
int ind = 0;
String customerNote;
for( CustomerInvoiceWriteoffLookupResult customerInvoiceWriteoffLookupResult : lookupResults ){
customerNote = customerInvoiceWriteoffLookupResult.getCustomerNote();
if (StringUtils.isEmpty(customerNote)) {
GlobalVariables.getMessageMap().putError(KFSConstants.CUSTOMER_INVOICE_WRITEOFF_LOOKUP_RESULT_ERRORS + "[" + ind +"]." + ArPropertyConstants.CustomerInvoiceWriteoffLookupResultFields.CUSTOMER_NOTE, ArKeyConstants.ERROR_CUSTOMER_INVOICE_WRITEOFF_CUSTOMER_NOTE_REQUIRED);
customerNoteMissingOrInvalid = true;
} else if (customerNote.trim().length() < 5) {
GlobalVariables.getMessageMap().putError(KFSConstants.CUSTOMER_INVOICE_WRITEOFF_LOOKUP_RESULT_ERRORS + "[" + ind +"]." + ArPropertyConstants.CustomerInvoiceWriteoffLookupResultFields.CUSTOMER_NOTE, ArKeyConstants.ERROR_CUSTOMER_INVOICE_WRITEOFF_CUSTOMER_NOTE_INVALID);
customerNoteMissingOrInvalid = true;
}
for (CustomerInvoiceDocument invoiceDocument : customerInvoiceWriteoffLookupResult.getCustomerInvoiceDocuments()) {
if (StringUtils.isNotBlank(invoiceDocument.getDocumentNumber())) {
anyFound = true;
}
}
ind++;
}
if (customerNoteMissingOrInvalid || !anyFound) {
// only submit this if there's at least one invoiceNumber in the stack
String lookupResultsSequenceNumber = customerInvoiceWriteoffLookupSummaryForm.getLookupResultsSequenceNumber();
GlobalVariables.getUserSession().addObject(KRADConstants.LOOKUP_RESULTS_SEQUENCE_NUMBER, lookupResultsSequenceNumber);
if (!anyFound) {
GlobalVariables.getMessageMap().putError(KFSConstants.GLOBAL_ERRORS, ArKeyConstants.ERROR_CUSTOMER_INVOICE_WRITEOFF_NO_INVOICES_SELECTED);
}
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
// send the batch file off
String filename = service.sendCustomerInvoiceWriteoffDocumentsToBatch(person, lookupResults);
// manually fire off the batch job
SpringContext.getBean(CustomerInvoiceWriteoffBatchService.class).loadFiles();
customerInvoiceWriteoffLookupSummaryForm.setSentToBatch(true);
KNSGlobalVariables.getMessageList().add(ArKeyConstants.ERROR_CUSTOMER_INVOICE_WRITEOFF_BATCH_SENT);
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
public ActionForward cancel(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
return mapping.findForward(KFSConstants.MAPPING_CANCEL);
}
}
| agpl-3.0 |
josesam/latinos | modules/vCals/vCal.php | 8214 | <?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address [email protected].
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/
require_once('modules/Calendar/Calendar.php');
class vCal extends SugarBean {
// Stored fields
var $id;
var $date_modified;
var $user_id;
var $content;
var $deleted;
var $type;
var $source;
var $module_dir = "vCals";
var $table_name = "vcals";
var $object_name = "vCal";
var $new_schema = true;
var $field_defs = array(
);
// This is used to retrieve related fields from form posts.
var $additional_column_fields = Array();
const UTC_FORMAT = 'Ymd\THi00\Z';
function vCal()
{
parent::SugarBean();
$this->disable_row_level_security = true;
}
function get_summary_text()
{
return "";
}
function fill_in_additional_list_fields()
{
}
function fill_in_additional_detail_fields()
{
}
function get_list_view_data()
{
}
// combines all freebusy vcals and returns just the FREEBUSY lines as a string
function get_freebusy_lines_cache(&$user_bean)
{
$str = '';
// First, get the list of IDs.
$query = "SELECT id from vcals where user_id='{$user_bean->id}' AND type='vfb' AND deleted=0";
$vcal_arr = $this->build_related_list($query, new vCal());
foreach ($vcal_arr as $focus)
{
if (empty($focus->content))
{
return '';
}
$lines = explode("\n",$focus->content);
foreach ($lines as $line)
{
if ( preg_match('/^FREEBUSY[;:]/i',$line))
{
$str .= "$line\n";
}
}
}
return $str;
}
// query and create the FREEBUSY lines for SugarCRM Meetings and Calls and
// return the string
function create_sugar_freebusy($user_bean, $start_date_time, $end_date_time)
{
$str = '';
global $DO_USER_TIME_OFFSET,$timedate;
$DO_USER_TIME_OFFSET = true;
if(empty($GLOBALS['current_user']) || empty($GLOBALS['current_user']->id)) {
$GLOBALS['current_user'] = $user_bean;
}
// get activities.. queries Meetings and Calls
$acts_arr =
CalendarActivity::get_activities($user_bean->id,
array("show_calls" => true),
$start_date_time,
$end_date_time,
'freebusy');
// loop thru each activity, get start/end time in UTC, and return FREEBUSY strings
foreach($acts_arr as $act)
{
$startTimeUTC = $act->start_time->format(self::UTC_FORMAT);
$endTimeUTC = $act->end_time->format(self::UTC_FORMAT);
$str .= "FREEBUSY:". $startTimeUTC ."/". $endTimeUTC."\n";
}
return $str;
}
// return a freebusy vcal string
function get_vcal_freebusy($user_focus,$cached=true)
{
global $locale, $timedate;
$str = "BEGIN:VCALENDAR\n";
$str .= "VERSION:2.0\n";
$str .= "PRODID:-//SugarCRM//SugarCRM Calendar//EN\n";
$str .= "BEGIN:VFREEBUSY\n";
$name = $locale->getLocaleFormattedName($user_focus->first_name, $user_focus->last_name);
$email = $user_focus->email1;
// get current date for the user
$now_date_time = $timedate->getNow(true);
// get start date ( 1 day ago )
$start_date_time = $now_date_time->get("yesterday");
// get date 2 months from start date
global $sugar_config;
$timeOffset = 2;
if (isset($sugar_config['vcal_time']) && $sugar_config['vcal_time'] != 0 && $sugar_config['vcal_time'] < 13)
{
$timeOffset = $sugar_config['vcal_time'];
}
$end_date_time = $start_date_time->get("+$timeOffset months");
// get UTC time format
$utc_start_time = $start_date_time->asDb();
$utc_end_time = $end_date_time->asDb();
$utc_now_time = $now_date_time->asDb();
$str .= "ORGANIZER;CN=$name:$email\n";
$str .= "DTSTART:$utc_start_time\n";
$str .= "DTEND:$utc_end_time\n";
// now insert the freebusy lines
// retrieve cached freebusy lines from vcals
if ($timeOffset != 0)
{
if ($cached == true)
{
$str .= $this->get_freebusy_lines_cache($user_focus);
}
// generate freebusy from Meetings and Calls
else
{
$str .= $this->create_sugar_freebusy($user_focus,$start_date_time,$end_date_time);
}
}
// UID:20030724T213406Z-10358-1000-1-12@phoenix
$str .= "DTSTAMP:$utc_now_time\n";
$str .= "END:VFREEBUSY\n";
$str .= "END:VCALENDAR\n";
return $str;
}
// static function:
// cache vcals
function cache_sugar_vcal(&$user_focus)
{
vCal::cache_sugar_vcal_freebusy($user_focus);
}
// static function:
// caches vcal for Activities in Sugar database
function cache_sugar_vcal_freebusy(&$user_focus)
{
$focus = new vCal();
// set freebusy members and save
$arr = array('user_id'=>$user_focus->id,'type'=>'vfb','source'=>'sugar');
$focus->retrieve_by_string_fields($arr);
$focus->content = $focus->get_vcal_freebusy($user_focus,false);
$focus->type = 'vfb';
$focus->date_modified = null;
$focus->source = 'sugar';
$focus->user_id = $user_focus->id;
$focus->save();
}
/**
* get ics file content for meeting invite email
*/
public static function get_ical_event(SugarBean $bean, User $user){
$str = "";
$str .= "BEGIN:VCALENDAR\n";
$str .= "VERSION:2.0\n";
$str .= "PRODID:-//SugarCRM//SugarCRM Calendar//EN\n";
$str .= "BEGIN:VEVENT\n";
$str .= "UID:".$bean->id."\n";
$str .= "ORGANIZER;CN=".$user->full_name.":".$user->email1."\n";
$str .= "DTSTART:".SugarDateTime::createFromFormat($GLOBALS['timedate']->get_db_date_time_format(),$bean->date_start)->format(self::UTC_FORMAT)."\n";
$str .= "DTEND:".SugarDateTime::createFromFormat($GLOBALS['timedate']->get_db_date_time_format(),$bean->date_end)->format(self::UTC_FORMAT)."\n";
$str .= "DTSTAMP:". $GLOBALS['timedate']->getNow(false)->format(self::UTC_FORMAT) ."\n";
$str .= "SUMMARY:" . $bean->name . "\n";
$str .= "DESCRIPTION:" . $bean->description . "\n";
$str .= "END:VEVENT\n";
$str .= "END:VCALENDAR\n";
return $str;
}
}
?>
| agpl-3.0 |
salesagility-davidthomson/SuiteCRM | modules/Emails/EmailException.php | 2301 | <?php
/**
*
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
*
* SuiteCRM is an extension to SugarCRM Community Edition developed by SalesAgility Ltd.
* Copyright (C) 2011 - 2017 SalesAgility Ltd.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address [email protected].
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not
* reasonably feasible for technical reasons, the Appropriate Legal Notices must
* display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM".
*/
if (!defined('sugarEntry') || !sugarEntry) {
die('Not A Valid Entry Point');
}
/**
* Class EmailException
*/
class EmailException extends Exception
{
const NO_DEFAULT_FROM_ADDR = 10;
const NO_DEFAULT_FROM_EMAIL = 20;
} | agpl-3.0 |
lpellegr/programming | programming-test/src/test/java/functionalTests/activeobject/request/immediateservice/A.java | 3153 | /*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2012 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: [email protected] or [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package functionalTests.activeobject.request.immediateservice;
import java.io.Serializable;
import org.objectweb.proactive.api.PAActiveObject;
import org.objectweb.proactive.core.util.wrapper.BooleanWrapper;
public class A implements Serializable {
private Thread myServiceThread;
/**
*
*/
DummyObject dum;
public A() {
}
public int init() {
PAActiveObject.setImmediateService("getBooleanSynchronous");
PAActiveObject.setImmediateService("getBooleanAsynchronous");
PAActiveObject.setImmediateService("getObject");
this.myServiceThread = Thread.currentThread();
return 0;
}
public A(String name) {
this.dum = new DummyObject(name);
}
public DummyObject getObject() {
return dum;
}
public boolean getBooleanSynchronous() {
return (!Thread.currentThread().equals(myServiceThread) && myServiceThread != null);
}
public BooleanWrapper getBooleanAsynchronous() {
return new BooleanWrapper(!Thread.currentThread().equals(myServiceThread) && myServiceThread != null);
}
public boolean getExceptionMethodArgs() {
try {
PAActiveObject.setImmediateService("getObject", new Class<?>[] { Integer.class });
} catch (NoSuchMethodError e) {
return true;
} catch (Throwable t) {
return false;
}
return false;
}
public boolean getExceptionMethodName() {
try {
PAActiveObject.setImmediateService("britney");
} catch (NoSuchMethodError e) {
return true;
} catch (Throwable t) {
return false;
}
return false;
}
}
| agpl-3.0 |
EzyWebwerkstaden/n2cms | src/WebForms/WebFormsTemplates.Tests/Wiki/HtmlFilterTests.cs | 1849 | using N2.Web;
using NUnit.Framework;
namespace N2.Templates.Tests.Wiki
{
[TestFixture]
public class HtmlFilterTests
{
public HtmlFilter filter = new HtmlFilter();
[Test]
public void DoesntFilter_TextWithoutTags()
{
string result = filter.FilterHtml("Hello world!");
Assert.That(result, Is.EqualTo("Hello world!"));
}
[Test]
public void DoesntFilter_Paragraphs()
{
string result = filter.FilterHtml("<p>Hello world!</p>");
Assert.That(result, Is.EqualTo("<p>Hello world!</p>"));
}
[Test]
public void DoesntFilter_Anchors()
{
string result = filter.FilterHtml("<p><a href=\"/wiki/hello.aspx\" title=\"click for greeting\">Hello world!</a></p>");
Assert.That(result, Is.EqualTo("<p><a href=\"/wiki/hello.aspx\" title=\"click for greeting\">Hello world!</a></p>"));
}
[Test]
public void DoesntFilter_Images()
{
string result = filter.FilterHtml("<p><img src=\"tussilago.jpg\" alt=\"flower\"/>Hello world!</p>");
Assert.That(result, Is.EqualTo("<p><img src=\"tussilago.jpg\" alt=\"flower\"/>Hello world!</p>"));
}
[Test]
public void Filters_UnsafeTags()
{
string result = filter.FilterHtml("<p>Hello world!<script>alert('gotcha!');</script></p>");
Assert.That(result, Is.EqualTo("<p>Hello world!alert('gotcha!');</p>"));
}
[Test]
public void Filters_Tags_WithOnClick()
{
string result = filter.FilterHtml("<p><a onclick=\"alert('gotcha!');\" href=\"/wiki/hello.aspx\">Hello world!</a></p>");
Assert.That(result, Is.EqualTo("<p><a href=\"/wiki/hello.aspx\">Hello world!</a></p>"));
}
}
}
| lgpl-2.1 |
iweiss/wildfly | clustering/infinispan/extension/src/main/java/org/jboss/as/clustering/infinispan/subsystem/ComponentResourceDefinition.java | 1690 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2015, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.clustering.infinispan.subsystem;
import org.jboss.as.clustering.controller.ChildResourceDefinition;
import org.jboss.as.clustering.controller.ManagementResourceRegistration;
import org.jboss.as.controller.PathElement;
/**
* @author Paul Ferraro
*/
public abstract class ComponentResourceDefinition extends ChildResourceDefinition<ManagementResourceRegistration> {
public static PathElement pathElement(String name) {
return PathElement.pathElement("component", name);
}
public ComponentResourceDefinition(PathElement path) {
super(path, InfinispanExtension.SUBSYSTEM_RESOLVER.createChildResolver(path));
}
}
| lgpl-2.1 |
kerenby/nabus | src/org/jitsi/impl/neomedia/codec/audio/g729/DeAcelp.java | 2119 | /*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
/*
* WARNING: The use of G.729 may require a license fee and/or royalty fee in
* some countries and is licensed by
* <a href="http://www.sipro.com">SIPRO Lab Telecom</a>.
*/
package org.jitsi.impl.neomedia.codec.audio.g729;
/**
* @author Lubomir Marinov (translation of ITU-T C source code to Java)
*/
class DeAcelp
{
/* ITU-T G.729 Software Package Release 2 (November 2006) */
/*
ITU-T G.729 Annex C - Reference C code for floating point
implementation of G.729
Version 1.01 of 15.September.98
*/
/*
----------------------------------------------------------------------
COPYRIGHT NOTICE
----------------------------------------------------------------------
ITU-T G.729 Annex C ANSI C source code
Copyright (C) 1998, AT&T, France Telecom, NTT, University of
Sherbrooke. All rights reserved.
----------------------------------------------------------------------
*/
/*
File : DE_ACELP.C
Used for the floating point version of both
G.729 main body and G.729A
*/
/**
* Algebraic codebook decoder.
*
* @param sign input : signs of 4 pulses
* @param index input : positions of 4 pulses
* @param cod output: innovative codevector
*/
static void decod_ACELP(
int sign,
int index,
float cod[]
)
{
int L_SUBFR = Ld8k.L_SUBFR;
int[] pos = new int[4];
int i, j;
/* decode the positions of 4 pulses */
i = index & 7;
pos[0] = i*5;
index >>= 3;
i = index & 7;
pos[1] = i*5 + 1;
index >>= 3;
i = index & 7;
pos[2] = i*5 + 2;
index >>= 3;
j = index & 1;
index >>= 1;
i = index & 7;
pos[3] = i*5 + 3 + j;
/* find the algebraic codeword */
for (i = 0; i < L_SUBFR; i++) cod[i] = 0;
/* decode the signs of 4 pulses */
for (j=0; j<4; j++)
{
i = sign & 1;
sign >>= 1;
if (i != 0) {
cod[pos[j]] = 1.0f;
}
else {
cod[pos[j]] = -1.0f;
}
}
}
}
| lgpl-2.1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.