max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
3,296 | <reponame>neonkingfr/ccv
#include "case.h"
#include "ccv_case.h"
#include "ccv_nnc_case.h"
#include <ccv.h>
#include <nnc/ccv_nnc.h>
#include <nnc/ccv_nnc_easy.h>
#include <3rdparty/dsfmt/dSFMT.h>
TEST_SETUP()
{
ccv_nnc_init();
}
TEST_CASE("reduce sum forward")
{
GUARD_ELSE_RETURN(ccv_nnc_cmd_ok(CCV_NNC_REDUCE_SUM_FORWARD, CCV_NNC_BACKEND_GPU_CUDNN));
ccv_nnc_tensor_t* const ha = ccv_nnc_tensor_new(0, CPU_TENSOR_NHWC(32F, 2, 3), 0);
ccv_nnc_tensor_t* const hb = ccv_nnc_tensor_new(0, CPU_TENSOR_NHWC(32F, 3), 0);
ha->data.f32[0] = 1;
ha->data.f32[1] = 2;
ha->data.f32[2] = 3;
ha->data.f32[3] = 4;
ha->data.f32[4] = 5;
ha->data.f32[5] = 6;
ccv_nnc_cmd_exec(CMD_REDUCE_SUM_FORWARD(0), ccv_nnc_no_hint, 0, TENSOR_LIST(ha), TENSOR_LIST(hb), 0);
ccv_nnc_tensor_t* const a = ccv_nnc_tensor_new(0, GPU_TENSOR_NHWC(000, 32F, 2, 3), 0);
ccv_nnc_tensor_t* const b = ccv_nnc_tensor_new(0, GPU_TENSOR_NHWC(000, 32F, 3), 0);
ccv_nnc_cmd_exec(CMD_DATA_TRANSFER_FORWARD(), ccv_nnc_no_hint, 0, TENSOR_LIST(ha), TENSOR_LIST(a), 0);
ccv_nnc_cmd_exec(CMD_REDUCE_SUM_FORWARD(0), ccv_nnc_no_hint, 0, TENSOR_LIST(a), TENSOR_LIST(b), 0);
ccv_nnc_tensor_t* const bt = ccv_nnc_tensor_new(0, CPU_TENSOR_NHWC(32F, 3), 0);
ccv_nnc_cmd_exec(CMD_DATA_TRANSFER_FORWARD(), ccv_nnc_no_hint, 0, TENSOR_LIST(b), TENSOR_LIST(bt), 0);
REQUIRE_TENSOR_EQ(hb, bt, "result should be equal");
ccv_nnc_tensor_free(ha);
ccv_nnc_tensor_free(hb);
ccv_nnc_tensor_free(a);
ccv_nnc_tensor_free(b);
ccv_nnc_tensor_free(bt);
}
TEST_CASE("reduce sum backward")
{
GUARD_ELSE_RETURN(ccv_nnc_cmd_ok(CCV_NNC_REDUCE_SUM_BACKWARD, CCV_NNC_BACKEND_GPU_CUDNN));
ccv_nnc_tensor_t* const ha = ccv_nnc_tensor_new(0, CPU_TENSOR_NHWC(32F, 2, 3), 0);
ccv_nnc_tensor_t* const hb = ccv_nnc_tensor_new(0, CPU_TENSOR_NHWC(32F, 3), 0);
hb->data.f32[0] = 1;
hb->data.f32[1] = 2;
hb->data.f32[2] = 3;
ccv_nnc_cmd_exec(CMD_REDUCE_SUM_BACKWARD(0), ccv_nnc_no_hint, 0, TENSOR_LIST(hb), TENSOR_LIST(ha), 0);
ccv_nnc_tensor_t* const a = ccv_nnc_tensor_new(0, GPU_TENSOR_NHWC(000, 32F, 2, 3), 0);
ccv_nnc_tensor_t* const b = ccv_nnc_tensor_new(0, GPU_TENSOR_NHWC(000, 32F, 3), 0);
ccv_nnc_cmd_exec(CMD_DATA_TRANSFER_FORWARD(), ccv_nnc_no_hint, 0, TENSOR_LIST(hb), TENSOR_LIST(b), 0);
ccv_nnc_cmd_exec(CMD_REDUCE_SUM_BACKWARD(0), ccv_nnc_no_hint, 0, TENSOR_LIST(b), TENSOR_LIST(a), 0);
ccv_nnc_tensor_t* const at = ccv_nnc_tensor_new(0, CPU_TENSOR_NHWC(32F, 2, 3), 0);
ccv_nnc_cmd_exec(CMD_DATA_TRANSFER_FORWARD(), ccv_nnc_no_hint, 0, TENSOR_LIST(a), TENSOR_LIST(at), 0);
REQUIRE_TENSOR_EQ(ha, at, "result should be equal");
ccv_nnc_tensor_free(ha);
ccv_nnc_tensor_free(hb);
ccv_nnc_tensor_free(a);
ccv_nnc_tensor_free(b);
ccv_nnc_tensor_free(at);
}
TEST_CASE("argmax with float")
{
GUARD_ELSE_RETURN(ccv_nnc_cmd_ok(CCV_NNC_ARGMAX_FORWARD, CCV_NNC_BACKEND_GPU_REF));
dsfmt_t dsfmt;
dsfmt_init_gen_rand(&dsfmt, 0);
ccv_nnc_tensor_t* const ha = ccv_nnc_tensor_new(0, CPU_TENSOR_NHWC(32F, 10, 3, 5, 3), 0);
ccv_nnc_tensor_t* const hb = ccv_nnc_tensor_new(0, CPU_TENSOR_NHWC(32S, 10, 1, 5, 3), 0);
int i;
for (i = 0; i < 10 * 3 * 5 * 3; i++)
ha->data.f32[i] = dsfmt_genrand_open_close(&dsfmt);
ccv_nnc_cmd_exec(CMD_ARGMAX_FORWARD(1), ccv_nnc_no_hint, 0, TENSOR_LIST(ha), TENSOR_LIST(hb), 0);
ccv_nnc_tensor_t* const a = ccv_nnc_tensor_new(0, GPU_TENSOR_NHWC(000, 32F, 10, 3, 5, 3), 0);
ccv_nnc_tensor_t* const b = ccv_nnc_tensor_new(0, GPU_TENSOR_NHWC(000, 32S, 10, 1, 5, 3), 0);
ccv_nnc_cmd_exec(CMD_DATA_TRANSFER_FORWARD(), ccv_nnc_no_hint, 0, TENSOR_LIST(ha), TENSOR_LIST(a), 0);
ccv_nnc_cmd_exec(CMD_ARGMAX_FORWARD(1), ccv_nnc_no_hint, 0, TENSOR_LIST(a), TENSOR_LIST(b), 0);
ccv_nnc_tensor_t* const bt = ccv_nnc_tensor_new(0, CPU_TENSOR_NHWC(32S, 10, 1, 5, 3), 0);
ccv_nnc_cmd_exec(CMD_DATA_TRANSFER_FORWARD(), ccv_nnc_no_hint, 0, TENSOR_LIST(b), TENSOR_LIST(bt), 0);
REQUIRE_TENSOR_EQ(hb, bt, "result should be equal");
ccv_nnc_tensor_free(ha);
ccv_nnc_tensor_free(hb);
ccv_nnc_tensor_free(a);
ccv_nnc_tensor_free(b);
ccv_nnc_tensor_free(bt);
}
#include "case_main.h"
| 2,257 |
1,078 | <filename>tests/api_resources/test_reversal.py<gh_stars>1000+
from __future__ import absolute_import, division, print_function
import pytest
import stripe
TEST_RESOURCE_ID = "trr_123"
class TestReversal(object):
def construct_resource(self):
reversal_dict = {
"id": TEST_RESOURCE_ID,
"object": "reversal",
"metadata": {},
"transfer": "tr_123",
}
return stripe.Reversal.construct_from(reversal_dict, stripe.api_key)
def test_has_instance_url(self, request_mock):
resource = self.construct_resource()
assert (
resource.instance_url()
== "/v1/transfers/tr_123/reversals/%s" % TEST_RESOURCE_ID
)
def test_is_not_modifiable(self, request_mock):
with pytest.raises(NotImplementedError):
stripe.Reversal.modify(TEST_RESOURCE_ID, metadata={"key": "value"})
def test_is_not_retrievable(self, request_mock):
with pytest.raises(NotImplementedError):
stripe.Reversal.retrieve(TEST_RESOURCE_ID)
def test_is_saveable(self, request_mock):
resource = self.construct_resource()
resource.metadata["key"] = "value"
resource.save()
request_mock.assert_requested(
"post", "/v1/transfers/tr_123/reversals/%s" % TEST_RESOURCE_ID
)
| 615 |
685 | {
"average-durations": "平均用时",
"average-tries-count": "平均尝试",
"back-today": "回到今天",
"cheatsheet": "速查表",
"check-assist": "辅助排除",
"colorblind-mode": "色彩增强",
"continue": "继续游戏",
"correct-answer": "正确答案",
"dashboard": "记分板",
"description": "汉字 Wordle",
"dont-spoiler": "分享时建议开启遮罩避免剧透",
"download": "下载",
"download-as-image": "保存为图片",
"example-1": "班门弄斧",
"example-2": "水落石出",
"example-3": "巧夺天工",
"example-4": "武运昌隆",
"failed-1": "今天你已经用完十次的尝试机会了",
"failed-2": "但是没关系,你还可以继续尝试",
"failed-3": "你也可以随时放弃并查看答案",
"feedback": "意见反馈",
"finals": "韵母",
"games-count": "游戏次数",
"guess-dist": "尝试次数分布",
"hanzi": "汉字",
"hard-mode": "禁用提示",
"hint": "提示",
"hint-level-1": "字音提示",
"hint-level-2": "汉字提示",
"hint-level-none": "无提示",
"hint-note": "答案包含以下",
"initials": "声母",
"input-placeholder": "输入四字词语...",
"intro-1": "你有十次的机会猜一个",
"intro-10": "每个格子的",
"intro-11": "汉字、声母、韵母、声调",
"intro-12": "都会独立进行颜色的指示。",
"intro-13": "例如,第一个",
"intro-14": "巧",
"intro-15": "汉字为灰色,而其 声母 与 韵母 均为青色,代表该位置的正确答案为其同音字但非",
"intro-16": "字本身。",
"intro-17": "同理,第二个字中韵母",
"intro-19": "为橙色,代表其韵母出现在四个字之中,但非位居第二。以此类推。",
"intro-2": "四字词语",
"intro-20": "当四个格子都为青色时,你便赢得了游戏!",
"intro-3": "每次猜测后,汉字与拼音的颜色将会标识其与正确答案的区别。",
"intro-4": "第二个字",
"intro-5": "门",
"intro-6": "为青色,表示其出现在答案中且在正确的位置。",
"intro-7": "第一个字",
"intro-8": "水",
"intro-9": "为橙色,表示其出现在答案中,但并不是第一个字。",
"invalid-idiom": "成语不在词库内",
"join-community": "加入社区进行分享与讨论",
"mask-off": "开启遮罩",
"mask-on": "关闭遮罩",
"minutes": "分",
"more-hint": "进一步提示",
"name": "汉兜",
"next-note": "距离下一题更新还有",
"no-future-play": "Ops,这道题目来自未来,还不能玩哦!",
"no-past-play": "这道题来自久远的过去,已经找不到了",
"no-quiz-today": "啊抱歉!这天的题目还没出好!",
"ok-spaced": "确 定",
"other-variants": "其他中文 Wordle 变体",
"pinyin": "拼音",
"playing-previous-1": "正在游玩",
"playing-previous-2": "天前的游戏",
"press-and-download-image": "长按下图保存到相册",
"privacy-notes": "隐私声明",
"rendering": "生成中...",
"rule": "游戏规则",
"seconds": "秒",
"select-share-method": "选择分享方式",
"send-game-data-button": "发送匿名游戏数据",
"share": "分享",
"share-copied": "分享内容已复制到剪贴板",
"share-not-copied": "请复制以下文本进行分享",
"share-with-system-api": "调用系统分享",
"share-with-text": "文本分享",
"shuangpin": "双拼",
"shuangpin-sougou": "搜狗双拼",
"shuangpin-xiaohe": "小鹤双拼",
"start": "开始游戏",
"strict-mode": "严格模式",
"time-format": "{0}时{1}分{2}秒",
"tone-number": "数字声调",
"tone-symbol": "符号声调",
"tries-rest": "剩余 {0} 次机会",
"twitter-community": "推特",
"update-tip": "* 新题目每日零时更新",
"used-words": "词语使用",
"valid-words-rate": "成语比例",
"view-answer": "查看答案",
"weibo-topic": "微博",
"win-count": "获胜次数",
"win-no-hint-count": "无提示",
"win-rate": "胜率",
"zhuyin": "注音",
"ziyin": "字音"
}
| 2,444 |
348 | <reponame>chamberone/Leaflet.PixiOverlay<filename>docs/data/leg-t2/062/06201416.json<gh_stars>100-1000
{"nom":"Hautecloque","circ":"1ère circonscription","dpt":"Pas-de-Calais","inscrits":169,"abs":68,"votants":101,"blancs":3,"nuls":3,"exp":95,"res":[{"nuance":"MDM","nom":"<NAME>","voix":49},{"nuance":"FN","nom":"<NAME>","voix":46}]} | 143 |
764 | <reponame>641589523/token-profile<filename>erc20/0xef6344de1fcfC5F48c30234C16c1389e8CdC572C.json
{"symbol": "DNA","address": "0xef6344de1fcfC5F48c30234C16c1389e8CdC572C","overview":{"en": ""},"email": "","website": "https://www.encrypgen.com/","state": "NORMAL","links": {"blog": "","twitter": "https://twitter.com/encrypgen","telegram": "","github": ""}} | 152 |
4,054 | // Copyright 2020 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#pragma once
#include <vespa/metrics/metricset.h>
#include <vespa/metrics/valuemetric.h>
#include <vespa/fnet/connection.h>
namespace storage {
// Simple wrapper around low-level fnet network metrics
class FnetMetricsWrapper : public metrics::MetricSet
{
private:
metrics::LongValueMetric _num_connections;
public:
explicit FnetMetricsWrapper(metrics::MetricSet* owner);
~FnetMetricsWrapper() override;
void update_metrics();
};
}
| 192 |
399 | <gh_stars>100-1000
package io.envoyproxy.envoymobile.engine.types;
public interface EnvoyLogger {
void log(String str);
}
| 44 |
692 | <gh_stars>100-1000
#include "mpi.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
int main(int argc, char *argv[])
{
int num_procs, num_local;
char mach_name[MPI_MAX_PROCESSOR_NAME];
int mach_len;
MPI_Init (&argc,&argv);
MPI_Comm_size (MPI_COMM_WORLD, &num_procs);
MPI_Comm_rank (MPI_COMM_WORLD, &num_local);
MPI_Get_processor_name(mach_name,&mach_len);
/* compare avail MPI tasks to requested. If not requested via argv,
convention is to assume 1 task */
if(argc > 1)
assert(num_procs == atoi(argv[1]));
else
assert(num_procs == 1);
/* Verify a quick collective */
int local=1;
int global;
MPI_Allreduce(&local,&global,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
assert(global == num_procs);
MPI_Finalize();
return 0;
}
| 350 |
7,629 | /* Copyright 2021 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "config.h"
#include "syshead.h"
#include "init.h"
#include "proxy.h"
#include "interval.h"
#include "route.h"
#include "buffer.h"
#include "fuzz_randomizer.h"
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
fuzz_random_init(data, size);
gb_init();
struct route_option_list *opt;
struct route_list rl;
int route_list_inited = 0;
int route_list_ipv6_inited = 0;
struct context c;
memset(&c, 0, sizeof(struct context));
gc_init(&c.gc);
c.es = env_set_create(&c.gc);
init_options(&c.options, true);
net_ctx_init(&c, &c.net_ctx);
init_verb_mute(&c, IVM_LEVEL_1);
init_options_dev(&c.options);
// options_postprocess(&c.options);
pre_setup(&c.options);
setenv_settings(c.es, &c.options);
ALLOC_OBJ_CLEAR_GC(c.options.connection_list, struct connection_list,
&c.options.gc);
context_init_1(&c);
in_addr_t remote_host;
ssize_t default_metric;
struct route_ipv6_list rl6;
struct route_ipv6_option_list *opt6;
memset(&rl, 0, sizeof(rl));
memset(&rl6, 0, sizeof(rl6));
memset(&opt, 0, sizeof(opt));
memset(&opt6, 0, sizeof(opt6));
opt6 = new_route_ipv6_option_list(&c.gc);
opt = new_route_option_list(&c.gc);
int total_to_fuzz = fuzz_randomizer_get_int(1, 20);
for (int i = 0; i < total_to_fuzz; i++) {
int selector = fuzz_randomizer_get_int(0, 13);
switch (selector) {
case 0:
if (route_list_inited == 0) {
const char *remote_endpoint = gb_get_random_string();
memset(&rl, 0, sizeof(struct route_list));
rl.flags = fuzz_randomizer_get_int(0, 0xffffff);
init_route_list(&rl, opt, remote_endpoint, default_metric, remote_host,
c.es, &c);
route_list_inited = 1;
}
break;
case 1:
if (route_list_inited) {
in_addr_t addr;
route_list_add_vpn_gateway(&rl, c.es, addr);
}
break;
case 2:
if (route_list_inited && route_list_ipv6_inited) {
struct tuntap tt;
memset(&tt, 0, sizeof(tt));
add_routes(&rl, &rl6, &tt, 0, c.es, &c);
}
break;
case 3:
if (route_list_inited) {
setenv_routes(c.es, &rl);
}
break;
case 4:
if (route_list_inited) {
struct route_ipv4 r;
struct route_option ro;
ro.network = gb_get_random_string();
ro.netmask = gb_get_random_string();
ro.gateway = gb_get_random_string();
ro.metric = gb_get_random_string();
ro.next = NULL;
memset(&r, 0, sizeof(struct route_ipv4));
r.option = &ro;
r.flags = RT_DEFINED;
add_route(&r, NULL, 0, NULL, c.es, &c);
}
break;
case 5:
if (route_list_inited) {
char *s1 = get_random_string();
is_special_addr(s1);
free(s1);
}
break;
case 6:
if (route_list_ipv6_inited == 0) {
const char *remote_endpoint = gb_get_random_string();
memset(&rl, 0, sizeof(struct route_list));
struct in6_addr remote_host;
rl6.rgi6.flags = fuzz_randomizer_get_int(0, 0xffffff);
fuzz_get_random_data(&rl6.rgi6.hwaddr, 6);
char *t1 = gb_get_random_string();
if (strlen(t1) > 16) {
memcpy(rl6.rgi6.iface, t1, 16);
} else {
memcpy(rl6.rgi6.iface, t1, strlen(t1));
}
init_route_ipv6_list(&rl6, opt6, remote_endpoint, 0, &remote_host, c.es,
&c);
route_list_ipv6_inited = 1;
}
break;
case 7: {
unsigned int flags;
struct route_ipv6 r6;
struct tuntap tt;
memset(&tt, 0, sizeof(tt));
tt.actual_name = gb_get_random_string();
r6.iface = gb_get_random_string();
r6.flags = fuzz_randomizer_get_int(0, 0xfffff);
r6.netbits = fuzz_randomizer_get_int(0, 0xfffff);
r6.metric = fuzz_randomizer_get_int(0, 0xfffff);
r6.next = NULL;
add_route_ipv6(&r6, &tt, 0, c.es, &c);
} break;
case 8:
if (route_list_ipv6_inited && route_list_inited) {
delete_routes(&rl, &rl6, NULL, 0, c.es, &c);
route_list_ipv6_inited = 0;
route_list_inited = 0;
}
break;
case 9:
if (route_list_ipv6_inited) {
setenv_routes_ipv6(c.es, &rl6);
}
break;
case 10: {
add_route_ipv6_to_option_list(opt6, gb_get_random_string(),
gb_get_random_string(),
gb_get_random_string());
} break;
case 11: {
print_route_options(opt, M_NONFATAL);
} break;
case 12: {
add_route_to_option_list(opt, gb_get_random_string(),
gb_get_random_string(), gb_get_random_string(),
gb_get_random_string());
} break;
default:
break;
}
}
if (route_list_inited) {
gc_free(&rl.gc);
}
env_set_destroy(c.es);
context_gc_free(&c);
fuzz_random_destroy();
gb_cleanup();
return 0;
}
| 2,738 |
1,192 | // Run lines below; this test is line- and column-sensitive.
void foo(void) __attribute__((availability(macosx,introduced=10.4,deprecated=10.5,obsoleted=10.7), availability(ios,introduced=3.2,deprecated=4.1)));
enum {
old_enum
} __attribute__((deprecated));
enum {
old_enum_plat
} __attribute__((availability(macosx,introduced=10.4,deprecated=10.5,obsoleted=10.7)
// RUN: c-index-test -test-load-source all %s > %t
// RUN: FileCheck -check-prefix=CHECK-1 %s < %t
// RUN: FileCheck -check-prefix=CHECK-2 %s < %t
// CHECK-1: (ios, introduced=3.2, deprecated=4.1)
// CHECK-2: (macosx, introduced=10.4, deprecated=10.5, obsoleted=10.7)
// CHECK-2: EnumConstantDecl=old_enum:6:3 (Definition) (deprecated)
// CHECK-2: EnumConstantDecl=old_enum_plat:10:3 {{.*}} (macosx, introduced=10.4, deprecated=10.5, obsoleted=10.7)
| 332 |
681 | <filename>AntiEmulator/src/diff/strazzere/anti/MainActivity.java
package diff.strazzere.anti;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import diff.strazzere.anti.debugger.FindDebugger;
import diff.strazzere.anti.emulator.FindEmulator;
import diff.strazzere.anti.monkey.FindMonkey;
import diff.strazzere.anti.taint.FindTaint;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread() {
@Override
public void run() {
super.run();
isTaintTrackingDetected();
isMonkeyDetected();
isDebugged();
isQEmuEnvDetected();
}
}.start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean isQEmuEnvDetected() {
log("Checking for QEmu env...");
log("hasKnownDeviceId : " + FindEmulator.hasKnownDeviceId(getApplicationContext()));
log("hasKnownPhoneNumber : " + FindEmulator.hasKnownPhoneNumber(getApplicationContext()));
log("isOperatorNameAndroid : " + FindEmulator.isOperatorNameAndroid(getApplicationContext()));
log("hasKnownImsi : " + FindEmulator.hasKnownImsi(getApplicationContext()));
log("hasEmulatorBuild : " + FindEmulator.hasEmulatorBuild(getApplicationContext()));
log("hasPipes : " + FindEmulator.hasPipes());
log("hasQEmuDriver : " + FindEmulator.hasQEmuDrivers());
log("hasQEmuFiles : " + FindEmulator.hasQEmuFiles());
log("hasGenyFiles : " + FindEmulator.hasGenyFiles());
log("hasEmulatorAdb :" + FindEmulator.hasEmulatorAdb());
for(String abi : Build.SUPPORTED_ABIS) {
if (abi.equalsIgnoreCase("armeabi-v7a")) {
log("hitsQemuBreakpoint : " + FindEmulator.checkQemuBreakpoint());
}
}
if (FindEmulator.hasKnownDeviceId(getApplicationContext())
|| FindEmulator.hasKnownImsi(getApplicationContext())
|| FindEmulator.hasEmulatorBuild(getApplicationContext())
|| FindEmulator.hasKnownPhoneNumber(getApplicationContext()) || FindEmulator.hasPipes()
|| FindEmulator.hasQEmuDrivers() || FindEmulator.hasEmulatorAdb()
|| FindEmulator.hasQEmuFiles()
|| FindEmulator.hasGenyFiles()) {
log("QEmu environment detected.");
return true;
} else {
log("QEmu environment not detected.");
return false;
}
}
public boolean isTaintTrackingDetected() {
log("Checking for Taint tracking...");
log("hasAppAnalysisPackage : " + FindTaint.hasAppAnalysisPackage(getApplicationContext()));
log("hasTaintClass : " + FindTaint.hasTaintClass());
log("hasTaintMemberVariables : " + FindTaint.hasTaintMemberVariables());
if (FindTaint.hasAppAnalysisPackage(getApplicationContext()) || FindTaint.hasTaintClass()
|| FindTaint.hasTaintMemberVariables()) {
log("Taint tracking was detected.");
return true;
} else {
log("Taint tracking was not detected.");
return false;
}
}
public boolean isMonkeyDetected() {
log("Checking for Monkey user...");
log("isUserAMonkey : " + FindMonkey.isUserAMonkey());
if (FindMonkey.isUserAMonkey()) {
log("Monkey user was detected.");
return true;
} else {
log("Monkey user was not detected.");
return false;
}
}
public boolean isDebugged() {
log("Checking for debuggers...");
boolean tracer = false;
try {
tracer = FindDebugger.hasTracerPid();
} catch (Exception exception) {
exception.printStackTrace();
}
if (FindDebugger.isBeingDebugged() || tracer) {
log("Debugger was detected");
return true;
} else {
log("No debugger was detected.");
return false;
}
}
public void log(String msg) {
Log.v("AntiEmulator", msg);
}
}
| 2,031 |
335 | {
"word": "Rocking",
"definitions": [
"Moving gently to and fro or from side to side.",
"(of a place) full of excitement or social activity."
],
"parts-of-speech": "Adjective"
} | 84 |
12,340 | <filename>sonic-iOS/Sonic/ResourceLoader/SonicResourceLoadOperation.h<gh_stars>1000+
//
// SonicResourceLoadOperation.h
// Sonic
//
// Tencent is pleased to support the open source community by making VasSonic available.
// Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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.
//
// Copyright © 2017年 Tencent. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "SonicSession.h"
@interface SonicResourceLoadOperation : NSOperation
/**
* Resource sessionID
* It is the MD5 string with the url.
*/
@property (nonatomic,readonly)NSString *sessionID;
/**
* The resource url.
*/
@property (nonatomic,readonly)NSString *url;
/**
* NSURLProtocol layer use this call back to get the resource data.
*/
@property (nonatomic,copy)SonicURLProtocolCallBack protocolCallBack;
/**
* Init an operation with the resource url.
*/
- (instancetype)initWithUrl:(NSString *)aUrl;
/**
* NSURLProtocol layer call this function to get the resource data.
*/
- (void)preloadDataWithProtocolCallBack:(SonicURLProtocolCallBack)callBack;
@end
| 468 |
479 | <filename>src/test/resources/restapi/roles_captains_tenants_malformed.json
{
"cluster_permissions" : [ "cluster:monitor*" ],
"index_permissions" : [ {
"index_patterns" : [ "sf" ],
"allowed_actions" : [ "OPENDISTRO_SECURITY_CRUD" ]
}, {
"index_patterns" : [ "pub" ],
"allowed_actions" : [ "OPENDISTRO_SECURITY_CRUD" ]
} ],
"tenantz_permissions" : [ {
"tenant_patterns" : [ "tenant2", "tenant4" ],
"allowed_actions" : [ "kibana_all_write" ]
}, {
"tenant_patterns" : [ "tenant1", "tenant3" ],
"allowed_actions" : [ "kibana_all_read" ]
} ]
}
| 262 |
643 | <filename>rns_shell/platform/graphics/PlatformDisplay.cpp
/*
* Copyright (C) 1994-2021 OpenTV, Inc. and Nagravision S.A.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "ReactSkia/utils/RnsUtils.h"
#if USE(EGL)
#include "egl/GLWindowContextEGL.h"
#elif USE(GLX)
#include "glx/GLWindowContextGLX.h"
#endif
#include "PlatformDisplay.h"
#if PLATFORM(X11)
#include "x11/PlatformDisplayX11.h"
#elif PLATFORM(LIBWPE) || USE(WPE_RENDERER)
#include "libwpe/PlatformDisplayLibWPE.h"
#endif
namespace RnsShell {
static PlatformDisplay* s_sharedDisplayForCompositing;
PlatformDisplay::PlatformDisplay(bool displayOwned)
: nativeDisplayOwned_(displayOwned)
#if USE(EGL)
, eglDisplay_(EGL_NO_DISPLAY)
#endif
{
}
PlatformDisplay::~PlatformDisplay() {
#if USE(EGL)
if (eglDisplay_ != EGL_NO_DISPLAY) {
eglTerminate(eglDisplay_);
eglDisplay_ = EGL_NO_DISPLAY;
}
#endif
if(this == s_sharedDisplayForCompositing)
s_sharedDisplayForCompositing = nullptr;
}
#if USE(EGL) || USE(GLX)
GLWindowContext* PlatformDisplay::sharingGLContext() {
RNS_LOG_TODO("Implement " << __func__ << " in GLWindowContext to call GLWindowContextEGL/GLX");
#if 0 // TODO implement this function in GLWindowContext to call GLWindowContextEGL
if (!sharingGLContext_)
sharingGLContext_ = GLWindowContext::createSharingContext();
#endif
return sharingGLContext_ ? sharingGLContext_.get() : nullptr;
}
#endif
#if USE(EGL)
EGLDisplay PlatformDisplay::eglDisplay() const {
if (!eglDisplayInitialized_)
const_cast<PlatformDisplay*>(this)->initializeEGLDisplay();
return eglDisplay_;
}
bool PlatformDisplay::eglCheckVersion(int major, int minor) const {
if (!eglDisplayInitialized_)
const_cast<PlatformDisplay*>(this)->initializeEGLDisplay();
return (eglMajorVersion_ > major) || ((eglMajorVersion_ == major) && (eglMinorVersion_ >= minor));
}
void PlatformDisplay::initializeEGLDisplay() {
eglDisplayInitialized_ = true;
if (eglDisplay_ == EGL_NO_DISPLAY) {
eglDisplay_ = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if (eglDisplay_ == EGL_NO_DISPLAY) {
RNS_LOG_ERROR("Cannot get default EGL display : " << GLWindowContextEGL::eglErrorString());
return;
}
}
EGLint majorVersion, minorVersion;
if (eglInitialize(eglDisplay_, &majorVersion, &minorVersion) == EGL_FALSE) {
RNS_LOG_ERROR("EGLDisplay Initialization failed : " << GLWindowContextEGL::eglErrorString());
terminateEGLDisplay();
return;
}
eglMajorVersion_ = majorVersion;
eglMinorVersion_ = minorVersion;
}
void PlatformDisplay::terminateEGLDisplay() {
sharingGLContext_ = nullptr;
SkASSERT(eglDisplayInitialized_);
if (eglDisplay_ == EGL_NO_DISPLAY)
return;
eglTerminate(eglDisplay_);
eglDisplay_ = EGL_NO_DISPLAY;
}
#endif // USE(EGL)
std::unique_ptr<PlatformDisplay> PlatformDisplay::createPlatformDisplay() {
#if PLATFORM(WAYLAND)
if (auto platformDisplay = PlatformDisplayWayland::create())
return platformDisplay;
else
return PlatformDisplayWayland::create(nullptr);
#endif
#if PLATFORM(X11)
if (auto platformDisplay = PlatformDisplayX11::create())
return platformDisplay;
else
return PlatformDisplayX11::create(nullptr);
#endif
#if PLATFORM(DFB)
return PlatformDisplayDfb::create();
#endif
#if PLATFORM(WIN)
return PlatformDisplayWin::create();
#elif PLATFORM(LIBWPE)
return PlatformDisplayLibWPE::create();
#endif
return nullptr;
}
PlatformDisplay& PlatformDisplay::sharedDisplay() {
#if PLATFORM(X11) || PLATFORM(LIBWPE)
static std::once_flag onceFlag;
static std::unique_ptr<PlatformDisplay> display;
std::call_once(onceFlag, []{
display = createPlatformDisplay();
});
return *display;
#else
#error "!!!!!!!!!! Atleast one Platform needs to be selected !!!!!!!!!!"
#endif
}
PlatformDisplay& PlatformDisplay::sharedDisplayForCompositing() {
return s_sharedDisplayForCompositing ? *s_sharedDisplayForCompositing : sharedDisplay();
}
bool PlatformDisplay::initialize() {
if(s_sharedDisplayForCompositing)
return true;
if(!(s_sharedDisplayForCompositing = &sharedDisplay()))
return false;
#if PLATFORM(LIBWPE)
return dynamic_cast<RnsShell::PlatformDisplayLibWPE*>(s_sharedDisplayForCompositing)->initialize(wpe_renderer_host_create_client());
#else
return true;
#endif
}
} // namespace RnsShell
| 1,713 |
6,989 | #include "slice.h"
#include "cuda_buffer.h"
#include <util/stream/output.h>
#include <util/string/cast.h>
template <>
void Out<TSlice>(IOutputStream& o, const TSlice& slice) {
o.Write("[" + ToString(slice.Left) + "-" + ToString(slice.Right) + "]");
}
| 104 |
558 | package syncer.replica.datatype.command.string;
import syncer.replica.datatype.command.GenericKeyValueCommand;
/**
* Append String
*/
public class AppendCommand extends GenericKeyValueCommand {
private static final long serialVersionUID = 1L;
public AppendCommand() {
}
public AppendCommand(byte[] key, byte[] value) {
super(key, value);
}
}
| 128 |
14,668 | // Copyright 2020 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 "chromecast/external_mojo/external_service_support/tracing_client_dummy.h"
namespace chromecast {
namespace external_service_support {
// static
const char TracingClient::kTracingServiceName[] = "unknown";
// static
std::unique_ptr<TracingClient> TracingClient::Create(
ExternalConnector* connector) {
return std::make_unique<TracingClientDummy>();
}
} // namespace external_service_support
} // namespace chromecast
| 173 |
1,284 | package org.akhq.configs;
import io.micronaut.context.annotation.ConfigurationProperties;
import io.micronaut.security.config.SecurityConfigurationProperties;
import lombok.Data;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@Data
@ConfigurationProperties("akhq.security.header-auth")
public class HeaderAuth {
String userHeader;
String groupsHeader;
String groupsHeaderSeparator = ",";
String defaultGroup;
List<GroupMapping> groups = new ArrayList<>();
List<UserMapping> users = new ArrayList<>();
List<String> ipPatterns = Collections.singletonList(SecurityConfigurationProperties.ANYWHERE);
}
| 207 |
789 | package io.advantageous.qbit.service.rest.endpoint.tests.tests;
import io.advantageous.boon.json.JsonFactory;
import io.advantageous.qbit.http.HttpHeaders;
import io.advantageous.qbit.http.request.HttpRequestBuilder;
import io.advantageous.qbit.http.request.HttpTextResponse;
import io.advantageous.qbit.server.EndpointServerBuilder;
import io.advantageous.qbit.server.ServiceEndpointServer;
import io.advantageous.qbit.service.rest.endpoint.tests.model.Employee;
import io.advantageous.qbit.service.rest.endpoint.tests.services.EmployeeServiceSingleObjectTestService;
import io.advantageous.qbit.service.rest.endpoint.tests.services.MyService;
import io.advantageous.qbit.service.rest.endpoint.tests.sim.HttpServerSimulator;
import io.advantageous.qbit.spi.FactorySPI;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import static io.advantageous.boon.core.IO.puts;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
public class SingleArgumentUserDefinedObjectRESTTest {
ServiceEndpointServer serviceEndpointServer;
HttpServerSimulator httpServerSimulator;
HttpRequestBuilder httpRequestBuilder;
EmployeeServiceSingleObjectTestService service;
@Before
public void before() {
httpRequestBuilder = HttpRequestBuilder.httpRequestBuilder();
httpServerSimulator = new HttpServerSimulator();
service = new EmployeeServiceSingleObjectTestService();
FactorySPI.setHttpServerFactory((options, endPointName, systemManager, serviceDiscovery,
healthServiceAsync, serviceDiscoveryTtl, serviceDiscoveryTtlTimeUnit, a, b, c)
-> httpServerSimulator);
serviceEndpointServer = EndpointServerBuilder.endpointServerBuilder()
.build()
.initServices(
service,
new MyService()
).startServer();
}
@Test
public void testRootMap() {
serviceEndpointServer = EndpointServerBuilder.endpointServerBuilder().setUri("/")
.build()
.initServices(
new MyService()
).startServer();
final HttpTextResponse httpResponse = httpServerSimulator.sendRequestRaw(
httpRequestBuilder.setUri("/ping")
.setMethodGet()
.build()
);
assertEquals(200, httpResponse.code());
assertEquals("true", httpResponse.body());
}
@Test
public void testDefaultRequestParam() {
final HttpTextResponse httpResponse = httpServerSimulator.sendRequest(
httpRequestBuilder.setUri("/es/string-request-param")
.setMethodGet()
.build()
);
assertEquals(200, httpResponse.code());
assertEquals("\"foo\"", httpResponse.body());
final HttpTextResponse httpResponse2 = httpServerSimulator.sendRequest(
httpRequestBuilder.setUri("/es/string-request-param")
.addParam("p", "something")
.setMethodGet()
.build()
);
assertEquals(200, httpResponse2.code());
assertEquals("\"something\"", httpResponse2.body());
}
@Test
public void testDefaultRequestParamNoDefault() {
final HttpTextResponse httpResponse = httpServerSimulator.sendRequest(
httpRequestBuilder.setUri("/es/string-request-param-no-default")
.setMethodGet()
.build()
);
assertEquals(200, httpResponse.code());
assertEquals("", httpResponse.body());
final HttpTextResponse httpResponse2 = httpServerSimulator.sendRequest(
httpRequestBuilder.setUri("/es/string-request-param-no-default")
.addParam("p", "something")
.setMethodGet()
.build()
);
assertEquals(200, httpResponse2.code());
assertEquals("\"something\"", httpResponse2.body());
}
@Test
public void testDefaultBooleanRequestParam() {
final HttpTextResponse httpResponse = httpServerSimulator.sendRequest(
httpRequestBuilder.setUri("/es/boolean-request-param")
.setMethodGet()
.build()
);
assertEquals(200, httpResponse.code());
assertEquals("true", httpResponse.body());
final HttpTextResponse httpResponse2 = httpServerSimulator.sendRequest(
httpRequestBuilder.setUri("/es/boolean-request-param")
.addParam("p", "false")
.setMethodGet()
.build()
);
assertEquals(200, httpResponse2.code());
assertEquals("false", httpResponse2.body());
}
@Test
public void testDefaultBooleanRequestParamNoDefault() {
final HttpTextResponse httpResponse = httpServerSimulator.sendRequest(
httpRequestBuilder.setUri("/es/boolean-request-param-no-default")
.setMethodGet()
.build()
);
assertEquals(200, httpResponse.code());
assertEquals("false", httpResponse.body());
final HttpTextResponse httpResponse2 = httpServerSimulator.sendRequest(
httpRequestBuilder.setUri("/es/boolean-request-param-no-default")
.addParam("p", "true")
.setMethodGet()
.build()
);
assertEquals(200, httpResponse2.code());
assertEquals("true", httpResponse2.body());
}
@Test
public void testDefaultIntRequestParam() {
final HttpTextResponse httpResponse = httpServerSimulator.sendRequest(
httpRequestBuilder.setUri("/es/int-request-param")
.setMethodGet()
.build()
);
assertEquals(200, httpResponse.code());
assertEquals("99", httpResponse.body());
final HttpTextResponse httpResponse2 = httpServerSimulator.sendRequest(
httpRequestBuilder.setUri("/es/int-request-param")
.addParam("p", "100")
.setMethodGet()
.build()
);
assertEquals(200, httpResponse2.code());
assertEquals("100", httpResponse2.body());
}
@Test
public void testDefaultIntRequestParamNoDefault() {
final HttpTextResponse httpResponse = httpServerSimulator.sendRequest(
httpRequestBuilder.setUri("/es/int-request-param-no-default")
.setMethodGet()
.build()
);
assertEquals(200, httpResponse.code());
assertEquals("0", httpResponse.body());
final HttpTextResponse httpResponse2 = httpServerSimulator.sendRequest(
httpRequestBuilder.setUri("/es/int-request-param-no-default")
.addParam("p", "66")
.setMethodGet()
.build()
);
assertEquals(200, httpResponse2.code());
assertEquals("66", httpResponse2.body());
}
@Test
public void testDefaultIntegerRequestParam() {
final HttpTextResponse httpResponse = httpServerSimulator.sendRequest(
httpRequestBuilder.setUri("/es/integer-request-param")
.setMethodGet()
.build()
);
assertEquals(200, httpResponse.code());
assertEquals("99", httpResponse.body());
final HttpTextResponse httpResponse2 = httpServerSimulator.sendRequest(
httpRequestBuilder.setUri("/es/integer-request-param")
.addParam("p", "100")
.setMethodGet()
.build()
);
assertEquals(200, httpResponse2.code());
assertEquals("100", httpResponse2.body());
}
@Test
public void testDefaultIntegerRequestParamNoDefault() {
final HttpTextResponse httpResponse = httpServerSimulator.sendRequest(
httpRequestBuilder.setUri("/es/integer-request-param-no-default")
.setMethodGet()
.build()
);
assertEquals(200, httpResponse.code());
assertEquals("", httpResponse.body());
final HttpTextResponse httpResponse2 = httpServerSimulator.sendRequest(
httpRequestBuilder.setUri("/es/integer-request-param-no-default")
.addParam("p", "66")
.setMethodGet()
.build()
);
assertEquals(200, httpResponse2.code());
assertEquals("66", httpResponse2.body());
}
@Test
public void testDefaultHeaderParam() {
final HttpTextResponse httpResponse = httpServerSimulator.sendRequest(
httpRequestBuilder.setUri("/es/string-header-param-default")
.setMethodGet()
.build()
);
assertEquals(200, httpResponse.code());
assertEquals("\"zoo\"", httpResponse.body());
final HttpTextResponse httpResponse2 = httpServerSimulator.sendRequest(
httpRequestBuilder.setUri("/es/string-header-param-default")
.addHeader("p", "something")
.setMethodGet()
.build()
);
assertEquals(200, httpResponse2.code());
assertEquals("\"something\"", httpResponse2.body());
}
@Test
public void testDefaultHeaderParamNoDefault() {
final HttpTextResponse httpResponse = httpServerSimulator.sendRequest(
httpRequestBuilder.setUri("/es/string-header-param-no-default")
.setMethodGet()
.build()
);
assertEquals(200, httpResponse.code());
assertEquals("", httpResponse.body());
final HttpTextResponse httpResponse2 = httpServerSimulator.sendRequest(
httpRequestBuilder.setUri("/es/string-header-param-no-default")
.addHeader("p", "something")
.setMethodGet()
.build()
);
assertEquals(200, httpResponse2.code());
assertEquals("\"something\"", httpResponse2.body());
}
@Test
public void testNoCacheHeaders() {
final HttpTextResponse httpResponse = httpServerSimulator.sendRequest(
httpRequestBuilder.setUri("/es/cache")
.setMethodGet().setContentType("foo")
.setBody("foo")
.build()
);
assertEquals(200, httpResponse.code());
final List<String> controls = (List<String>) httpResponse.headers().getAll(HttpHeaders.CACHE_CONTROL);
Assert.assertEquals("max-age=0", controls.get(0));
Assert.assertEquals("no-cache, no-store", controls.get(1));
assertEquals("true", httpResponse.body());
}
@Test
public void testNoJSONParseWithBytes() {
final HttpTextResponse httpResponse = httpServerSimulator.sendRequest(
httpRequestBuilder.setUri("/es/body/bytes")
.setMethodPost().setContentType("foo")
.setBody("foo")
.build()
);
puts(httpResponse);
assertEquals(200, httpResponse.code());
assertEquals("true", httpResponse.body());
}
@Test
public void testNoJSONParseWithString() {
final HttpTextResponse httpResponse = httpServerSimulator.sendRequest(
httpRequestBuilder.setUri("/es/body/string")
.setMethodPost().setContentType("foo")
.setBody("foo")
.build()
);
puts(httpResponse);
assertEquals(200, httpResponse.code());
assertEquals("true", httpResponse.body());
}
@Test
public void testPing() {
final HttpTextResponse httpResponse = httpServerSimulator.get("/es/ping");
assertEquals(200, httpResponse.code());
assertEquals("true", httpResponse.body());
}
@Test
public void testRequiredParam() {
final HttpTextResponse httpResponse = httpServerSimulator.sendRequest(
httpRequestBuilder.setUri("/es/echo1").addParam("foo", "bar").build()
);
puts(httpResponse);
assertEquals(200, httpResponse.code());
assertEquals("\"bar\"", httpResponse.body());
}
@Test
public void testRequiredParamMissing() {
final HttpTextResponse httpResponse = httpServerSimulator.sendRequest(
httpRequestBuilder.setUri("/es/echo1").build()
);
puts(httpResponse);
assertEquals(400, httpResponse.code());
assertEquals("[\"Unable to find required request param foo\\n\"]", httpResponse.body());
}
@Test
public void testDefaultParam() {
final HttpTextResponse httpResponse = httpServerSimulator.sendRequest(
httpRequestBuilder.setUri("/es/echo2").build()
);
puts(httpResponse);
assertEquals(200, httpResponse.code());
assertEquals("\"mom\"", httpResponse.body());
}
@Test
public void testCustomHttpExceptionCode() {
final HttpTextResponse httpResponse = httpServerSimulator.sendRequest(
httpRequestBuilder.setUri("/es/echo3").build()
);
puts(httpResponse);
assertEquals(700, httpResponse.code());
assertEquals("\"Ouch!\"", httpResponse.body());
}
@Test
public void testCustomHttpExceptionCode2() {
final HttpTextResponse httpResponse = httpServerSimulator.sendRequest(
httpRequestBuilder.setUri("/es/echo4").build()
);
puts(httpResponse);
assertEquals(900, httpResponse.code());
assertEquals("\"Ouch!!\"", httpResponse.body());
}
@Test
public void testCustomHttpExceptionCode3() {
final HttpTextResponse httpResponse = httpServerSimulator.sendRequest(
httpRequestBuilder.setUri("/es/echo5").build()
);
puts(httpResponse);
assertEquals(666, httpResponse.code());
assertEquals("\"Shoot!!\"", httpResponse.body());
}
@Test
public void addEmployeeAsyncNoReturn() {
final HttpTextResponse httpResponse = httpServerSimulator.postBody("/es/employee-add-async-no-return",
new Employee(1, "Rick"));
assertEquals(202, httpResponse.code());
assertEquals("\"success\"", httpResponse.body());
}
@Test
public void echoEmployeeStringToInt() {
final HttpTextResponse httpResponse = httpServerSimulator.postBodyPlain("/es/echoEmployee",
"{\"id\":\"1\",\"name\":\"Rick\"}");
assertEquals(200, httpResponse.code());
assertEquals("{\"id\":1,\"name\":\"Rick\"}", httpResponse.body());
}
@Test
public void echoBadJson() {
final HttpTextResponse httpResponse = httpServerSimulator.postBodyPlain("/es/echoEmployee",
"{\"id\":\"a\",\"name\":\"Rick\"}");
assertEquals(400, httpResponse.code());
assertTrue(httpResponse.body().contains("Unable to JSON parse body"));
}
@Test
public void addEmployeeBadJSON() {
final HttpTextResponse httpResponse = httpServerSimulator.postBodyPlain("/es/employee-ack",
"{rick:name}");
assertEquals(400, httpResponse.code());
assertTrue(httpResponse.body().startsWith("[\"Unable to JSON parse"));
}
@Test
public void addEmployeeWithReturn() {
final HttpTextResponse httpResponse = httpServerSimulator.postBody("/es/employee-ack",
new Employee(1, "Rick"));
assertEquals(200, httpResponse.code());
assertEquals("true", httpResponse.body());
}
@Test
public void addEmployeeUsingCallback() {
final HttpTextResponse httpResponse = httpServerSimulator.postBody("/es/employee-async-ack",
new Employee(1, "Rick"));
assertEquals(200, httpResponse.code());
assertEquals("true", httpResponse.body());
}
@Test
public void addEmployeeThrowException() {
final HttpTextResponse httpResponse = httpServerSimulator.postBody("/es/throw",
new Employee(1, "Rick"));
assertEquals(500, httpResponse.code());
assertTrue(httpResponse.body().contains("\"message\":"));
puts(httpResponse.body());
}
@Test
public void testReturnEmployee() {
final HttpTextResponse httpResponse = httpServerSimulator.get("/es/returnemployee");
assertEquals(200, httpResponse.code());
Employee employee = JsonFactory.fromJson(httpResponse.body(), Employee.class);
assertEquals(1, employee.getId());
assertEquals("Rick", employee.getName());
}
@Test
public void testReturnEmployeeCaseDoesNotMatter() {
final HttpTextResponse httpResponse = httpServerSimulator.get("/es/Returnemployee");
assertEquals(200, httpResponse.code());
Employee employee = JsonFactory.fromJson(httpResponse.body(), Employee.class);
assertEquals(1, employee.getId());
assertEquals("Rick", employee.getName());
}
@Test
public void returnEmployeeCallback() {
final HttpTextResponse httpResponse = httpServerSimulator.get("/es/returnEmployeeCallback");
assertEquals(200, httpResponse.code());
Employee employee = JsonFactory.fromJson(httpResponse.body(), Employee.class);
assertEquals(1, employee.getId());
assertEquals("Rick", employee.getName());
}
@Test
public void returnEmployeeCallback2() {
final HttpTextResponse httpResponse = httpServerSimulator.get("/es/returnEmployeeCallback2");
assertEquals(777, httpResponse.code());
assertEquals("crap/crap", httpResponse.contentType());
assertEquals("Employee{id=1, name='Rick'}", httpResponse.body());
puts(httpResponse);
}
}
| 8,157 |
575 | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef EXTENSIONS_BROWSER_API_EXECUTE_CODE_FUNCTION_IMPL_H_
#define EXTENSIONS_BROWSER_API_EXECUTE_CODE_FUNCTION_IMPL_H_
#include "extensions/browser/api/execute_code_function.h"
#include <algorithm>
#include <utility>
#include "base/bind.h"
#include "extensions/browser/extension_api_frame_id_map.h"
#include "extensions/browser/load_and_localize_file.h"
#include "extensions/common/error_utils.h"
#include "extensions/common/extension.h"
#include "extensions/common/extension_resource.h"
#include "extensions/common/mojom/action_type.mojom-shared.h"
#include "extensions/common/mojom/css_origin.mojom-shared.h"
#include "extensions/common/mojom/run_location.mojom-shared.h"
namespace {
// Error messages
const char kNoCodeOrFileToExecuteError[] = "No source code or file specified.";
const char kMoreThanOneValuesError[] =
"Code and file should not be specified "
"at the same time in the second argument.";
const char kBadFileEncodingError[] =
"Could not load file '*' for content script. It isn't UTF-8 encoded.";
const char kLoadFileError[] = "Failed to load file: \"*\". ";
const char kCSSOriginForNonCSSError[] =
"CSS origin should be specified only for CSS code.";
}
namespace extensions {
using api::extension_types::InjectDetails;
ExecuteCodeFunction::ExecuteCodeFunction() {
}
ExecuteCodeFunction::~ExecuteCodeFunction() {
}
void ExecuteCodeFunction::DidLoadAndLocalizeFile(
const std::string& file,
bool success,
std::unique_ptr<std::string> data) {
if (!success) {
// TODO(viettrungluu): bug: there's no particular reason the path should be
// UTF-8, in which case this may fail.
Respond(Error(ErrorUtils::FormatErrorMessage(kLoadFileError, file)));
return;
}
if (!base::IsStringUTF8(*data)) {
Respond(Error(ErrorUtils::FormatErrorMessage(kBadFileEncodingError, file)));
return;
}
std::string error;
if (!Execute(*data, &error))
Respond(Error(std::move(error)));
// If Execute() succeeds, the function will respond in
// OnExecuteCodeFinished().
}
bool ExecuteCodeFunction::Execute(const std::string& code_string,
std::string* error) {
ScriptExecutor* executor = GetScriptExecutor(error);
if (!executor)
return false;
// TODO(lazyboy): Set |error|?
if (!extension() && !IsWebView())
return false;
DCHECK(!(ShouldInsertCSS() && ShouldRemoveCSS()));
auto action_type = mojom::ActionType::kAddJavascript;
if (ShouldInsertCSS())
action_type = mojom::ActionType::kAddCss;
else if (ShouldRemoveCSS())
action_type = mojom::ActionType::kRemoveCss;
ScriptExecutor::FrameScope frame_scope =
details_->all_frames.get() && *details_->all_frames
? ScriptExecutor::INCLUDE_SUB_FRAMES
: ScriptExecutor::SPECIFIED_FRAMES;
root_frame_id_ = details_->frame_id.get()
? *details_->frame_id
: ExtensionApiFrameIdMap::kTopFrameId;
ScriptExecutor::MatchAboutBlank match_about_blank =
details_->match_about_blank.get() && *details_->match_about_blank
? ScriptExecutor::MATCH_ABOUT_BLANK
: ScriptExecutor::DONT_MATCH_ABOUT_BLANK;
mojom::RunLocation run_at = mojom::RunLocation::kUndefined;
switch (details_->run_at) {
case api::extension_types::RUN_AT_NONE:
case api::extension_types::RUN_AT_DOCUMENT_IDLE:
run_at = mojom::RunLocation::kDocumentIdle;
break;
case api::extension_types::RUN_AT_DOCUMENT_START:
run_at = mojom::RunLocation::kDocumentStart;
break;
case api::extension_types::RUN_AT_DOCUMENT_END:
run_at = mojom::RunLocation::kDocumentEnd;
break;
}
CHECK_NE(mojom::RunLocation::kUndefined, run_at);
mojom::CSSOrigin css_origin = mojom::CSSOrigin::kAuthor;
switch (details_->css_origin) {
case api::extension_types::CSS_ORIGIN_NONE:
case api::extension_types::CSS_ORIGIN_AUTHOR:
css_origin = mojom::CSSOrigin::kAuthor;
break;
case api::extension_types::CSS_ORIGIN_USER:
css_origin = mojom::CSSOrigin::kUser;
break;
}
executor->ExecuteScript(
host_id_, action_type, code_string, frame_scope, {root_frame_id_},
match_about_blank, run_at,
IsWebView() ? ScriptExecutor::WEB_VIEW_PROCESS
: ScriptExecutor::DEFAULT_PROCESS,
GetWebViewSrc(), script_url_, user_gesture(), css_origin,
has_callback() ? ScriptExecutor::JSON_SERIALIZED_RESULT
: ScriptExecutor::NO_RESULT,
base::BindOnce(&ExecuteCodeFunction::OnExecuteCodeFinished, this));
return true;
}
ExtensionFunction::ResponseAction ExecuteCodeFunction::Run() {
InitResult init_result = Init();
EXTENSION_FUNCTION_VALIDATE(init_result != VALIDATION_FAILURE);
if (init_result == FAILURE)
return RespondNow(Error(init_error_.value_or(kUnknownErrorDoNotUse)));
if (!details_->code && !details_->file)
return RespondNow(Error(kNoCodeOrFileToExecuteError));
if (details_->code && details_->file)
return RespondNow(Error(kMoreThanOneValuesError));
if (details_->css_origin != api::extension_types::CSS_ORIGIN_NONE &&
!ShouldInsertCSS() && !ShouldRemoveCSS()) {
return RespondNow(Error(kCSSOriginForNonCSSError));
}
std::string error;
if (!CanExecuteScriptOnPage(&error))
return RespondNow(Error(std::move(error)));
if (details_->code) {
if (!Execute(*details_->code, &error))
return RespondNow(Error(std::move(error)));
return did_respond() ? AlreadyResponded() : RespondLater();
}
DCHECK(details_->file);
if (!LoadFile(*details_->file, &error))
return RespondNow(Error(std::move(error)));
// LoadFile will respond asynchronously later.
return RespondLater();
}
bool ExecuteCodeFunction::LoadFile(const std::string& file,
std::string* error) {
ExtensionResource resource = extension()->GetResource(file);
if (resource.extension_root().empty() || resource.relative_path().empty()) {
*error = kNoCodeOrFileToExecuteError;
return false;
}
script_url_ = extension()->GetResourceURL(file);
bool might_require_localization = ShouldInsertCSS() || ShouldRemoveCSS();
LoadAndLocalizeResource(
*extension(), resource, might_require_localization,
base::BindOnce(&ExecuteCodeFunction::DidLoadAndLocalizeFile, this,
resource.relative_path().AsUTF8Unsafe()));
return true;
}
void ExecuteCodeFunction::OnExecuteCodeFinished(
std::vector<ScriptExecutor::FrameResult> results) {
DCHECK(!results.empty());
auto root_frame_result =
std::find_if(results.begin(), results.end(),
[root_frame_id = root_frame_id_](const auto& frame_result) {
return frame_result.frame_id == root_frame_id;
});
DCHECK(root_frame_result != results.end());
// We just error out if we never injected in the root frame.
// TODO(devlin): That's a bit odd, because other injections may have
// succeeded. It seems like it might be worth passing back the values
// anyway.
if (!root_frame_result->error.empty()) {
// If the frame never responded (e.g. the frame was removed or didn't
// exist), we provide a different error message for backwards
// compatibility.
if (!root_frame_result->frame_responded) {
root_frame_result->error =
root_frame_id_ == ExtensionApiFrameIdMap::kTopFrameId
? "The tab was closed."
: "The frame was removed.";
}
Respond(Error(std::move(root_frame_result->error)));
return;
}
if (ShouldInsertCSS() || ShouldRemoveCSS()) {
// insertCSS and removeCSS don't have a result argument.
Respond(NoArguments());
return;
}
// Place the root frame result at the beginning.
std::iter_swap(root_frame_result, results.begin());
base::Value result_list(base::Value::Type::LIST);
for (auto& result : results) {
if (result.error.empty())
result_list.Append(std::move(result.value));
}
Respond(OneArgument(std::move(result_list)));
}
} // namespace extensions
#endif // EXTENSIONS_BROWSER_API_EXECUTE_CODE_FUNCTION_IMPL_H_
| 3,150 |
506 | // https://codeforces.com/contest/1186/problem/D
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
cin.tie(0);
ios::sync_with_stdio(0);
int n, s = 0;
cin >> n;
vector<ll> b(n);
vector<bool> c(n);
for (int i = 0; i < n; i++) {
double x;
cin >> x;
b[i] = ll(ceil(x));
c[i] = x != ceil(x);
s += b[i];
}
for (int i = 0; s; i++)
if (c[i])
b[i]--, s--;
for (ll x : b) cout << x << "\n";
}
| 243 |
678 | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>.
//
#import "MMService.h"
#import "MMService.h"
@class NSMutableArray, NSMutableDictionary, NSString, WAReportOuterMenuActionItem;
@interface WAWebViewReportStatMgr : MMService <MMService>
{
NSMutableDictionary *m_menuActionTimestampDict;
NSMutableDictionary *m_outActionTimestampDict;
NSMutableDictionary *m_apiActionDict;
NSMutableArray *m_mutiSelectMsgList;
unsigned long long m_stayTime;
unsigned long long m_costTime;
_Bool _isOpenDebugState;
unsigned int m_nsLastClickTimeStamp;
WAReportOuterMenuActionItem *m_mutiSelectBaseItem;
unsigned long long m_nsLastClickTimeInMs;
}
@property(nonatomic) _Bool isOpenDebugState; // @synthesize isOpenDebugState=_isOpenDebugState;
@property(nonatomic) unsigned int m_nsLastClickTimeStamp; // @synthesize m_nsLastClickTimeStamp;
@property(nonatomic) unsigned long long m_nsLastClickTimeInMs; // @synthesize m_nsLastClickTimeInMs;
@property(retain, nonatomic) WAReportOuterMenuActionItem *m_mutiSelectBaseItem; // @synthesize m_mutiSelectBaseItem;
- (void).cxx_destruct;
- (_Bool)getJSApiEventAction:(unsigned int)arg1 withActionItem:(id)arg2;
- (void)registerJSApiAction:(id)arg1 callid:(unsigned int)arg2;
- (_Bool)hasJSApiEventAction:(unsigned int)arg1;
- (_Bool)needReportJSApiAction:(id)arg1;
- (void)reportOutMenuActionOnMutiSelectMsgResult:(unsigned long long)arg1 contacts:(id)arg2;
- (void)registOutMenuActionOnMutiSelectMsgArray:(id)arg1;
- (id)outActionItemFromMgr:(unsigned long long)arg1;
- (void)registOutMenuAction:(id)arg1;
- (id)menuActionItemFromMgr:(unsigned long long)arg1;
- (void)registWebMenuAction:(unsigned long long)arg1;
- (unsigned long long)pageIndexCostTime;
- (unsigned long long)pageStayTime;
- (void)onWebPageIndexFinish;
- (void)onEnterNewPage;
- (void)onClick;
- (id)init;
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
| 772 |
2,151 | <gh_stars>1000+
print "sample\\path\\foo.cpp"
| 19 |
367 | from .drop import DropPath
from .inverted_residual import InvertedResidual, InvertedResidualV3
from .make_divisible import make_divisible
from .res_layer import ResLayer
from .se_layer import SELayer
from .self_attention_block import SelfAttentionBlock
from .up_conv_block import UpConvBlock
from .weight_init import trunc_normal_
__all__ = [
'ResLayer', 'SelfAttentionBlock', 'make_divisible', 'InvertedResidual',
'UpConvBlock', 'InvertedResidualV3', 'SELayer', 'DropPath', 'trunc_normal_'
]
| 170 |
23,901 | <reponame>DionysisChristopoulos/google-research<filename>group_agnostic_fairness/adversarial_reweighting_model.py
# coding=utf-8
# Copyright 2021 The Google Research 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.
# Lint as: python3
# pylint: disable=dangerous-default-value
"""A custom estimator for adversarial reweighting model."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.compat.v1 as tf
from tensorflow.contrib import framework as contrib_framework
from tensorflow.contrib import layers as contrib_layers
from tensorflow.contrib import metrics as contrib_metrics
class _AdversarialReweightingModel():
"""TensorFlow AdversarialReweightingModel base class.
AdversarialReweightingModel class can be used to define an adversarial
reweighting estimator.
Adversarial reweighting estimator can be used to train a model with two DNNs:
A primary DNN that trains for the main task.
A adversarial DNN that aims to assign weights to examples based on the
primary's example loss.
The two models are jointly trained to optimize for a min max problem between
primary and adversary by alternating between the two loss functions.
"""
def __init__(
self,
feature_columns,
label_column_name,
config,
model_dir,
primary_hidden_units=[64, 32],
adversary_hidden_units=[32],
batch_size=256,
primary_learning_rate=0.01,
adversary_learning_rate=0.01,
optimizer='Adagrad',
activation=tf.nn.relu,
adversary_loss_type='ce_loss',
adversary_include_label=True,
upweight_positive_instance_only=False,
pretrain_steps=5000
):
"""Initializes an adversarial reweighting estimator.
Args:
feature_columns: list of feature_columns.
label_column_name: (string) name of the target variable.
config: `RunConfig` object to configure the runtime settings.
model_dir: Directory to save model parameters, graph and etc. This can
also be used to load checkpoints from the directory into an estimator to
continue training a previously saved model.
primary_hidden_units: List with number of hidden units per layer for the
shared bottom. All layers are fully connected. Ex. `[64, 32]` means
first layer has 64 nodes and second one has 32.
adversary_hidden_units: List with number of hidden units per layer for the
shared bottom. All layers are fully connected. Ex. `[32]` means first
layer has 32 nodes.
batch_size: (int) batch size.
primary_learning_rate: learning rate of primary DNN.
adversary_learning_rate: learning rate of adversary DNN.
optimizer: An instance of `tf.Optimizer` used to train the model.
activation: Activation function applied to each layer.
adversary_loss_type: (string) specifying the type of loss function to be
used in adversary. Takes values in ["hinge_loss", "ce_loss"], which
stand for hinge loss, and sigmoid cross entropy loss, respectively.
adversary_include_label: Boolean flag. If set, adds label as input to the
adversary feature columns.
upweight_positive_instance_only: Boolean flag. If set, weights only
positive examples in adversary hinge_loss.
pretrain_steps: (int) The number of training steps for whih the model
should train only primary model, before switching to alternate training
between primary and adversary.
Raises:
ValueError: if label_column_name not specified.
ValueError: if primary_hidden_units is not a list.
ValueError: if adversary_hidden_units is not a list.
"""
if not label_column_name:
raise ValueError('Need to specify a label_column_name.')
if not isinstance(primary_hidden_units, list):
raise ValueError('primary_hidden_units should be a list of size 2.')
if not isinstance(adversary_hidden_units, list):
raise ValueError('adversary_hidden_units should be a list of size 1.')
self._feature_columns = feature_columns
self._primary_learning_rate = primary_learning_rate
self._adversary_learning_rate = adversary_learning_rate
self._optimizer = optimizer
self._model_dir = model_dir
self._primary_hidden_units = primary_hidden_units
self._adversary_hidden_units = adversary_hidden_units
self._config = config
self._activation = activation
self._batch_size = batch_size
self._label_column_name = label_column_name
self._adversary_include_label = adversary_include_label
self._adversary_loss_type = adversary_loss_type
self._pretrain_steps = pretrain_steps
self._upweight_positive_instance_only = upweight_positive_instance_only
def _primary_loss(self, labels, logits, example_weights):
"""Computes weighted sigmoid cross entropy loss.
Args:
labels: Labels.
logits: Logits.
example_weights: a float tensor of shape [batch_size, 1] for the
reweighting values for each example in the batch.
Returns:
loss: (scalar) loss
"""
with tf.name_scope(None, 'primary_loss', (logits, labels)) as name:
sigmoid_loss = tf.nn.sigmoid_cross_entropy_with_logits(
labels=labels, logits=logits, name=name)
primary_weighted_loss = (example_weights * sigmoid_loss)
primary_weighted_loss = tf.reduce_mean(primary_weighted_loss)
return primary_weighted_loss
def _get_hinge_loss(self, labels, logits, pos_weights):
"""Computes hinge loss over labels and logits from primary task.
Args:
labels: Labels.
logits: Logits.
pos_weights: a float tensor of shape [batch_size, 1]. Assigns weight 1
for positive examples, and weight 0 for negative examples in the batch.
Returns:
loss: a float tensor of shape [batch_size, 1] containing hinge loss.
"""
# If set, gives weight to only positive instances
if self._upweight_positive_instance_only:
hinge_loss = tf.losses.hinge_loss(
labels=labels, logits=logits, weights=pos_weights, reduction='none')
else:
hinge_loss = tf.losses.hinge_loss(labels=labels,
logits=logits,
reduction='none')
# To avoid numerical errors at loss = ``0''
hinge_loss = tf.maximum(hinge_loss, 0.1)
return hinge_loss
def _get_cross_entropy_loss(self, labels, logits):
"""Computes cross-entropy loss over labels and logits from primary task."""
return tf.nn.sigmoid_cross_entropy_with_logits(labels=labels, logits=logits)
def _adversary_loss(self,
labels,
logits,
pos_weights,
example_weights,
adversary_loss_type='hinge_loss'):
"""Computes (negative) adversary loss.
At the end of this function, the calculated loss
is multiplied with -1, so that it can be maximized later on by minimizing
the output of this function.
Args:
labels: Labels.
logits: Logits.
pos_weights: a float tensor of shape [batch_size, 1]
to compute weighted hinge_loss
example_weights: a float tensor of shape [batch_size, 1] for the
reweighting values for each example in the batch.
adversary_loss_type: (string) flag defining which loss type to use.
Takes values in ["hinge_loss","ce_loss"].
Returns:
loss: (scalar) loss
"""
with tf.name_scope(None, 'adversary_loss', (logits, labels, pos_weights)):
if adversary_loss_type == 'hinge_loss':
loss = self._get_hinge_loss(labels, logits, pos_weights)
tf.summary.histogram('hinge_loss', loss)
elif adversary_loss_type == 'ce_loss':
loss = self._get_cross_entropy_loss(labels, logits)
tf.summary.histogram('ce_loss', loss)
# Multiplies loss by -1 so that the adversary loss is maximimized.
adversary_weighted_loss = -(example_weights * loss)
return tf.reduce_mean(adversary_weighted_loss)
def _get_or_create_global_step_var(self):
"""Return the global_step variable, creating it if it does not exist.
Prefer GetGlobalStep if a tensor rather than a tf.Variable is sufficient.
Returns:
The global_step variable, or a new created one if it does not exist.
"""
return tf.train.get_or_create_global_step()
def _get_adversary_features_and_feature_columns(self, features, targets):
"""Return adversary features and feature columns."""
adversarial_features = features.copy()
adversary_feature_columns = self._feature_columns[:]
# Adds label to adversarial features
if self._adversary_include_label:
adversary_feature_columns.append(
tf.feature_column.numeric_column(self._label_column_name))
adversarial_features[self._label_column_name] = targets[
self._label_column_name]
return adversarial_features, adversary_feature_columns
def _compute_example_weights(self, adv_output_layer):
"""Applies sigmoid to adversary output layer and returns normalized example weight."""
example_weights = tf.nn.sigmoid(adv_output_layer)
mean_example_weights = tf.reduce_mean(example_weights)
example_weights /= tf.maximum(mean_example_weights, 1e-4)
example_weights = tf.ones_like(example_weights)+example_weights
return example_weights
def _get_model_fn(self):
"""Method that gets a model_fn for creating an `Estimator` Object."""
def model_fn(features, labels, mode):
"""AdversarialReweightingModel model_fn.
Args:
features: `Tensor` or `dict` of `Tensor`.
labels: A `dict` of `Tensor` Objects. Expects to have a key/value pair
for the key self.label_column_name.
mode: Defines whether this is training, evaluation or prediction. See
`ModeKeys`. Currently PREDICT mode is not implemented.
Returns:
An instance of `tf.estimator.EstimatorSpec', which encapsulates the
`mode`, `predictions`, `loss` and the `train_op`. Note that here
`predictions` is either a `Tensor` or a `dict` of `Tensor` objects,
representing the prediction of the bianry classification model.
'loss` is a scalar containing the loss of the step and `train_op` is the
op for training.
"""
# Instantiates a tensor with weight for positive class examples only
pos_weights = tf.cast(tf.equal(labels[self._label_column_name], 1),
dtype=tf.float32)
# Instantiates a tensor with true class labels
class_labels = labels[self._label_column_name]
# Initialize a global step variable used for alternate training
current_step = self._get_or_create_global_step_var()
if mode == tf.estimator.ModeKeys.EVAL:
tf.logging.info('model_fn: EVAL, {}'.format(mode))
elif mode == tf.estimator.ModeKeys.TRAIN:
tf.logging.info('model_fn: TRAIN, {}'.format(mode))
# Creates a DNN architecture for primary binary classification task
with tf.name_scope('primary_NN'):
with tf.variable_scope('primary'):
input_layer = tf.feature_column.input_layer(features,
self._feature_columns)
h1 = tf.layers.Dense(self._primary_hidden_units[0],
activation=self._activation)(input_layer)
h2 = tf.layers.Dense(self._primary_hidden_units[1],
activation=self._activation)(h1)
logits = tf.layers.Dense(1)(h2)
sigmoid_output = tf.nn.sigmoid(logits, name='sigmoid')
class_predictions = tf.cast(
tf.greater(sigmoid_output, 0.5), tf.float32)
tf.summary.histogram('class_predictions', class_predictions)
# Creates a network architecture for the adversarial regression task
with tf.name_scope('adversary_NN'):
with tf.variable_scope('adversary'):
# Gets adversary features and features columns
adversarial_features, adversary_feature_columns = self._get_adversary_features_and_feature_columns(features, labels) # pylint: disable=line-too-long
adv_input_layer = tf.feature_column.input_layer(
adversarial_features, adversary_feature_columns)
adv_h1 = tf.layers.Dense(self._adversary_hidden_units[0])(
adv_input_layer)
adv_output_layer = tf.layers.Dense(1, use_bias=True)(adv_h1)
example_weights = tf.cond(
tf.greater(current_step, self._pretrain_steps),
true_fn=lambda: self._compute_example_weights(adv_output_layer),
false_fn=lambda: tf.ones_like(class_labels))
# Adds summary variables to tensorboard
with tf.name_scope('example_weights'):
tf.summary.histogram('example_weights', example_weights)
tf.summary.histogram('label', class_labels)
# Initializes Loss Functions
primary_loss = self._primary_loss(class_labels, logits, example_weights)
adversary_loss = self._adversary_loss(class_labels, logits, pos_weights,
example_weights,
self._adversary_loss_type)
# Sets up dictionaries used for computing performance metrics
predictions = {
(self._label_column_name, 'class_ids'):
tf.reshape(class_predictions, [-1]),
(self._label_column_name, 'logistic'):
tf.reshape(sigmoid_output, [-1]),
('example_weights'):
tf.reshape(example_weights, [-1])
}
class_id_kwargs = {
'labels': class_labels,
'predictions': class_predictions
}
logistics_kwargs = {'labels': class_labels, 'predictions': sigmoid_output}
# EVAL Mode
if mode == tf.estimator.ModeKeys.EVAL:
with tf.name_scope('eval_metrics'):
eval_metric_ops = {
'accuracy': tf.metrics.accuracy(**class_id_kwargs),
'precision': tf.metrics.precision(**class_id_kwargs),
'recall': tf.metrics.recall(**class_id_kwargs),
'fp': tf.metrics.false_positives(**class_id_kwargs),
'fn': tf.metrics.false_negatives(**class_id_kwargs),
'tp': tf.metrics.true_positives(**class_id_kwargs),
'tn': tf.metrics.true_negatives(**class_id_kwargs),
'fpr': contrib_metrics.streaming_false_positive_rate(**class_id_kwargs), # pylint: disable=line-too-long
'fnr': contrib_metrics.streaming_false_negative_rate(**class_id_kwargs), # pylint: disable=line-too-long
'auc': tf.metrics.auc(curve='ROC', **logistics_kwargs),
'aucpr': tf.metrics.auc(curve='PR', **logistics_kwargs)
}
# EstimatorSpec object for evaluation
estimator_spec = tf.estimator.EstimatorSpec(
mode=mode,
predictions=predictions,
loss=primary_loss,
eval_metric_ops=eval_metric_ops)
# TRAIN Mode
if mode == tf.estimator.ModeKeys.TRAIN:
# Filters trainable variables for each task
all_trainable_vars = tf.trainable_variables()
primary_trainable_vars = [
v for v in all_trainable_vars if 'primary' in v.op.name
]
adversary_trainable_vars = [
v for v in all_trainable_vars if 'adversary' in v.op.name
]
# TRAIN_OP for adversary DNN
train_op_adversary = contrib_layers.optimize_loss(
loss=adversary_loss,
variables=adversary_trainable_vars,
global_step=contrib_framework.get_global_step(),
learning_rate=self._adversary_learning_rate,
optimizer=self._optimizer)
# TRAIN_OP for primary DNN
train_op_primary = contrib_layers.optimize_loss(
loss=primary_loss,
variables=primary_trainable_vars,
global_step=contrib_framework.get_global_step(),
learning_rate=self._primary_learning_rate,
optimizer=self._optimizer)
# Upto ``pretrain_steps'' trains primary only.
# Beyond ``pretrain_steps'' alternates between primary and adversary.
estimator_spec = tf.estimator.EstimatorSpec(
mode=mode,
predictions=predictions,
loss=primary_loss + adversary_loss,
train_op=tf.cond(
tf.greater(current_step, self._pretrain_steps),
true_fn=lambda: tf.group([train_op_primary, train_op_adversary]), # pylint: disable=line-too-long
false_fn=lambda: tf.group([train_op_primary])))
return estimator_spec
return model_fn
class _AdversarialReweightingEstimator(tf.estimator.Estimator):
"""An estimator based on the core estimator."""
def __init__(self, *args, **kwargs):
"""Initializes the estimator."""
self.model = _AdversarialReweightingModel(*args, **kwargs)
super(_AdversarialReweightingEstimator, self).__init__(
model_fn=self.model._get_model_fn(), # pylint: disable=protected-access
model_dir=self.model._model_dir, # pylint: disable=protected-access
config=self.model._config # pylint: disable=protected-access
)
def get_estimator(*args, **kwargs):
return _AdversarialReweightingEstimator(*args, **kwargs)
| 7,123 |
677 | /*
* Copyright (C) 2017 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#if ENABLE(B3_JIT)
#include "AirCode.h"
#include "AirTmp.h"
#include <wtf/IndexMap.h>
namespace JSC { namespace B3 { namespace Air {
// As an alternative to this, you could use IndexMap<Tmp::LinearlyIndexed, ...>, but this would fail
// as soon as you added a new GP tmp.
template<typename Value>
class TmpMap {
public:
TmpMap()
{
}
template<typename... Args>
TmpMap(Code& code, const Args&... args)
: m_gp(Tmp::absoluteIndexEnd(code, GP), args...)
, m_fp(Tmp::absoluteIndexEnd(code, FP), args...)
{
}
template<typename... Args>
void resize(Code& code, const Args&... args)
{
m_gp.resize(Tmp::absoluteIndexEnd(code, GP), args...);
m_fp.resize(Tmp::absoluteIndexEnd(code, FP), args...);
}
template<typename... Args>
void clear(const Args&... args)
{
m_gp.clear(args...);
m_fp.clear(args...);
}
const Value& operator[](Tmp tmp) const
{
if (tmp.isGP())
return m_gp[tmp];
return m_fp[tmp];
}
Value& operator[](Tmp tmp)
{
if (tmp.isGP())
return m_gp[tmp];
return m_fp[tmp];
}
template<typename PassedValue>
void append(Tmp tmp, PassedValue&& value)
{
if (tmp.isGP())
m_gp.append(tmp, std::forward<PassedValue>(value));
else
m_fp.append(tmp, std::forward<PassedValue>(value));
}
private:
IndexMap<Tmp::AbsolutelyIndexed<GP>, Value> m_gp;
IndexMap<Tmp::AbsolutelyIndexed<FP>, Value> m_fp;
};
} } } // namespace JSC::B3::Air
#endif // ENABLE(B3_JIT)
| 1,158 |
1,826 | package com.vladsch.flexmark.ext.wikilink.internal;
| 19 |
700 | <reponame>Robin5605/site
# Generated by Django 3.0.14 on 2021-11-05 05:18
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0072_merge_20210724_1354'),
('api', '0073_otn_allow_GT_and_LT'),
]
operations = [
]
| 128 |
371 | <reponame>sekikn2/bigtop
# pylint: disable=unused-argument
# 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.
from charms.reactive import when_any, is_state
from charmhelpers.core.hookenv import status_set
@when_any(
'bigtop.available',
'apache-bigtop-datanode.pending',
'apache-bigtop-nodemanager.pending',
'apache-bigtop-datanode.installed',
'apache-bigtop-nodemanager.installed',
'apache-bigtop-datanode.started',
'apache-bigtop-nodemanager.started',
'namenode.joined',
'namenode.ready',
'resourcemanager.joined',
'resourcemanager.ready',
)
def update_status():
hdfs_rel = is_state('namenode.joined')
yarn_rel = is_state('resourcemanager.joined')
hdfs_ready = is_state('namenode.ready')
yarn_ready = is_state('resourcemanager.ready')
if not (hdfs_rel or yarn_rel):
status_set('blocked',
'missing required namenode and/or resourcemanager relation')
elif hdfs_rel and not hdfs_ready:
status_set('waiting', 'waiting for hdfs to become ready')
elif yarn_rel and not yarn_ready:
status_set('waiting', 'waiting for yarn to become ready')
else:
ready = []
if hdfs_ready:
ready.append('datanode')
if yarn_ready:
ready.append('nodemanager')
status_set('active', 'ready ({})'.format(' & '.join(ready)))
| 747 |
23,572 | <reponame>suryatmodulus/puppeteer
{
"compilerOptions": {
"module": "commonjs",
"strict": true,
"outDir": "dist",
"moduleResolution": "node"
},
"files": ["good.ts", "bad.ts"]
}
| 90 |
4,772 | package example.repo;
import example.model.Customer1369;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
public interface Customer1369Repository extends CrudRepository<Customer1369, Long> {
List<Customer1369> findByLastName(String lastName);
}
| 87 |
2,706 | <reponame>17zhangw/peloton
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "any.h"
#include <kj/debug.h>
#if !CAPNP_LITE
#include "capability.h"
#endif // !CAPNP_LITE
namespace capnp {
#if !CAPNP_LITE
kj::Own<ClientHook> PipelineHook::getPipelinedCap(kj::Array<PipelineOp>&& ops) {
return getPipelinedCap(ops.asPtr());
}
kj::Own<ClientHook> AnyPointer::Reader::getPipelinedCap(
kj::ArrayPtr<const PipelineOp> ops) const {
_::PointerReader pointer = reader;
for (auto& op: ops) {
switch (op.type) {
case PipelineOp::Type::NOOP:
break;
case PipelineOp::Type::GET_POINTER_FIELD:
pointer = pointer.getStruct(nullptr).getPointerField(bounded(op.pointerIndex) * POINTERS);
break;
}
}
return pointer.getCapability();
}
AnyPointer::Pipeline AnyPointer::Pipeline::noop() {
auto newOps = kj::heapArray<PipelineOp>(ops.size());
for (auto i: kj::indices(ops)) {
newOps[i] = ops[i];
}
return Pipeline(hook->addRef(), kj::mv(newOps));
}
AnyPointer::Pipeline AnyPointer::Pipeline::getPointerField(uint16_t pointerIndex) {
auto newOps = kj::heapArray<PipelineOp>(ops.size() + 1);
for (auto i: kj::indices(ops)) {
newOps[i] = ops[i];
}
auto& newOp = newOps[ops.size()];
newOp.type = PipelineOp::GET_POINTER_FIELD;
newOp.pointerIndex = pointerIndex;
return Pipeline(hook->addRef(), kj::mv(newOps));
}
kj::Own<ClientHook> AnyPointer::Pipeline::asCap() {
return hook->getPipelinedCap(ops);
}
#endif // !CAPNP_LITE
Equality AnyStruct::Reader::equals(AnyStruct::Reader right) {
auto dataL = getDataSection();
size_t dataSizeL = dataL.size();
while(dataSizeL > 0 && dataL[dataSizeL - 1] == 0) {
-- dataSizeL;
}
auto dataR = right.getDataSection();
size_t dataSizeR = dataR.size();
while(dataSizeR > 0 && dataR[dataSizeR - 1] == 0) {
-- dataSizeR;
}
if(dataSizeL != dataSizeR) {
return Equality::NOT_EQUAL;
}
if(0 != memcmp(dataL.begin(), dataR.begin(), dataSizeL)) {
return Equality::NOT_EQUAL;
}
auto ptrsL = getPointerSection();
size_t ptrsSizeL = ptrsL.size();
while (ptrsSizeL > 0 && ptrsL[ptrsSizeL - 1].isNull()) {
-- ptrsSizeL;
}
auto ptrsR = right.getPointerSection();
size_t ptrsSizeR = ptrsR.size();
while (ptrsSizeR > 0 && ptrsR[ptrsSizeR - 1].isNull()) {
-- ptrsSizeR;
}
if(ptrsSizeL != ptrsSizeR) {
return Equality::NOT_EQUAL;
}
size_t i = 0;
auto eqResult = Equality::EQUAL;
for (; i < ptrsSizeL; i++) {
auto l = ptrsL[i];
auto r = ptrsR[i];
switch(l.equals(r)) {
case Equality::EQUAL:
break;
case Equality::NOT_EQUAL:
return Equality::NOT_EQUAL;
case Equality::UNKNOWN_CONTAINS_CAPS:
eqResult = Equality::UNKNOWN_CONTAINS_CAPS;
break;
default:
KJ_UNREACHABLE;
}
}
return eqResult;
}
kj::StringPtr KJ_STRINGIFY(Equality res) {
switch(res) {
case Equality::NOT_EQUAL:
return "NOT_EQUAL";
case Equality::EQUAL:
return "EQUAL";
case Equality::UNKNOWN_CONTAINS_CAPS:
return "UNKNOWN_CONTAINS_CAPS";
}
KJ_UNREACHABLE;
}
Equality AnyList::Reader::equals(AnyList::Reader right) {
if(size() != right.size()) {
return Equality::NOT_EQUAL;
}
if (getElementSize() != right.getElementSize()) {
return Equality::NOT_EQUAL;
}
auto eqResult = Equality::EQUAL;
switch(getElementSize()) {
case ElementSize::VOID:
case ElementSize::BIT:
case ElementSize::BYTE:
case ElementSize::TWO_BYTES:
case ElementSize::FOUR_BYTES:
case ElementSize::EIGHT_BYTES: {
size_t cmpSize = getRawBytes().size();
if (getElementSize() == ElementSize::BIT && size() % 8 != 0) {
// The list does not end on a byte boundary. We need special handling for the final
// byte because we only care about the bits that are actually elements of the list.
uint8_t mask = (1 << (size() % 8)) - 1; // lowest size() bits set
if ((getRawBytes()[cmpSize - 1] & mask) != (right.getRawBytes()[cmpSize - 1] & mask)) {
return Equality::NOT_EQUAL;
}
cmpSize -= 1;
}
if (memcmp(getRawBytes().begin(), right.getRawBytes().begin(), cmpSize) == 0) {
return Equality::EQUAL;
} else {
return Equality::NOT_EQUAL;
}
}
case ElementSize::POINTER:
case ElementSize::INLINE_COMPOSITE: {
auto llist = as<List<AnyStruct>>();
auto rlist = right.as<List<AnyStruct>>();
for(size_t i = 0; i < size(); i++) {
switch(llist[i].equals(rlist[i])) {
case Equality::EQUAL:
break;
case Equality::NOT_EQUAL:
return Equality::NOT_EQUAL;
case Equality::UNKNOWN_CONTAINS_CAPS:
eqResult = Equality::UNKNOWN_CONTAINS_CAPS;
break;
default:
KJ_UNREACHABLE;
}
}
return eqResult;
}
}
KJ_UNREACHABLE;
}
Equality AnyPointer::Reader::equals(AnyPointer::Reader right) {
if(getPointerType() != right.getPointerType()) {
return Equality::NOT_EQUAL;
}
switch(getPointerType()) {
case PointerType::NULL_:
return Equality::EQUAL;
case PointerType::STRUCT:
return getAs<AnyStruct>().equals(right.getAs<AnyStruct>());
case PointerType::LIST:
return getAs<AnyList>().equals(right.getAs<AnyList>());
case PointerType::CAPABILITY:
return Equality::UNKNOWN_CONTAINS_CAPS;
}
// There aren't currently any other types of pointers
KJ_UNREACHABLE;
}
bool AnyPointer::Reader::operator==(AnyPointer::Reader right) {
switch(equals(right)) {
case Equality::EQUAL:
return true;
case Equality::NOT_EQUAL:
return false;
case Equality::UNKNOWN_CONTAINS_CAPS:
KJ_FAIL_REQUIRE(
"operator== cannot determine equality of capabilities; use equals() instead if you need to handle this case");
}
KJ_UNREACHABLE;
}
bool AnyStruct::Reader::operator==(AnyStruct::Reader right) {
switch(equals(right)) {
case Equality::EQUAL:
return true;
case Equality::NOT_EQUAL:
return false;
case Equality::UNKNOWN_CONTAINS_CAPS:
KJ_FAIL_REQUIRE(
"operator== cannot determine equality of capabilities; use equals() instead if you need to handle this case");
}
KJ_UNREACHABLE;
}
bool AnyList::Reader::operator==(AnyList::Reader right) {
switch(equals(right)) {
case Equality::EQUAL:
return true;
case Equality::NOT_EQUAL:
return false;
case Equality::UNKNOWN_CONTAINS_CAPS:
KJ_FAIL_REQUIRE(
"operator== cannot determine equality of capabilities; use equals() instead if you need to handle this case");
}
KJ_UNREACHABLE;
}
} // namespace capnp
| 3,109 |
1,481 | <gh_stars>1000+
package apoc.math;
import apoc.util.TestUtil;
import org.apache.commons.math3.stat.regression.SimpleRegression;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.neo4j.test.rule.DbmsRule;
import org.neo4j.test.rule.ImpermanentDbmsRule;
import static org.junit.Assert.assertEquals;
/**
* @author <a href="mailto:<EMAIL>">AliArslan</a>
*/
public class RegressionTest {
@ClassRule
public static DbmsRule db = new ImpermanentDbmsRule();
@BeforeClass
public static void setUp() throws Exception {
TestUtil.registerProcedure(db, Regression.class);
}
@Test
public void testCalculateRegr() throws Throwable {
db.executeTransactionally("CREATE " +
"(:REGR_TEST {x_property: 1 , y_property: 2 })," +
"(:REGR_TEST {x_property: 2 , y_property: 3 })," +
"(:REGR_TEST {y_property: 10000 })," +
"(:REGR_TEST {x_property: 3 , y_property: 6 })");
SimpleRegression expectedRegr = new SimpleRegression(false);
expectedRegr.addData(new double[][]{
{1, 1},
{2, 3},
//{3, 10000},
{3, 6}
});
TestUtil.testCall(db, "CALL apoc.math.regr('REGR_TEST', 'y_property', 'x_property')",
result -> {
assertEquals(expectedRegr.getRSquare(), (Double)result.get("r2"), 0.1);
assertEquals(2.0, (Double)result.get("avgX"), 0.1);
assertEquals(3.67, (Double)result.get("avgY"), 0.1);
assertEquals(expectedRegr.getSlope(), (Double)result.get("slope"), 0.1);
});
}
@Test
public void testRegrR2isOne() throws Throwable {
db.executeTransactionally("CREATE " +
"(:REGR_TEST2 {x_property: 1 , y_property: 1 })," +
"(:REGR_TEST2 {x_property: 1 , y_property: 1 })," +
"(:REGR_TEST2 {y_property: 10000 })," +
"(:REGR_TEST2 {x_property: 1 , y_property: 1 })");
SimpleRegression expectedRegr = new SimpleRegression(false);
expectedRegr.addData(new double[][]{
{1, 1},
{1, 1},
//{3, 10000},
{1, 1}
});
TestUtil.testCall(db, "CALL apoc.math.regr('REGR_TEST2', 'y_property', 'x_property')",
result -> {
assertEquals(expectedRegr.getRSquare(), (Double)result.get("r2"), 0.1);
assertEquals(expectedRegr.getSlope(), (Double)result.get("slope"), 0.1);
});
}
}
| 1,327 |
1,031 | #!/usr/bin/env python
import sys
import os
def failed(message):
if message == "":
print("mkrelease.py failed to complete")
else:
print(message)
sys.exit(2)
import argparse
parser = argparse.ArgumentParser(description="Build a SWIG distribution source tarball swig-x.y.z.tar.gz and the Windows zip package swigwin-x.y.z.zip.\nUpload them both to SourceForge ready for release.\nThe release notes are also uploaded.")
parser.add_argument("version", help="version string in format x.y.z")
parser.add_argument("-b", "--branch", required=False, default="master", help="git branch name to create tarball from [master]")
parser.add_argument("-f", "--force-tag", required=False, action="store_true", help="force tag (replace git tag if it already exists)")
parser.add_argument("-s", "--skip-checks", required=False, action="store_true", help="skip checks (that local and remote repos are in sync)")
parser.add_argument("-u", "--username", required=False, help="SourceForge username (upload to SourceForge will be skipped if not provided)")
args = parser.parse_args()
version = args.version
branch = args.branch
dirname = "swig-" + version
force_tag = args.force_tag
skip_checks = args.skip_checks
username = args.username
print("Looking for rsync")
os.system("which rsync") and failed("rsync not installed/found. Please install.")
print("Making source tarball")
force = "--force-tag" if force_tag else ""
skip = "--skip-checks" if skip_checks else ""
os.system("python ./mkdist.py {} {} --branch {} {}".format(force, skip, branch, version)) and failed("")
print("Build Windows package")
os.system("./mkwindows.sh " + version) and failed("")
if username:
print("Uploading to SourceForge")
swig_dir_sf = username + ",<EMAIL>:/home/frs/project/s/sw/swig/swig/swig-" + version + "/"
swigwin_dir_sf = username + ",<EMAIL>:/home/frs/project/s/sw/swig/swigwin/swigwin-" + version + "/"
# If a file with 'readme' in the name exists in the same folder as the zip/tarball, it gets automatically displayed as the release notes by SF
full_readme_file = "readme-" + version + ".txt"
os.system("rm -f " + full_readme_file)
os.system("cat swig-" + version + "/README " + "swig-" + version + "/CHANGES.current " + "swig-" + version + "/RELEASENOTES " + "> " + full_readme_file)
os.system("rsync --archive --verbose -P --times -e ssh " + "swig-" + version + ".tar.gz " + full_readme_file + " " + swig_dir_sf) and failed("")
os.system("rsync --archive --verbose -P --times -e ssh " + "swigwin-" + version + ".zip " + full_readme_file + " " + swigwin_dir_sf) and failed("")
print("Finished")
print("Now log in to SourceForge and set the operating systems applicable to the newly uploaded tarball and zip file. Also remember to do a 'git push --tags'.")
| 919 |
2,151 | <filename>third_party/blink/renderer/core/animation/worklet_animation_controller.cc
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/animation/worklet_animation_controller.h"
#include "third_party/blink/renderer/core/animation/worklet_animation_base.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
WorkletAnimationController::WorkletAnimationController(Document* document)
: document_(document) {}
WorkletAnimationController::~WorkletAnimationController() = default;
void WorkletAnimationController::AttachAnimation(
WorkletAnimationBase& animation) {
DCHECK(IsMainThread());
DCHECK(!pending_animations_.Contains(&animation));
DCHECK(!compositor_animations_.Contains(&animation));
pending_animations_.insert(&animation);
DCHECK_EQ(document_, animation.GetDocument());
if (LocalFrameView* view = animation.GetDocument()->View())
view->ScheduleAnimation();
}
void WorkletAnimationController::DetachAnimation(
WorkletAnimationBase& animation) {
DCHECK(IsMainThread());
pending_animations_.erase(&animation);
compositor_animations_.erase(&animation);
}
void WorkletAnimationController::InvalidateAnimation(
WorkletAnimationBase& animation) {
DCHECK(IsMainThread());
pending_animations_.insert(&animation);
if (LocalFrameView* view = animation.GetDocument()->View())
view->ScheduleAnimation();
}
void WorkletAnimationController::UpdateAnimationCompositingStates() {
DCHECK(IsMainThread());
HeapHashSet<Member<WorkletAnimationBase>> animations;
animations.swap(pending_animations_);
for (const auto& animation : animations) {
if (animation->UpdateCompositingState()) {
compositor_animations_.insert(animation);
}
}
}
void WorkletAnimationController::UpdateAnimationTimings(
TimingUpdateReason reason) {
DCHECK(IsMainThread());
// Worklet animations inherited time values are only ever updated once per
// animation frame. This means the inherited time does not change outside of
// the frame so return early in the on-demand case.
if (reason == kTimingUpdateOnDemand)
return;
for (const auto& animation : compositor_animations_) {
animation->Update(reason);
}
}
void WorkletAnimationController::Trace(blink::Visitor* visitor) {
visitor->Trace(pending_animations_);
visitor->Trace(compositor_animations_);
visitor->Trace(document_);
}
} // namespace blink
| 825 |
471 | <gh_stars>100-1000
/////////////////////////////////////////////////////////////////////////////
// Name: class_webview.h
// Purpose: WebView classes group docs
// Author: wxWidgets team
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
/**
@defgroup group_class_webview WebView
@ingroup group_class
The wxWebView library is a set of classes for viewing complex web documents and
for internet browsing. It is built around a series of backends, and exposes
common functions for them.
*/ | 147 |
1,644 | // Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.util;
import com.google.common.reflect.Reflection;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Objects;
import javax.annotation.Nullable;
/**
* Abstract InvocationHandler comparing two implementations of some interface.
*
* <p>Given an interface, and two instances of that interface (the "original" instance we know
* works, and a "second" instance we wish to test), creates an InvocationHandler that acts like an
* exact proxy to the "original" instance.
*
* <p>In addition, it will log any differences in return values or thrown exception between the
* "original" and "second" instances.
*
* <p>This can be used to create an exact proxy to the original instance that can be placed in any
* code, while live testing the second instance.
*/
public abstract class ComparingInvocationHandler<T> implements InvocationHandler {
private final T actualImplementation;
private final T secondImplementation;
private final Class<T> interfaceClass;
/**
* Creates a new InvocationHandler for the given interface.
*
* @param interfaceClass the interface we want to create.
* @param actualImplementation the resulting proxy will be an exact proxy to this object
* @param secondImplementation Only used to log difference compared to actualImplementation.
* Otherwise has no effect on the resulting proxy's behavior.
*/
public ComparingInvocationHandler(
Class<T> interfaceClass, T actualImplementation, T secondImplementation) {
this.actualImplementation = actualImplementation;
this.secondImplementation = secondImplementation;
this.interfaceClass = interfaceClass;
}
/**
* Returns the proxy to the actualImplementation.
*
* <p>The return value is a drop-in replacement to the actualImplementation, but will log any
* difference with the secondImplementation during normal execution.
*/
public final T makeProxy() {
return Reflection.newProxy(interfaceClass, this);
}
/**
* Called when there was a difference between the implementations.
*
* @param method the method where the difference was found
* @param message human readable description of the difference found
*/
protected abstract void log(Method method, String message);
/**
* Implements toString for specific types.
*
* <p>By default objects are logged using their .toString. If .toString isn't implemented for
* some relevant classes (or if we want to use a different version), override this method with
* the desired implementation.
*
* @param method the method whose return value is given
* @param object the object returned by a call to method
*/
protected String stringifyResult(
@SuppressWarnings("unused") Method method,
@Nullable Object object) {
return String.valueOf(object);
}
/**
* Checks whether the method results are as similar as we expect.
*
* <p>By default objects are compared using their .equals. If .equals isn't implemented for some
* relevant classes (or if we want change what is considered "not equal"), override this method
* with the desired implementation.
*
* @param method the method whose return value is given
* @param actual the object returned by a call to method for the "actual" implementation
* @param second the object returned by a call to method for the "second" implementation
*/
protected boolean compareResults(
@SuppressWarnings("unused") Method method,
@Nullable Object actual,
@Nullable Object second) {
return Objects.equals(actual, second);
}
/**
* Checks whether the thrown exceptions are as similar as we expect.
*
* <p>By default this returns 'true' for any input: all we check by default is that both
* implementations threw something. Override if you need to actually compare both throwables.
*
* @param method the method whose return value is given
* @param actual the exception thrown by a call to method for the "actual" implementation
* @param second the exception thrown by a call to method for the "second" implementation
*/
protected boolean compareThrown(
@SuppressWarnings("unused") Method method,
Throwable actual,
Throwable second) {
return true;
}
/**
* Implements toString for thrown exceptions.
*
* <p>By default exceptions are logged using their .toString. If more data is needed (part of
* stack trace for example), override this method with the desired implementation.
*
* @param method the method whose return value is given
* @param throwable the exception thrown by a call to method
*/
protected String stringifyThrown(
@SuppressWarnings("unused") Method method,
Throwable throwable) {
return throwable.toString();
}
@Override
public final Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object actualResult = null;
Throwable actualException = null;
try {
actualResult = method.invoke(actualImplementation, args);
} catch (InvocationTargetException e) {
actualException = e.getCause();
}
Object secondResult = null;
Throwable secondException = null;
try {
secondResult = method.invoke(secondImplementation, args);
} catch (InvocationTargetException e) {
secondException = e.getCause();
}
// First compare the two implementations' result, and log any differences:
if (actualException != null && secondException != null) {
if (!compareThrown(method, actualException, secondException)) {
log(
method,
String.format(
"Both implementations threw, but got different exceptions! '%s' vs '%s'",
stringifyThrown(method, actualException),
stringifyThrown(method, secondException)));
}
} else if (actualException != null) {
log(
method,
String.format(
"Only actual implementation threw exception: %s",
stringifyThrown(method, actualException)));
} else if (secondException != null) {
log(
method,
String.format(
"Only second implementation threw exception: %s",
stringifyThrown(method, secondException)));
} else {
// Neither threw exceptions - we compare the results
if (!compareResults(method, actualResult, secondResult)) {
log(
method,
String.format(
"Got different results! '%s' vs '%s'",
stringifyResult(method, actualResult),
stringifyResult(method, secondResult)));
}
}
// Now reproduce the actual implementation's behavior:
if (actualException != null) {
throw actualException;
}
return actualResult;
}
}
| 2,292 |
792 | <filename>python/setup.py
"""
While inside this file folder, run `python setup.py install` or `python setup.py build` to compile this library
NOTE: Visual Studio is required to build C extensions on Windows.
"""
from distutils.core import setup, Extension
gjk = Extension(
name = "gjk",
sources = ["gjk_wrapper.c"],
include_dirs = [".."],
)
setup(
name = "gjk",
description = "Python wrapper of Igor Kroitor implementation Gilbert-Johnson-Keerthi (GJK) collision detection algorithm",
ext_modules = [gjk],
)
| 176 |
680 | <gh_stars>100-1000
package org.ff4j.hazelcast;
/*
* #%L
* ff4j-store-jcache
* %%
* Copyright (C) 2013 - 2015 FF4J
* %%
* 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%
*/
import javax.cache.CacheManager;
import org.ff4j.cache.FF4JCacheManager;
import org.ff4j.test.cache.AbstractCacheManagerJUnitTest;
import org.junit.BeforeClass;
/**
* Implementation of {@link CacheManager} for feautres and HazelCast
*
* @author <NAME> (@clunven)</a>
*/
public class CacheManagerHazelCastTest extends AbstractCacheManagerJUnitTest {
private static CacheManagerHazelCast cacheManagerHazelCast;
@BeforeClass
public static void setupHazelcast() {
cacheManagerHazelCast = new CacheManagerHazelCast();
}
/**
* {@inheritDoc}
*/
protected FF4JCacheManager getCacheManager() {
return cacheManagerHazelCast;
}
}
| 444 |
348 | <gh_stars>100-1000
{"nom":"Bazoncourt","circ":"3ème circonscription","dpt":"Moselle","inscrits":409,"abs":207,"votants":202,"blancs":6,"nuls":3,"exp":193,"res":[{"nuance":"LR","nom":"<NAME>-<NAME>","voix":128},{"nuance":"REM","nom":"<NAME>","voix":65}]} | 103 |
1,644 | // Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.tools;
import static google.registry.util.PreconditionsUtils.checkArgumentNotNull;
import static google.registry.util.PreconditionsUtils.checkArgumentPresent;
import com.beust.jcommander.Parameters;
import google.registry.config.RegistryEnvironment;
import google.registry.model.registrar.Registrar;
import javax.annotation.Nullable;
/** Command to update a Registrar. */
@Parameters(separators = " =", commandDescription = "Update registrar account(s)")
final class UpdateRegistrarCommand extends CreateOrUpdateRegistrarCommand {
@Override
Registrar getOldRegistrar(String clientId) {
return checkArgumentPresent(
Registrar.loadByRegistrarId(clientId), "Registrar %s not found", clientId);
}
@Override
void checkModifyAllowedTlds(@Nullable Registrar oldRegistrar) {
// Only allow modifying allowed TLDs if we're in a non-PRODUCTION environment, if the registrar
// is not REAL, or the registrar has a WHOIS abuse contact set.
checkArgumentNotNull(oldRegistrar, "Old registrar was not present during modification");
boolean isRealRegistrar =
Registrar.Type.REAL.equals(registrarType)
|| (Registrar.Type.REAL.equals(oldRegistrar.getType()) && registrarType == null);
if (RegistryEnvironment.PRODUCTION.equals(RegistryEnvironment.get()) && isRealRegistrar) {
checkArgumentPresent(
oldRegistrar.getWhoisAbuseContact(),
"Cannot modify allowed TLDs if there is no WHOIS abuse contact set. Please use the"
+ " \"nomulus registrar_contact\" command on this registrar to set a WHOIS abuse"
+ " contact.");
}
}
}
| 713 |
4,879 | <gh_stars>1000+
#ifndef OSMIUM_IO_WRITER_HPP
#define OSMIUM_IO_WRITER_HPP
/*
This file is part of Osmium (http://osmcode.org/libosmium).
Copyright 2013-2015 <NAME> <<EMAIL>> and others (see README).
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <memory>
#include <string>
#include <utility>
#include <osmium/io/compression.hpp>
#include <osmium/io/detail/output_format.hpp>
#include <osmium/io/detail/read_write.hpp>
#include <osmium/io/detail/write_thread.hpp>
#include <osmium/io/file.hpp>
#include <osmium/io/header.hpp>
#include <osmium/io/overwrite.hpp>
#include <osmium/memory/buffer.hpp>
#include <osmium/thread/util.hpp>
namespace osmium {
namespace io {
/**
* This is the user-facing interface for writing OSM files. Instantiate
* an object of this class with a file name or osmium::io::File object
* and optionally the data for the header and then call operator() on it
* to write Buffers. Call close() to finish up.
*/
class Writer {
osmium::io::File m_file;
osmium::io::detail::data_queue_type m_output_queue;
std::unique_ptr<osmium::io::detail::OutputFormat> m_output;
std::unique_ptr<osmium::io::Compressor> m_compressor;
std::future<bool> m_write_future;
public:
/**
* The constructor of the Writer object opens a file and writes the
* header to it.
*
* @param file File (contains name and format info) to open.
* @param header Optional header data. If this is not given sensible
* defaults will be used. See the default constructor
* of osmium::io::Header for details.
* @param allow_overwrite Allow overwriting of existing file? Can be
* osmium::io::overwrite::allow or osmium::io::overwrite::no
* (default).
*
* @throws std::runtime_error If the file could not be opened.
* @throws std::system_error If the file could not be opened.
*/
explicit Writer(const osmium::io::File& file, const osmium::io::Header& header = osmium::io::Header(), overwrite allow_overwrite = overwrite::no) :
m_file(file),
m_output_queue(20, "raw_output"), // XXX
m_output(osmium::io::detail::OutputFormatFactory::instance().create_output(m_file, m_output_queue)),
m_compressor(osmium::io::CompressionFactory::instance().create_compressor(file.compression(), osmium::io::detail::open_for_writing(m_file.filename(), allow_overwrite))),
m_write_future(std::async(std::launch::async, detail::WriteThread(m_output_queue, m_compressor.get()))) {
assert(!m_file.buffer());
m_output->write_header(header);
}
explicit Writer(const std::string& filename, const osmium::io::Header& header = osmium::io::Header(), overwrite allow_overwrite = overwrite::no) :
Writer(osmium::io::File(filename), header, allow_overwrite) {
}
explicit Writer(const char* filename, const osmium::io::Header& header = osmium::io::Header(), overwrite allow_overwrite = overwrite::no) :
Writer(osmium::io::File(filename), header, allow_overwrite) {
}
Writer(const Writer&) = delete;
Writer& operator=(const Writer&) = delete;
~Writer() {
close();
}
/**
* Write contents of a buffer to the output file.
*
* @throws Some form of std::runtime_error when there is a problem.
*/
void operator()(osmium::memory::Buffer&& buffer) {
osmium::thread::check_for_exception(m_write_future);
if (buffer.committed() > 0) {
m_output->write_buffer(std::move(buffer));
}
}
/**
* Flush writes to output file and closes it. If you do not
* call this, the destructor of Writer will also do the same
* thing. But because this call might thrown an exception,
* it is better to call close() explicitly.
*
* @throws Some form of std::runtime_error when there is a problem.
*/
void close() {
m_output->close();
osmium::thread::wait_until_done(m_write_future);
}
}; // class Writer
} // namespace io
} // namespace osmium
#endif // OSMIUM_IO_WRITER_HPP
| 2,474 |
577 | <filename>src/org/python/modules/_weakref/ReferenceBackend.java
package org.python.modules._weakref;
import org.python.core.PyObject;
import org.python.core.PyList;
public interface ReferenceBackend {
public PyObject get();
public void add(AbstractReference ref);
public boolean isCleared();
public AbstractReference find(Class<?> cls);
public int pythonHashCode();
public PyList refs();
public void restore(PyObject formerReferent);
public int count();
}
| 152 |
1,255 | /*
Copyright (c) 2009-2010 <NAME>. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of LibCat nor the names of its contributors may be used
to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CAT_EASY_HANDSHAKE_HPP
#define CAT_EASY_HANDSHAKE_HPP
#include <cat/crypt/tunnel/KeyAgreementInitiator.hpp>
#include <cat/crypt/tunnel/KeyAgreementResponder.hpp>
#include <cat/crypt/cookie/CookieJar.hpp>
namespace cat {
/*
The EasyHandshake classes implement a simplified version of my Tunnel protocol.
This only works for single-threaded servers and only produces a single authenticated encryption
object for each handshake. Explanations on how to use the library with a multi-threaded
server, and how to use one handshake to secure several TCP streams, are documented in the
comments of these classes.
Over the network, the handshake will look like this:
client --> server : CHALLENGE (64 random-looking bytes)
server --> client : ANSWER (128 random-looking bytes)
client --> server : PROOF (32 random-looking bytes) + first encrypted packet can be appended here
As far as coding goes, the function calls fit into the protocol like this:
server is offline:
During startup, both the client and server should initialize the library.
This is necessary also just for generating keys:
----------------------------------------------------------------
#include <cat/AllTunnel.hpp>
using namespace cat;
if (!EasyHandshake::Initialize())
{
printf("ERROR:Unable to initialize crypto subsystem\n");
}
----------------------------------------------------------------
Generate the server public and private key pairs:
----------------------------------------------------------------
u8 public_key[EasyHandshake::PUBLIC_KEY_BYTES];
u8 private_key[EasyHandshake::PRIVATE_KEY_BYTES];
EasyHandshake temp;
temp.GenerateServerKey(public_key, private_key);
----------------------------------------------------------------
(keys are stored to disk for reading on start-up)
(public key is given to the client somehow)
+ built into the client code
+ provided by a trusted server
server comes online:
----------------------------------------------------------------
ServerEasyHandshake server_handshake;
server_handshake.Initialize(public_key, private_key);
----------------------------------------------------------------
client comes online:
----------------------------------------------------------------
ClientEasyHandshake client_handshake;
client_handshake.Initialize(public_key);
u8 challenge[EasyHandshake::CHALLENGE_BYTES];
client_handshake.GenerateChallenge(challenge);
----------------------------------------------------------------
client --> server : CHALLENGE (64 random-looking bytes)
----------------------------------------------------------------
AuthenticatedEncryption server_e;
u8 answer[EasyHandshake::ANSWER_BYTES];
server_handshake.ProcessChallenge(challenge, answer, &server_e);
----------------------------------------------------------------
server --> client : ANSWER (128 random-looking bytes)
----------------------------------------------------------------
AuthenticatedEncryption client_e;
client_handshake.ProcessAnswer(answer, &client_e);
u8 proof[EasyHandshake::PROOF_BYTES];
client_e.GenerateProof(proof, EasyHandshake::PROOF_BYTES);
----------------------------------------------------------------
Encryption example:
----------------------------------------------------------------
// Example message encryption of "Hello". Note that encryption
// inflates the size of the message by OVERHEAD_BYTES.
const int PLAINTEXT_BYTES = 5;
const int BUFFER_BYTES = \
PLAINTEXT_BYTES + AuthenticatedEncryption::OVERHEAD_BYTES;
int msg_bytes = PLAINTEXT_BYTES;
// Note that it makes room for message inflation
const u8 message[CIPHERTEXT_BYTES] = {
'H', 'e', 'l', 'l', 'o'
};
// Note the second parameter is the size of the buffer, and
// the third parameter will be adjusted to the size of the
// encrypted message:
if (client_e.Encrypt(message, BUFFER_BYTES, msg_bytes))
{
// msg_bytes is now adjusted to be the size of the ciphertext
}
----------------------------------------------------------------
client --> server : PROOF (32 random-looking bytes) + first encrypted packet can be appended here
----------------------------------------------------------------
server_e.ValidateProof(proof, EasyHandshake::PROOF_BYTES);
----------------------------------------------------------------
Decryption example:
----------------------------------------------------------------
int buf_bytes = msg_bytes;
// The second parameter is the number of bytes in the encrypted message
if (server_e.Decrypt(message, buf_bytes))
{
// buf_bytes is now adjusted to be the size of the plaintext
}
----------------------------------------------------------------
During program termination, the client and server should clean up:
----------------------------------------------------------------
EasyHandshake::Shutdown();
----------------------------------------------------------------
NOTES:
Once the authenticated encryption objects are created, if the messages received are always
guaranteed to be in order, then the following flag can be set to make the object reject
packets received out of order, which would indicate tampering:
auth_enc.AllowOutOfOrder(false);
By default the messages are assumed to arrive in any order up to 1024 messages out of order.
The server similarly can encrypt messages the same way the client does in the examples.
Encrypted messages are inflated by 11 random-looking bytes for a MAC and an IV.
Modifications to the code can allow lower overhead if needed.
The EasyHandshake classes are *NOT* THREAD-SAFE.
The AuthenticatedEncryption class is *NOT* THREAD-SAFE. Simultaneously, only ONE thread
can be encrypting messages. And only ONE thread can be decrypting messages. Encryption
and decryption are separate and safe to perform simultaneously.
*/
/*
Common data needed for handshaking
*/
class CAT_EXPORT EasyHandshake
{
protected:
// Normally these would be created per-thread.
// To free memory associated with these objects just delete them.
BigTwistedEdwards *tls_math;
FortunaOutput *tls_csprng;
public:
static const int BITS = 256;
static const int BYTES = BITS / 8;
static const int PUBLIC_KEY_BYTES = BYTES * 2;
static const int PRIVATE_KEY_BYTES = BYTES;
static const int CHALLENGE_BYTES = BYTES * 2; // Packet # 1 in handshake, sent to server
static const int ANSWER_BYTES = BYTES * 4; // Packet # 2 in handshake, sent to client
static const int PROOF_BYTES = BYTES; // Packet # 3 in handshake, sent to server
static const int IDENTITY_BYTES = BYTES * 5; // [optional] Packet # 3 in handshake, sent to server, proves identity of client also
public:
// Demonstrates how to allocate and free the math and prng objects
EasyHandshake();
~EasyHandshake();
public:
static bool Initialize();
static void Shutdown();
public:
// Generate a server (public, private) key pair
// Connecting clients will need to know the public key in order to connect
bool GenerateServerKey(void *out_public_key /* EasyHandshake::PUBLIC_KEY_BYTES */,
void *out_private_key /* EasyHandshake::PRIVATE_KEY_BYTES */);
// Fills the given buffer with a variable number of random bytes
// Returns false on failure
bool GenerateRandomNumber(void *out_num, int bytes);
};
/*
Implements the simple case of a server that performs handshakes with clients
from a single thread. Note that this implementation is not thread-safe.
*/
class CAT_EXPORT ServerEasyHandshake : public EasyHandshake
{
KeyAgreementResponder tun_server;
public:
ServerEasyHandshake();
~ServerEasyHandshake();
// Prepare a cookie jar for hungry consumers
void FillCookieJar(CookieJar *jar);
// Provide the public and private key for the server, previously generated offline
bool Initialize(const void *in_public_key /* EasyHandshake::PUBLIC_KEY_BYTES */,
const void *in_private_key /* EasyHandshake::PRIVATE_KEY_BYTES */);
// Process a client challenge and generate a server answer
// Returns false if challenge was invalid
bool ProcessChallenge(const void *in_challenge /* EasyHandshake::CHALLENGE_BYTES */,
void *out_answer /* EasyHandshake::ANSWER_BYTES */,
AuthenticatedEncryption *auth_enc);
// Validate a client proof of identity
// Returns false if proof was invalid
bool VerifyInitiatorIdentity(const void *in_answer /* EasyHandshake::ANSWER_BYTES */,
const void *in_proof /* EasyHandshake::IDENTITY_BYTES */,
void *out_public_key /* EasyHandshake::PUBLIC_KEY_BYTES */);
};
/*
Implements the simple case of a client that performs handshakes with servers
from a single thread. Note that this implementation is not thread-safe.
*/
class CAT_EXPORT ClientEasyHandshake : public EasyHandshake
{
KeyAgreementInitiator tun_client;
public:
ClientEasyHandshake();
~ClientEasyHandshake();
// Provide the public key for the server, acquired through some secure means
bool Initialize(const void *in_public_key /* EasyHandshake::PUBLIC_KEY_BYTES */);
// (optional) Provide the identity for the client
bool SetIdentity(const void *in_public_key /* EasyHandshake::PUBLIC_KEY_BYTES */,
const void *in_private_key /* EasyHandshake::PRIVATE_KEY_BYTES */);
// Generate a challenge for the server to answer
bool GenerateChallenge(void *out_challenge /* EasyHandshake::CHALLENGE_BYTES */);
// Process a server answer to our challenge
// Returns false if answer was invalid
bool ProcessAnswer(const void *in_answer /* EasyHandshake::ANSWER_BYTES */,
AuthenticatedEncryption *auth_enc);
// Process a server answer to our challenge and provide a proof of client identity
// Returns false if answer was invalid
bool ProcessAnswerWithIdentity(const void *in_answer /* EasyHandshake::ANSWER_BYTES */,
void *out_identity /* EasyHandshake::IDENTITY_BYTES */,
AuthenticatedEncryption *auth_enc);
};
} // namespace cat
#endif // CAT_EASY_HANDSHAKE_HPP
| 3,569 |
575 | <gh_stars>100-1000
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_SAFE_BROWSING_CLOUD_CONTENT_SCANNING_BINARY_UPLOAD_SERVICE_FACTORY_H_
#define CHROME_BROWSER_SAFE_BROWSING_CLOUD_CONTENT_SCANNING_BINARY_UPLOAD_SERVICE_FACTORY_H_
#include "base/memory/singleton.h"
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
class KeyedService;
class Profile;
namespace safe_browsing {
class BinaryUploadService;
// Singleton that owns BinaryUploadService objects, one for each active
// Profile. It listens to profile destroy events and destroy its associated
// service. It returns a separate instance if the profile is in the Incognito
// mode.
class BinaryUploadServiceFactory : public BrowserContextKeyedServiceFactory {
public:
// Creates the service if it doesn't exist already for the given |profile|.
// If the service already exists, return its pointer.
static BinaryUploadService* GetForProfile(Profile* profile);
// Get the singleton instance.
static BinaryUploadServiceFactory* GetInstance();
private:
friend struct base::DefaultSingletonTraits<BinaryUploadServiceFactory>;
BinaryUploadServiceFactory();
~BinaryUploadServiceFactory() override = default;
// BrowserContextKeyedServiceFactory:
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* context) const override;
content::BrowserContext* GetBrowserContextToUse(
content::BrowserContext* context) const override;
DISALLOW_COPY_AND_ASSIGN(BinaryUploadServiceFactory);
};
} // namespace safe_browsing
#endif // CHROME_BROWSER_SAFE_BROWSING_CLOUD_CONTENT_SCANNING_BINARY_UPLOAD_SERVICE_FACTORY_H_
| 540 |
12,366 | // Copyright 2020 Google LLC
//
// 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.
//
///////////////////////////////////////////////////////////////////////////////
// Implementation of a StreamingAEAD Service.
#include "streaming_aead_impl.h"
#include "tink/streaming_aead.h"
#include "tink/binary_keyset_reader.h"
#include "tink/cleartext_keyset_handle.h"
#include "tink/util/istream_input_stream.h"
#include "tink/util/ostream_output_stream.h"
#include "tink/util/status.h"
#include "proto/testing/testing_api.grpc.pb.h"
namespace tink_testing_api {
namespace tinkutil = ::crypto::tink::util;
using ::crypto::tink::BinaryKeysetReader;
using ::crypto::tink::CleartextKeysetHandle;
using ::crypto::tink::InputStream;
using ::crypto::tink::util::IstreamInputStream;
using ::crypto::tink::util::OstreamOutputStream;
using ::grpc::ServerContext;
using ::grpc::Status;
// Encrypts a message
::grpc::Status StreamingAeadImpl::Encrypt(
grpc::ServerContext* context,
const StreamingAeadEncryptRequest* request,
StreamingAeadEncryptResponse* response) {
auto reader_result = BinaryKeysetReader::New(request->keyset());
if (!reader_result.ok()) {
response->set_err(reader_result.status().error_message());
return ::grpc::Status::OK;
}
auto handle_result =
CleartextKeysetHandle::Read(std::move(reader_result.ValueOrDie()));
if (!handle_result.ok()) {
response->set_err(handle_result.status().error_message());
return ::grpc::Status::OK;
}
auto streaming_aead_result =
handle_result.ValueOrDie()->GetPrimitive<crypto::tink::StreamingAead>();
if (!streaming_aead_result.ok()) {
response->set_err(streaming_aead_result.status().error_message());
return ::grpc::Status::OK;
}
auto ciphertext_stream = absl::make_unique<std::stringstream>();
auto ciphertext_buf = ciphertext_stream->rdbuf();
auto ciphertext_destination(
absl::make_unique<OstreamOutputStream>(std::move(ciphertext_stream)));
auto encrypting_stream_result =
streaming_aead_result.ValueOrDie()->NewEncryptingStream(
std::move(ciphertext_destination), request->associated_data());
if (!encrypting_stream_result.ok()) {
response->set_err(encrypting_stream_result.status().error_message());
return ::grpc::Status::OK;
}
auto encrypting_stream = std::move(encrypting_stream_result.ValueOrDie());
auto contents = request->plaintext();
void* buffer;
int pos = 0;
int remaining = contents.length();
int available_space = 0;
int available_bytes = 0;
while (remaining > 0) {
auto next_result = encrypting_stream->Next(&buffer);
if (!next_result.ok()) {
response->set_err(next_result.status().error_message());
return ::grpc::Status::OK;
}
available_space = next_result.ValueOrDie();
available_bytes = std::min(available_space, remaining);
memcpy(buffer, contents.data() + pos, available_bytes);
remaining -= available_bytes;
pos += available_bytes;
}
if (available_space > available_bytes) {
encrypting_stream->BackUp(available_space - available_bytes);
}
auto close_status = encrypting_stream->Close();
if (!close_status.ok()) {
response->set_err(close_status.error_message());
return ::grpc::Status::OK;
}
response->set_ciphertext(ciphertext_buf->str());
return ::grpc::Status::OK;
}
// Decrypts a ciphertext
::grpc::Status StreamingAeadImpl::Decrypt(
grpc::ServerContext* context,
const StreamingAeadDecryptRequest* request,
StreamingAeadDecryptResponse* response) {
auto reader_result = BinaryKeysetReader::New(request->keyset());
if (!reader_result.ok()) {
response->set_err(reader_result.status().error_message());
return ::grpc::Status::OK;
}
auto handle_result =
CleartextKeysetHandle::Read(std::move(reader_result.ValueOrDie()));
if (!handle_result.ok()) {
response->set_err(handle_result.status().error_message());
return ::grpc::Status::OK;
}
auto streaming_aead_result =
handle_result.ValueOrDie()->GetPrimitive<crypto::tink::StreamingAead>();
if (!streaming_aead_result.ok()) {
response->set_err(streaming_aead_result.status().error_message());
return ::grpc::Status::OK;
}
auto ciphertext_stream =
absl::make_unique<std::stringstream>(request->ciphertext());
std::unique_ptr<InputStream> ciphertext_source(
absl::make_unique<IstreamInputStream>(std::move(ciphertext_stream)));
auto decrypting_stream_result =
streaming_aead_result.ValueOrDie()->NewDecryptingStream(
std::move(ciphertext_source), request->associated_data());
if (!decrypting_stream_result.ok()) {
response->set_err(decrypting_stream_result.status().error_message());
return ::grpc::Status::OK;
}
auto decrypting_stream = std::move(decrypting_stream_result.ValueOrDie());
std::string plaintext;
const void* buffer;
while (true) {
auto next_result = decrypting_stream->Next(&buffer);
if (next_result.status().error_code() == tinkutil::error::OUT_OF_RANGE) {
// End of stream.
break;
}
if (!next_result.ok()) {
response->set_err(next_result.status().error_message());
return ::grpc::Status::OK;
}
auto read_bytes = next_result.ValueOrDie();
if (read_bytes > 0) {
plaintext.append(
std::string(reinterpret_cast<const char*>(buffer), read_bytes));
}
}
response->set_plaintext(plaintext);
return ::grpc::Status::OK;
}
} // namespace tink_testing_api
| 2,065 |
14,668 | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_BATTERY_NOTIFICATION_H_
#define ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_BATTERY_NOTIFICATION_H_
#include <cstdint>
#include "third_party/abseil-cpp/absl/types/optional.h"
namespace ash {
namespace quick_pair {
// Fast Pair battery information from notification. See
// https://developers.google.com/nearby/fast-pair/spec#BatteryNotification
struct BatteryInfo {
BatteryInfo();
explicit BatteryInfo(bool is_charging);
BatteryInfo(bool is_charging, int8_t percentage);
BatteryInfo(const BatteryInfo&);
BatteryInfo(BatteryInfo&&);
BatteryInfo& operator=(const BatteryInfo&);
BatteryInfo& operator=(BatteryInfo&&);
~BatteryInfo();
static absl::optional<BatteryInfo> FromByte(uint8_t byte);
uint8_t ToByte() const;
bool is_charging = false;
absl::optional<int8_t> percentage;
};
// Fast Pair battery notification. See
// https://developers.google.com/nearby/fast-pair/spec#BatteryNotification
struct BatteryNotification {
BatteryNotification();
BatteryNotification(bool show_ui,
BatteryInfo left_bud_info,
BatteryInfo right_bud_info,
BatteryInfo case_info);
BatteryNotification(const BatteryNotification&);
BatteryNotification(BatteryNotification&&);
BatteryNotification& operator=(const BatteryNotification&);
BatteryNotification& operator=(BatteryNotification&&);
~BatteryNotification();
static absl::optional<BatteryNotification> FromBytes(
const std::vector<uint8_t>& bytes,
bool show_ui);
bool show_ui = false;
BatteryInfo left_bud_info;
BatteryInfo right_bud_info;
BatteryInfo case_info;
};
} // namespace quick_pair
} // namespace ash
#endif // ASH_SERVICES_QUICK_PAIR_PUBLIC_CPP_BATTERY_NOTIFICATION_H_
| 667 |
353 | package com.wepay.waltz.server;
import com.wepay.riff.network.SSLConfig;
import com.wepay.riff.config.ConfigException;
import org.junit.Test;
import org.yaml.snakeyaml.Yaml;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class WaltzServerConfigTest {
@Test
public void testParsers() {
Map<Object, Object> map = new HashMap<>();
map.put(WaltzServerConfig.ZOOKEEPER_CONNECT_STRING, "fakehost:9999");
map.put(WaltzServerConfig.ZOOKEEPER_SESSION_TIMEOUT, "1000");
map.put(WaltzServerConfig.CLUSTER_ROOT, "/cluster");
map.put(WaltzServerConfig.SERVER_PORT, "8888");
map.put(WaltzServerConfig.OPTIMISTIC_LOCK_TABLE_SIZE, "2000");
map.put(WaltzServerConfig.FEED_CACHE_SIZE, "1000");
map.put(WaltzServerConfig.MIN_FETCH_SIZE, "50");
map.put(WaltzServerConfig.REALTIME_THRESHOLD, "500");
map.put(WaltzServerConfig.MAX_BATCH_SIZE, "500");
map.put(WaltzServerConfig.INITIAL_RETRY_INTERVAL, "30");
map.put(WaltzServerConfig.MAX_RETRY_INTERVAL, "30000");
WaltzServerConfig config = new WaltzServerConfig(map);
Object value;
value = config.get(WaltzServerConfig.ZOOKEEPER_CONNECT_STRING);
assertTrue(value instanceof String);
assertEquals("fakehost:9999", value);
value = config.get(WaltzServerConfig.ZOOKEEPER_SESSION_TIMEOUT);
assertTrue(value instanceof Integer);
assertEquals(1000, value);
value = config.get(WaltzServerConfig.CLUSTER_ROOT);
assertTrue(value instanceof String);
assertEquals("/cluster", value);
value = config.get(WaltzServerConfig.SERVER_PORT);
assertTrue(value instanceof Integer);
assertEquals(8888, value);
value = config.get(WaltzServerConfig.OPTIMISTIC_LOCK_TABLE_SIZE);
assertTrue(value instanceof Integer);
assertEquals(2000, value);
value = config.get(WaltzServerConfig.FEED_CACHE_SIZE);
assertTrue(value instanceof Integer);
assertEquals(1000, value);
value = config.get(WaltzServerConfig.MIN_FETCH_SIZE);
assertTrue(value instanceof Integer);
assertEquals(50, value);
value = config.get(WaltzServerConfig.REALTIME_THRESHOLD);
assertTrue(value instanceof Integer);
assertEquals(500, value);
value = config.get(WaltzServerConfig.MAX_BATCH_SIZE);
assertTrue(value instanceof Integer);
assertEquals(500, value);
value = config.get(WaltzServerConfig.INITIAL_RETRY_INTERVAL);
assertTrue(value instanceof Long);
assertEquals(30L, value);
value = config.get(WaltzServerConfig.MAX_RETRY_INTERVAL);
assertTrue(value instanceof Long);
assertEquals(30000L, value);
}
@Test
public void testDefaultValues() {
WaltzServerConfig config = new WaltzServerConfig(Collections.emptyMap());
Object value;
try {
value = config.get(WaltzServerConfig.ZOOKEEPER_CONNECT_STRING);
fail();
} catch (ConfigException ex) {
// Ignore
} catch (Exception ex) {
fail();
}
try {
value = config.get(WaltzServerConfig.ZOOKEEPER_SESSION_TIMEOUT);
fail();
} catch (ConfigException ex) {
// Ignore
} catch (Exception ex) {
fail();
}
try {
value = config.get(WaltzServerConfig.SERVER_PORT);
fail();
} catch (ConfigException ex) {
// Ignore
} catch (Exception ex) {
fail();
}
value = config.get(WaltzServerConfig.OPTIMISTIC_LOCK_TABLE_SIZE);
assertTrue(value instanceof Integer);
assertEquals(WaltzServerConfig.DEFAULT_OPTIMISTIC_LOCK_TABLE_SIZE, value);
value = config.get(WaltzServerConfig.FEED_CACHE_SIZE);
assertTrue(value instanceof Integer);
assertEquals(WaltzServerConfig.DEFAULT_FEED_CACHE_SIZE, value);
value = config.get(WaltzServerConfig.MIN_FETCH_SIZE);
assertTrue(value instanceof Integer);
assertEquals(WaltzServerConfig.DEFAULT_MIN_FETCH_SIZE, value);
value = config.get(WaltzServerConfig.REALTIME_THRESHOLD);
assertTrue(value instanceof Integer);
assertEquals(WaltzServerConfig.DEFAULT_REALTIME_THRESHOLD, value);
value = config.get(WaltzServerConfig.MAX_BATCH_SIZE);
assertTrue(value instanceof Integer);
assertEquals(WaltzServerConfig.DEFAULT_MAX_BATCH_SIZE, value);
value = config.get(WaltzServerConfig.INITIAL_RETRY_INTERVAL);
assertTrue(value instanceof Long);
assertEquals(WaltzServerConfig.DEFAULT_INITIAL_RETRY_INTERVAL, value);
value = config.get(WaltzServerConfig.MAX_RETRY_INTERVAL);
assertTrue(value instanceof Long);
assertEquals(WaltzServerConfig.DEFAULT_MAX_RETRY_INTERVAL, value);
}
@Test
public void testSSLConfigs() {
testSSLConfigs("");
testSSLConfigs("test.");
}
private void testSSLConfigs(String prefix) {
Map<Object, Object> map = new HashMap<>();
map.put(prefix + WaltzServerConfig.SERVER_SSL_CONFIG_PREFIX + SSLConfig.KEY_STORE_LOCATION, "/ks");
WaltzServerConfig serverConfig = new WaltzServerConfig(prefix, map);
SSLConfig config;
Object value;
config = serverConfig.getSSLConfig();
value = config.get(SSLConfig.KEY_STORE_LOCATION);
assertTrue(value instanceof String);
assertEquals("/ks", value);
}
@Test
public void testYamlNestedMap() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (OutputStreamWriter writer = new OutputStreamWriter(baos, StandardCharsets.UTF_8)) {
writer.write("zookeeper:\n");
writer.write(" connectString: fakehost:9999\n");
writer.write(" sessionTimeout: 30000\n");
writer.write("cluster.root: /cluster\n");
writer.write("server:\n");
writer.write(" port: 8888\n");
writer.write("storage:\n");
writer.write(" initialRetryInterval: 1000\n");
writer.write(" maxRetryInterval: \"10000\"\n");
}
try (InputStream input = new ByteArrayInputStream(baos.toByteArray())) {
WaltzServerConfig config = new WaltzServerConfig(new Yaml().load(input));
Object value;
value = config.get(WaltzServerConfig.ZOOKEEPER_CONNECT_STRING);
assertTrue(value instanceof String);
assertEquals("fakehost:9999", value);
value = config.get(WaltzServerConfig.ZOOKEEPER_SESSION_TIMEOUT);
assertTrue(value instanceof Integer);
assertEquals(30000, value);
value = config.get(WaltzServerConfig.CLUSTER_ROOT);
assertTrue(value instanceof String);
assertEquals("/cluster", value);
value = config.get(WaltzServerConfig.SERVER_PORT);
assertTrue(value instanceof Integer);
assertEquals(8888, value);
value = config.get(WaltzServerConfig.INITIAL_RETRY_INTERVAL);
assertTrue(value instanceof Long);
assertEquals(1000L, value);
value = config.get(WaltzServerConfig.MAX_RETRY_INTERVAL);
assertTrue(value instanceof Long);
assertEquals(10000L, value);
}
}
@Test
public void testYamlReference() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (OutputStreamWriter writer = new OutputStreamWriter(baos, StandardCharsets.UTF_8)) {
writer.write("commonSsl: &ssl\n");
writer.write(" keyStore:\n");
writer.write(" location: /ks\n");
writer.write(" password: <PASSWORD>");
writer.write("server:\n");
writer.write(" ssl: *ssl\n");
writer.write("storage:\n");
writer.write(" ssl: *ssl\n");
}
try (InputStream input = new ByteArrayInputStream(baos.toByteArray())) {
WaltzServerConfig config = new WaltzServerConfig(new Yaml().load(input));
SSLConfig sslConfig;
sslConfig = config.getSSLConfig();
assertEquals("/ks", sslConfig.get(SSLConfig.KEY_STORE_LOCATION));
assertEquals("secret", sslConfig.get(SSLConfig.KEY_STORE_PASSWORD));
sslConfig = config.getSSLConfig();
assertEquals("/ks", sslConfig.get(SSLConfig.KEY_STORE_LOCATION));
assertEquals("secret", sslConfig.get(SSLConfig.KEY_STORE_PASSWORD));
}
}
}
| 3,943 |
5,169 | {
"name": "EvoPayTokenizer",
"version": "1.1.6",
"summary": "EvoPayTokenizer helps you get a token for a bank card through evopay Payment Provider.",
"description": "EvoPayTokenizer provides a simple interface to get a token for a payment card, that your users specify. This token will further be used when working with other evopay services.",
"homepage": "https://tranzzo.com",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"EvoPay": "<EMAIL>"
},
"source": {
"git": "https://github.com/evo-company/ios-card-tokenizer.git",
"tag": "1.1.6"
},
"platforms": {
"ios": "9.0"
},
"source_files": "TranzzoTokenizer/**/*.{h,m,swift}",
"swift_versions": [
"5.0",
"5.1"
],
"swift_version": "5.1"
}
| 308 |
5,710 | <reponame>mattiapenati/web-frameworks
from masonite.request import Request
from masonite.controllers import Controller
class PageController(Controller):
def index(self):
return ""
def show_user(self, request: Request):
return request.param("id")
def create_user(self):
return ""
| 113 |
575 | // 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 "content/public/common/content_features.h"
#include "base/feature_list.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "content/common/buildflags.h"
#if defined(OS_WIN)
#include "base/win/windows_version.h"
#endif
namespace features {
// All features in alphabetical order.
// Enables the allowActivationDelegation attribute on iframes.
// https://www.chromestatus.com/features/6025124331388928
//
// TODO(mustaq): Deprecated, see kUserActivationPostMessageTransfer.
const base::Feature kAllowActivationDelegationAttr{
"AllowActivationDelegationAttr", base::FEATURE_DISABLED_BY_DEFAULT};
// Enables content-initiated, main frame navigations to data URLs.
// TODO(meacer): Remove when the deprecation is complete.
// https://www.chromestatus.com/feature/5669602927312896
const base::Feature kAllowContentInitiatedDataUrlNavigations{
"AllowContentInitiatedDataUrlNavigations",
base::FEATURE_DISABLED_BY_DEFAULT};
// Allows Blink to request fonts from the Android Downloadable Fonts API through
// the service implemented on the Java side.
const base::Feature kAndroidDownloadableFontsMatching{
"AndroidDownloadableFontsMatching", base::FEATURE_ENABLED_BY_DEFAULT};
#if defined(OS_WIN)
const base::Feature kAudioProcessHighPriorityWin{
"AudioProcessHighPriorityWin", base::FEATURE_DISABLED_BY_DEFAULT};
#endif
// Launches the audio service on the browser startup.
const base::Feature kAudioServiceLaunchOnStartup{
"AudioServiceLaunchOnStartup", base::FEATURE_DISABLED_BY_DEFAULT};
// Runs the audio service in a separate process.
const base::Feature kAudioServiceOutOfProcess {
"AudioServiceOutOfProcess",
// TODO(crbug.com/1052397): Remove !IS_CHROMEOS_LACROS once lacros starts being
// built with OS_CHROMEOS instead of OS_LINUX.
#if defined(OS_WIN) || defined(OS_MAC) || \
(defined(OS_LINUX) && !BUILDFLAG(IS_CHROMEOS_LACROS))
base::FEATURE_ENABLED_BY_DEFAULT
#else
base::FEATURE_DISABLED_BY_DEFAULT
#endif
};
// Enables the audio-service sandbox. This feature has an effect only when the
// kAudioServiceOutOfProcess feature is enabled.
const base::Feature kAudioServiceSandbox {
"AudioServiceSandbox",
#if defined(OS_WIN) || defined(OS_MAC) || defined(OS_FUCHSIA)
base::FEATURE_ENABLED_BY_DEFAULT
#else
base::FEATURE_DISABLED_BY_DEFAULT
#endif
};
// Kill switch for Background Fetch.
const base::Feature kBackgroundFetch{"BackgroundFetch",
base::FEATURE_ENABLED_BY_DEFAULT};
// Enable using the BackForwardCache.
const base::Feature kBackForwardCache{"BackForwardCache",
base::FEATURE_DISABLED_BY_DEFAULT};
// BackForwardCache is disabled on low memory devices. The threshold is defined
// via a field trial param: "memory_threshold_for_back_forward_cache_in_mb"
// It is compared against base::SysInfo::AmountOfPhysicalMemoryMB().
// "BackForwardCacheMemoryControls" is checked before "BackForwardCache". It
// means the low memory devices will activate neither the control group nor the
// experimental group of the BackForwardCache field trial.
// BackForwardCacheMemoryControls is enabled only on Android to disable
// BackForwardCache for lower memory devices due to memory limiations.
#if defined(OS_ANDROID)
const base::Feature kBackForwardCacheMemoryControls{
"BackForwardCacheMemoryControls", base::FEATURE_ENABLED_BY_DEFAULT};
#else
const base::Feature kBackForwardCacheMemoryControls{
"BackForwardCacheMemoryControls", base::FEATURE_DISABLED_BY_DEFAULT};
#endif
// Block subresource requests whose URLs contain embedded credentials (e.g.
// `https://user:[email protected]/resource`).
const base::Feature kBlockCredentialedSubresources{
"BlockCredentialedSubresources", base::FEATURE_ENABLED_BY_DEFAULT};
// When kBlockInsecurePrivateNetworkRequests is enabled, requests initiated
// from a less-private network may only target a more-private network if the
// initiating context is secure.
//
// See also:
// - https://wicg.github.io/cors-rfc1918/#integration-fetch
// - kBlockInsecurePrivateNetworkRequestsForNavigations
const base::Feature kBlockInsecurePrivateNetworkRequests{
"BlockInsecurePrivateNetworkRequests", base::FEATURE_DISABLED_BY_DEFAULT};
// When both kBlockInsecurePrivateNetworkRequestsForNavigations and
// kBlockInsecurePrivateNetworkRequests are enabled, navigations initiated
// by documents in a less-private network may only target a more-private network
// if the initiating context is secure.
const base::Feature kBlockInsecurePrivateNetworkRequestsForNavigations{
"BlockInsecurePrivateNetworkRequestsForNavigations",
base::FEATURE_DISABLED_BY_DEFAULT,
};
// Use ThreadPriority::DISPLAY for browser UI and IO threads.
#if defined(OS_ANDROID) || BUILDFLAG(IS_CHROMEOS_ASH)
const base::Feature kBrowserUseDisplayThreadPriority{
"BrowserUseDisplayThreadPriority", base::FEATURE_ENABLED_BY_DEFAULT};
#else
const base::Feature kBrowserUseDisplayThreadPriority{
"BrowserUseDisplayThreadPriority", base::FEATURE_DISABLED_BY_DEFAULT};
#endif
// When enabled, keyboard user activation will be verified by the browser side.
const base::Feature kBrowserVerifiedUserActivationKeyboard{
"BrowserVerifiedUserActivationKeyboard", base::FEATURE_DISABLED_BY_DEFAULT};
// When enabled, mouse user activation will be verified by the browser side.
const base::Feature kBrowserVerifiedUserActivationMouse{
"BrowserVerifiedUserActivationMouse", base::FEATURE_DISABLED_BY_DEFAULT};
// Enables code caching for inline scripts.
const base::Feature kCacheInlineScriptCode{"CacheInlineScriptCode",
base::FEATURE_ENABLED_BY_DEFAULT};
// If Canvas2D Image Chromium is allowed, this feature controls whether it is
// enabled.
const base::Feature kCanvas2DImageChromium {
"Canvas2DImageChromium",
#if defined(OS_MAC)
base::FEATURE_ENABLED_BY_DEFAULT
#else
base::FEATURE_DISABLED_BY_DEFAULT
#endif
};
// Clear the frame name for the top-level cross-browsing-context-group
// navigation.
const base::Feature kClearCrossBrowsingContextGroupMainFrameName{
"ClearCrossBrowsingContextGroupMainFrameName",
base::FEATURE_DISABLED_BY_DEFAULT};
const base::Feature kCapabilityDelegationPaymentRequest{
"CapabilityDelegationPaymentRequest", base::FEATURE_DISABLED_BY_DEFAULT};
const base::Feature kClickPointerEvent{"ClickPointerEvent",
base::FEATURE_DISABLED_BY_DEFAULT};
const base::Feature kCompositeBGColorAnimation{
"CompositeBGColorAnimation", base::FEATURE_DISABLED_BY_DEFAULT};
// When enabled, code cache does not use a browsing_data filter for deletions.
extern const base::Feature kCodeCacheDeletionWithoutFilter{
"CodeCacheDeletionWithoutFilter", base::FEATURE_ENABLED_BY_DEFAULT};
// When enabled, event.movement is calculated in blink instead of in browser.
const base::Feature kConsolidatedMovementXY{"ConsolidatedMovementXY",
base::FEATURE_ENABLED_BY_DEFAULT};
// Controls whether the Conversion Measurement API infrastructure is enabled.
const base::Feature kConversionMeasurement{"ConversionMeasurement",
base::FEATURE_ENABLED_BY_DEFAULT};
// Enables Blink cooperative scheduling.
const base::Feature kCooperativeScheduling{"CooperativeScheduling",
base::FEATURE_DISABLED_BY_DEFAULT};
// Enables crash reporting via Reporting API.
// https://www.w3.org/TR/reporting/#crash-report
const base::Feature kCrashReporting{"CrashReporting",
base::FEATURE_ENABLED_BY_DEFAULT};
// Enables support for the `Critical-CH` response header.
// https://github.com/WICG/client-hints-infrastructure/blob/master/reliability.md#critical-ch
const base::Feature kCriticalClientHint{"CriticalClientHint",
base::FEATURE_DISABLED_BY_DEFAULT};
// Puts save-data header in the holdback mode. This disables sending of
// save-data header to origins, and to the renderer processes within Chrome.
const base::Feature kDataSaverHoldback{"DataSaverHoldback",
base::FEATURE_DISABLED_BY_DEFAULT};
// Enable changing source dynamically for desktop capture.
const base::Feature kDesktopCaptureChangeSource{
"DesktopCaptureChangeSource", base::FEATURE_ENABLED_BY_DEFAULT};
// Enable document policy for configuring and restricting feature behavior.
const base::Feature kDocumentPolicy{"DocumentPolicy",
base::FEATURE_ENABLED_BY_DEFAULT};
// Enable document policy negotiation mechanism.
const base::Feature kDocumentPolicyNegotiation{
"DocumentPolicyNegotiation", base::FEATURE_DISABLED_BY_DEFAULT};
// Enable Early Hints subresource preloads for navigation.
const base::Feature kEarlyHintsPreloadForNavigation{
"EarlyHintsPreloadForNavigation", base::FEATURE_DISABLED_BY_DEFAULT};
// Requires documents embedded via <iframe>, etc, to explicitly opt-into the
// embedding: https://github.com/mikewest/embedding-requires-opt-in.
const base::Feature kEmbeddingRequiresOptIn{"EmbeddingRequiresOptIn",
base::FEATURE_DISABLED_BY_DEFAULT};
// Enables new canvas 2d api features. Enabled either with either
// enable-experimental-canvas-features or new-canvas-2d-api runtime flags
const base::Feature kEnableNewCanvas2DAPI{"EnableNewCanvas2DAPI",
base::FEATURE_DISABLED_BY_DEFAULT};
// If this feature is enabled and device permission is not granted by the user,
// media-device enumeration will provide at most one device per type and the
// device IDs will not be available.
// TODO(crbug.com/1019176): remove the feature in M89.
const base::Feature kEnumerateDevicesHideDeviceIDs {
"EnumerateDevicesHideDeviceIDs",
#if defined(OS_ANDROID)
base::FEATURE_DISABLED_BY_DEFAULT
#else
base::FEATURE_ENABLED_BY_DEFAULT
#endif
};
// When a screen reader is detected, allow users the option of letting
// Google provide descriptions for unlabeled images.
const base::Feature kExperimentalAccessibilityLabels{
"ExperimentalAccessibilityLabels", base::FEATURE_ENABLED_BY_DEFAULT};
// Content counterpart of ExperimentalContentSecurityPolicyFeatures in
// third_party/blink/renderer/platform/runtime_enabled_features.json5. Enables
// experimental Content Security Policy features ('navigate-to' and
// 'prefetch-src').
const base::Feature kExperimentalContentSecurityPolicyFeatures{
"ExperimentalContentSecurityPolicyFeatures",
base::FEATURE_DISABLED_BY_DEFAULT};
// Throttle tasks in Blink background timer queues based on CPU budgets
// for the background tab. Bug: https://crbug.com/639852.
const base::Feature kExpensiveBackgroundTimerThrottling{
"ExpensiveBackgroundTimerThrottling", base::FEATURE_ENABLED_BY_DEFAULT};
// Extra CORS safelisted headers. See https://crbug.com/999054.
const base::Feature kExtraSafelistedRequestHeadersForOutOfBlinkCors{
"ExtraSafelistedRequestHeadersForOutOfBlinkCors",
base::FEATURE_DISABLED_BY_DEFAULT};
// Controls whether Client Hints are guarded by Permissions Policy.
const base::Feature kFeaturePolicyForClientHints{
"FeaturePolicyForClientHints", base::FEATURE_ENABLED_BY_DEFAULT};
// Enables fixes for matching src: local() for web fonts correctly against full
// font name or postscript name. Rolling out behind a flag, as enabling this
// enables a font indexer on Android which we need to test in the field first.
const base::Feature kFontSrcLocalMatching{"FontSrcLocalMatching",
base::FEATURE_ENABLED_BY_DEFAULT};
#if !defined(OS_ANDROID)
// Feature controlling whether or not memory pressure signals will be forwarded
// to the GPU process.
const base::Feature kForwardMemoryPressureEventsToGpuProcess {
"ForwardMemoryPressureEventsToGpuProcess",
#if defined(OS_FUCHSIA) || defined(OS_WIN)
base::FEATURE_ENABLED_BY_DEFAULT
#else
base::FEATURE_DISABLED_BY_DEFAULT
#endif
};
#endif
// Enables scrollers inside Blink to store scroll offsets in fractional
// floating-point numbers rather than truncating to integers.
const base::Feature kFractionalScrollOffsets{"FractionalScrollOffsets",
base::FEATURE_DISABLED_BY_DEFAULT};
// Puts network quality estimate related Web APIs in the holdback mode. When the
// holdback is enabled the related Web APIs return network quality estimate
// set by the experiment (regardless of the actual quality).
const base::Feature kNetworkQualityEstimatorWebHoldback{
"NetworkQualityEstimatorWebHoldback", base::FEATURE_DISABLED_BY_DEFAULT};
// Determines if an extra brand version pair containing possibly escaped double
// quotes and escaped backslashed should be added to the Sec-CH-UA header
// (activated by kUserAgentClientHint)
const base::Feature kGreaseUACH{"GreaseUACH", base::FEATURE_ENABLED_BY_DEFAULT};
// If a page does a client side redirect or adds to the history without a user
// gesture, then skip it on back/forward UI.
const base::Feature kHistoryManipulationIntervention{
"HistoryManipulationIntervention", base::FEATURE_ENABLED_BY_DEFAULT};
// Prevents sandboxed iframes from using the history API to navigate frames
// outside their subttree, if they are restricted from doing top-level
// navigations.
const base::Feature kHistoryPreventSandboxedNavigation{
"HistoryPreventSandboxedNavigation", base::FEATURE_ENABLED_BY_DEFAULT};
// This is intended as a kill switch for the Idle Detection feature. To enable
// this feature, the experimental web platform features flag should be set,
// or the site should obtain an Origin Trial token.
const base::Feature kIdleDetection{"IdleDetection",
base::FEATURE_ENABLED_BY_DEFAULT};
// Kill switch for the GetInstalledRelatedApps API.
const base::Feature kInstalledApp{"InstalledApp",
base::FEATURE_ENABLED_BY_DEFAULT};
// Allow Windows specific implementation for the GetInstalledRelatedApps API.
const base::Feature kInstalledAppProvider{"InstalledAppProvider",
base::FEATURE_ENABLED_BY_DEFAULT};
// Show warning about clearing data from installed apps in the clear browsing
// data flow. The warning will be shown in a second dialog.
const base::Feature kInstalledAppsInCbd{"InstalledAppsInCbd",
base::FEATURE_DISABLED_BY_DEFAULT};
// Alternative to switches::kIsolateOrigins, for turning on origin isolation.
// List of origins to isolate has to be specified via
// kIsolateOriginsFieldTrialParamName.
const base::Feature kIsolateOrigins{"IsolateOrigins",
base::FEATURE_DISABLED_BY_DEFAULT};
const char kIsolateOriginsFieldTrialParamName[] = "OriginsList";
// Experimental handling of accept-language via client hints.
const base::Feature kLangClientHintHeader{"LangClientHintHeader",
base::FEATURE_DISABLED_BY_DEFAULT};
const base::Feature kLazyFrameLoading{"LazyFrameLoading",
base::FEATURE_ENABLED_BY_DEFAULT};
const base::Feature kLazyFrameVisibleLoadTimeMetrics {
"LazyFrameVisibleLoadTimeMetrics",
#if defined(OS_ANDROID)
base::FEATURE_ENABLED_BY_DEFAULT
#else
base::FEATURE_DISABLED_BY_DEFAULT
#endif
};
const base::Feature kLazyImageLoading{"LazyImageLoading",
base::FEATURE_ENABLED_BY_DEFAULT};
const base::Feature kLazyImageVisibleLoadTimeMetrics {
"LazyImageVisibleLoadTimeMetrics",
#if defined(OS_ANDROID)
base::FEATURE_ENABLED_BY_DEFAULT
#else
base::FEATURE_DISABLED_BY_DEFAULT
#endif
};
// Enable lazy initialization of the media controls.
const base::Feature kLazyInitializeMediaControls{
"LazyInitializeMediaControls", base::FEATURE_ENABLED_BY_DEFAULT};
// Configures whether Blink on Windows 8.0 and below should use out of process
// API font fallback calls to retrieve a fallback font family name as opposed to
// using a hard-coded font lookup table.
const base::Feature kLegacyWindowsDWriteFontFallback{
"LegacyWindowsDWriteFontFallback", base::FEATURE_DISABLED_BY_DEFAULT};
const base::Feature kLogJsConsoleMessages {
"LogJsConsoleMessages",
#if defined(OS_ANDROID)
base::FEATURE_DISABLED_BY_DEFAULT
#else
base::FEATURE_ENABLED_BY_DEFAULT
#endif
};
// The MBI mode controls whether or not communication over the
// AgentSchedulingGroup is ordered with respect to the render-process-global
// legacy IPC channel, as well as the granularity of AgentSchedulingGroup
// creation. This will break ordering guarantees between different agent
// scheduling groups (ordering withing a group is still preserved).
// DO NOT USE! The feature is not yet fully implemented. See crbug.com/1111231.
const base::Feature kMBIMode {
"MBIMode",
#if BUILDFLAG(MBI_MODE_PER_RENDER_PROCESS_HOST) || \
BUILDFLAG(MBI_MODE_PER_SITE_INSTANCE)
base::FEATURE_ENABLED_BY_DEFAULT
#else
base::FEATURE_DISABLED_BY_DEFAULT
#endif
};
const base::FeatureParam<MBIMode>::Option mbi_mode_types[] = {
{MBIMode::kLegacy, "legacy"},
{MBIMode::kEnabledPerRenderProcessHost, "per_render_process_host"},
{MBIMode::kEnabledPerSiteInstance, "per_site_instance"}};
const base::FeatureParam<MBIMode> kMBIModeParam {
&kMBIMode, "mode",
#if BUILDFLAG(MBI_MODE_PER_RENDER_PROCESS_HOST)
MBIMode::kEnabledPerRenderProcessHost,
#elif BUILDFLAG(MBI_MODE_PER_SITE_INSTANCE)
MBIMode::kEnabledPerSiteInstance,
#else
MBIMode::kLegacy,
#endif
&mbi_mode_types
};
// If this feature is enabled, media-device enumerations use a cache that is
// invalidated upon notifications sent by base::SystemMonitor. If disabled, the
// cache is considered invalid on every enumeration request.
const base::Feature kMediaDevicesSystemMonitorCache {
"MediaDevicesSystemMonitorCaching",
#if defined(OS_MAC) || defined(OS_WIN)
base::FEATURE_ENABLED_BY_DEFAULT
#else
base::FEATURE_DISABLED_BY_DEFAULT
#endif
};
// If enabled Mojo uses a dedicated background thread to listen for incoming
// IPCs. Otherwise it's configured to use Content's IO thread for that purpose.
const base::Feature kMojoDedicatedThread{"MojoDedicatedThread",
base::FEATURE_DISABLED_BY_DEFAULT};
// Enables/disables the video capture service.
const base::Feature kMojoVideoCapture{"MojoVideoCapture",
base::FEATURE_ENABLED_BY_DEFAULT};
// A secondary switch used in combination with kMojoVideoCapture.
// This is intended as a kill switch to allow disabling the service on
// particular groups of devices even if they forcibly enable kMojoVideoCapture
// via a command-line argument.
const base::Feature kMojoVideoCaptureSecondary{
"MojoVideoCaptureSecondary", base::FEATURE_ENABLED_BY_DEFAULT};
// When enable, iframe does not implicit capture mouse event.
const base::Feature kMouseSubframeNoImplicitCapture{
"MouseSubframeNoImplicitCapture", base::FEATURE_DISABLED_BY_DEFAULT};
// If the network service is enabled, runs it in process.
const base::Feature kNetworkServiceInProcess {
"NetworkServiceInProcess",
#if defined(OS_ANDROID)
base::FEATURE_ENABLED_BY_DEFAULT
#else
base::FEATURE_DISABLED_BY_DEFAULT
#endif
};
const base::Feature kNeverSlowMode{"NeverSlowMode",
base::FEATURE_DISABLED_BY_DEFAULT};
// Kill switch for Web Notification content images.
const base::Feature kNotificationContentImage{"NotificationContentImage",
base::FEATURE_ENABLED_BY_DEFAULT};
// Enables the notification trigger API.
const base::Feature kNotificationTriggers{"NotificationTriggers",
base::FEATURE_ENABLED_BY_DEFAULT};
// Controls the Origin-Agent-Cluster header. Tracking bug
// https://crbug.com/1042415; flag removal bug (for when this is fully launched)
// https://crbug.com/1148057.
//
// The name is "OriginIsolationHeader" because that was the old name when the
// feature was under development.
const base::Feature kOriginIsolationHeader{"OriginIsolationHeader",
base::FEATURE_ENABLED_BY_DEFAULT};
// Origin Policy. See https://crbug.com/751996
const base::Feature kOriginPolicy{"OriginPolicy",
base::FEATURE_DISABLED_BY_DEFAULT};
// Some WebXR features may have been enabled for ARCore, but are not yet ready
// to be plumbed up from the OpenXR backend. This feature provides a mechanism
// to gate such support in a generic way. Note that this feature should not be
// used for features we intend to ship simultaneously on both OpenXR and ArCore.
// For those features, a feature-specific flag should be created if needed.
const base::Feature kOpenXrExtendedFeatureSupport{
"OpenXrExtendedFeatureSupport", base::FEATURE_DISABLED_BY_DEFAULT};
// History navigation in response to horizontal overscroll (aka gesture-nav).
const base::Feature kOverscrollHistoryNavigation{
"OverscrollHistoryNavigation", base::FEATURE_ENABLED_BY_DEFAULT};
// Whether web apps can run periodic tasks upon network connectivity.
const base::Feature kPeriodicBackgroundSync{"PeriodicBackgroundSync",
base::FEATURE_DISABLED_BY_DEFAULT};
// If Pepper 3D Image Chromium is allowed, this feature controls whether it is
// enabled.
const base::Feature kPepper3DImageChromium {
"Pepper3DImageChromium",
#if defined(OS_MAC)
base::FEATURE_ENABLED_BY_DEFAULT
#else
base::FEATURE_DISABLED_BY_DEFAULT
#endif
};
// Kill-switch to introduce a compatibility breaking restriction.
const base::Feature kPepperCrossOriginRedirectRestriction{
"PepperCrossOriginRedirectRestriction", base::FEATURE_ENABLED_BY_DEFAULT};
// All ProcessHost objects live on UI thread.
// https://crbug.com/904556
const base::Feature kProcessHostOnUI{"ProcessHostOnUI",
base::FEATURE_DISABLED_BY_DEFAULT};
// Enable in-browser script loading for a brand new service worker.
const base::Feature kPlzServiceWorker{"PlzServiceWorker",
base::FEATURE_DISABLED_BY_DEFAULT};
// Enables process sharing for sites that do not require a dedicated process
// by using a default SiteInstance. Default SiteInstances will only be used
// on platforms that do not use full site isolation.
// Note: This feature is mutally exclusive with
// kProcessSharingWithStrictSiteInstances. Only one of these should be enabled
// at a time.
const base::Feature kProcessSharingWithDefaultSiteInstances{
"ProcessSharingWithDefaultSiteInstances", base::FEATURE_ENABLED_BY_DEFAULT};
// Whether cross-site frames should get their own SiteInstance even when
// strict site isolation is disabled. These SiteInstances will still be
// grouped into a shared default process based on BrowsingInstance.
const base::Feature kProcessSharingWithStrictSiteInstances{
"ProcessSharingWithStrictSiteInstances", base::FEATURE_DISABLED_BY_DEFAULT};
// Tells the RenderFrameHost to send beforeunload messages on a different
// local frame interface which will handle the messages at a higher priority.
const base::Feature kHighPriorityBeforeUnload{
"HighPriorityBeforeUnload", base::FEATURE_DISABLED_BY_DEFAULT};
// Under this flag bootstrap (aka startup) tasks will be prioritized. This flag
// is used by various modules to determine whether special scheduling
// arrangements need to be made to prioritize certain tasks.
const base::Feature kPrioritizeBootstrapTasks = {
"PrioritizeBootstrapTasks", base::FEATURE_ENABLED_BY_DEFAULT};
// Enable the ProactivelySwapBrowsingInstance experiment. A browsing instance
// represents a set of frames that can script each other. Currently, Chrome does
// not always switch BrowsingInstance when navigating in between two unrelated
// pages. This experiment makes Chrome swap BrowsingInstances for cross-site
// HTTP(S) navigations when the BrowsingInstance doesn't contain any other
// windows.
const base::Feature kProactivelySwapBrowsingInstance{
"ProactivelySwapBrowsingInstance", base::FEATURE_DISABLED_BY_DEFAULT};
// Fires the `pushsubscriptionchange` event defined here:
// https://w3c.github.io/push-api/#the-pushsubscriptionchange-event
// for subscription refreshes, revoked permissions or subscription losses
const base::Feature kPushSubscriptionChangeEvent{
"PushSubscriptionChangeEvent", base::FEATURE_DISABLED_BY_DEFAULT};
// Enables the Direct Sockets API.
const base::Feature kDirectSockets{"DirectSockets",
base::FEATURE_DISABLED_BY_DEFAULT};
// Causes hidden tabs with crashed subframes to be marked for reload, meaning
// that if a user later switches to that tab, the current page will be
// reloaded. This will hide crashed subframes from the user at the cost of
// extra reloads.
const base::Feature kReloadHiddenTabsWithCrashedSubframes {
"ReloadHiddenTabsWithCrashedSubframes",
#if defined(OS_ANDROID)
base::FEATURE_ENABLED_BY_DEFAULT
#else
base::FEATURE_DISABLED_BY_DEFAULT
#endif
};
// RenderDocument:
//
// Currently, a RenderFrameHost represents neither a frame nor a document, but a
// frame in a given process. A new one is created after a different-process
// navigation. The goal of RenderDocument is to get a new one for each document
// instead.
//
// Design doc: https://bit.ly/renderdocument
// Main bug tracker: https://crbug.com/936696
// Enable using the RenderDocument.
const base::Feature kRenderDocument{"RenderDocument",
base::FEATURE_ENABLED_BY_DEFAULT};
// Enables skipping the early call to CommitPending when navigating away from a
// crashed frame.
const base::Feature kSkipEarlyCommitPendingForCrashedFrame{
"SkipEarlyCommitPendingForCrashedFrame", base::FEATURE_DISABLED_BY_DEFAULT};
// Run video capture service in the Browser process as opposed to a dedicated
// utility process
const base::Feature kRunVideoCaptureServiceInBrowserProcess{
"RunVideoCaptureServiceInBrowserProcess",
base::FEATURE_DISABLED_BY_DEFAULT};
// Enables saving pages as Web Bundle.
const base::Feature kSavePageAsWebBundle{"SavePageAsWebBundle",
base::FEATURE_DISABLED_BY_DEFAULT};
// Browser-side feature flag for SecurePaymentConfirmation, which can be used to
// disable the feature. Enabling the browser-side feature by itself does not
// actually enable the feature by default. The feature is also controlled by the
// Blink runtime feature "SecurePaymentConfirmation". Both have to be enabled
// for SecurePaymentConfirmation to be available.
const base::Feature kSecurePaymentConfirmation {
"SecurePaymentConfirmationBrowser",
#if defined(OS_MAC) || defined(OS_WIN)
base::FEATURE_ENABLED_BY_DEFAULT
#else
base::FEATURE_DISABLED_BY_DEFAULT
#endif
};
// Used to control whether to remove the restriction that PaymentCredential in
// WebAuthn and secure payment confirmation method in PaymentRequest API must
// use a user verifying platform authenticator. When enabled, this allows using
// such devices as UbiKey on Linux, which can make development easier.
const base::Feature kSecurePaymentConfirmationDebug{
"SecurePaymentConfirmationDebug", base::FEATURE_DISABLED_BY_DEFAULT};
// Make sendBeacon throw for a Blob with a non simple type.
const base::Feature kSendBeaconThrowForBlobWithNonSimpleType{
"SendBeaconThrowForBlobWithNonSimpleType",
base::FEATURE_DISABLED_BY_DEFAULT};
// Service worker based payment apps as defined by w3c here:
// https://w3c.github.io/webpayments-payment-apps-api/
// TODO(rouslan): Remove this.
const base::Feature kServiceWorkerPaymentApps{"ServiceWorkerPaymentApps",
base::FEATURE_ENABLED_BY_DEFAULT};
// If enabled, prefer to start service workers in an unused renderer process if
// available. This helps let navigations and service workers use the same
// process when a process was already created for a navigation but not yet
// claimed by it (as is common for navigations from the Android New Tab Page).
const base::Feature kServiceWorkerPrefersUnusedProcess{
"ServiceWorkerPrefersUnusedProcess", base::FEATURE_DISABLED_BY_DEFAULT};
// Use this feature to experiment terminating a service worker when it doesn't
// control any clients: https://crbug.com/1043845.
const base::Feature kServiceWorkerTerminationOnNoControllee{
"ServiceWorkerTerminationOnNoControllee",
base::FEATURE_DISABLED_BY_DEFAULT};
// http://tc39.github.io/ecmascript_sharedmem/shmem.html
// This feature is also enabled independently of this flag for cross-origin
// isolated renderers.
const base::Feature kSharedArrayBuffer{"SharedArrayBuffer",
base::FEATURE_DISABLED_BY_DEFAULT};
// If enabled, SharedArrayBuffer is present and can be transferred on desktop
// platforms. This flag is used only as a "kill switch" as we migrate towards
// requiring 'crossOriginIsolated'.
const base::Feature kSharedArrayBufferOnDesktop{
"SharedArrayBufferOnDesktop", base::FEATURE_ENABLED_BY_DEFAULT};
// Signed HTTP Exchange prefetch cache for navigations
// https://crbug.com/968427
const base::Feature kSignedExchangePrefetchCacheForNavigations{
"SignedExchangePrefetchCacheForNavigations",
base::FEATURE_DISABLED_BY_DEFAULT};
// Signed Exchange Reporting for distributors
// https://www.chromestatus.com/features/5687904902840320
const base::Feature kSignedExchangeReportingForDistributors{
"SignedExchangeReportingForDistributors", base::FEATURE_ENABLED_BY_DEFAULT};
// Subresource prefetching+loading via Signed HTTP Exchange
// https://www.chromestatus.com/features/5126805474246656
const base::Feature kSignedExchangeSubresourcePrefetch{
"SignedExchangeSubresourcePrefetch", base::FEATURE_ENABLED_BY_DEFAULT};
// Origin-Signed HTTP Exchanges (for WebPackage Loading)
// https://www.chromestatus.com/features/5745285984681984
const base::Feature kSignedHTTPExchange{"SignedHTTPExchange",
base::FEATURE_ENABLED_BY_DEFAULT};
// Whether to send a ping to the inner URL upon navigation or not.
const base::Feature kSignedHTTPExchangePingValidity{
"SignedHTTPExchangePingValidity", base::FEATURE_DISABLED_BY_DEFAULT};
// This is intended as a kill switch for the WebOTP Service feature. To enable
// this feature, the experimental web platform features flag should be set.
const base::Feature kWebOTP{"WebOTP", base::FEATURE_ENABLED_BY_DEFAULT};
// Enables WebOTP calls in cross-origin iframes if allowed by Permissions
// Policy.
const base::Feature kWebOTPAssertionFeaturePolicy{
"WebOTPAssertionFeaturePolicy", base::FEATURE_DISABLED_BY_DEFAULT};
// Controls whether to isolate sites of documents that specify an eligible
// Cross-Origin-Opener-Policy header. Note that this is only intended to be
// used on Android, which does not use strict site isolation. See
// https://crbug.com/1018656.
const base::Feature kSiteIsolationForCrossOriginOpenerPolicy{
"SiteIsolationForCrossOriginOpenerPolicy",
base::FEATURE_DISABLED_BY_DEFAULT};
// Controls whether SpareRenderProcessHostManager tries to always have a warm
// spare renderer process around for the most recently requested BrowserContext.
// This feature is only consulted in site-per-process mode.
const base::Feature kSpareRendererForSitePerProcess{
"SpareRendererForSitePerProcess", base::FEATURE_ENABLED_BY_DEFAULT};
// Enables the out-of-process Storage Service.
const base::Feature kStorageServiceOutOfProcess{
"StorageServiceOutOfProcess", base::FEATURE_ENABLED_BY_DEFAULT};
// Controls whether site isolation should use origins instead of scheme and
// eTLD+1.
const base::Feature kStrictOriginIsolation{"StrictOriginIsolation",
base::FEATURE_DISABLED_BY_DEFAULT};
// Enables subresource loading with Web Bundles.
const base::Feature kSubresourceWebBundles{"SubresourceWebBundles",
base::FEATURE_DISABLED_BY_DEFAULT};
// Disallows window.{alert, prompt, confirm} if triggered inside a subframe that
// is not same origin with the main frame.
const base::Feature kSuppressDifferentOriginSubframeJSDialogs{
"SuppressDifferentOriginSubframeJSDialogs",
base::FEATURE_DISABLED_BY_DEFAULT};
// Dispatch touch events to "SyntheticGestureController" for events from
// Devtool Protocol Input.dispatchTouchEvent to simulate touch events close to
// real OS events.
const base::Feature kSyntheticPointerActions{"SyntheticPointerActions",
base::FEATURE_DISABLED_BY_DEFAULT};
// Throttle Blink timers in out-of-view cross origin frames.
const base::Feature kTimerThrottlingForHiddenFrames{
"TimerThrottlingForHiddenFrames", base::FEATURE_ENABLED_BY_DEFAULT};
// Enables async touchpad pinch zoom events. We check the ACK of the first
// synthetic wheel event in a pinch sequence, then send the rest of the
// synthetic wheel events of the pinch sequence as non-blocking if the first
// event’s ACK is not canceled.
const base::Feature kTouchpadAsyncPinchEvents{"TouchpadAsyncPinchEvents",
base::FEATURE_ENABLED_BY_DEFAULT};
// Allows swipe left/right from touchpad change browser navigation. Currently
// only enabled by default on CrOS.
const base::Feature kTouchpadOverscrollHistoryNavigation {
"TouchpadOverscrollHistoryNavigation",
#if BUILDFLAG(IS_CHROMEOS_ASH) || defined(OS_WIN)
base::FEATURE_ENABLED_BY_DEFAULT
#else
base::FEATURE_DISABLED_BY_DEFAULT
#endif
};
// Controls whether the Trusted Types API is available.
const base::Feature kTrustedDOMTypes{"TrustedDOMTypes",
base::FEATURE_ENABLED_BY_DEFAULT};
// This feature is for a reverse Origin Trial, enabling SharedArrayBuffer and
// WebAssemblyThreads for sites as they migrate towards requiring cross-origin
// isolation for these features.
// TODO(bbudge): Remove when the deprecation is complete.
// https://developer.chrome.com/origintrials/#/view_trial/303992974847508481
// https://crbug.com/1144104
const base::Feature kUnrestrictedSharedArrayBuffer{
"UnrestrictedSharedArrayBuffer", base::FEATURE_DISABLED_BY_DEFAULT};
// Allows user activation propagation to all frames having the same origin as
// the activation notifier frame. This is an intermediate measure before we
// have an iframe attribute to declaratively allow user activation propagation
// to subframes.
const base::Feature kUserActivationSameOriginVisibility{
"UserActivationSameOriginVisibility", base::FEATURE_ENABLED_BY_DEFAULT};
// An experimental replacement for the `User-Agent` header, defined in
// https://tools.ietf.org/html/draft-west-ua-client-hints.
const base::Feature kUserAgentClientHint{"UserAgentClientHint",
base::FEATURE_ENABLED_BY_DEFAULT};
// Enables comparing browser and renderer's DidCommitProvisionalLoadParams in
// RenderFrameHostImpl::VerifyThatBrowserAndRendererCalculatedDidCommitParamsMatch.
const base::Feature kVerifyDidCommitParams{"VerifyDidCommitParams",
base::FEATURE_DISABLED_BY_DEFAULT};
// Controls whether the <video>.getVideoPlaybackQuality() API is enabled.
const base::Feature kVideoPlaybackQuality{"VideoPlaybackQuality",
base::FEATURE_ENABLED_BY_DEFAULT};
// Enables future V8 VM features
const base::Feature kV8VmFuture{"V8VmFuture",
base::FEATURE_DISABLED_BY_DEFAULT};
// Enable window controls overlays for desktop PWAs
const base::Feature kWebAppWindowControlsOverlay{
"WebAppWindowControlsOverlay", base::FEATURE_DISABLED_BY_DEFAULT};
// Enable WebAssembly baseline compilation (Liftoff).
const base::Feature kWebAssemblyBaseline{"WebAssemblyBaseline",
base::FEATURE_ENABLED_BY_DEFAULT};
// Enable WebAssembly lazy compilation (JIT on first call).
const base::Feature kWebAssemblyLazyCompilation{
"WebAssemblyLazyCompilation", base::FEATURE_DISABLED_BY_DEFAULT};
// Enable WebAssembly SIMD.
// https://github.com/WebAssembly/Simd
const base::Feature kWebAssemblySimd{"WebAssemblySimd",
base::FEATURE_ENABLED_BY_DEFAULT};
// Enable WebAssembly tiering (Liftoff -> TurboFan).
const base::Feature kWebAssemblyTiering{"WebAssemblyTiering",
base::FEATURE_ENABLED_BY_DEFAULT};
// Enable WebAssembly threads.
// https://github.com/WebAssembly/threads
// This feature is also enabled independently of this flag for cross-origin
// isolated renderers.
const base::Feature kWebAssemblyThreads {
"WebAssemblyThreads",
base::FEATURE_DISABLED_BY_DEFAULT
};
// Enable WebAssembly trap handler.
#if (defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_WIN) || \
defined(OS_MAC)) && \
defined(ARCH_CPU_X86_64)
const base::Feature kWebAssemblyTrapHandler{"WebAssemblyTrapHandler",
base::FEATURE_ENABLED_BY_DEFAULT};
#else
const base::Feature kWebAssemblyTrapHandler{"WebAssemblyTrapHandler",
base::FEATURE_DISABLED_BY_DEFAULT};
#endif
// Controls whether the WebAuthentication API is enabled:
// https://w3c.github.io/webauthn
const base::Feature kWebAuth{"WebAuthentication",
base::FEATURE_ENABLED_BY_DEFAULT};
// Controls whether CTAP2 devices can communicate via the WebAuthentication API
// using pairingless BLE protocol.
// https://w3c.github.io/webauthn
const base::Feature kWebAuthCable {
"WebAuthenticationCable",
// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch
// of lacros-chrome is complete.
// If updating this, also update kWebAuthCableServerLink.
#if BUILDFLAG(IS_CHROMEOS_LACROS) || defined(OS_LINUX)
base::FEATURE_DISABLED_BY_DEFAULT
#else
base::FEATURE_ENABLED_BY_DEFAULT
#endif
};
// Controls whether WebAuthn conditional UI requests are supported.
const base::Feature kWebAuthConditionalUI{"WebAuthenticationConditionalUI",
base::FEATURE_DISABLED_BY_DEFAULT};
// Controls whether Web Bluetooth should use the new permissions backend. The
// new permissions backend uses ChooserContextBase, which is used by other
// device APIs, such as WebUSB.
const base::Feature kWebBluetoothNewPermissionsBackend{
"WebBluetoothNewPermissionsBackend", base::FEATURE_DISABLED_BY_DEFAULT};
// Controls whether Web Bundles (Bundled HTTP Exchanges) is enabled.
// https://wicg.github.io/webpackage/draft-yasskin-wpack-bundled-exchanges.html
// When this feature is enabled, Chromium can load unsigned Web Bundles local
// file under file:// URL (and content:// URI on Android).
const base::Feature kWebBundles{"WebBundles",
base::FEATURE_DISABLED_BY_DEFAULT};
// When this feature is enabled, Chromium will be able to load unsigned Web
// Bundles file under https: URL and localhost http: URL.
// TODO(crbug.com/1018640): Implement this feature.
const base::Feature kWebBundlesFromNetwork{"WebBundlesFromNetwork",
base::FEATURE_DISABLED_BY_DEFAULT};
// If WebGL Image Chromium is allowed, this feature controls whether it is
// enabled.
const base::Feature kWebGLImageChromium{"WebGLImageChromium",
base::FEATURE_ENABLED_BY_DEFAULT};
// Enable browser mediation API for federated identity interactions.
const base::Feature kWebID{"WebID", base::FEATURE_DISABLED_BY_DEFAULT};
// Controls which backend is used to retrieve OTP on Android. When disabled
// we use User Consent API.
const base::Feature kWebOtpBackendAuto{"WebOtpBackendAuto",
base::FEATURE_DISABLED_BY_DEFAULT};
// The JavaScript API for payments on the web.
const base::Feature kWebPayments{"WebPayments",
base::FEATURE_ENABLED_BY_DEFAULT};
// Minimal user interface experience for payments on the web.
const base::Feature kWebPaymentsMinimalUI{"WebPaymentsMinimalUI",
base::FEATURE_DISABLED_BY_DEFAULT};
// Use GpuMemoryBuffer backed VideoFrames in media streams.
const base::Feature kWebRtcUseGpuMemoryBufferVideoFrames{
"WebRTC-UseGpuMemoryBufferVideoFrames", base::FEATURE_ENABLED_BY_DEFAULT};
// Enables report-only Trusted Types experiment on WebUIs
const base::Feature kWebUIReportOnlyTrustedTypes{
"WebUIReportOnlyTrustedTypes", base::FEATURE_DISABLED_BY_DEFAULT};
// Controls whether the WebUSB API is enabled:
// https://wicg.github.io/webusb
const base::Feature kWebUsb{"WebUSB", base::FEATURE_ENABLED_BY_DEFAULT};
// Controls whether the WebXR Device API is enabled.
const base::Feature kWebXr{"WebXR", base::FEATURE_ENABLED_BY_DEFAULT};
// Enables access to AR features via the WebXR API.
const base::Feature kWebXrArModule{"WebXRARModule",
base::FEATURE_ENABLED_BY_DEFAULT};
// Enables access to articulated hand tracking sensor input.
const base::Feature kWebXrHandInput{"WebXRHandInput",
base::FEATURE_DISABLED_BY_DEFAULT};
// Enables access to raycasting against estimated XR scene geometry.
const base::Feature kWebXrHitTest{"WebXRHitTest",
base::FEATURE_ENABLED_BY_DEFAULT};
// Enables access to experimental WebXR features.
const base::Feature kWebXrIncubations{"WebXRIncubations",
base::FEATURE_DISABLED_BY_DEFAULT};
#if defined(OS_ANDROID)
// Autofill Accessibility in Android.
// crbug.com/627860
const base::Feature kAndroidAutofillAccessibility{
"AndroidAutofillAccessibility", base::FEATURE_ENABLED_BY_DEFAULT};
// Sets moderate binding to background renderers playing media, when enabled.
// Else the renderer will have strong binding.
const base::Feature kBackgroundMediaRendererHasModerateBinding{
"BackgroundMediaRendererHasModerateBinding",
base::FEATURE_DISABLED_BY_DEFAULT};
// If enabled, BindingManager will use Context.BIND_NOT_FOREGROUND to avoid
// affecting cpu scheduling priority.
const base::Feature kBindingManagementWaiveCpu{
"BindingManagementWaiveCpu", base::FEATURE_DISABLED_BY_DEFAULT};
// Screen Capture API support for Android
const base::Feature kUserMediaScreenCapturing{
"UserMediaScreenCapturing", base::FEATURE_DISABLED_BY_DEFAULT};
// Pre-warm up the network process on browser startup.
const base::Feature kWarmUpNetworkProcess{"WarmUpNetworkProcess",
base::FEATURE_DISABLED_BY_DEFAULT};
// Kill switch for the WebNFC feature. This feature can be enabled for all sites
// using the kEnableExperimentalWebPlatformFeatures flag.
// https://w3c.github.io/web-nfc/
const base::Feature kWebNfc{"WebNFC", base::FEATURE_ENABLED_BY_DEFAULT};
#endif // defined(OS_ANDROID)
#if defined(OS_MAC)
// Enables caching of media devices for the purpose of enumerating them.
const base::Feature kDeviceMonitorMac{"DeviceMonitorMac",
base::FEATURE_ENABLED_BY_DEFAULT};
// Enable IOSurface based screen capturer.
const base::Feature kIOSurfaceCapturer{"IOSurfaceCapturer",
base::FEATURE_ENABLED_BY_DEFAULT};
const base::Feature kMacSyscallSandbox{"MacSyscallSandbox",
base::FEATURE_DISABLED_BY_DEFAULT};
// Enables retrying to obtain list of available cameras on Macbooks after
// restarting the video capture service if a previous attempt delivered zero
// cameras.
const base::Feature kRetryGetVideoCaptureDeviceInfos{
"RetryGetVideoCaptureDeviceInfos", base::FEATURE_DISABLED_BY_DEFAULT};
const base::Feature kDesktopCaptureMacV2{"DesktopCaptureMacV2",
base::FEATURE_DISABLED_BY_DEFAULT};
const base::Feature kWindowCaptureMacV2{"WindowCaptureMacV2",
base::FEATURE_ENABLED_BY_DEFAULT};
#endif // defined(OS_MAC)
#if defined(OS_LINUX) || defined(OS_CHROMEOS)
// If the JavaScript on a WebUI page has an error (such as an unhandled
// exception), report that error back the crash reporting infrastructure, same
// as we do for program crashes.
const base::Feature kSendWebUIJavaScriptErrorReports{
"SendWebUIJavaScriptErrorReports", base::FEATURE_DISABLED_BY_DEFAULT};
// Parameter: Should we send the error reports to the production server? If
// false, we send to the staging server, which is useful for developers (doesn't
// pollute the report database).
const char kSendWebUIJavaScriptErrorReportsSendToProductionVariation[] =
"send_webui_js_errors_to_production";
const base::FeatureParam<bool>
kWebUIJavaScriptErrorReportsSendToProductionParam{
&kSendWebUIJavaScriptErrorReports,
kSendWebUIJavaScriptErrorReportsSendToProductionVariation, true};
#endif
#if defined(WEBRTC_USE_PIPEWIRE)
// Controls whether the PipeWire support for screen capturing is enabled on the
// Wayland display server.
const base::Feature kWebRtcPipeWireCapturer{"WebRTCPipeWireCapturer",
base::FEATURE_DISABLED_BY_DEFAULT};
#endif // defined(WEBRTC_USE_PIPEWIRE)
enum class VideoCaptureServiceConfiguration {
kEnabledForOutOfProcess,
kEnabledForBrowserProcess,
kDisabled
};
bool ShouldEnableVideoCaptureService() {
return base::FeatureList::IsEnabled(features::kMojoVideoCapture) &&
base::FeatureList::IsEnabled(features::kMojoVideoCaptureSecondary);
}
VideoCaptureServiceConfiguration GetVideoCaptureServiceConfiguration() {
if (!ShouldEnableVideoCaptureService())
return VideoCaptureServiceConfiguration::kDisabled;
// On ChromeOS the service must run in the browser process, because parts of the
// code depend on global objects that are only available in the Browser process.
// See https://crbug.com/891961.
#if defined(OS_ANDROID) || BUILDFLAG(IS_CHROMEOS_ASH) || \
BUILDFLAG(IS_CHROMEOS_LACROS)
return VideoCaptureServiceConfiguration::kEnabledForBrowserProcess;
#else
#if defined(OS_WIN)
if (base::win::GetVersion() <= base::win::Version::WIN7)
return VideoCaptureServiceConfiguration::kEnabledForBrowserProcess;
#endif
return base::FeatureList::IsEnabled(
features::kRunVideoCaptureServiceInBrowserProcess)
? VideoCaptureServiceConfiguration::kEnabledForBrowserProcess
: VideoCaptureServiceConfiguration::kEnabledForOutOfProcess;
#endif
}
bool IsVideoCaptureServiceEnabledForOutOfProcess() {
return GetVideoCaptureServiceConfiguration() ==
VideoCaptureServiceConfiguration::kEnabledForOutOfProcess;
}
bool IsVideoCaptureServiceEnabledForBrowserProcess() {
return GetVideoCaptureServiceConfiguration() ==
VideoCaptureServiceConfiguration::kEnabledForBrowserProcess;
}
} // namespace features
| 16,228 |
486 | package com.ptrprograms.gallery.model;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import android.util.Log;
public class Image implements Parcelable {
private String largeImage;
private String thumbNailImage;
private String caption;
public Image() {
}
public Image( Parcel source ) {
largeImage = source.readString();
thumbNailImage = source.readString();
caption = source.readString();
}
public String getLargeImage() {
return ( largeImage == null ) ? "" : largeImage;
}
public void setLargeImage( String largeImage ) {
if( TextUtils.isEmpty( largeImage ) )
return;
this.largeImage = largeImage;
}
public String getThumbNailImage() {
return ( thumbNailImage == null ) ? "" : thumbNailImage;
}
public void setThumbNailImage( String thumbNailImage ) {
if( TextUtils.isEmpty( thumbNailImage ) )
return;
this.thumbNailImage = thumbNailImage;
}
public String getCaption() {
return ( caption == null ) ? "" : caption;
}
public void setCaption( String caption ) {
if( TextUtils.isEmpty( caption ) )
return;
this.caption = caption;
}
public static Creator<Image> CREATOR = new Creator<Image>()
{
@Override
public Image createFromParcel(Parcel source) {
return new Image( source );
}
@Override
public Image[] newArray(int size) {
return new Image[size];
}
};
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString( largeImage );
parcel.writeString( thumbNailImage );
parcel.writeString( caption );
}
@Override
public int describeContents() {
return 0;
}
}
| 759 |
1,236 | <filename>flume/runtime/common/processor_executor.h
/***************************************************************************
*
* Copyright (c) 2013 Baidu, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**************************************************************************/
// Author: <NAME> <<EMAIL>>
#ifndef FLUME_RUNTIME_COMMON_PROCESSOR_EXECUTOR_H_
#define FLUME_RUNTIME_COMMON_PROCESSOR_EXECUTOR_H_
#include <map>
#include <string>
#include <utility>
#include <vector>
#include "boost/ptr_container/ptr_vector.hpp"
#include "boost/scoped_ptr.hpp"
#include "toft/base/closure.h"
#include "toft/base/scoped_ptr.h"
#include "toft/base/string/string_piece.h"
#include "flume/core/entity.h"
#include "flume/core/objector.h"
#include "flume/core/processor.h"
#include "flume/proto/physical_plan.pb.h"
#include "flume/runtime/common/executor_base.h"
#include "flume/runtime/dispatcher.h"
#include "flume/runtime/executor.h"
#include "flume/runtime/status_table.h"
#include "flume/util/bitset.h"
namespace baidu {
namespace flume {
namespace runtime {
namespace internal {
class ProcessorRunner : public ExecutorRunner, public core::Emitter {
public:
ProcessorRunner();
virtual ~ProcessorRunner();
virtual void setup(const PbExecutor& message, ExecutorContext* context);
// called when all inputs is ready
virtual void begin_group(const std::vector<toft::StringPiece>& keys);
// called after all inputs is done.
virtual void end_group();
protected:
virtual bool Emit(void *object);
virtual void Done();
private:
class DummyIterator : public core::Iterator {
public:
virtual bool HasNext() const { return false; }
virtual void* NextValue() {
LOG(FATAL) << "Dummy iterator contains no records.";
return NULL;
}
virtual void Reset() {}
virtual void Done() {}
};
virtual void set_message(const PbProcessorExecutor& message) = 0;
virtual core::Processor* begin_processing(const std::vector<toft::StringPiece>& keys,
const std::vector<core::Iterator*>& inputs,
core::Emitter* emitter) = 0;
virtual void end_processing(core::Processor* processor, bool is_done) = 0;
void on_prepared_iterator_come(int index, core::Iterator* iterator);
void on_flushing_iterator_come(int index, core::Iterator* iterator);
void on_input_come(int index, const std::vector<toft::StringPiece>& keys,
void* object, const toft::StringPiece& binary);
void check_is_processing();
void flush_iterator(int index, core::Iterator* iterator);
PbProcessorExecutor _message;
boost::ptr_vector<DummyIterator> _dummy_iterators;
ExecutorContext* _context;
Dispatcher* _output;
std::vector<Source::Handle*> _handles;
std::vector<core::Iterator*> _initial_inputs;
std::vector<toft::StringPiece> _keys;
bool _in_processing;
bool _is_done;
core::Processor* _processor;
std::vector<core::Iterator*> _prepared_inputs;
std::vector< std::pair<size_t, core::Iterator*> > _pending_inputs;
};
} // namespace internal
class NormalProcessorRunner : public internal::ProcessorRunner {
public:
NormalProcessorRunner() : _key_number(0), _processor(NULL) {}
~NormalProcessorRunner() {}
virtual void set_message(const PbProcessorExecutor& message);
virtual core::Processor* begin_processing(const std::vector<toft::StringPiece>& keys,
const std::vector<core::Iterator*>& inputs,
core::Emitter* emitter);
virtual void end_processing(core::Processor* processor, bool is_done);
private:
uint32_t _key_number;
toft::scoped_ptr<core::Processor> _processor;
std::vector<toft::StringPiece> _partial_keys;
};
class StatusProcessorRunner : public internal::ProcessorRunner {
public:
StatusProcessorRunner() : _status_table(NULL), _visitor(NULL) {}
~StatusProcessorRunner() {}
virtual void set_message(const PbProcessorExecutor& message);
void SetStatusTable(StatusTable* status_table);
virtual core::Processor* begin_processing(const std::vector<toft::StringPiece>& keys,
const std::vector<core::Iterator*>& inputs,
core::Emitter* emitter);
protected:
PbProcessorExecutor _message;
StatusTable* _status_table;
StatusTable::NodeVisitor* _visitor;
};
class UpdateStatusProcessorRunner : public StatusProcessorRunner {
public:
virtual void end_processing(core::Processor* processor, bool is_done);
};
class FlushStatusProcessorRunner : public StatusProcessorRunner {
public:
virtual void end_processing(core::Processor* processor, bool is_done);
};
Executor* new_shuffle_executor(uint32_t partition,
uint32_t input_scope_level, const PbExecutor& message,
const std::vector<Executor*>& childs,
DatasetManager* dataset_manager);
} // namespace runtime
} // namespace flume
} // namespace baidu
#endif // FLUME_RUNTIME_COMMON_PROCESSOR_EXECUTOR_H_
| 2,197 |
665 | <gh_stars>100-1000
/* http_client_test.cc
<NAME>, January 2014
This file is part of MLDB. Copyright 2014-20176 mldb.ai inc.
All rights reserved.
Test for HttpClient
*/
#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK
#include <chrono>
#include <memory>
#include <iostream>
#include <ostream>
#include <string>
#include <tuple>
#include <thread>
#include <boost/test/unit_test.hpp>
#include "http_client_test_common.h"
#include "mldb/ext/jsoncpp/value.h"
#include "mldb/ext/jsoncpp/reader.h"
#include "mldb/arch/wait_on_address.h"
#include "mldb/utils/testing/watchdog.h"
#include "mldb/io/asio_thread_pool.h"
#include "mldb/io/event_loop.h"
#include "mldb/io/legacy_event_loop.h"
#include "mldb/http/http_client.h"
#include "mldb/http/testing/test_http_services.h"
#include "mldb/utils/testing/print_utils.h"
using namespace std;
using namespace MLDB;
/* helpers functions used in tests */
namespace {
}
/* Ensures that all requests are correctly performed under load, including
when "Connection: close" is encountered once in a while.
Not a performance test. */
BOOST_AUTO_TEST_CASE( test_http_client_stress_test )
{
cerr << "stress_test\n";
// const int mask = 0x3ff; /* mask to use for displaying counts */
MLDB::Watchdog watchdog(300);
auto doStressTest = [&] (int numParallel) {
cerr << ("stress test with "
+ to_string(numParallel) + " parallel connections\n");
EventLoop eventLoop;
AsioThreadPool threadPool(eventLoop);
TestHttpGetService service(eventLoop);
string baseUrl = service.start();
LegacyEventLoop legacyLoop;
legacyLoop.start();
HttpClient client(legacyLoop, baseUrl, numParallel);
int maxReqs(30000), numReqs(0), missedReqs(0);
std::atomic<int> numResponses(0);
auto onDone = [&] (const HttpRequest & rq,
HttpClientError errorCode, int status,
string && headers, string && body) {
numResponses++;
BOOST_CHECK_EQUAL(errorCode, HttpClientError::None);
BOOST_CHECK_EQUAL(status, 200);
if (numResponses == numReqs) {
MLDB::wake_by_address(numResponses);
}
};
while (numReqs < maxReqs) {
const char * url = "/counter";
auto cbs = make_shared<HttpClientSimpleCallbacks>(onDone);
if (client.get(url, cbs)) {
numReqs++;
// if ((numReqs & mask) == 0 || numReqs == maxReqs) {
// cerr << "performed " + to_string(numReqs) + " requests\n";
// }
}
else {
missedReqs++;
}
}
cerr << "all requests performed, awaiting responses...\n";
while (numResponses < maxReqs) {
int old(numResponses);
MLDB::wait_on_address(numResponses, old);
}
cerr << ("performed " + to_string(maxReqs)
+ " requests; missed: " + to_string(missedReqs)
+ "\n");
threadPool.shutdown();
};
doStressTest(1);
doStressTest(8);
doStressTest(50);
}
| 1,482 |
353 | <filename>lhotse/bin/lhotse.py
#!/usr/bin/env python3
"""
Use this script like:
$ lhotse --help
$ lhotse make-feats --help
$ lhotse make-feats --compressed recording_manifest.yml mfcc_dir/
$ lhotse write-default-feature-config feat-conf.yml
$ lhotse kaldi import data/train 16000 train_manifests/
$ lhotse split 3 audio.yml split_manifests/
$ lhotse combine feature.1.yml feature.2.yml combined_feature.yml
$ lhotse recipe --help
$ lhotse recipe librimix-dataprep path/to/librimix.csv output_manifests_dir/
$ lhotse recipe librimix-obtain target_dir/
$ lhotse recipe mini-librispeech-dataprep corpus_dir/ output_manifests_dir/
$ lhotse recipe mini-librispeech-obtain target_dir/
$ lhotse cut --help
$ lhotse cut simple supervisions.yml features.yml simple_cuts.yml
$ lhotse cut stereo-mixed supervisions.yml features.yml mixed_cuts.yml
"""
# Note: we import all the CLI modes here so they get auto-registered
# in Lhotse's main CLI entry-point. Then, setuptools is told to
# invoke the "cli()" method from this script.
from lhotse.bin.modes import *
| 392 |
2,434 | <gh_stars>1000+
package io.github.swagger2markup.adoc.ast.impl;
import org.asciidoctor.ast.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.*;
public class TableImpl extends StructuralNodeImpl implements Table {
public static final String OPTION_UNBREAKABLE = "unbreakable";
public static final String OPTION_BREAKABLE = "breakable";
private Logger logger = LoggerFactory.getLogger(getClass());
public static final String CONTEXT = "table";
private static final String FRAME_ATTR = "frame";
private static final String GRID_ATTR = "grid";
private RowList headerRows;
private RowList bodyRows;
private RowList footerRows;
private List<Column> columns = new ArrayList<>();
public TableImpl(StructuralNode parent) {
this(parent, new HashMap<>(), new ArrayList<>());
}
public TableImpl(StructuralNode parent, Map<String, Object> attributes, List<String> roles) {
this(parent, attributes, roles, calculateLevel(parent));
}
public TableImpl(StructuralNode parent, Map<String, Object> attributes, List<String> roles, Integer level) {
this(parent, attributes, roles, null, new ArrayList<>(), level, "", new ArrayList<>());
}
public TableImpl(StructuralNode parent, Map<String, Object> attributes, List<String> roles,
Object content, List<StructuralNode> blocks, Integer level, String contentModel, List<String> subs) {
super(parent, CONTEXT, attributes, roles, content, blocks, level, contentModel, subs);
this.headerRows = new RowList(new ArrayList<>());
this.bodyRows = new RowList(new ArrayList<>());
this.footerRows = new RowList(new ArrayList<>());
}
@Override
public boolean hasHeaderOption() {
return isOption("header");
}
@Override
public String getFrame() {
return (String) getAttribute(FRAME_ATTR, "all");
}
@Override
public void setFrame(String frame) {
setAttribute(FRAME_ATTR, frame, true);
}
@Override
public String getGrid() {
return (String) getAttribute(GRID_ATTR, "all");
}
@Override
public void setGrid(String grid) {
setAttribute(GRID_ATTR, grid, true);
}
@Override
public List<Column> getColumns() {
return columns;
}
@Override
public List<Row> getHeader() {
return headerRows;
}
public void setHeaderRow(Row row) {
headerRows.clear();
headerRows.add(row);
scanRowForColumns(row);
}
public void setHeaderRow(List<Cell> cells) {
setHeaderRow(new RowImpl(cells));
}
public void setHeaderRow(String... documentContents) {
headerRows.clear();
headerRows.add(generateRow(documentContents));
}
public RowImpl generateRow(Document... innerDocs) {
List<Cell> cells = new ArrayList<>();
for (int i = 0; i < innerDocs.length; i++) {
Column column = null;
try {
column = columns.get(i);
} catch (Exception ignored) {
}
if (null == column) {
ColumnImpl newColumn = new ColumnImpl(this);
newColumn.setColumnNumber(i + 1);
column = newColumn;
addColumnAt(column, i);
}
cells.add(new CellImpl(column, innerDocs[i]));
}
return new RowImpl(cells);
}
public RowImpl generateRow(String... documentContents) {
Document[] documents = Arrays.stream(documentContents).map(documentContent -> {
Document innerDoc = new DocumentImpl();
Block paragraph = new ParagraphBlockImpl(innerDoc);
paragraph.setSource(documentContent);
innerDoc.append(paragraph);
return innerDoc;
}).toArray(Document[]::new);
return generateRow(documents);
}
@Override
public List<Row> getBody() {
return bodyRows;
}
public void setBodyRows(List<Row> rows) {
bodyRows.clear();
bodyRows.addAll(rows);
bodyRows.forEach(this::scanRowForColumns);
}
public void addRow(Row row) {
bodyRows.add(row);
scanRowForColumns(row);
}
public void addRow(List<Cell> cells) {
bodyRows.add(new RowImpl(cells));
}
public RowImpl addRow(Document... documentContents) {
RowImpl row = generateRow(documentContents);
bodyRows.add(row);
return row;
}
public RowImpl addRow(String... documentContents) {
RowImpl row = generateRow(documentContents);
bodyRows.add(row);
return row;
}
@Override
public List<Row> getFooter() {
return footerRows;
}
public void setFooterRow(Row row) {
footerRows.clear();
footerRows.add(row);
scanRowForColumns(row);
}
public void setFooterRow(String... documentContents) {
footerRows.clear();
footerRows.add(generateRow(documentContents));
}
private void scanRowForColumns(Row row) {
row.getCells().forEach(cell -> {
Column column = cell.getColumn();
int i = column.getColumnNumber() - 1;
addColumnAt(column, i);
});
}
private void addColumnAt(Column column, int i) {
if (columns.size() >= i) {
columns.add(i, column);
} else {
while (columns.size() < i) {
columns.add(columns.size(), null);
}
columns.add(column);
}
}
public void setFooterRow(List<Cell> cells) {
setFooterRow(new RowImpl(cells));
}
class RowList extends AbstractList<Row> {
private final List<Row> rubyArray;
private RowList(List<Row> rubyArray) {
this.rubyArray = rubyArray;
}
@Override
public int size() {
return rubyArray.size();
}
@Override
public boolean isEmpty() {
return rubyArray.isEmpty();
}
@Override
public boolean contains(Object o) {
return rubyArray.contains(o);
}
@Override
public boolean add(Row row) {
boolean changed = false;
try {
changed = rubyArray.add(row);
setAttribute("rowcount", size(), true);
} catch (Exception e) {
logger.debug("Couldn't add row", e);
}
return changed;
}
@Override
public boolean remove(Object o) {
if (!(o instanceof RowImpl)) {
return false;
}
try {
boolean changed = rubyArray.remove(o);
setAttribute("rowcount", size(), true);
return changed;
} catch (Exception e) {
logger.debug("Couldn't add row", e);
return false;
}
}
@Override
public boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
rubyArray.clear();
setAttribute("rowcount", size(), true);
}
@Override
public Row get(int index) {
return rubyArray.get(index);
}
@Override
public Row set(int index, Row element) {
Row oldRow = get(index);
rubyArray.set(index, element);
return oldRow;
}
@Override
public void add(int index, Row element) {
rubyArray.add(index, element);
setAttribute("rowcount", size(), true);
}
@Override
public Row remove(int index) {
Row removed = rubyArray.remove(index);
setAttribute("rowcount", size(), true);
return removed;
}
@Override
public int indexOf(Object o) {
if (!(o instanceof RowImpl)) {
return -1;
}
return rubyArray.indexOf(o);
}
@Override
public int lastIndexOf(Object o) {
if (!(o instanceof RowImpl)) {
return -1;
}
return rubyArray.lastIndexOf(o);
}
}
protected static Integer calculateLevel(StructuralNode parent) {
int level = 1;
if (parent instanceof Table)
level = parent.getLevel() + 1;
return level;
}
}
| 3,842 |
348 | <filename>docs/data/leg-t2/022/02205016.json
{"nom":"Ile-de-Bréhat","circ":"5ème circonscription","dpt":"Côtes-d'Armor","inscrits":444,"abs":163,"votants":281,"blancs":27,"nuls":3,"exp":251,"res":[{"nuance":"REM","nom":"<NAME>","voix":149},{"nuance":"UDI","nom":"<NAME>","voix":102}]} | 119 |
14,668 | <filename>chrome/browser/extensions/api/enterprise_networking_attributes/enterprise_networking_attributes_api.h<gh_stars>1000+
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_EXTENSIONS_API_ENTERPRISE_NETWORKING_ATTRIBUTES_ENTERPRISE_NETWORKING_ATTRIBUTES_API_H_
#define CHROME_BROWSER_EXTENSIONS_API_ENTERPRISE_NETWORKING_ATTRIBUTES_ENTERPRISE_NETWORKING_ATTRIBUTES_API_H_
#include "chromeos/crosapi/mojom/networking_attributes.mojom.h"
#include "extensions/browser/extension_function.h"
#include "extensions/browser/extension_function_histogram_value.h"
namespace extensions {
class EnterpriseNetworkingAttributesGetNetworkDetailsFunction
: public ExtensionFunction {
public:
EnterpriseNetworkingAttributesGetNetworkDetailsFunction();
protected:
~EnterpriseNetworkingAttributesGetNetworkDetailsFunction() override;
ResponseAction Run() override;
private:
void OnResult(crosapi::mojom::GetNetworkDetailsResultPtr result);
DECLARE_EXTENSION_FUNCTION(
"enterprise.networkingAttributes.getNetworkDetails",
ENTERPRISE_NETWORKINGATTRIBUTES_GETNETWORKDETAILS)
};
} // namespace extensions
#endif // CHROME_BROWSER_EXTENSIONS_API_ENTERPRISE_NETWORKING_ATTRIBUTES_ENTERPRISE_NETWORKING_ATTRIBUTES_API_H_
| 461 |
463 | <reponame>yanz08/rv8-wezh<filename>src/gen/gen-markdown.cc
//
// gen-map.cc
//
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <algorithm>
#include <memory>
#include <string>
#include <vector>
#include <deque>
#include <map>
#include <set>
#include <unistd.h>
#include "util.h"
#include "cmdline.h"
#include "model.h"
#include "gen.h"
std::vector<cmdline_option> rv_gen_markdown::get_cmdline_options()
{
return std::vector<cmdline_option>{
{ "-md", "--print-markdown", cmdline_arg_type_none,
"Print instruction reference in markdown",
[&](std::string s) { return gen->set_option("print_markdown"); } },
};
}
static void print_markdown(rv_gen *gen)
{
static const char* fmt = "%s | %s | %s\n";
for (auto &ext : gen->extensions) {
if (ext->opcodes.size() == 0 || (gen->ext_subset.size() > 0 &&
std::find(gen->ext_subset.begin(), gen->ext_subset.end(), ext) == gen->ext_subset.end())) {
continue;
}
printf("_**%s**_\n\n", ext->description.c_str());
printf(fmt, "Format", "Name", "Pseudocode");
printf(fmt, ":--", ":--", ":--");
for (auto &opcode : ext->opcodes) {
if (opcode->is_pseudo()) continue;
auto name = opcode->name;
auto operand_comps = split(opcode->format->operands, ",");
std::transform(name.begin(), name.end(), name.begin(), ::toupper);
if (operand_comps.size() == 1 && operand_comps[0] == "none") operand_comps[0] = "";
std::string format;
format.append("<code><sub>");
format.append(name);
if (operand_comps.size() > 0) {
format.append(" ");
format.append(join(operand_comps, ","));
}
format.append("</sub></code>");
std::string fullname;
fullname.append("<sub>");
fullname.append(opcode->fullname);
fullname.append("</sub>");
std::string pseudocode;
pseudocode.append("<sub>");
pseudocode.append(opcode->pseudocode_alt);
pseudocode.append("</sub>");
printf(fmt, format.c_str(), fullname.c_str(), pseudocode.c_str());
}
printf("\n");
}
}
void rv_gen_markdown::generate()
{
if (gen->has_option("print_markdown")) print_markdown(gen);
}
| 889 |
3,422 | package com.volokh.danylo.video_player_manager.player_messages;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import com.volokh.danylo.video_player_manager.manager.VideoPlayerManagerCallback;
import com.volokh.danylo.video_player_manager.ui.VideoPlayerView;
/**
* This PlayerMessage calls {@link MediaPlayer#setDataSource(Context, Uri)} on the instance that is used inside {@link VideoPlayerView}
*/
public class SetUrlDataSourceMessage extends SetDataSourceMessage{
private final String mVideoUrl;
public SetUrlDataSourceMessage(VideoPlayerView videoPlayerView, String videoUrl, VideoPlayerManagerCallback callback) {
super(videoPlayerView, callback);
mVideoUrl = videoUrl;
}
@Override
protected void performAction(VideoPlayerView currentPlayer) {
currentPlayer.setDataSource(mVideoUrl);
}
}
| 277 |
8,232 | <reponame>isra-fel/STL
// Copyright (c) Microsoft Corporation.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#define _CONTAINER_DEBUG_LEVEL 1
#include <algorithm>
#include <span>
#include <stddef.h>
#include <vector>
#include <test_death.hpp>
using namespace std;
int globalArray[5]{10, 20, 30, 40, 50};
int otherArray[5]{10, 20, 30, 40, 50};
void test_case_operator_dereference_value_initialized_iterator() {
span<int>::iterator it; // note: for IDL to work correctly, default-init and value-init are equivalent
(void) *it; // cannot dereference value-initialized span iterator
}
void test_case_operator_dereference_end_iterator() {
span<int> sp(globalArray);
span<int>::iterator it = sp.end();
(void) *it; // cannot dereference end span iterator
}
void test_case_operator_arrow_value_initialized_iterator() {
span<int>::iterator it;
(void) it.operator->(); // cannot dereference value-initialized span iterator
}
void test_case_operator_arrow_end_iterator() {
span<int> sp(globalArray);
span<int>::iterator it = sp.end();
(void) it.operator->(); // cannot dereference end span iterator
}
void test_case_operator_preincrement_value_initialized_iterator() {
span<int>::iterator it;
++it; // cannot increment value-initialized span iterator
}
void test_case_operator_preincrement_after_end() {
span<int> sp(globalArray);
span<int>::iterator it = sp.end();
++it; // cannot increment span iterator past end
}
void test_case_operator_predecrement_value_initialized_iterator() {
span<int>::iterator it;
--it; // cannot decrement value-initialized span iterator
}
void test_case_operator_predecrement_before_begin() {
span<int> sp(globalArray);
span<int>::iterator it = sp.begin();
--it; // cannot decrement span iterator before begin
}
void test_case_operator_advance_value_initialized_iterator() {
span<int>::iterator it;
it += 1; // cannot seek value-initialized span iterator
}
void test_case_operator_advance_value_initialized_iterator_zero() {
span<int>::iterator it;
it += 0; // OK
}
void test_case_operator_advance_before_begin() {
span<int> sp(globalArray);
span<int>::iterator it = sp.begin();
it += -1; // cannot seek span iterator before begin
}
void test_case_operator_advance_after_end() {
span<int> sp(globalArray);
span<int>::iterator it = sp.end();
it += 1; // cannot seek span iterator after end
}
void test_case_operator_retreat_value_initialized_iterator() {
span<int>::iterator it;
it -= 1; // cannot seek value-initialized span iterator
}
void test_case_operator_retreat_value_initialized_iterator_zero() {
span<int>::iterator it;
it -= 0; // OK
}
void test_case_operator_retreat_before_begin() {
span<int> sp(globalArray);
span<int>::iterator it = sp.begin();
it -= 1; // cannot seek span iterator before begin
}
void test_case_operator_retreat_after_end() {
span<int> sp(globalArray);
span<int>::iterator it = sp.end();
it -= -1; // cannot seek span iterator after end
}
void test_case_operator_subtract_incompatible_different_data() {
span<int> sp1(globalArray);
span<int> sp2(otherArray);
(void) (sp1.begin() - sp2.begin()); // cannot subtract incompatible span iterators
}
void test_case_operator_subtract_incompatible_different_size() {
span<int> sp1(globalArray, 3);
span<int> sp2(globalArray, 4);
(void) (sp1.begin() - sp2.begin()); // cannot subtract incompatible span iterators
}
void test_case_operator_subtract_incompatible_value_initialized() {
span<int> sp(globalArray);
(void) (sp.begin() - span<int>::iterator{}); // cannot subtract incompatible span iterators
}
void test_case_operator_equal_incompatible_different_data() {
span<int> sp1(globalArray);
span<int> sp2(otherArray);
(void) (sp1.begin() == sp2.begin()); // cannot compare incompatible span iterators for equality
}
void test_case_operator_equal_incompatible_different_size() {
span<int> sp1(globalArray, 3);
span<int> sp2(globalArray, 4);
(void) (sp1.begin() == sp2.begin()); // cannot compare incompatible span iterators for equality
}
void test_case_operator_equal_incompatible_value_initialized() {
span<int> sp(globalArray);
(void) (sp.begin() == span<int>::iterator{}); // cannot compare incompatible span iterators for equality
}
void test_case_operator_less_incompatible_different_data() {
span<int> sp1(globalArray);
span<int> sp2(otherArray);
(void) (sp1.begin() < sp2.begin()); // cannot compare incompatible span iterators
}
void test_case_operator_less_incompatible_different_size() {
span<int> sp1(globalArray, 3);
span<int> sp2(globalArray, 4);
(void) (sp1.begin() < sp2.begin()); // cannot compare incompatible span iterators
}
void test_case_operator_less_incompatible_value_initialized() {
span<int> sp(globalArray);
(void) (sp.begin() < span<int>::iterator{}); // cannot compare incompatible span iterators
}
void test_case_algorithm_incompatible_different_data() {
span<int> sp1(globalArray);
span<int> sp2(otherArray);
(void) find(sp1.begin(), sp2.begin(), -1); // span iterators from different views do not form a range
}
void test_case_algorithm_incompatible_different_size() {
span<int> sp1(globalArray, 3);
span<int> sp2(globalArray, 4);
(void) find(sp1.begin(), sp2.begin(), -1); // span iterators from different views do not form a range
}
void test_case_algorithm_incompatible_value_initialized() {
span<int> sp(globalArray);
(void) find(sp.begin(), span<int>::iterator{}, -1); // span iterators from different views do not form a range
}
void test_case_algorithm_incompatible_transposed() {
span<int> sp(globalArray);
(void) find(sp.end(), sp.begin(), -1); // span iterator range transposed
}
void test_case_constructor_first_count_incompatible_extent() {
span<int, 3> sp(begin(globalArray),
size(globalArray)); // Cannot construct span with static extent from range [first, first + count) as count !=
// extent
(void) sp;
}
void test_case_constructor_first_last_incompatible_extent() {
span<int, 3> sp(begin(globalArray), end(globalArray)); // Cannot construct span with static extent from range
// [first, last) as last - first != extent
(void) sp;
}
void test_case_constructor_range_incompatible_extent() {
vector<int> v(begin(globalArray), end(globalArray));
span<int, 3> sp(v); // Cannot construct span with static extent from range r as std::ranges::size(r) != extent
(void) sp;
}
void test_case_constructor_span_incompatible_extent() {
span<int> sp(begin(globalArray), end(globalArray));
span<int, 3> sp2(sp); // Cannot construct span with static extent from other span as other.size() != extent
(void) sp2;
}
void test_case_first_excessive_compiletime_count() {
span<int> sp(globalArray);
(void) sp.first<6>(); // Count out of range in span::first()
}
void test_case_first_excessive_runtime_count_dynamic_extent() {
span<int> sp(globalArray);
(void) sp.first(6); // Count out of range in span::first(count)
}
void test_case_first_excessive_runtime_count_static_extent() {
span<int, 5> sp(globalArray);
(void) sp.first(6); // Count out of range in span::first(count)
}
void test_case_last_excessive_compiletime_count() {
span<int> sp(globalArray);
(void) sp.last<6>(); // Count out of range in span::last()
}
void test_case_last_excessive_runtime_count_dynamic_extent() {
span<int> sp(globalArray);
(void) sp.last(6); // Count out of range in span::last(count)
}
void test_case_last_excessive_runtime_count_static_extent() {
span<int, 5> sp(globalArray);
(void) sp.last(6); // Count out of range in span::last(count)
}
void test_case_subspan_excessive_compiletime_offset() {
span<int> sp(globalArray);
(void) sp.subspan<6>(); // Offset out of range in span::subspan()
}
void test_case_subspan_excessive_compiletime_count() {
span<int> sp(globalArray);
(void) sp.subspan<2, 4>(); // Count out of range in span::subspan()
}
void test_case_subspan_excessive_runtime_offset_dynamic_extent() {
span<int> sp(globalArray);
(void) sp.subspan(6); // Offset out of range in span::subspan(offset, count)
}
void test_case_subspan_excessive_runtime_count_dynamic_extent() {
span<int> sp(globalArray);
(void) sp.subspan(2, 4); // Count out of range in span::subspan(offset, count)
}
void test_case_subspan_excessive_runtime_offset_static_extent() {
span<int, 5> sp(globalArray);
(void) sp.subspan(6); // Offset out of range in span::subspan(offset, count)
}
void test_case_subspan_excessive_runtime_count_static_extent() {
span<int, 5> sp(globalArray);
(void) sp.subspan(2, 4); // Count out of range in span::subspan(offset, count)
}
void test_case_size_bytes_overflow() {
span<int> sp(begin(globalArray), static_cast<size_t>(-2)); // undefined behavior, not detected here
(void) sp.size_bytes(); // size of span in bytes exceeds std::numeric_limits<size_t>::max()
}
void test_case_operator_subscript_out_of_range_dynamic_extent() {
span<int> sp(globalArray);
(void) sp[5]; // span index out of range
}
void test_case_operator_subscript_out_of_range_static_extent() {
span<int, 5> sp(globalArray);
(void) sp[5]; // span index out of range
}
void test_case_front_empty_dynamic_extent() {
span<int> sp;
(void) sp.front(); // front of empty span
}
void test_case_back_empty_dynamic_extent() {
span<int> sp;
(void) sp.back(); // back of empty span
}
void test_case_front_empty_static_extent() {
span<int, 0> sp;
(void) sp.front(); // front of empty span
}
void test_case_back_empty_static_extent() {
span<int, 0> sp;
(void) sp.back(); // back of empty span
}
int main(int argc, char* argv[]) {
std_testing::death_test_executive exec([] {
test_case_operator_advance_value_initialized_iterator_zero();
test_case_operator_retreat_value_initialized_iterator_zero();
});
#if _ITERATOR_DEBUG_LEVEL != 0
exec.add_death_tests({
test_case_operator_dereference_value_initialized_iterator,
test_case_operator_dereference_end_iterator,
test_case_operator_arrow_value_initialized_iterator,
test_case_operator_arrow_end_iterator,
test_case_operator_preincrement_value_initialized_iterator,
test_case_operator_preincrement_after_end,
test_case_operator_predecrement_value_initialized_iterator,
test_case_operator_predecrement_before_begin,
test_case_operator_advance_value_initialized_iterator,
test_case_operator_advance_before_begin,
test_case_operator_advance_after_end,
test_case_operator_retreat_value_initialized_iterator,
test_case_operator_retreat_before_begin,
test_case_operator_retreat_after_end,
test_case_operator_subtract_incompatible_different_data,
test_case_operator_subtract_incompatible_different_size,
test_case_operator_subtract_incompatible_value_initialized,
test_case_operator_equal_incompatible_different_data,
test_case_operator_equal_incompatible_different_size,
test_case_operator_equal_incompatible_value_initialized,
test_case_operator_less_incompatible_different_data,
test_case_operator_less_incompatible_different_size,
test_case_operator_less_incompatible_value_initialized,
test_case_algorithm_incompatible_different_data,
test_case_algorithm_incompatible_different_size,
test_case_algorithm_incompatible_value_initialized,
test_case_algorithm_incompatible_transposed,
});
#endif // _ITERATOR_DEBUG_LEVEL != 0
// _CONTAINER_DEBUG_LEVEL tests
exec.add_death_tests({
test_case_constructor_first_count_incompatible_extent,
test_case_constructor_first_last_incompatible_extent,
test_case_constructor_range_incompatible_extent,
test_case_constructor_span_incompatible_extent,
test_case_first_excessive_compiletime_count,
test_case_first_excessive_runtime_count_dynamic_extent,
test_case_first_excessive_runtime_count_static_extent,
test_case_last_excessive_compiletime_count,
test_case_last_excessive_runtime_count_dynamic_extent,
test_case_last_excessive_runtime_count_static_extent,
test_case_subspan_excessive_compiletime_offset,
test_case_subspan_excessive_compiletime_count,
test_case_subspan_excessive_runtime_offset_dynamic_extent,
test_case_subspan_excessive_runtime_count_dynamic_extent,
test_case_subspan_excessive_runtime_offset_static_extent,
test_case_subspan_excessive_runtime_count_static_extent,
test_case_size_bytes_overflow,
test_case_operator_subscript_out_of_range_dynamic_extent,
test_case_operator_subscript_out_of_range_static_extent,
test_case_front_empty_dynamic_extent,
test_case_back_empty_dynamic_extent,
test_case_front_empty_static_extent,
test_case_back_empty_static_extent,
});
return exec.run(argc, argv);
}
| 5,329 |
3,274 | <reponame>tyang513/QLExpress
package com.ql.util.express;
import java.util.HashMap;
@SuppressWarnings("serial")
public class DefaultContext<K,V> extends HashMap<K,V> implements IExpressContext<K,V> {
}
| 76 |
190,993 | /* Copyright 2020 The TensorFlow Authors. 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.
==============================================================================*/
#include "tensorflow/c/experimental/saved_model/core/revived_types/tf_signature_def_function.h"
#include <memory>
#include <string>
#include "absl/types/span.h"
#include "tensorflow/c/eager/abstract_tensor_handle.h"
#include "tensorflow/c/eager/immediate_execution_operation.h"
#include "tensorflow/c/eager/immediate_execution_tensor_handle.h"
#include "tensorflow/c/experimental/saved_model/core/revived_types/flat_tensor_function.h"
#include "tensorflow/core/common_runtime/eager/context.h"
#include "tensorflow/core/framework/function.pb.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/status.h"
#include "tensorflow/core/protobuf/saved_object_graph.pb.h"
#include "tensorflow/core/protobuf/struct.pb.h"
namespace tensorflow {
TFSignatureDefFunction::TFSignatureDefFunction(
std::unique_ptr<FlatTensorFunction> func,
SignatureDefFunctionMetadata metadata)
: func_(std::move(func)), metadata_(std::move(metadata)) {}
Status TFSignatureDefFunction::Create(
const FunctionDef* function_def,
std::vector<ImmediateExecutionTensorHandle*> captures,
SignatureDefFunctionMetadata metadata, ImmediateExecutionContext* ctx,
std::unique_ptr<TFSignatureDefFunction>* out) {
std::unique_ptr<FlatTensorFunction> func;
TF_RETURN_IF_ERROR(FlatTensorFunction::Create(
function_def, std::move(captures), ctx, &func));
out->reset(new TFSignatureDefFunction(std::move(func), std::move(metadata)));
return Status();
}
const SignatureDefFunctionMetadata&
TFSignatureDefFunction::GetFunctionMetadata() const {
return metadata_;
}
Status TFSignatureDefFunction::MakeCallOp(
absl::Span<AbstractTensorHandle* const> inputs, ImmediateOpPtr* out) const {
return func_->MakeCallOp(inputs, out);
}
} // namespace tensorflow
| 802 |
628 | <reponame>gaybro8777/osf.io
# -*- coding: utf-8 -*-
from rest_framework import permissions
from rest_framework import exceptions
from api.base.utils import get_user_auth, assert_resource_type
from api.nodes.permissions import (
AdminOrPublic as NodeAdminOrPublic,
)
from osf.models import Preprint, OSFUser, PreprintContributor, Identifier
from addons.osfstorage.models import OsfStorageFolder
from osf.utils.workflows import DefaultStates
from osf.utils import permissions as osf_permissions
class PreprintPublishedOrAdmin(permissions.BasePermission):
acceptable_models = (Preprint,)
def has_object_permission(self, request, view, obj):
if isinstance(obj, OsfStorageFolder):
obj = obj.target
assert_resource_type(obj, self.acceptable_models)
auth = get_user_auth(request)
if request.method in permissions.SAFE_METHODS:
if auth.user is None:
return obj.verified_publishable
else:
user_has_permissions = (
obj.verified_publishable or
(obj.is_public and auth.user.has_perm('view_submissions', obj.provider)) or
obj.has_permission(auth.user, osf_permissions.ADMIN) or
(obj.is_contributor(auth.user) and obj.machine_state != DefaultStates.INITIAL.value)
)
return user_has_permissions
else:
if not obj.has_permission(auth.user, osf_permissions.ADMIN):
raise exceptions.PermissionDenied(detail='User must be an admin to make these preprint edits.')
return True
class PreprintPublishedOrWrite(PreprintPublishedOrAdmin):
def has_object_permission(self, request, view, obj):
auth = get_user_auth(request)
if isinstance(obj, dict):
obj = obj.get('self', None)
if request.method in permissions.SAFE_METHODS:
return super(PreprintPublishedOrWrite, self).has_object_permission(request, view, obj)
else:
if not obj.has_permission(auth.user, osf_permissions.WRITE):
raise exceptions.PermissionDenied(detail='User must have admin or write permissions to the preprint.')
return True
class ContributorDetailPermissions(PreprintPublishedOrAdmin):
"""Permissions for preprint contributor detail page."""
acceptable_models = (Preprint, OSFUser, PreprintContributor)
def load_resource(self, context, view):
return Preprint.load(context[view.preprint_lookup_url_kwarg])
def has_object_permission(self, request, view, obj):
assert_resource_type(obj, self.acceptable_models)
context = request.parser_context['kwargs']
preprint = self.load_resource(context, view)
auth = get_user_auth(request)
user = OSFUser.load(context['user_id'])
if request.method in permissions.SAFE_METHODS:
return super(ContributorDetailPermissions, self).has_object_permission(request, view, preprint)
elif request.method == 'DELETE':
return preprint.has_permission(auth.user, osf_permissions.ADMIN) or auth.user == user
else:
return preprint.has_permission(auth.user, osf_permissions.ADMIN)
class PreprintIdentifierDetailPermissions(PreprintPublishedOrAdmin):
acceptable_models = (Identifier, Preprint)
def has_object_permission(self, request, view, obj):
assert_resource_type(obj, self.acceptable_models)
referent = obj.referent
if not isinstance(referent, Preprint):
return True
return super(PreprintIdentifierDetailPermissions, self).has_object_permission(request, view, referent)
class AdminOrPublic(NodeAdminOrPublic):
acceptable_models = (Preprint,)
class PreprintFilesPermissions(PreprintPublishedOrAdmin):
"""Permissions for preprint files and provider views."""
acceptable_models = (Preprint,)
def load_resource(self, context, view):
return Preprint.load(context[view.preprint_lookup_url_kwarg])
def has_object_permission(self, request, view, obj):
context = request.parser_context['kwargs']
preprint = self.load_resource(context, view)
assert_resource_type(preprint, self.acceptable_models)
if preprint.is_retracted and request.method in permissions.SAFE_METHODS:
return preprint.can_view_files(get_user_auth(request))
return super(PreprintFilesPermissions, self).has_object_permission(request, view, preprint)
class ModeratorIfNeverPublicWithdrawn(permissions.BasePermission):
# Handles case where moderators should be able to see
# a withdrawn preprint, regardless of "ever_public"
acceptable_models = (Preprint,)
def has_object_permission(self, request, view, obj):
assert_resource_type(obj, self.acceptable_models)
if not obj.is_retracted:
return True
if (obj.is_retracted and obj.ever_public):
# Tombstone page should be public
return True
auth = get_user_auth(request)
if auth.user is None:
raise exceptions.NotFound
if auth.user.has_perm('view_submissions', obj.provider):
if request.method not in permissions.SAFE_METHODS:
# Withdrawn preprints should not be editable
raise exceptions.PermissionDenied(detail='Withdrawn preprints may not be edited')
return True
raise exceptions.NotFound
| 2,131 |
11,247 | /*
* Copyright 2017 JessYan
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jess.arms.base.delegate;
import android.app.Activity;
import android.app.Application;
import android.app.Service;
import android.content.ComponentCallbacks2;
import android.content.ContentProvider;
import android.content.Context;
import android.content.res.Configuration;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import com.jess.arms.base.App;
import com.jess.arms.base.BaseApplication;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.di.component.DaggerAppComponent;
import com.jess.arms.di.module.GlobalConfigModule;
import com.jess.arms.integration.ConfigModule;
import com.jess.arms.integration.ManifestParser;
import com.jess.arms.integration.cache.IntelligentCache;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.Preconditions;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
/**
* ================================================
* AppDelegate 可以代理 Application 的生命周期,在对应的生命周期,执行对应的逻辑,因为 Java 只能单继承
* 所以当遇到某些三方库需要继承于它的 Application 的时候,就只有自定义 Application 并继承于三方库的 Application
* 这时就不用再继承 BaseApplication,只用在自定义Application中对应的生命周期调用AppDelegate对应的方法
* (Application一定要实现APP接口),框架就能照常运行
*
* @see BaseApplication
* @see <a href="https://github.com/JessYanCoding/MVPArms/wiki#3.12">AppDelegate wiki 官方文档</a>
* Created by JessYan on 24/04/2017 09:44
* <a href="mailto:<EMAIL>">Contact me</a>
* <a href="https://github.com/JessYanCoding">Follow me</a>
* ================================================
*/
public class AppDelegate implements App, AppLifecycles {
@Inject
@Named("ActivityLifecycle")
protected Application.ActivityLifecycleCallbacks mActivityLifecycle;
@Inject
@Named("ActivityLifecycleForRxLifecycle")
protected Application.ActivityLifecycleCallbacks mActivityLifecycleForRxLifecycle;
private Application mApplication;
private AppComponent mAppComponent;
private List<ConfigModule> mModules;
private List<AppLifecycles> mAppLifecycles = new ArrayList<>();
private List<Application.ActivityLifecycleCallbacks> mActivityLifecycles = new ArrayList<>();
private ComponentCallbacks2 mComponentCallback;
public AppDelegate(@NonNull Context context) {
//用反射, 将 AndroidManifest.xml 中带有 ConfigModule 标签的 class 转成对象集合(List<ConfigModule>)
this.mModules = new ManifestParser(context).parse();
//遍历之前获得的集合, 执行每一个 ConfigModule 实现类的某些方法
for (ConfigModule module : mModules) {
//将框架外部, 开发者实现的 Application 的生命周期回调 (AppLifecycles) 存入 mAppLifecycles 集合 (此时还未注册回调)
module.injectAppLifecycle(context, mAppLifecycles);
//将框架外部, 开发者实现的 Activity 的生命周期回调 (ActivityLifecycleCallbacks) 存入 mActivityLifecycles 集合 (此时还未注册回调)
module.injectActivityLifecycle(context, mActivityLifecycles);
}
}
@Override
public void attachBaseContext(@NonNull Context base) {
//遍历 mAppLifecycles, 执行所有已注册的 AppLifecycles 的 attachBaseContext() 方法 (框架外部, 开发者扩展的逻辑)
for (AppLifecycles lifecycle : mAppLifecycles) {
lifecycle.attachBaseContext(base);
}
}
@Override
public void onCreate(@NonNull Application application) {
this.mApplication = application;
mAppComponent = DaggerAppComponent
.builder()
.application(mApplication)//提供application
.globalConfigModule(getGlobalConfigModule(mApplication, mModules))//全局配置
.build();
mAppComponent.inject(this);
//将 ConfigModule 的实现类的集合存放到缓存 Cache, 可以随时获取
//使用 IntelligentCache.KEY_KEEP 作为 key 的前缀, 可以使储存的数据永久存储在内存中
//否则存储在 LRU 算法的存储空间中 (大于或等于缓存所能允许的最大 size, 则会根据 LRU 算法清除之前的条目)
//前提是 extras 使用的是 IntelligentCache (框架默认使用)
mAppComponent.extras().put(IntelligentCache.getKeyOfKeep(ConfigModule.class.getName()), mModules);
this.mModules = null;
//注册框架内部已实现的 Activity 生命周期逻辑
mApplication.registerActivityLifecycleCallbacks(mActivityLifecycle);
//注册框架内部已实现的 RxLifecycle 逻辑
mApplication.registerActivityLifecycleCallbacks(mActivityLifecycleForRxLifecycle);
//注册框架外部, 开发者扩展的 Activity 生命周期逻辑
//每个 ConfigModule 的实现类可以声明多个 Activity 的生命周期回调
//也可以有 N 个 ConfigModule 的实现类 (完美支持组件化项目 各个 Module 的各种独特需求)
for (Application.ActivityLifecycleCallbacks lifecycle : mActivityLifecycles) {
mApplication.registerActivityLifecycleCallbacks(lifecycle);
}
mComponentCallback = new AppComponentCallbacks(mApplication, mAppComponent);
//注册回掉: 内存紧张时释放部分内存
mApplication.registerComponentCallbacks(mComponentCallback);
//执行框架外部, 开发者扩展的 App onCreate 逻辑
for (AppLifecycles lifecycle : mAppLifecycles) {
lifecycle.onCreate(mApplication);
}
}
@Override
public void onTerminate(@NonNull Application application) {
if (mActivityLifecycle != null) {
mApplication.unregisterActivityLifecycleCallbacks(mActivityLifecycle);
}
if (mActivityLifecycleForRxLifecycle != null) {
mApplication.unregisterActivityLifecycleCallbacks(mActivityLifecycleForRxLifecycle);
}
if (mComponentCallback != null) {
mApplication.unregisterComponentCallbacks(mComponentCallback);
}
if (mActivityLifecycles != null && mActivityLifecycles.size() > 0) {
for (Application.ActivityLifecycleCallbacks lifecycle : mActivityLifecycles) {
mApplication.unregisterActivityLifecycleCallbacks(lifecycle);
}
}
if (mAppLifecycles != null && mAppLifecycles.size() > 0) {
for (AppLifecycles lifecycle : mAppLifecycles) {
lifecycle.onTerminate(mApplication);
}
}
this.mAppComponent = null;
this.mActivityLifecycle = null;
this.mActivityLifecycleForRxLifecycle = null;
this.mActivityLifecycles = null;
this.mComponentCallback = null;
this.mAppLifecycles = null;
this.mApplication = null;
}
/**
* 将app的全局配置信息封装进module(使用Dagger注入到需要配置信息的地方)
* 需要在AndroidManifest中声明{@link ConfigModule}的实现类,和Glide的配置方式相似
*
* @return GlobalConfigModule
*/
private GlobalConfigModule getGlobalConfigModule(Context context, List<ConfigModule> modules) {
GlobalConfigModule.Builder builder = GlobalConfigModule
.builder();
//遍历 ConfigModule 集合, 给全局配置 GlobalConfigModule 添加参数
for (ConfigModule module : modules) {
module.applyOptions(context, builder);
}
return builder.build();
}
/**
* 将 {@link AppComponent} 返回出去, 供其它地方使用, {@link AppComponent} 接口中声明的方法返回的实例, 在 {@link #getAppComponent()} 拿到对象后都可以直接使用
*
* @return AppComponent
* @see ArmsUtils#obtainAppComponentFromContext(Context) 可直接获取 {@link AppComponent}
*/
@NonNull
@Override
public AppComponent getAppComponent() {
Preconditions.checkNotNull(mAppComponent,
"%s == null, first call %s#onCreate(Application) in %s#onCreate()",
AppComponent.class.getName(), getClass().getName(), mApplication == null
? Application.class.getName() : mApplication.getClass().getName());
return mAppComponent;
}
/**
* {@link ComponentCallbacks2} 是一个细粒度的内存回收管理回调
* {@link Application}、{@link Activity}、{@link Service}、{@link ContentProvider}、{@link Fragment} 实现了 {@link ComponentCallbacks2} 接口
* 开发者应该实现 {@link ComponentCallbacks2#onTrimMemory(int)} 方法, 细粒度 release 内存, 参数的值不同可以体现出不同程度的内存可用情况
* 响应 {@link ComponentCallbacks2#onTrimMemory(int)} 回调, 开发者的 App 会存活的更持久, 有利于用户体验
* 不响应 {@link ComponentCallbacks2#onTrimMemory(int)} 回调, 系统 kill 掉进程的几率更大
*/
private static class AppComponentCallbacks implements ComponentCallbacks2 {
AppComponentCallbacks(Application application, AppComponent appComponent) {
}
/**
* 在你的 App 生命周期的任何阶段, {@link ComponentCallbacks2#onTrimMemory(int)} 发生的回调都预示着你设备的内存资源已经开始紧张
* 你应该根据 {@link ComponentCallbacks2#onTrimMemory(int)} 发生回调时的内存级别来进一步决定释放哪些资源
* {@link ComponentCallbacks2#onTrimMemory(int)} 的回调可以发生在 {@link Application}、{@link Activity}、{@link Service}、{@link ContentProvider}、{@link Fragment}
*
* @param level 内存级别
* @see <a href="https://developer.android.com/reference/android/content/ComponentCallbacks2.html#TRIM_MEMORY_RUNNING_MODERATE">level 官方文档</a>
*/
@Override
public void onTrimMemory(int level) {
//状态1. 当开发者的 App 正在运行
//设备开始运行缓慢, 不会被 kill, 也不会被列为可杀死的, 但是设备此时正运行于低内存状态下, 系统开始触发杀死 LRU 列表中的进程的机制
// case TRIM_MEMORY_RUNNING_MODERATE:
//设备运行更缓慢了, 不会被 kill, 但请你回收 unused 资源, 以便提升系统的性能, 你应该释放不用的资源用来提升系统性能 (但是这也会直接影响到你的 App 的性能)
// case TRIM_MEMORY_RUNNING_LOW:
//设备运行特别慢, 当前 App 还不会被杀死, 但是系统已经把 LRU 列表中的大多数进程都已经杀死, 因此你应该立即释放所有非必须的资源
//如果系统不能回收到足够的 RAM 数量, 系统将会清除所有的 LRU 列表中的进程, 并且开始杀死那些之前被认为不应该杀死的进程, 例如那个包含了一个运行态 Service 的进程
// case TRIM_MEMORY_RUNNING_CRITICAL:
//状态2. 当前 App UI 不再可见, 这是一个回收大个资源的好时机
// case TRIM_MEMORY_UI_HIDDEN:
//状态3. 当前的 App 进程被置于 Background LRU 列表中
//进程位于 LRU 列表的上端, 尽管你的 App 进程并不是处于被杀掉的高危险状态, 但系统可能已经开始杀掉 LRU 列表中的其他进程了
//你应该释放那些容易恢复的资源, 以便于你的进程可以保留下来, 这样当用户回退到你的 App 的时候才能够迅速恢复
// case TRIM_MEMORY_BACKGROUND:
//系统正运行于低内存状态并且你的进程已经已经接近 LRU 列表的中部位置, 如果系统的内存开始变得更加紧张, 你的进程是有可能被杀死的
// case TRIM_MEMORY_MODERATE:
//系统正运行于低内存的状态并且你的进程正处于 LRU 列表中最容易被杀掉的位置, 你应该释放任何不影响你的 App 恢复状态的资源
//低于 API 14 的 App 可以使用 onLowMemory 回调
// case TRIM_MEMORY_COMPLETE:
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
}
/**
* 当系统开始清除 LRU 列表中的进程时, 尽管它会首先按照 LRU 的顺序来清除, 但是它同样会考虑进程的内存使用量, 因此消耗越少的进程则越容易被留下来
* {@link ComponentCallbacks2#onTrimMemory(int)} 的回调是在 API 14 才被加进来的, 对于老的版本, 你可以使用 {@link ComponentCallbacks2#onLowMemory} 方法来进行兼容
* {@link ComponentCallbacks2#onLowMemory} 相当于 {@code onTrimMemory(TRIM_MEMORY_COMPLETE)}
*
* @see #TRIM_MEMORY_COMPLETE
*/
@Override
public void onLowMemory() {
//系统正运行于低内存的状态并且你的进程正处于 LRU 列表中最容易被杀掉的位置, 你应该释放任何不影响你的 App 恢复状态的资源
}
}
}
| 6,920 |
14,668 | <reponame>zealoussnow/chromium
// 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 "third_party/blink/renderer/core/layout/style_retain_scope.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/platform/wtf/thread_specific.h"
namespace blink {
namespace {
StyleRetainScope** CurrentPtr() {
DEFINE_THREAD_SAFE_STATIC_LOCAL(ThreadSpecific<StyleRetainScope*>, current,
());
return &*current;
}
} // namespace
StyleRetainScope::StyleRetainScope() {
StyleRetainScope** current_ptr = CurrentPtr();
parent_ = *current_ptr;
*current_ptr = this;
}
StyleRetainScope::~StyleRetainScope() {
StyleRetainScope** current_ptr = CurrentPtr();
DCHECK_EQ(*current_ptr, this);
*current_ptr = parent_;
}
StyleRetainScope* StyleRetainScope::Current() {
return *CurrentPtr();
}
} // namespace blink
| 366 |
1,655 | <reponame>chaosink/tungsten
#ifndef SAMPLERECORD_HPP_
#define SAMPLERECORD_HPP_
#include "math/MathUtil.hpp"
#include "math/Vec.hpp"
#include "io/FileUtils.hpp"
namespace Tungsten {
struct SampleRecord
{
uint32 sampleCount, nextSampleCount, sampleIndex;
float adaptiveWeight;
float mean, runningVariance;
SampleRecord()
: sampleCount(0), nextSampleCount(0), sampleIndex(0),
adaptiveWeight(0.0f),
mean(0.0f), runningVariance(0.0f)
{
}
void saveState(OutputStreamHandle &out)
{
FileUtils::streamWrite(out, sampleCount);
FileUtils::streamWrite(out, nextSampleCount);
FileUtils::streamWrite(out, sampleIndex);
FileUtils::streamWrite(out, adaptiveWeight);
FileUtils::streamWrite(out, mean);
FileUtils::streamWrite(out, runningVariance);
}
void loadState(InputStreamHandle &in)
{
FileUtils::streamRead(in, sampleCount);
FileUtils::streamRead(in, nextSampleCount);
FileUtils::streamRead(in, sampleIndex);
FileUtils::streamRead(in, adaptiveWeight);
FileUtils::streamRead(in, mean);
FileUtils::streamRead(in, runningVariance);
}
inline void addSample(float x)
{
sampleCount++;
float delta = x - mean;
mean += delta/sampleCount;
runningVariance += delta*(x - mean);
}
inline void addSample(const Vec3f &x)
{
addSample(x.luminance());
}
inline float variance() const
{
return runningVariance/(sampleCount - 1);
}
inline float errorEstimate() const
{
return variance()/(sampleCount*max(mean*mean, 1e-3f));
}
};
}
#endif /* SAMPLERECORD_HPP_ */
| 723 |
828 | package net.hasor.dataql.runtime.basic;
import net.hasor.dataql.AbstractTestResource;
import net.hasor.dataql.HintValue;
import net.hasor.dataql.Query;
import net.hasor.dataql.domain.DataModel;
import net.hasor.dataql.domain.ValueModel;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
public class IfRuntimeTest extends AbstractTestResource implements HintValue {
@Test
public void if_1_Test() throws Exception {
Map<String, Object> objectMap = new HashMap<String, Object>() {{
put("a", true);
}};
//
Query compilerQL = compilerQL(" if (${a}) return 123 else return 321");
DataModel dataModel = compilerQL.execute(objectMap).getData();
assert dataModel.isValue();
assert ((ValueModel) dataModel).isNumber();
assert ((ValueModel) dataModel).asInt() == 123;
}
@Test
public void if_2_Test() throws Exception {
Map<String, Object> objectMap = new HashMap<String, Object>() {{
put("a", false);
}};
//
Query compilerQL = compilerQL(" if (${a}) return 123 else return 321");
DataModel dataModel = compilerQL.execute(objectMap).getData();
assert dataModel.isValue();
assert ((ValueModel) dataModel).isNumber();
assert ((ValueModel) dataModel).asInt() == 321;
}
@Test
public void if_3_Test() throws Exception {
Map<String, Object> objectMap = new HashMap<String, Object>() {{
put("a", false);
}};
//
Query compilerQL = compilerQL("return ${a} ? 123 : 321");
DataModel dataModel = compilerQL.execute(objectMap).getData();
assert dataModel.isValue();
assert ((ValueModel) dataModel).isNumber();
assert ((ValueModel) dataModel).asInt() == 321;
}
@Test
public void if_4_Test() throws Exception {
Map<String, Object> objectMap = new HashMap<String, Object>() {{
put("a", true);
}};
//
Query compilerQL = compilerQL("return ${a} ? 123 : 321");
DataModel dataModel = compilerQL.execute(objectMap).getData();
assert dataModel.isValue();
assert ((ValueModel) dataModel).isNumber();
assert ((ValueModel) dataModel).asInt() == 123;
}
@Test
public void if_5_Test() throws Exception {
Map<String, Object> objectMap = new HashMap<String, Object>() {{
put("a", 2);
}};
//
Query compilerQL = compilerQL("if (${a} == 1) return 'a1' else if ( ${a} ==2 ) return 'a2' else return 'a3'");
DataModel dataModel = compilerQL.execute(objectMap).getData();
assert dataModel.isValue();
assert ((ValueModel) dataModel).isString();
assert ((ValueModel) dataModel).asString().equals("a2");
}
} | 1,130 |
14,668 | <reponame>zealoussnow/chromium
/* See LICENSE file for copyright and license details. */
#include <utf.h>
#include "tap.h"
#define CHECK(S,N,R,RS) do { \
Rune r; \
if(is(utflen(S), 1, #S" is 1 rune long")) { \
is(chartorune(&r, (S)), (N), "rune in "#S" is "#N" bytes long"); \
is(r, (R), "rune in "#S" is "RS); \
} \
else \
skip(2, #S" is an unexpected number of runes long"); \
} while(0)
int
main(void)
{
plan(50);
{
Rune r;
is(chartorune(&r, ""), 1, "rune in \"\" is 1 byte long");
is(r, RUNE_C(0x0000), "rune in \"\" is U+0000 NULL");
}
CHECK("\xC2\x80", 2, RUNE_C(0x00000080), "U+00000080 <control>");
CHECK("\xE0\xA0\x80", 3, RUNE_C(0x00000800), "U+00000800 SAMARITAN LETTER ALAF");
CHECK("\xF0\x90\x80\x80", 4, RUNE_C(0x00010000), "U+00010000 LINEAR B SYLLABLE B008 A");
CHECK("\xF8\x88\x80\x80\x80", 5, Runeerror, "U+00200000 <not a character>");
CHECK("\xFC\x84\x80\x80\x80\x80", 6, Runeerror, "U+04000000 <not a character>");
CHECK("\x7F", 1, RUNE_C(0x0000007F), "U+0000007F DELETE");
CHECK("\xDF\xBF", 2, RUNE_C(0x000007FF), "U+000007FF");
CHECK("\xEF\xBF\xBF", 3, Runeerror, "U+0000FFFF <not a character>");
CHECK("\xF7\xBF\xBF\xBF", 4, Runeerror, "U+001FFFFF <not a character>");
CHECK("\xFB\xBF\xBF\xBF\xBF", 5, Runeerror, "U+03FFFFFF <not a character>");
CHECK("\xFD\xBF\xBF\xBF\xBF\xBF", 6, Runeerror, "U+7FFFFFFF <not a character>");
CHECK("\xED\x9F\xBF", 3, RUNE_C(0x0000D7FF), "U+0000D7FF");
CHECK("\xEE\x80\x80", 3, RUNE_C(0x0000E000), "U+0000E000 <Private Use, First>");
CHECK("\xEF\xBF\xBD", 3, RUNE_C(0x0000FFFD), "U+0000FFFD REPLACEMENT CHARACTER");
CHECK("\xF4\x8F\xBF\xBF", 4, Runeerror, "U+0010FFFF <not a character>");
CHECK("\xF4\x90\x80\x80", 4, Runeerror, "U+00110000 <not a character>");
return 0;
}
| 1,080 |
1,056 | <filename>enterprise/web.el/src/org/netbeans/modules/web/el/completion/ELSanitizer.java
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.web.el.completion;
import com.sun.el.parser.Node;
import java.util.HashSet;
import java.util.Set;
import javax.el.ELException;
import org.netbeans.modules.el.lexer.api.ELTokenId;
import org.netbeans.modules.web.el.ELElement;
import org.netbeans.modules.web.el.ELParser;
import org.netbeans.modules.web.el.ELPreprocessor;
import org.openide.util.Pair;
/**
* Attempts to sanitize EL statements. Check the unit test
* for finding out what cases are currently handled.
*
* @author <NAME>
*/
public final class ELSanitizer {
static final String ADDED_SUFFIX = "x"; // NOI18N
static final String ADDED_QUOTED_SUFFIX = "'x'"; // NOI18N
private final ELPreprocessor expression;
private final ELElement element;
private static final Set<Pair<ELTokenId, ELTokenId>> BRACKETS;
private final int relativeOffset;
static {
BRACKETS = new HashSet<>();
BRACKETS.add(Pair.of(ELTokenId.LBRACKET, ELTokenId.RBRACKET));
BRACKETS.add(Pair.of(ELTokenId.LPAREN, ELTokenId.RPAREN));
}
public ELSanitizer(ELElement element, int relativeOffset) {
this.element = element;
this.expression = element.getExpression();
this.relativeOffset = relativeOffset;
}
/**
* Attempts to sanitize the contained element.
* @return Returns a
* sanitized copy of the element if sanitization was successful, otherwise
* the element itself. In other words, the returned element is <strong>not</strong>
* guaranteed to be valid.
*/
public ELElement sanitized() {
try {
String sanitizedExpression = sanitize(expression.getOriginalExpression(), relativeOffset); //use original expression!
ELPreprocessor elp = new ELPreprocessor(sanitizedExpression, ELPreprocessor.XML_ENTITY_REFS_CONVERSION_TABLE);
Node sanitizedNode = ELParser.parse(elp);
return element.makeValidCopy(sanitizedNode, elp);
} catch (ELException ex) {
return element;
}
}
// package private for unit tests
static String sanitize(final String expression) {
return sanitize(expression, -1);
}
static String sanitize(final String expression, int relativeOffset) {
boolean closingCurlyBracketAdded = false;
String copy = expression;
if (!expression.endsWith("}")) {
copy += "}";
closingCurlyBracketAdded = true;
}
CleanExpression cleanExpression = CleanExpression.getCleanExression(copy);
if (cleanExpression == null) {
return expression;
}
//the CleanExpression removed the #{ or ${ prefix
relativeOffset -= 2;
String result = cleanExpression.clean;
if (closingCurlyBracketAdded && relativeOffset >= 0) {
result = secondPass(result, relativeOffset);
}
if (result.trim().isEmpty()) {
result += ADDED_SUFFIX;
}
// resolve completion invoked within the EL
if (relativeOffset > 0 && relativeOffset < result.length()) {
String exprEnd = result.substring(relativeOffset);
String exprStart = result.substring(0, relativeOffset);
result = thirdPass(exprStart, exprEnd) + exprEnd;
} else {
result = thirdPass(result, ""); //NOI18N
}
return cleanExpression.prefix + result + cleanExpression.suffix;
}
//unclosed expressions handling
private static String secondPass(String expression, int relativeOffset) {
//Cut everything after up to the relative offset (caret)
return expression.substring(0, relativeOffset);
}
private static String thirdPass(String expression, String ending) {
String spaces = "";
if (expression.endsWith(" ")) {
int lastNonWhiteSpace = findLastNonWhiteSpace(expression);
if (lastNonWhiteSpace > 0) {
spaces = expression.substring(lastNonWhiteSpace + 1);
expression = expression.substring(0, lastNonWhiteSpace + 1);
}
}
if (!expression.isEmpty()) {
char lastChar = expression.charAt(expression.length() - 1);
if (lastChar == '\'' || lastChar == '"') { //NOI18N
expression += lastChar;
}
}
for (ELTokenId elToken : ELTokenId.values()) {
if (elToken.fixedText() == null || !expression.endsWith(elToken.fixedText())) {
continue;
}
// special handling for brackets
for (Pair<ELTokenId, ELTokenId> bracket : BRACKETS) {
if (expression.endsWith(bracket.first().fixedText())) {
if (expression.endsWith(ELTokenId.LBRACKET.fixedText())) {
return expression + ADDED_QUOTED_SUFFIX + bracket.second().fixedText();
}
return expression + bracket.second().fixedText();
} else if (expression.endsWith(bracket.second().fixedText())) {
if (expression.endsWith(ELTokenId.RBRACKET.fixedText())) {
// e.g. #{bean.items[|]}
return expression.substring(0, expression.length() - 1) + ADDED_QUOTED_SUFFIX + ELTokenId.RBRACKET.fixedText();
} else if (expression.endsWith(ELTokenId.DOT.fixedText() + ELTokenId.RPAREN.fixedText())
// for opened classname call - e.g. #{(java.|)}
|| expression.endsWith(ELTokenId.LAMBDA.fixedText() + ELTokenId.RPAREN.fixedText())) {
// for started lambda expression - e.g. #{[1,4].stream().peek(i->|)}
return expression.substring(0, expression.length() - 1) + ADDED_SUFFIX + ELTokenId.RPAREN.fixedText();
}
}
}
// sanitizes cases where the expressions ends with dot and spaces,
// e.g. #{foo. }
if (ELTokenId.DOT == elToken) {
if (unbalancedLeftParen(expression + ending)) {
return expression + ADDED_SUFFIX + ELTokenId.RPAREN.fixedText() + spaces ;
} else {
return expression + ADDED_SUFFIX + spaces ;
}
}
// for COLON - e.g. #{foo:
if (ELTokenId.COLON == elToken) {
return expression + ADDED_SUFFIX + ELTokenId.LPAREN.fixedText()
+ ELTokenId.RPAREN.fixedText() + spaces;
}
// for operators
if (ELTokenId.ELTokenCategories.OPERATORS.hasCategory(elToken)) {
return expression + spaces + ADDED_SUFFIX;
}
if (ELTokenId.ELTokenCategories.KEYWORDS.hasCategory(elToken)) {
return expression + " " + spaces + ADDED_SUFFIX;
}
}
// for COLON - e.g. #{foo:foo
if (expression.contains(ELTokenId.COLON.fixedText())) {
return expression + ELTokenId.LPAREN.fixedText() + ELTokenId.RPAREN.fixedText() + spaces;
}
if (unbalancedLeftBracket(expression)) {
return expression + ELTokenId.RBRACKET.fixedText();
}
return expression + spaces;
}
private static boolean unbalancedLeftBracket(String expression) {
return (expression.indexOf(ELTokenId.LBRACKET.fixedText()) > expression.indexOf(ELTokenId.RBRACKET.fixedText()));
}
private static boolean unbalancedLeftParen(String expression) {
return (expression.indexOf(ELTokenId.LPAREN.fixedText()) > expression.indexOf(ELTokenId.RPAREN.fixedText()));
}
// package private for tests
static int findLastNonWhiteSpace(String str) {
int lastNonWhiteSpace = -1;
for (int i = str.length() - 1; i >= 0; i--) {
if (!Character.isWhitespace(str.charAt(i))) {
lastNonWhiteSpace = i;
break;
}
}
return lastNonWhiteSpace;
}
private static class CleanExpression {
private final String clean, prefix, suffix;
public CleanExpression(String clean, String prefix, String suffix) {
this.clean = clean;
this.prefix = prefix;
this.suffix = suffix;
}
private static CleanExpression getCleanExression(String expression) {
if ((expression.startsWith("#{") || expression.startsWith("${"))
&& expression.endsWith("}")) {
String prefix = expression.substring(0, 2);
String clean = expression.substring(2, expression.length() - 1);
String suffix = expression.substring(expression.length() - 1);
return new CleanExpression(clean, prefix, suffix);
}
return null;
}
}
}
| 4,150 |
777 | // Copyright (c) 2012 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/extensions/api/cloud_print_private/cloud_print_private_api.h"
#include <string>
#include "base/memory/ptr_util.h"
#include "base/threading/sequenced_worker_pool.h"
#include "chrome/browser/printing/cloud_print/cloud_print_proxy_service.h"
#include "chrome/browser/printing/cloud_print/cloud_print_proxy_service_factory.h"
#include "chrome/common/extensions/api/cloud_print_private.h"
#include "google_apis/google_api_keys.h"
#include "net/base/network_interfaces.h"
#include "printing/features/features.h"
namespace extensions {
namespace {
#if BUILDFLAG(ENABLE_PRINT_PREVIEW)
const char kErrorIncognito[] = "Cannot access in incognito mode";
#endif
CloudPrintTestsDelegate* g_instance = nullptr;
} // namespace
CloudPrintTestsDelegate* CloudPrintTestsDelegate::Get() {
return g_instance;
}
CloudPrintTestsDelegate::CloudPrintTestsDelegate() {
g_instance = this;
}
CloudPrintTestsDelegate::~CloudPrintTestsDelegate() {
g_instance = nullptr;
}
CloudPrintPrivateSetupConnectorFunction::
CloudPrintPrivateSetupConnectorFunction() {
}
CloudPrintPrivateSetupConnectorFunction::
~CloudPrintPrivateSetupConnectorFunction() {
}
bool CloudPrintPrivateSetupConnectorFunction::RunAsync() {
#if BUILDFLAG(ENABLE_PRINT_PREVIEW)
using api::cloud_print_private::SetupConnector::Params;
std::unique_ptr<Params> params(Params::Create(*args_));
if (CloudPrintTestsDelegate::Get()) {
CloudPrintTestsDelegate::Get()->SetupConnector(
params->user_email, params->robot_email, params->credentials,
params->user_settings);
} else {
std::unique_ptr<base::DictionaryValue> user_settings(
params->user_settings.ToValue());
CloudPrintProxyService* service =
CloudPrintProxyServiceFactory::GetForProfile(GetProfile());
if (!service) {
error_ = kErrorIncognito;
return false;
}
service->EnableForUserWithRobot(params->credentials, params->robot_email,
params->user_email, *user_settings);
}
SendResponse(true);
return true;
#else
return false;
#endif
}
CloudPrintPrivateGetHostNameFunction::CloudPrintPrivateGetHostNameFunction() {
}
CloudPrintPrivateGetHostNameFunction::~CloudPrintPrivateGetHostNameFunction() {
}
bool CloudPrintPrivateGetHostNameFunction::RunAsync() {
SetResult(base::MakeUnique<base::StringValue>(
CloudPrintTestsDelegate::Get()
? CloudPrintTestsDelegate::Get()->GetHostName()
: net::GetHostName()));
SendResponse(true);
return true;
}
CloudPrintPrivateGetPrintersFunction::CloudPrintPrivateGetPrintersFunction() {
}
CloudPrintPrivateGetPrintersFunction::~CloudPrintPrivateGetPrintersFunction() {
}
void CloudPrintPrivateGetPrintersFunction::SendResults(
const std::vector<std::string>& printers) {
results_ = api::cloud_print_private::GetPrinters::Results::Create(printers);
SendResponse(true);
}
bool CloudPrintPrivateGetPrintersFunction::RunAsync() {
#if BUILDFLAG(ENABLE_PRINT_PREVIEW)
if (CloudPrintTestsDelegate::Get()) {
SendResults(CloudPrintTestsDelegate::Get()->GetPrinters());
} else {
CloudPrintProxyService* service =
CloudPrintProxyServiceFactory::GetForProfile(GetProfile());
if (!service) {
error_ = kErrorIncognito;
return false;
}
service->GetPrinters(
base::Bind(&CloudPrintPrivateGetPrintersFunction::SendResults, this));
}
return true;
#else
return false;
#endif
}
CloudPrintPrivateGetClientIdFunction::CloudPrintPrivateGetClientIdFunction() {
}
CloudPrintPrivateGetClientIdFunction::~CloudPrintPrivateGetClientIdFunction() {
}
bool CloudPrintPrivateGetClientIdFunction::RunAsync() {
SetResult(base::MakeUnique<base::StringValue>(
CloudPrintTestsDelegate::Get()
? CloudPrintTestsDelegate::Get()->GetClientId()
: google_apis::GetOAuth2ClientID(google_apis::CLIENT_CLOUD_PRINT)));
SendResponse(true);
return true;
}
} // namespace extensions
| 1,412 |
1,056 | <reponame>timfel/netbeans
/*
* 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.netbeans.modules.maven.model.pom.impl;
import java.util.*;
import org.w3c.dom.Element;
import org.netbeans.modules.maven.model.pom.*;
import org.netbeans.modules.maven.model.pom.POMComponentVisitor;
/**
*
* @author mkleint
*/
public class DependencyManagementImpl extends POMComponentImpl implements DependencyManagement {
public DependencyManagementImpl(POMModel model, Element element) {
super(model, element);
}
public DependencyManagementImpl(POMModel model) {
this(model, createElementNS(model, model.getPOMQNames().DEPENDENCYMANAGEMENT));
}
// attributes
@Override
public List<Dependency> getDependencies() {
ModelList<Dependency> childs = getChild(DependencyImpl.List.class);
if (childs != null) {
return childs.getListChildren();
}
return null;
}
@Override
public void addDependency(Dependency dep) {
ModelList<Dependency> childs = getChild(DependencyImpl.List.class);
if (childs == null) {
setChild(DependencyImpl.List.class,
getModel().getPOMQNames().DEPENDENCIES.getQName().getLocalPart(),
getModel().getFactory().create(this, getModel().getPOMQNames().DEPENDENCIES.getQName()),
Collections.<Class<? extends POMComponent>>emptyList());
childs = getChild(DependencyImpl.List.class);
assert childs != null;
}
childs.addListChild(dep);
}
@Override
public void removeDependency(Dependency dep) {
remove(dep, getModel().getPOMQNames().DEPENDENCIES.getName(), DependencyImpl.List.class);
}
@Override
public Dependency findDependencyById(String groupId, String artifactId, String classifier) {
assert groupId != null;
assert artifactId != null;
List<Dependency> deps = getDependencies();
if (deps != null) {
for (Dependency d : deps) {
if (groupId.equals(d.getGroupId()) && artifactId.equals(d.getArtifactId()) &&
(classifier == null || classifier.equals(d.getClassifier()))) {
return d;
}
}
}
return null;
}
@Override
public void accept(POMComponentVisitor visitor) {
visitor.visit(this);
}
public static class DMList extends DependencyImpl.List {
public DMList(POMModel model, Element element) {
super(model, element);
}
public DMList(POMModel model) {
super(model);
}
@Override
protected DependencyContainer getDependencyContainer() {
return getModel().getProject().getDependencyManagement();
}
}
}
| 1,406 |
346 | <filename>src/game/Utils/Cinematics.h
#ifndef CINEMATICS_H
#define CINEMATICS_H
#include "Types.h"
struct SMKFLIC;
void SmkInitialize(void);
void SmkShutdown(void);
SMKFLIC* SmkPlayFlic(const char* filename, UINT32 left, UINT32 top, BOOLEAN auto_close);
BOOLEAN SmkPollFlics(void);
void SmkCloseFlic(SMKFLIC*);
#endif
| 154 |
1,359 | import torch
import torch.nn as nn
import torch.nn.functional as F
from .BasePIFuNet import BasePIFuNet
from .SurfaceClassifier import SurfaceClassifier
from .DepthNormalizer import DepthNormalizer
from .ConvFilters import *
from ..net_util import init_net
class ConvPIFuNet(BasePIFuNet):
'''
Conv Piximp network is the standard 3-phase network that we will use.
The image filter is a pure multi-layer convolutional network,
while during feature extraction phase all features in the pyramid at the projected location
will be aggregated.
It does the following:
1. Compute image feature pyramids and store it in self.im_feat_list
2. Calculate calibration and indexing on each of the feat, and append them together
3. Classification.
'''
def __init__(self,
opt,
projection_mode='orthogonal',
error_term=nn.MSELoss(),
):
super(ConvPIFuNet, self).__init__(
projection_mode=projection_mode,
error_term=error_term)
self.name = 'convpifu'
self.opt = opt
self.num_views = self.opt.num_views
self.image_filter = self.define_imagefilter(opt)
self.surface_classifier = SurfaceClassifier(
filter_channels=self.opt.mlp_dim,
num_views=self.opt.num_views,
no_residual=self.opt.no_residual,
last_op=nn.Sigmoid())
self.normalizer = DepthNormalizer(opt)
# This is a list of [B x Feat_i x H x W] features
self.im_feat_list = []
init_net(self)
def define_imagefilter(self, opt):
net = None
if opt.netIMF == 'multiconv':
net = MultiConv(opt.enc_dim)
elif 'resnet' in opt.netIMF:
net = ResNet(model=opt.netIMF)
elif opt.netIMF == 'vgg16':
net = Vgg16()
else:
raise NotImplementedError('model name [%s] is not recognized' % opt.imf_type)
return net
def filter(self, images):
'''
Filter the input images
store all intermediate features.
:param images: [B, C, H, W] input images
'''
self.im_feat_list = self.image_filter(images)
def query(self, points, calibs, transforms=None, labels=None):
'''
Given 3D points, query the network predictions for each point.
Image features should be pre-computed before this call.
store all intermediate features.
query() function may behave differently during training/testing.
:param points: [B, 3, N] world space coordinates of points
:param calibs: [B, 3, 4] calibration matrices for each image
:param transforms: Optional [B, 2, 3] image space coordinate transforms
:param labels: Optional [B, Res, N] gt labeling
:return: [B, Res, N] predictions for each point
'''
if labels is not None:
self.labels = labels
xyz = self.projection(points, calibs, transforms)
xy = xyz[:, :2, :]
z = xyz[:, 2:3, :]
z_feat = self.normalizer(z)
# This is a list of [B, Feat_i, N] features
point_local_feat_list = [self.index(im_feat, xy) for im_feat in self.im_feat_list]
point_local_feat_list.append(z_feat)
# [B, Feat_all, N]
point_local_feat = torch.cat(point_local_feat_list, 1)
self.preds = self.surface_classifier(point_local_feat)
| 1,497 |
367 | import asyncio
from opal_common.schemas.data import DataUpdateReport
from opal_client.callbacks.reporter import CallbacksReporter
from opal_client.callbacks.register import CallbacksRegister
from opal_client.data.fetcher import DataFetcher
from typing import List, Optional
import pydantic
from fastapi_websocket_rpc.rpc_channel import RpcChannel
from fastapi_websocket_pubsub import PubSubClient
from opal_common.schemas.store import TransactionType
from opal_common.config import opal_common_config
from opal_common.utils import get_authorization_header
from opal_common.schemas.policy import PolicyBundle, PolicyUpdateMessage
from opal_common.topics.utils import (
pubsub_topics_from_directories,
POLICY_PREFIX,
remove_prefix
)
from opal_client.logger import logger
from opal_client.config import opal_client_config
from opal_client.policy.fetcher import PolicyFetcher
from opal_client.policy_store.base_policy_store_client import BasePolicyStoreClient
from opal_client.policy_store.policy_store_client_factory import DEFAULT_POLICY_STORE_GETTER
from opal_client.policy.topics import default_subscribed_policy_directories
class PolicyUpdater:
"""
Keeps policy-stores (e.g. OPA) up to date with relevant policy code
(e.g: rego) and static data (e.g: data.json files like in OPA bundles).
Uses Pub/Sub to subscribe to specific directories in the policy code
repository (i.e: git), and fetches bundles containing updated policy code.
"""
def __init__(
self,
token: str = None,
pubsub_url: str = None,
subscription_directories: List[str] = None,
policy_store: BasePolicyStoreClient = None,
data_fetcher: Optional[DataFetcher] = None,
callbacks_register: Optional[CallbacksRegister] = None,
opal_client_id: str = None
):
"""inits the policy updater.
Args:
token (str, optional): Auth token to include in connections to OPAL server. Defaults to CLIENT_TOKEN.
pubsub_url (str, optional): URL for Pub/Sub updates for policy. Defaults to OPAL_SERVER_PUBSUB_URL.
subscription_directories (List[str], optional): directories in the policy source repo to subscribe to.
Defaults to POLICY_SUBSCRIPTION_DIRS. every time the directory is updated by a commit we will receive
a message on its respective topic. we dedups directories with ancestral relation, and will only
receive one message for each updated file.
policy_store (BasePolicyStoreClient, optional): Policy store client to use to store policy code. Defaults to DEFAULT_POLICY_STORE.
"""
# defaults
token: str = token or opal_client_config.CLIENT_TOKEN
pubsub_url: str = pubsub_url or opal_client_config.SERVER_PUBSUB_URL
self._subscription_directories: List[str] = subscription_directories or opal_client_config.POLICY_SUBSCRIPTION_DIRS
self._opal_client_id = opal_client_id
# The policy store we'll save policy modules into (i.e: OPA)
self._policy_store = policy_store or DEFAULT_POLICY_STORE_GETTER()
# pub/sub server url and authentication data
self._server_url = pubsub_url
self._token = token
if self._token is None:
self._extra_headers = None
else:
self._extra_headers = [get_authorization_header(self._token)]
# Pub/Sub topics we subscribe to for policy updates
self._topics = pubsub_topics_from_directories(self._subscription_directories)
# The pub/sub client for data updates
self._client = None
# The task running the Pub/Sub subcribing client
self._subscriber_task = None
self._stopping = False
# policy fetcher - fetches policy bundles
self._policy_fetcher = PolicyFetcher()
# callbacks on policy changes
self._data_fetcher = data_fetcher or DataFetcher()
self._callbacks_register = callbacks_register or CallbacksRegister()
self._callbacks_reporter = CallbacksReporter(self._callbacks_register, self._data_fetcher)
self._should_send_reports = opal_client_config.SHOULD_REPORT_ON_DATA_UPDATES or False
async def __aenter__(self):
await self.start()
return self
async def __aexit__(self, exc_type, exc, tb):
if not self._stopping:
await self.stop()
async def _update_policy_callback(self, data: dict = None, topic: str = "", **kwargs):
"""
Pub/Sub callback - triggering policy updates
will run when we get notifications on the policy topic.
i.e: when the source repository changes (new commits)
"""
if data is None:
logger.warning("got policy update message without data, skipping policy update!")
return
try:
message = PolicyUpdateMessage(**data)
except pydantic.ValidationError as e:
logger.warning(f"Got invalid policy update message from server: {repr(e)}")
return
logger.info(
"Received policy update: topic={topic}, message={message}",
topic=topic,
message=message.dict()
)
directories = list(set(message.changed_directories).intersection(set(self._subscription_directories)))
await self.update_policy(directories)
async def _on_connect(self, client: PubSubClient, channel: RpcChannel):
"""
Pub/Sub on_connect callback
On connection to backend, whether its the first connection,
or reconnecting after downtime, refetch the state opa needs.
As long as the connection is alive we know we are in sync with the server,
when the connection is lost we assume we need to start from scratch.
"""
logger.info("Connected to server")
await self.update_policy()
if opal_common_config.STATISTICS_ENABLED:
await self._client.wait_until_ready()
# publish statistics to the server about new connection from client (only if STATISTICS_ENABLED is True, default to False)
await self._client.publish([opal_common_config.STATISTICS_ADD_CLIENT_CHANNEL], data={'topics': self._topics, 'client_id': self._opal_client_id, 'rpc_id': channel.id})
async def _on_disconnect(self, channel: RpcChannel):
"""
Pub/Sub on_disconnect callback
"""
logger.info("Disconnected from server")
async def start(self):
"""
launches the policy updater
"""
logger.info("Launching policy updater")
if self._subscriber_task is None:
self._subscriber_task = asyncio.create_task(self._subscriber())
await self._data_fetcher.start()
async def stop(self):
"""
stops the policy updater
"""
self._stopping = True
logger.info("Stopping policy updater")
# disconnect from Pub/Sub
if self._client is not None:
try:
await asyncio.wait_for(self._client.disconnect(), timeout=3)
except asyncio.TimeoutError:
logger.debug("Timeout waiting for PolicyUpdater pubsub client to disconnect")
# stop subscriber task
if self._subscriber_task is not None:
logger.debug("Cancelling PolicyUpdater subscriber task")
self._subscriber_task.cancel()
try:
await self._subscriber_task
except asyncio.CancelledError as exc:
logger.debug("PolicyUpdater subscriber task was force-cancelled: {exc}", exc=repr(exc))
self._subscriber_task = None
logger.debug("PolicyUpdater subscriber task was cancelled")
await self._data_fetcher.stop()
async def wait_until_done(self):
if self._subscriber_task is not None:
await self._subscriber_task
async def _subscriber(self):
"""
Coroutine meant to be spunoff with create_task to listen in
the background for policy update events and pass them to the
update_policy() callback (which will fetch the relevant policy
bundle from the server and update the policy store).
"""
logger.info("Subscribing to topics: {topics}", topics=self._topics)
self._client = PubSubClient(
topics=self._topics,
callback=self._update_policy_callback,
on_connect=[self._on_connect],
on_disconnect=[self._on_disconnect],
extra_headers=self._extra_headers,
keep_alive=opal_client_config.KEEP_ALIVE_INTERVAL,
server_uri=self._server_url
)
async with self._client:
await self._client.wait_until_done()
async def update_policy(self, directories: List[str] = None, force_full_update=False):
"""
fetches policy (code, e.g: rego) from backend and stores it in the policy store.
Args:
policy_store (BasePolicyStoreClient, optional): Policy store client to use to store policy code.
directories (List[str], optional): specific source directories we want.
force_full_update (bool, optional): if true, ignore stored hash and fetch full policy bundle.
"""
directories = directories if directories is not None else default_subscribed_policy_directories()
if force_full_update:
logger.info("full update was forced (ignoring stored hash if exists)")
base_hash = None
else:
base_hash = await self._policy_store.get_policy_version()
if base_hash is None:
logger.info("Refetching policy code (full bundle)")
else:
logger.info("Refetching policy code (delta bundle), base hash: '{base_hash}'", base_hash=base_hash)
bundle_error = None
bundle = None
bundle_succeeded = True
try:
bundle: Optional[PolicyBundle] = await self._policy_fetcher.fetch_policy_bundle(directories, base_hash=base_hash)
if bundle:
if bundle.old_hash is None:
logger.info(
"Got policy bundle with {rego_files} rego files, {data_files} data files, commit hash: '{commit_hash}'",
rego_files=len(bundle.policy_modules),
data_files=len(bundle.data_modules),
commit_hash=bundle.hash,
manifest=bundle.manifest
)
else:
deleted_files = None if bundle.deleted_files is None else bundle.deleted_files.dict()
logger.info(
"got policy bundle (delta): '{diff_against_hash}' -> '{commit_hash}'",
commit_hash=bundle.hash,
diff_against_hash=bundle.old_hash,
manifest=bundle.manifest,
deleted=deleted_files
)
except Exception as err:
bundle_error = repr(err)
bundle_succeeded = False
bundle_hash = None if bundle is None else bundle.hash
# store policy bundle in OPA cache
# We wrap our interaction with the policy store with a transaction, so that
# if the write-op fails, we will mark the transaction as failed.
async with self._policy_store.transaction_context(bundle_hash, transaction_type=TransactionType.policy) as store_transaction:
store_transaction._update_remote_status(url=self._policy_fetcher.policy_endpoint_url, status=bundle_succeeded, error=bundle_error)
if bundle:
await store_transaction.set_policies(bundle)
# if we got here, we did not throw during the transaction
if self._should_send_reports:
# spin off reporting (no need to wait on it)
report = DataUpdateReport(policy_hash=bundle.hash, reports=[])
asyncio.create_task(self._callbacks_reporter.report_update_results(report))
| 4,935 |
1,527 | {
"name": "Stringer",
"description": "A self-hosted, anti-social RSS reader.",
"logo": "https://raw.githubusercontent.com/swanson/stringer/master/screenshots/logo.png",
"keywords": [
"RSS",
"Ruby"
],
"website": "https://github.com/swanson/stringer",
"success_url": "/heroku",
"scripts": {
"postdeploy": "bundle exec rake db:migrate"
},
"env": {
"SECRET_TOKEN": {
"description": "Secret key used as the session secret",
"generator": "secret"
},
"LOCALE": {
"description": "Specify the translation locale you wish to use",
"value": "en"
},
"ENFORCE_SSL": {
"description": "Force all clients to connect over SSL",
"value": "true"
},
"WORKER_EMBEDDED": {
"description": "Force worker threads to be spawned by main process",
"value": "true"
},
"WORKER_RETRY": {
"description": "Number of times to respawn the worker thread if it fails",
"value": "3"
}
},
"addons": [
"heroku-postgresql:hobby-dev",
"scheduler:standard"
]
}
| 436 |
1,283 | /*
* PriceList_serialization.h
*
* Created on: 2019-5-26
* Author: fasiondog
*/
#pragma once
#ifndef PRICELIST_SERIALIZATION_H_
#define PRICELIST_SERIALIZATION_H_
#include "../config.h"
#include "../DataType.h"
#if HKU_SUPPORT_SERIALIZATION
#if HKU_SUPPORT_XML_ARCHIVE
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/split_free.hpp>
namespace boost {
namespace serialization {
template <class Archive>
void save(Archive& ar, hku::PriceList& values, unsigned int version) {
size_t count = values.size();
unsigned int item_version = 0;
ar& BOOST_SERIALIZATION_NVP(count);
ar& BOOST_SERIALIZATION_NVP(item_version);
for (size_t i = 0; i < count; i++) {
if (std::isnan(values[i])) {
ar& boost::serialization::make_nvp("item", "nan");
} else if (std::isinf(values[i])) {
ar& boost::serialization::make_nvp("item", values[i] > 0 ? "+inf" : "-inf");
} else {
ar& boost::serialization::make_nvp("item", values[i]);
}
}
}
template <class Archive>
void load(Archive& ar, hku::PriceList& values, unsigned int version) {
size_t count = 0;
unsigned int item_version = 0;
ar& BOOST_SERIALIZATION_NVP(count);
ar& BOOST_SERIALIZATION_NVP(item_version);
values.resize(count);
for (size_t i = 0; i < count; i++) {
std::string vstr;
ar >> boost::serialization::make_nvp("item", vstr);
if (vstr == "nan") {
values[i] = std::numeric_limits<double>::quiet_NaN();
} else if (vstr == "+inf") {
values[i] = std::numeric_limits<double>::infinity();
} else if (vstr == "-inf") {
values[i] = 0.0 - std::numeric_limits<double>::infinity();
} else {
values[i] = std::atof(vstr.c_str());
}
}
}
} // namespace serialization
} // namespace boost
BOOST_SERIALIZATION_SPLIT_FREE(hku::PriceList)
#endif /* HKU_SUPPORT_XML_ARCHIVE */
#endif /* HKU_SUPPORT_SERIALIZATION */
#endif /* PRICELIST_SERIALIZATION_H_ */
| 910 |
1,068 | <filename>assertj-android/src/main/java/org/assertj/android/api/widget/ListPopupWindowInputMethodMode.java
package org.assertj.android.api.widget;
import android.support.annotation.IntDef;
import android.widget.ListPopupWindow;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.SOURCE;
@IntDef({
ListPopupWindow.INPUT_METHOD_FROM_FOCUSABLE,
ListPopupWindow.INPUT_METHOD_NEEDED,
ListPopupWindow.INPUT_METHOD_NOT_NEEDED
})
@Retention(SOURCE)
@interface ListPopupWindowInputMethodMode {
}
| 188 |
1,808 | import hyperion, time, random, math
# Initialize the led data
ledData = bytearray()
for i in range(hyperion.ledCount):
ledData += bytearray((0,0,0))
sleepTime = float(hyperion.args.get('speed', 1.0)) * 0.004
minStepTime = float(hyperion.latchTime)/1000.0
if minStepTime == 0: minStepTime = 0.001
factor = 1 if sleepTime > minStepTime else int(math.ceil(minStepTime/sleepTime))
runners = [
{ "i":0, "pos":0, "c":0, "step":9, "lvl":255},
{ "i":1, "pos":0, "c":0, "step":8, "lvl":255},
{ "i":2, "pos":0, "c":0, "step":7, "lvl":255},
{ "i":0, "pos":0, "c":0, "step":6, "lvl":100},
{ "i":1, "pos":0, "c":0, "step":5, "lvl":100},
{ "i":2, "pos":0, "c":0, "step":4, "lvl":100},
]
# Start the write data loop
i = 0
while not hyperion.abort():
for r in runners:
if r["c"] == 0:
#ledData[r["pos"]*3+r["i"]] = 0
r["c"] = r["step"]
r["pos"] = (r["pos"]+1)%hyperion.ledCount
ledData[r["pos"]*3+r["i"]] = int(r["lvl"]*(0.2+0.8*random.random()))
else:
r["c"] -= 1
i += 1
if i % factor == 0:
hyperion.setColor(ledData)
i = 0
time.sleep(sleepTime)
| 515 |
597 |
///////////////////////////////////////////////////////////////////////////////
// Copyright 2014 <NAME>
// Copyright 2014 <NAME>
// Copyright 2014 <NAME>
// Copyright 2014 <NAME>
// Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef BOOST_MATH_HYPERGEOMETRIC_1F1_BESSEL_HPP
#define BOOST_MATH_HYPERGEOMETRIC_1F1_BESSEL_HPP
#include <boost/math/tools/series.hpp>
#include <boost/math/special_functions/bessel.hpp>
#include <boost/math/special_functions/laguerre.hpp>
#include <boost/math/special_functions/detail/hypergeometric_pFq_checked_series.hpp>
#include <boost/math/special_functions/bessel_iterators.hpp>
namespace boost { namespace math { namespace detail {
template <class T, class Policy>
T hypergeometric_1F1_divergent_fallback(const T& a, const T& b, const T& z, const Policy& pol, int& log_scaling);
template <class T>
bool hypergeometric_1F1_is_tricomi_viable_positive_b(const T& a, const T& b, const T& z)
{
BOOST_MATH_STD_USING
if ((z < b) && (a > -50))
return false; // might as well fall through to recursion
if (b <= 100)
return true;
// Even though we're in a reasonable domain for Tricomi's approximation,
// the arguments to the Bessel functions may be so large that we can't
// actually evaluate them:
T x = sqrt(fabs(2 * z * b - 4 * a * z));
T v = b - 1;
return log(boost::math::constants::e<T>() * x / (2 * v)) * v > tools::log_min_value<T>();
}
//
// Returns an arbitrarily small value compared to "target" for use as a seed
// value for Bessel recurrences. Note that we'd better not make it too small
// or underflow may occur resulting in either one of the terms in the
// recurrence being zero, or else the result being zero. Using 1/epsilon
// as a safety factor ensures that if we do underflow to zero, all of the digits
// will have been cancelled out anyway:
//
template <class T>
T arbitrary_small_value(const T& target)
{
using std::fabs;
return (tools::min_value<T>() / tools::epsilon<T>()) * (fabs(target) > 1 ? target : 1);
}
template <class T, class Policy>
struct hypergeometric_1F1_AS_13_3_7_tricomi_series
{
typedef T result_type;
enum { cache_size = 64 };
hypergeometric_1F1_AS_13_3_7_tricomi_series(const T& a, const T& b, const T& z, const Policy& pol_)
: A_minus_2(1), A_minus_1(0), A(b / 2), mult(z / 2), term(1), b_minus_1_plus_n(b - 1),
bessel_arg((b / 2 - a) * z),
two_a_minus_b(2 * a - b), pol(pol_), n(2)
{
BOOST_MATH_STD_USING
term /= pow(fabs(bessel_arg), b_minus_1_plus_n / 2);
mult /= sqrt(fabs(bessel_arg));
bessel_cache[cache_size - 1] = bessel_arg > 0 ? boost::math::cyl_bessel_j(b_minus_1_plus_n - 1, 2 * sqrt(bessel_arg), pol) : boost::math::cyl_bessel_i(b_minus_1_plus_n - 1, 2 * sqrt(-bessel_arg), pol);
if (fabs(bessel_cache[cache_size - 1]) < tools::min_value<T>() / tools::epsilon<T>())
{
// We get very limited precision due to rapid denormalisation/underflow of the Bessel values, raise an exception and try something else:
policies::raise_evaluation_error("hypergeometric_1F1_AS_13_3_7_tricomi_series<%1%>", "Underflow in Bessel functions", bessel_cache[cache_size - 1], pol);
}
if ((term * bessel_cache[cache_size - 1] < tools::min_value<T>() / (tools::epsilon<T>() * tools::epsilon<T>())) || !(boost::math::isfinite)(term) || (!std::numeric_limits<T>::has_infinity && (fabs(term) > tools::max_value<T>())))
{
term = -log(fabs(bessel_arg)) * b_minus_1_plus_n / 2;
log_scale = itrunc(term);
term -= log_scale;
term = exp(term);
}
else
log_scale = 0;
#ifndef BOOST_NO_CXX17_IF_CONSTEXPR
if constexpr (std::numeric_limits<T>::has_infinity)
{
if (!(boost::math::isfinite)(bessel_cache[cache_size - 1]))
policies::raise_evaluation_error("hypergeometric_1F1_AS_13_3_7_tricomi_series<%1%>", "Expected finite Bessel function result but got %1%", bessel_cache[cache_size - 1], pol);
}
else
if ((boost::math::isnan)(bessel_cache[cache_size - 1]) || (fabs(bessel_cache[cache_size - 1]) >= tools::max_value<T>()))
policies::raise_evaluation_error("hypergeometric_1F1_AS_13_3_7_tricomi_series<%1%>", "Expected finite Bessel function result but got %1%", bessel_cache[cache_size - 1], pol);
#else
if ((std::numeric_limits<T>::has_infinity && !(boost::math::isfinite)(bessel_cache[cache_size - 1]))
|| (!std::numeric_limits<T>::has_infinity && ((boost::math::isnan)(bessel_cache[cache_size - 1]) || (fabs(bessel_cache[cache_size - 1]) >= tools::max_value<T>()))))
policies::raise_evaluation_error("hypergeometric_1F1_AS_13_3_7_tricomi_series<%1%>", "Expected finite Bessel function result but got %1%", bessel_cache[cache_size - 1], pol);
#endif
cache_offset = -cache_size;
refill_cache();
}
T operator()()
{
//
// We return the n-2 term, and do 2 terms at once as every other term can be
// very small (or zero) when b == 2a:
//
BOOST_MATH_STD_USING
if(n - 2 - cache_offset >= cache_size)
refill_cache();
T result = A_minus_2 * term * bessel_cache[n - 2 - cache_offset];
term *= mult;
++n;
T A_next = ((b_minus_1_plus_n + 2) * A_minus_1 + two_a_minus_b * A_minus_2) / n;
b_minus_1_plus_n += 1;
A_minus_2 = A_minus_1;
A_minus_1 = A;
A = A_next;
if (A_minus_2 != 0)
{
if (n - 2 - cache_offset >= cache_size)
refill_cache();
result += A_minus_2 * term * bessel_cache[n - 2 - cache_offset];
}
term *= mult;
++n;
A_next = ((b_minus_1_plus_n + 2) * A_minus_1 + two_a_minus_b * A_minus_2) / n;
b_minus_1_plus_n += 1;
A_minus_2 = A_minus_1;
A_minus_1 = A;
A = A_next;
return result;
}
int scale()const
{
return log_scale;
}
private:
T A_minus_2, A_minus_1, A, mult, term, b_minus_1_plus_n, bessel_arg, two_a_minus_b;
std::array<T, cache_size> bessel_cache;
const Policy& pol;
int n, log_scale, cache_offset;
hypergeometric_1F1_AS_13_3_7_tricomi_series operator=(const hypergeometric_1F1_AS_13_3_7_tricomi_series&);
void refill_cache()
{
BOOST_MATH_STD_USING
//
// We don't calculate a new bessel I/J value: instead start our iterator off
// with an arbitrary small value, then when we get back to the last value in the previous cache
// calculate the ratio and use it to renormalise all the new values. This is more efficient, but
// also avoids problems with J_v(x) or I_v(x) underflowing to zero.
//
cache_offset += cache_size;
T last_value = bessel_cache.back();
T ratio;
if (bessel_arg > 0)
{
//
// We will be calculating Bessel J.
// We need a different recurrence strategy for positive and negative orders:
//
if (b_minus_1_plus_n > 0)
{
bessel_j_backwards_iterator<T> i(b_minus_1_plus_n + (int)cache_size - 1, 2 * sqrt(bessel_arg), arbitrary_small_value(last_value));
for (int j = cache_size - 1; j >= 0; --j, ++i)
{
bessel_cache[j] = *i;
//
// Depending on the value of bessel_arg, the values stored in the cache can grow so
// large as to overflow, if that looks likely then we need to rescale all the
// existing terms (most of which will then underflow to zero). In this situation
// it's likely that our series will only need 1 or 2 terms of the series but we
// can't be sure of that:
//
if ((j < cache_size - 2) && (tools::max_value<T>() / fabs(64 * bessel_cache[j] / bessel_cache[j + 1]) < fabs(bessel_cache[j])))
{
T rescale = pow(fabs(bessel_cache[j] / bessel_cache[j + 1]), j + 1) * 2;
if (!((boost::math::isfinite)(rescale)))
rescale = tools::max_value<T>();
for (int k = j; k < cache_size; ++k)
bessel_cache[k] /= rescale;
bessel_j_backwards_iterator<T> ti(b_minus_1_plus_n + j, 2 * sqrt(bessel_arg), bessel_cache[j + 1], bessel_cache[j]);
i = ti;
}
}
ratio = last_value / *i;
}
else
{
//
// Negative order is difficult: the J_v(x) recurrence relations are unstable
// *in both directions* for v < 0, except as v -> -INF when we have
// J_-v(x) ~= -sin(pi.v)Y_v(x).
// For small v what we can do is compute every other Bessel function and
// then fill in the gaps using the recurrence relation. This *is* stable
// provided that v is not so negative that the above approximation holds.
//
bessel_cache[1] = cyl_bessel_j(b_minus_1_plus_n + 1, 2 * sqrt(bessel_arg), pol);
bessel_cache[0] = (last_value + bessel_cache[1]) / (b_minus_1_plus_n / sqrt(bessel_arg));
int pos = 2;
while ((pos < cache_size - 1) && (b_minus_1_plus_n + pos < 0))
{
bessel_cache[pos + 1] = cyl_bessel_j(b_minus_1_plus_n + pos + 1, 2 * sqrt(bessel_arg), pol);
bessel_cache[pos] = (bessel_cache[pos-1] + bessel_cache[pos+1]) / ((b_minus_1_plus_n + pos) / sqrt(bessel_arg));
pos += 2;
}
if (pos < cache_size)
{
//
// We have crossed over into the region where backward recursion is the stable direction
// start from arbitrary value and recurse down to "pos" and normalise:
//
bessel_j_backwards_iterator<T> i2(b_minus_1_plus_n + (int)cache_size - 1, 2 * sqrt(bessel_arg), arbitrary_small_value(bessel_cache[pos-1]));
for (int loc = cache_size - 1; loc >= pos; --loc)
bessel_cache[loc] = *i2++;
ratio = bessel_cache[pos - 1] / *i2;
//
// Sanity check, if we normalised to an unusually small value then it was likely
// to be near a root and the calculated ratio is garbage, if so perform one
// more J_v(x) evaluation at position and normalise again:
//
if (fabs(bessel_cache[pos] * ratio / bessel_cache[pos - 1]) > 5)
ratio = cyl_bessel_j(b_minus_1_plus_n + pos, 2 * sqrt(bessel_arg), pol) / bessel_cache[pos];
while (pos < cache_size)
bessel_cache[pos++] *= ratio;
}
ratio = 1;
}
}
else
{
//
// Bessel I.
// We need a different recurrence strategy for positive and negative orders:
//
if (b_minus_1_plus_n > 0)
{
bessel_i_backwards_iterator<T> i(b_minus_1_plus_n + (int)cache_size - 1, 2 * sqrt(-bessel_arg), arbitrary_small_value(last_value));
for (int j = cache_size - 1; j >= 0; --j, ++i)
{
bessel_cache[j] = *i;
//
// Depending on the value of bessel_arg, the values stored in the cache can grow so
// large as to overflow, if that looks likely then we need to rescale all the
// existing terms (most of which will then underflow to zero). In this situation
// it's likely that our series will only need 1 or 2 terms of the series but we
// can't be sure of that:
//
if ((j < cache_size - 2) && (tools::max_value<T>() / fabs(64 * bessel_cache[j] / bessel_cache[j + 1]) < fabs(bessel_cache[j])))
{
T rescale = pow(fabs(bessel_cache[j] / bessel_cache[j + 1]), j + 1) * 2;
if (!((boost::math::isfinite)(rescale)))
rescale = tools::max_value<T>();
for (int k = j; k < cache_size; ++k)
bessel_cache[k] /= rescale;
i = bessel_i_backwards_iterator<T>(b_minus_1_plus_n + j, 2 * sqrt(-bessel_arg), bessel_cache[j + 1], bessel_cache[j]);
}
}
ratio = last_value / *i;
}
else
{
//
// Forwards iteration is stable:
//
bessel_i_forwards_iterator<T> i(b_minus_1_plus_n, 2 * sqrt(-bessel_arg));
int pos = 0;
while ((pos < cache_size) && (b_minus_1_plus_n + pos < 0.5))
{
bessel_cache[pos++] = *i++;
}
if (pos < cache_size)
{
//
// We have crossed over into the region where backward recursion is the stable direction
// start from arbitrary value and recurse down to "pos" and normalise:
//
bessel_i_backwards_iterator<T> i2(b_minus_1_plus_n + (int)cache_size - 1, 2 * sqrt(-bessel_arg), arbitrary_small_value(last_value));
for (int loc = cache_size - 1; loc >= pos; --loc)
bessel_cache[loc] = *i2++;
ratio = bessel_cache[pos - 1] / *i2;
while (pos < cache_size)
bessel_cache[pos++] *= ratio;
}
ratio = 1;
}
}
if(ratio != 1)
for (auto j = bessel_cache.begin(); j != bessel_cache.end(); ++j)
*j *= ratio;
//
// Very occationally our normalisation fails because the normalisztion value
// is sitting right on top of a root (or very close to it). When that happens
// best to calculate a fresh Bessel evaluation and normalise again.
//
if (fabs(bessel_cache[0] / last_value) > 5)
{
ratio = (bessel_arg < 0 ? cyl_bessel_i(b_minus_1_plus_n, 2 * sqrt(-bessel_arg), pol) : cyl_bessel_j(b_minus_1_plus_n, 2 * sqrt(bessel_arg), pol)) / bessel_cache[0];
if (ratio != 1)
for (auto j = bessel_cache.begin(); j != bessel_cache.end(); ++j)
*j *= ratio;
}
}
};
template <class T, class Policy>
T hypergeometric_1F1_AS_13_3_7_tricomi(const T& a, const T& b, const T& z, const Policy& pol, int& log_scale)
{
BOOST_MATH_STD_USING
//
// Works for a < 0, b < 0, z > 0.
//
// For convergence we require A * term to be converging otherwise we get
// a divergent alternating series. It's actually really hard to analyse this
// and the best purely heuristic policy we've found is
// z < fabs((2 * a - b) / (sqrt(fabs(a)))) ; b > 0 or:
// z < fabs((2 * a - b) / (sqrt(fabs(ab)))) ; b < 0
//
T prefix(0);
int prefix_sgn(0);
bool use_logs = false;
int scale = 0;
//
// We can actually support the b == 2a case within here, but we haven't
// as we appear never to get here in practice. Which means this get out
// clause is a bit of defensive programming....
//
if(b == 2 * a)
return hypergeometric_1F1_divergent_fallback(a, b, z, pol, log_scale);
try
{
prefix = boost::math::tgamma(b, pol);
prefix *= exp(z / 2);
}
catch (const std::runtime_error&)
{
use_logs = true;
}
if (use_logs || (prefix == 0) || !(boost::math::isfinite)(prefix) || (!std::numeric_limits<T>::has_infinity && (fabs(prefix) >= tools::max_value<T>())))
{
use_logs = true;
prefix = boost::math::lgamma(b, &prefix_sgn, pol) + z / 2;
scale = itrunc(prefix);
log_scale += scale;
prefix -= scale;
}
T result(0);
boost::uintmax_t max_iter = boost::math::policies::get_max_series_iterations<Policy>();
bool retry = false;
int series_scale = 0;
try
{
hypergeometric_1F1_AS_13_3_7_tricomi_series<T, Policy> s(a, b, z, pol);
series_scale = s.scale();
log_scale += s.scale();
try
{
T norm = 0;
result = 0;
if((a < 0) && (b < 0))
result = boost::math::tools::checked_sum_series(s, boost::math::policies::get_epsilon<T, Policy>(), max_iter, result, norm);
else
result = boost::math::tools::sum_series(s, boost::math::policies::get_epsilon<T, Policy>(), max_iter, result);
if (!(boost::math::isfinite)(result) || (result == 0) || (!std::numeric_limits<T>::has_infinity && (fabs(result) >= tools::max_value<T>())))
retry = true;
if (norm / fabs(result) > 1 / boost::math::tools::root_epsilon<T>())
retry = true; // fatal cancellation
}
catch (const std::overflow_error&)
{
retry = true;
}
catch (const boost::math::evaluation_error&)
{
retry = true;
}
}
catch (const std::overflow_error&)
{
log_scale -= scale;
return hypergeometric_1F1_divergent_fallback(a, b, z, pol, log_scale);
}
catch (const boost::math::evaluation_error&)
{
log_scale -= scale;
return hypergeometric_1F1_divergent_fallback(a, b, z, pol, log_scale);
}
if (retry)
{
log_scale -= scale;
log_scale -= series_scale;
return hypergeometric_1F1_divergent_fallback(a, b, z, pol, log_scale);
}
boost::math::policies::check_series_iterations<T>("boost::math::hypergeometric_1F1_AS_13_3_7<%1%>(%1%,%1%,%1%)", max_iter, pol);
if (use_logs)
{
int sgn = boost::math::sign(result);
prefix += log(fabs(result));
result = sgn * prefix_sgn * exp(prefix);
}
else
{
if ((fabs(result) > 1) && (fabs(prefix) > 1) && (tools::max_value<T>() / fabs(result) < fabs(prefix)))
{
// Overflow:
scale = itrunc(tools::log_max_value<T>()) - 10;
log_scale += scale;
result /= exp(T(scale));
}
result *= prefix;
}
return result;
}
template <class T>
struct cyl_bessel_i_large_x_sum
{
typedef T result_type;
cyl_bessel_i_large_x_sum(const T& v, const T& x) : v(v), z(x), term(1), k(0) {}
T operator()()
{
T result = term;
++k;
term *= -(4 * v * v - (2 * k - 1) * (2 * k - 1)) / (8 * k * z);
return result;
}
T v, z, term;
int k;
};
template <class T, class Policy>
T cyl_bessel_i_large_x_scaled(const T& v, const T& x, int& log_scaling, const Policy& pol)
{
BOOST_MATH_STD_USING
cyl_bessel_i_large_x_sum<T> s(v, x);
boost::uintmax_t max_iter = boost::math::policies::get_max_series_iterations<Policy>();
T result = boost::math::tools::sum_series(s, boost::math::policies::get_epsilon<T, Policy>(), max_iter);
boost::math::policies::check_series_iterations<T>("boost::math::cyl_bessel_i_large_x<%1%>(%1%,%1%)", max_iter, pol);
int scale = boost::math::itrunc(x);
log_scaling += scale;
return result * exp(x - scale) / sqrt(boost::math::constants::two_pi<T>() * x);
}
template <class T, class Policy>
struct hypergeometric_1F1_AS_13_3_6_series
{
typedef T result_type;
enum { cache_size = 64 };
//
// This series is only convergent/useful for a and b approximately equal
// (ideally |a-b| < 1). The series can also go divergent after a while
// when b < 0, which limits precision to around that of double. In that
// situation we return 0 to terminate the series as otherwise the divergent
// terms will destroy all the bits in our result before they do eventually
// converge again. One important use case for this series is for z < 0
// and |a| << |b| so that either b-a == b or at least most of the digits in a
// are lost in the subtraction. Note that while you can easily convince yourself
// that the result should be unity when b-a == b, in fact this is not (quite)
// the case for large z.
//
hypergeometric_1F1_AS_13_3_6_series(const T& a, const T& b, const T& z, const T& b_minus_a, const Policy& pol_)
: b_minus_a(b_minus_a), half_z(z / 2), poch_1(2 * b_minus_a - 1), poch_2(b_minus_a - a), b_poch(b), term(1), last_result(1), sign(1), n(0), cache_offset(-cache_size), scale(0), pol(pol_)
{
bessel_i_cache[cache_size - 1] = half_z > tools::log_max_value<T>() ?
cyl_bessel_i_large_x_scaled(T(b_minus_a - 1.5f), half_z, scale, pol) : boost::math::cyl_bessel_i(b_minus_a - 1.5f, half_z, pol);
refill_cache();
}
T operator()()
{
BOOST_MATH_STD_USING
if(n - cache_offset >= cache_size)
refill_cache();
T result = term * (b_minus_a - 0.5f + n) * sign * bessel_i_cache[n - cache_offset];
++n;
term *= poch_1;
poch_1 = (n == 1) ? T(2 * b_minus_a) : T(poch_1 + 1);
term *= poch_2;
poch_2 += 1;
term /= n;
term /= b_poch;
b_poch += 1;
sign = -sign;
if ((fabs(result) > fabs(last_result)) && (n > 100))
return 0; // series has gone divergent!
last_result = result;
return result;
}
int scaling()const
{
return scale;
}
private:
T b_minus_a, half_z, poch_1, poch_2, b_poch, term, last_result;
int sign;
int n, cache_offset, scale;
const Policy& pol;
std::array<T, cache_size> bessel_i_cache;
void refill_cache()
{
BOOST_MATH_STD_USING
//
// We don't calculate a new bessel I value: instead start our iterator off
// with an arbitrary small value, then when we get back to the last value in the previous cache
// calculate the ratio and use it to renormalise all the values. This is more efficient, but
// also avoids problems with I_v(x) underflowing to zero.
//
cache_offset += cache_size;
T last_value = bessel_i_cache.back();
bessel_i_backwards_iterator<T> i(b_minus_a + cache_offset + (int)cache_size - 1.5f, half_z, tools::min_value<T>() * (fabs(last_value) > 1 ? last_value : 1) / tools::epsilon<T>());
for (int j = cache_size - 1; j >= 0; --j, ++i)
{
bessel_i_cache[j] = *i;
//
// Depending on the value of half_z, the values stored in the cache can grow so
// large as to overflow, if that looks likely then we need to rescale all the
// existing terms (most of which will then underflow to zero). In this situation
// it's likely that our series will only need 1 or 2 terms of the series but we
// can't be sure of that:
//
if((j < cache_size - 2) && (bessel_i_cache[j + 1] != 0) && (tools::max_value<T>() / fabs(64 * bessel_i_cache[j] / bessel_i_cache[j + 1]) < fabs(bessel_i_cache[j])))
{
T rescale = pow(fabs(bessel_i_cache[j] / bessel_i_cache[j + 1]), j + 1) * 2;
if (rescale > tools::max_value<T>())
rescale = tools::max_value<T>();
for (int k = j; k < cache_size; ++k)
bessel_i_cache[k] /= rescale;
i = bessel_i_backwards_iterator<T>(b_minus_a -0.5f + cache_offset + j, half_z, bessel_i_cache[j + 1], bessel_i_cache[j]);
}
}
T ratio = last_value / *i;
for (auto j = bessel_i_cache.begin(); j != bessel_i_cache.end(); ++j)
*j *= ratio;
}
hypergeometric_1F1_AS_13_3_6_series();
hypergeometric_1F1_AS_13_3_6_series(const hypergeometric_1F1_AS_13_3_6_series&);
hypergeometric_1F1_AS_13_3_6_series& operator=(const hypergeometric_1F1_AS_13_3_6_series&);
};
template <class T, class Policy>
T hypergeometric_1F1_AS_13_3_6(const T& a, const T& b, const T& z, const T& b_minus_a, const Policy& pol, int& log_scaling)
{
BOOST_MATH_STD_USING
if(b_minus_a == 0)
{
// special case: M(a,a,z) == exp(z)
int scale = itrunc(z, pol);
log_scaling += scale;
return exp(z - scale);
}
hypergeometric_1F1_AS_13_3_6_series<T, Policy> s(a, b, z, b_minus_a, pol);
boost::uintmax_t max_iter = boost::math::policies::get_max_series_iterations<Policy>();
T result = boost::math::tools::sum_series(s, boost::math::policies::get_epsilon<T, Policy>(), max_iter);
boost::math::policies::check_series_iterations<T>("boost::math::hypergeometric_1F1_AS_13_3_6<%1%>(%1%,%1%,%1%)", max_iter, pol);
result *= boost::math::tgamma(b_minus_a - 0.5f) * pow(z / 4, -b_minus_a + 0.5f);
int scale = itrunc(z / 2);
log_scaling += scale;
log_scaling += s.scaling();
result *= exp(z / 2 - scale);
return result;
}
/****************************************************************************************************************/
//
// The following are not used at present and are commented out for that reason:
//
/****************************************************************************************************************/
#if 0
template <class T, class Policy>
struct hypergeometric_1F1_AS_13_3_8_series
{
//
// TODO: store and cache Bessel function evaluations via backwards recurrence.
//
// The C term grows by at least an order of magnitude with each iteration, and
// rate of growth is largely independent of the arguments. Free parameter h
// seems to give accurate results for small values (almost zero) or h=1.
// Convergence and accuracy, only when -a/z > 100, this appears to have no
// or little benefit over 13.3.7 as it generally requires more iterations?
//
hypergeometric_1F1_AS_13_3_8_series(const T& a, const T& b, const T& z, const T& h, const Policy& pol_)
: C_minus_2(1), C_minus_1(-b * h), C(b * (b + 1) * h * h / 2 - (2 * h - 1) * a / 2),
bessel_arg(2 * sqrt(-a * z)), bessel_order(b - 1), power_term(std::pow(-a * z, (1 - b) / 2)), mult(z / std::sqrt(-a * z)),
a_(a), b_(b), z_(z), h_(h), n(2), pol(pol_)
{
}
T operator()()
{
// we actually return the n-2 term:
T result = C_minus_2 * power_term * boost::math::cyl_bessel_j(bessel_order, bessel_arg, pol);
bessel_order += 1;
power_term *= mult;
++n;
T C_next = ((1 - 2 * h_) * (n - 1) - b_ * h_) * C
+ ((1 - 2 * h_) * a_ - h_ * (h_ - 1) *(b_ + n - 2)) * C_minus_1
- h_ * (h_ - 1) * a_ * C_minus_2;
C_next /= n;
C_minus_2 = C_minus_1;
C_minus_1 = C;
C = C_next;
return result;
}
T C, C_minus_1, C_minus_2, bessel_arg, bessel_order, power_term, mult, a_, b_, z_, h_;
const Policy& pol;
int n;
typedef T result_type;
};
template <class T, class Policy>
T hypergeometric_1F1_AS_13_3_8(const T& a, const T& b, const T& z, const T& h, const Policy& pol)
{
BOOST_MATH_STD_USING
T prefix = exp(h * z) * boost::math::tgamma(b);
hypergeometric_1F1_AS_13_3_8_series<T, Policy> s(a, b, z, h, pol);
boost::uintmax_t max_iter = boost::math::policies::get_max_series_iterations<Policy>();
T result = boost::math::tools::sum_series(s, boost::math::policies::get_epsilon<T, Policy>(), max_iter);
boost::math::policies::check_series_iterations<T>("boost::math::hypergeometric_1F1_AS_13_3_8<%1%>(%1%,%1%,%1%)", max_iter, pol);
result *= prefix;
return result;
}
//
// This is the series from https://dlmf.nist.gov/13.11
// It appears to be unusable for a,z < 0, and for
// b < 0 appears to never be better than the defining series
// for 1F1.
//
template <class T, class Policy>
struct hypergeometric_1f1_13_11_1_series
{
typedef T result_type;
hypergeometric_1f1_13_11_1_series(const T& a, const T& b, const T& z, const Policy& pol_)
: term(1), two_a_minus_1_plus_s(2 * a - 1), two_a_minus_b_plus_s(2 * a - b), b_plus_s(b), a_minus_half_plus_s(a - 0.5f), half_z(z / 2), s(0), pol(pol_)
{
}
T operator()()
{
T result = term * a_minus_half_plus_s * boost::math::cyl_bessel_i(a_minus_half_plus_s, half_z, pol);
term *= two_a_minus_1_plus_s * two_a_minus_b_plus_s / (b_plus_s * ++s);
two_a_minus_1_plus_s += 1;
a_minus_half_plus_s += 1;
two_a_minus_b_plus_s += 1;
b_plus_s += 1;
return result;
}
T term, two_a_minus_1_plus_s, two_a_minus_b_plus_s, b_plus_s, a_minus_half_plus_s, half_z;
int s;
const Policy& pol;
};
template <class T, class Policy>
T hypergeometric_1f1_13_11_1(const T& a, const T& b, const T& z, const Policy& pol, int& log_scaling)
{
BOOST_MATH_STD_USING
bool use_logs = false;
T prefix;
int prefix_sgn = 1;
if (true/*(a < boost::math::max_factorial<T>::value) && (a > 0)*/)
prefix = boost::math::tgamma(a - 0.5f, pol);
else
{
prefix = boost::math::lgamma(a - 0.5f, &prefix_sgn, pol);
use_logs = true;
}
if (use_logs)
{
prefix += z / 2;
prefix += log(z / 4) * (0.5f - a);
}
else if (z > 0)
{
prefix *= pow(z / 4, 0.5f - a);
prefix *= exp(z / 2);
}
else
{
prefix *= exp(z / 2);
prefix *= pow(z / 4, 0.5f - a);
}
hypergeometric_1f1_13_11_1_series<T, Policy> s(a, b, z, pol);
boost::uintmax_t max_iter = boost::math::policies::get_max_series_iterations<Policy>();
T result = boost::math::tools::sum_series(s, boost::math::policies::get_epsilon<T, Policy>(), max_iter);
boost::math::policies::check_series_iterations<T>("boost::math::hypergeometric_1f1_13_11_1<%1%>(%1%,%1%,%1%)", max_iter, pol);
if (use_logs)
{
int scaling = itrunc(prefix);
log_scaling += scaling;
prefix -= scaling;
result *= exp(prefix) * prefix_sgn;
}
else
result *= prefix;
return result;
}
#endif
} } } // namespaces
#endif // BOOST_MATH_HYPERGEOMETRIC_1F1_BESSEL_HPP
| 16,646 |
402 | /*
* Copyright 2000-2021 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.client.flow.collection;
import java.util.HashMap;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
public class JreMapTest {
@Test
public void testMap() {
JsMap<String, Integer> map = JsCollections.map();
Assert.assertEquals(0, map.size());
map.set("One", 1).set("Two", 2);
Assert.assertEquals(2, map.size());
Assert.assertTrue(map.has("One"));
Assert.assertTrue(map.has("Two"));
Assert.assertFalse(map.has("Three"));
Assert.assertEquals(1, (int) map.get("One"));
Assert.assertEquals(2, (int) map.get("Two"));
Assert.assertNull(map.get("Three"));
Assert.assertTrue(map.delete("One"));
Assert.assertFalse(map.delete("Three"));
Assert.assertFalse(map.has("One"));
map.clear();
Assert.assertEquals(0, map.size());
Assert.assertFalse(map.has("Two"));
}
@Test
public void testMapValues() {
JsMap<String, Integer> map = JsCollections.map();
map.set("One", 1).set("Two", 2);
JsArray<Integer> values = map.mapValues();
Assert.assertEquals(2, values.length());
Assert.assertEquals(1, values.get(0).intValue());
Assert.assertEquals(2, values.get(1).intValue());
map.delete("One");
values = map.mapValues();
Assert.assertEquals(1, values.length());
Assert.assertEquals(2, values.get(0).intValue());
map.clear();
values = map.mapValues();
Assert.assertEquals(0, values.length());
}
@Test
public void testMapForEach() {
Map<String, Integer> seenValues = new HashMap<>();
JsMap<String, Integer> map = JsCollections.map();
map.set("One", 1).set("Two", 2);
map.forEach((value, key) -> seenValues.put(key, value));
Map<String, Integer> expectedValues = new HashMap<>();
expectedValues.put("One", 1);
expectedValues.put("Two", 2);
Assert.assertEquals(expectedValues, seenValues);
}
}
| 1,066 |
1,236 | package com.example.spotlight;
import android.content.Context;
import android.graphics.Typeface;
import java.util.HashMap;
import java.util.Map;
/**
* Adapted from github.com/romannurik/muzei/
* <p/>
* Also see https://code.google.com/p/android/issues/detail?id=9904
*/
public class FontUtil {
private FontUtil() {
}
private static final Map<String, Typeface> sTypefaceCache = new HashMap<String, Typeface>();
public static Typeface get(Context context, String font) {
synchronized (sTypefaceCache) {
if (!sTypefaceCache.containsKey(font)) {
Typeface tf = Typeface.createFromAsset(
context.getApplicationContext().getAssets(), font + ".ttf");
sTypefaceCache.put(font, tf);
}
return sTypefaceCache.get(font);
}
}
}
| 353 |
2,655 | <gh_stars>1000+
{
"page-assets-bazaar": "Conceptos básicos de Ethereum",
"page-assets-blocks": "Bloques de construcción",
"page-assets-doge": "Doge usando dapps",
"page-assets-download-artist": "Artista:",
"page-assets-download-download": "Descargar",
"page-assets-enterprise": "Ethereum para empresas",
"page-assets-eth": "Ether (ETH)",
"page-assets-eth-diamond-color": "Diamante ETH (color)",
"page-assets-eth-diamond-glyph": "Diamante ETH (glifo)",
"page-assets-eth-diamond-gray": "Diamante ETH (gris)",
"page-assets-eth-diamond-purple": "Diamante ETH (morado)",
"page-assets-eth-diamond-white": "Diamante ETH (blanco)",
"page-assets-eth-glyph-video-dark": "Vídeo de glifos ETH (oscuro)",
"page-assets-eth-glyph-video-light": "Vídeo de glifos ETH (claro)",
"page-assets-eth-logo-landscape-gray": "Logo ETH horizontal (gris)",
"page-assets-eth-logo-landscape-purple": "Logo ETH horizontal (morado)",
"page-assets-eth-logo-landscape-white": "Logo ETH horizontal (blanco)",
"page-assets-eth-logo-portrait-gray": "Logo ETH vertical (gris)",
"page-assets-eth-logo-portrait-purple": "Logo ETH vertical (morado)",
"page-assets-eth-logo-portrait-white": "Logo ETH vertical (blanco)",
"page-assets-eth-wordmark-gray": "Marca denominativa EHT (Gris)",
"page-assets-eth-wordmark-purple": "Marca denominativa ETH (morada)",
"page-assets-eth-wordmark-white": "Marca denominativa ETH (blanca)",
"page-assets-ethereum-brand-assets": "Activos de marca de Ethereum",
"page-assets-h1": "activos de ethereum.org",
"page-assets-hero": "protagonista de ethereum.org",
"page-assets-hero-particles": "Imagen de partículas ETH",
"page-assets-historical-artwork": "Obra histórica",
"page-assets-illustrations": "Ilustraciones",
"page-assets-meta-desc": "Explora y descarga los activos de marca, las ilustraciones y los medios de Ethereum y ethereum.org.",
"page-assets-meta-title": "Activos de marca de Ethereum",
"page-assets-page-assets-solid-background": "Fondo sólido",
"page-assets-page-assets-transparent-background": "Fondo transparente",
"page-assets-robot": "Cartera robot"
}
| 792 |
10,225 | package io.quarkus.undertow.deployment;
import java.util.Optional;
import org.eclipse.microprofile.config.ConfigProvider;
import org.jboss.metadata.property.PropertyResolver;
public class MPConfigPropertyResolver implements PropertyResolver {
@Override
public String resolve(String propertyName) {
Optional<String> val = ConfigProvider.getConfig().getOptionalValue(propertyName, String.class);
return val.orElse(null);
}
}
| 143 |
1,443 | {
"copyright": "subtub, https://github.com/subtub",
"url": "https://github.com/subtub",
"email": "<EMAIL>",
"format": "html",
"gravatar": false,
"theme": "plaintext"
}
| 74 |
782 | <gh_stars>100-1000
/*
* Copyright (c) 2021, <NAME>. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* 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 boofcv.struct.calib;
import org.ejml.FancyPrint;
import static boofcv.struct.calib.CameraPinholeBrown.toStringArray;
/**
* <p>Camera model for omnidirectional single viewpoint sensors [1]. Designed to work with parabolic,
* hyperbolic, wide-angle, and spherical sensors. The FOV that this model can describe is dependent
* on the mirror parameter ξ. See [1] for details, but for example ξ=0 is a pinhole camera,
* ξ=1 can describe fisheye cameras, but a value larger than 1 is limited to 180 degrees due to
* multiple points on the unit sphere intersecting the same projection line. This is the same model as
* {@link CameraPinholeBrown} except that there is a change in reference frame which allows it to model wider FOV.</p>
*
* Forward Projection
* <ol>
* <li>Given a 3D point X=(x,y,z) in camera (mirror) coordinates</li>
* <li>Project onto unit sphere X<sub>s</sub>=X/||X||</li>
* <li>Change reference frame X'=(x',y',z') = (x<sub>s</sub>,y<sub>s</sub>,z<sub>s</sub> + ξ)</li>
* <li>Compute normalized image coordinates (u,v)=(x'/z', y'/z')</li>
* <li>Apply radial and tangential distortion (see below)</li>
* <li>Convert into pixels p = K*distort([u;v])</li>
* </ol>
*
* <pre>
* Camera Projection
* [ fx skew cx ]
* K = [ 0 fy cy ]
* [ 0 0 1 ]
* </pre>
*
* <p>
* Radial and Tangential Distortion:<br>
* x<sub>d</sub> = x<sub>n</sub> + x<sub>n</sub>[k<sub>1</sub> r<sup>2</sup> + ... + k<sub>n</sub> r<sup>2n</sup>]<br>
* dx<sub>u</sub> = [ 2t<sub>1</sub> u v + t<sub>2</sub>(r<sup>2</sup> + 2u<sup>2</sup>)] <br>
* dx<sub>v</sub> = [ t<sub>1</sub>(r<sup>2</sup> + 2v<sup>2</sup>) + 2 t<sub>2</sub> u v]<br>
* <br>
* r<sup>2</sup> = u<sup>2</sup> + v<sup>2</sup><br>
* where x<sub>d</sub> is the distorted normalized image coordinates, x<sub>n</sub>=(u,v) is
* undistorted normalized image coordinates.
* </p>
*
* <p>NOTE: The only difference from [1] is that skew is used instead of fx*alpha.</p>
* <p>
* [1] <NAME>, and <NAME>. "Single view point omnidirectional camera calibration
* from planar grids." ICRA 2007.
* </p>
*
* @author <NAME>
*/
public class CameraUniversalOmni extends CameraPinhole {
/** Mirror offset distance. ξ */
public double mirrorOffset;
/** radial distortion parameters: k<sub>1</sub>,...,k<sub>n</sub> */
public double[] radial;
/** tangential distortion parameters */
public double t1, t2;
/**
* Constructor for specifying number of radial distortion
*
* @param numRadial Number of radial distortion parameters
*/
public CameraUniversalOmni( int numRadial ) {
this.radial = new double[numRadial];
}
/**
* Copy constructor
*
* @param original Model which is to be copied
*/
public CameraUniversalOmni( CameraUniversalOmni original ) {
setTo(original);
}
public CameraUniversalOmni fsetMirror( double mirrorOffset ) {
this.mirrorOffset = mirrorOffset;
return this;
}
public CameraUniversalOmni fsetRadial( double... radial ) {
this.radial = radial.clone();
return this;
}
public CameraUniversalOmni fsetTangental( double t1, double t2 ) {
this.t1 = t1;
this.t2 = t2;
return this;
}
/**
* Assigns this model to be identical to the passed in model
*
* @param original Model which is to be copied
*/
public void setTo( CameraUniversalOmni original ) {
super.setTo(original);
this.mirrorOffset = original.mirrorOffset;
if (radial.length != original.radial.length)
radial = new double[original.radial.length];
System.arraycopy(original.radial, 0, radial, 0, radial.length);
this.t1 = original.t1;
this.t2 = original.t2;
}
@Override
public <T extends CameraModel> T createLike() {
return (T)new CameraUniversalOmni(radial.length);
}
public double[] getRadial() {
return radial;
}
public void setRadial( double[] radial ) {
this.radial = radial;
}
public double getT1() {
return t1;
}
public void setT1( double t1 ) {
this.t1 = t1;
}
public double getT2() {
return t2;
}
public void setT2( double t2 ) {
this.t2 = t2;
}
public double getMirrorOffset() {
return mirrorOffset;
}
public void setMirrorOffset( double mirrorOffset ) {
this.mirrorOffset = mirrorOffset;
}
@Override public String toString() {
FancyPrint fp = new FancyPrint();
String txt = "CameraUniversalOmni{" +
"width=" + width +
", height=" + height +
", fx=" + fx +
", fy=" + fy +
", skew=" + skew +
", cx=" + cx +
", cy=" + cy +
", mirrorOffset=" + fp.s(mirrorOffset);
txt += toStringArray(fp, "r", radial);
if (t1 != 0 || t2 != 0) {
txt += ", t1=" + fp.s(t1) + " t2=" + fp.s(t2);
}
txt += '}';
return txt;
}
@Override
public void print() {
super.print();
if (radial != null) {
for (int i = 0; i < radial.length; i++) {
System.out.printf("radial[%d] = %6.2e\n", i, radial[i]);
}
} else {
System.out.println("No radial");
}
if (t1 != 0 && t2 != 0)
System.out.printf("tangential = ( %6.2e , %6.2e)\n", t1, t2);
else {
System.out.println("No tangential");
}
System.out.printf("mirror offset = %7.3f", mirrorOffset);
}
}
| 2,166 |
2,023 | <gh_stars>1000+
"""
An alternative running scheme for unittest test suites.
Superceded by the TestOOB Python unit testing framework,
http://testoob.sourceforge.net
"""
__author__ = "<NAME>"
import unittest, sys
from itertools import ifilter
###############################################################################
# apply_runner
###############################################################################
# David Eppstein's breadth_first
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/231503
def _breadth_first(tree,children=iter):
"""Traverse the nodes of a tree in breadth-first order.
The first argument should be the tree root; children
should be a function taking as argument a tree node and
returning an iterator of the node's children.
"""
yield tree
last = tree
for node in _breadth_first(tree,children):
for child in children(node):
yield child
last = child
if last == node:
return
def extract_fixtures(suite, recursive_iterator=_breadth_first):
"""Extract the text fixtures from a suite.
Descends recursively into sub-suites."""
def test_children(node):
if isinstance(node, unittest.TestSuite): return iter(node)
return []
return ifilter(lambda test: isinstance(test, unittest.TestCase),
recursive_iterator(suite, children=test_children))
def apply_runner(suite, runner_class, result_class=unittest.TestResult,
test_extractor=extract_fixtures):
"""Runs the suite."""
runner = runner_class(result_class)
for fixture in test_extractor(suite):
runner.run(fixture)
return runner.result()
###############################################################################
# Runners
###############################################################################
class SimpleRunner:
def __init__(self, result_class):
self._result = result_class()
self._done = False
def run(self, fixture):
assert not self._done
fixture(self._result)
def result(self):
self._done = True
return self._result
# <NAME>'s (<EMAIL>ellybarnes at yahoo.com) threadclass
# http://mail.python.org/pipermail/python-list/2004-June/225478.html
import types, threading
def _threadclass(C):
"""Returns a 'threadsafe' copy of class C.
All public methods are modified to lock the
object when called."""
class D(C):
def __init__(self, *args, **kwargs):
self.lock = threading.RLock()
C.__init__(self, *args, **kwargs)
def ubthreadfunction(f):
def g(self, *args, **kwargs):
self.lock.acquire()
try:
return f(self, *args, **kwargs)
finally:
self.lock.release()
return g
for a in dir(D):
f = getattr(D, a)
if isinstance(f, types.UnboundMethodType) and a[:2] != '__':
setattr(D, a, ubthreadfunction(f))
return D
class ThreadedRunner(SimpleRunner):
"""Run tests using a threadpool.
Uses TwistedPython's thread pool"""
def __init__(self, result_class):
from twisted.python.threadpool import ThreadPool
SimpleRunner.__init__(self, _threadclass(result_class))
self._pool = ThreadPool()
self._pool.start()
def run(self, fixture):
assert not self._done
self._pool.dispatch(None, fixture, self._result)
def result(self):
self._pool.stop()
return SimpleRunner.result(self)
###############################################################################
# text_run
###############################################################################
def _print_results(result, timeTaken):
# code modified from Python 2.4's standard unittest module
stream = result.stream
result.printErrors()
stream.writeln(result.separator2)
run = result.testsRun
stream.writeln("Ran %d test%s in %.3fs" %
(run, run != 1 and "s" or "", timeTaken))
stream.writeln()
if not result.wasSuccessful():
stream.write("FAILED (")
failed, errored = map(len, (result.failures, result.errors))
if failed:
stream.write("failures=%d" % failed)
if errored:
if failed: stream.write(", ")
stream.write("errors=%d" % errored)
stream.writeln(")")
else:
stream.writeln("OK")
class _TextTestResult(unittest._TextTestResult):
"""provide defaults for unittest._TextTestResult"""
def __init__(self, stream = sys.stderr, descriptions=1, verbosity=1):
stream = unittest._WritelnDecorator(stream)
unittest._TextTestResult.__init__(self, stream, descriptions, verbosity)
def text_run(suite, runner_class=SimpleRunner, **kwargs):
"""Run a suite and generate output similar to unittest.TextTestRunner's"""
import time
start = time.time()
result = apply_runner(suite, runner_class, result_class=_TextTestResult,
**kwargs)
timeTaken = time.time() - start
_print_results(result, timeTaken)
###############################################################################
# Test extractors
###############################################################################
def regexp_extractor(regexp):
"""Filter tests based on matching a regexp to their id.
Matching is performed with re.search"""
import re
compiled = re.compile(regexp)
def pred(test): return compiled.search(test.id())
def wrapper(suite):
return ifilter(pred, extract_fixtures(suite))
return wrapper
###############################################################################
# examples
###############################################################################
def examples(suite):
print "== sequential =="
text_run(suite)
print "== threaded =="
text_run(suite, ThreadedRunner)
print "== filtered =="
text_run(suite, test_extractor = regexp_extractor("Th"))
| 2,078 |
10,225 | <filename>extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/multipart/AbstractMultipartTest.java
package io.quarkus.resteasy.reactive.server.test.multipart;
import static org.awaitility.Awaitility.await;
import java.io.File;
import java.nio.file.Path;
import java.time.Duration;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
abstract class AbstractMultipartTest {
protected boolean isDirectoryEmpty(Path uploadDir) {
File[] files = uploadDir.toFile().listFiles();
if (files == null) {
return true;
}
return files.length == 0;
}
protected void clearDirectory(Path uploadDir) {
File[] files = uploadDir.toFile().listFiles();
if (files == null) {
return;
}
for (File file : files) {
if (!file.isDirectory()) {
file.delete();
}
}
}
protected void awaitUploadDirectoryToEmpty(Path uploadDir) {
await().atMost(10, TimeUnit.SECONDS)
.pollInterval(Duration.ofSeconds(1))
.until(new Callable<Boolean>() {
@Override
public Boolean call() {
return isDirectoryEmpty(uploadDir);
}
});
}
}
| 633 |
1,697 | <reponame>Paranoid-L/IOT-Technical-Guide
package iot.technology.actor.core;
import iot.technology.actor.ActorCreator;
import iot.technology.actor.message.ActorId;
import iot.technology.actor.message.ActorMsg;
import java.util.List;
import java.util.function.Predicate;
import java.util.function.Supplier;
/**
* @author mushuwei
*/
public interface ActorCtx extends ActorRef {
ActorId getSelf();
ActorRef getParentRef();
void tell(ActorId target, ActorMsg msg);
void stop(ActorId target);
ActorRef getOrCreateChildActor(ActorId actorId, Supplier<String> dispatcher, Supplier<ActorCreator> creator);
void broadcastToChildren(ActorMsg msg);
void broadcastToChildren(ActorMsg msg, Predicate<ActorId> childFilter);
List<ActorId> filterChildren(Predicate<ActorId> childFilter);
}
| 260 |
343 | #include "bindings.h"
#pragma once
#if defined(ON_PYTHON_COMPILE)
void initBitmapBindings(pybind11::module& m);
#else
void initBitmapBindings(void* m);
#endif
class BND_Bitmap : public BND_CommonObject
{
public:
ON_Bitmap* m_bitmap = nullptr;
public:
BND_Bitmap();
BND_Bitmap(ON_Bitmap* bitmap, const ON_ModelComponentReference* compref);
int Width() const { return m_bitmap->Width(); }
int Height() const { return m_bitmap->Height(); }
int BitsPerPixel() const { return m_bitmap->BitsPerPixel(); }
size_t SizeOfScan() const { return m_bitmap->SizeofScan(); }
size_t SizeOfImage() const { return m_bitmap->SizeofImage(); }
//unsigned char* Bits(int scan_line_index);
//const unsigned char* Bits(int scan_line_index) const;
//const ON_FileReference& FileReference() const;
//void SetFileReference(const ON_FileReference& file_reference);
void SetFileFullPath(std::wstring path) { m_bitmap->SetFileFullPath(path.c_str(), true); }
protected:
void SetTrackedPointer(ON_Bitmap* bitmap, const ON_ModelComponentReference* compref);
}; | 367 |
358 | <filename>Resources/Softwares/Apache Tomcat 7.0.75/webapps/examples/WEB-INF/classes/websocket/drawboard/DrawMessage.java
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package websocket.drawboard;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Arc2D;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
/**
* A message that represents a drawing action.
* Note that we use primitive types instead of Point, Color etc.
* to reduce object allocation.<br><br>
*
* TODO: But a Color objects needs to be created anyway for drawing this
* onto a Graphics2D object, so this probably does not save much.
*/
public final class DrawMessage {
private int type;
private byte colorR, colorG, colorB, colorA;
private double thickness;
private double x1, y1, x2, y2;
private boolean lastInChain;
/**
* The type.<br>
* 1: Brush<br>
* 2: Line<br>
* 3: Rectangle<br>
* 4: Ellipse
*/
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public double getThickness() {
return thickness;
}
public void setThickness(double thickness) {
this.thickness = thickness;
}
public byte getColorR() {
return colorR;
}
public void setColorR(byte colorR) {
this.colorR = colorR;
}
public byte getColorG() {
return colorG;
}
public void setColorG(byte colorG) {
this.colorG = colorG;
}
public byte getColorB() {
return colorB;
}
public void setColorB(byte colorB) {
this.colorB = colorB;
}
public byte getColorA() {
return colorA;
}
public void setColorA(byte colorA) {
this.colorA = colorA;
}
public double getX1() {
return x1;
}
public void setX1(double x1) {
this.x1 = x1;
}
public double getX2() {
return x2;
}
public void setX2(double x2) {
this.x2 = x2;
}
public double getY1() {
return y1;
}
public void setY1(double y1) {
this.y1 = y1;
}
public double getY2() {
return y2;
}
public void setY2(double y2) {
this.y2 = y2;
}
/**
* Specifies if this DrawMessage is the last one in a chain
* (e.g. a chain of brush paths).<br>
* Currently it is unused.
*/
public boolean isLastInChain() {
return lastInChain;
}
public void setLastInChain(boolean lastInChain) {
this.lastInChain = lastInChain;
}
public DrawMessage(int type, byte colorR, byte colorG, byte colorB,
byte colorA, double thickness, double x1, double x2, double y1,
double y2, boolean lastInChain) {
this.type = type;
this.colorR = colorR;
this.colorG = colorG;
this.colorB = colorB;
this.colorA = colorA;
this.thickness = thickness;
this.x1 = x1;
this.x2 = x2;
this.y1 = y1;
this.y2 = y2;
this.lastInChain = lastInChain;
}
/**
* Draws this DrawMessage onto the given Graphics2D.
* @param g
*/
public void draw(Graphics2D g) {
g.setStroke(new BasicStroke((float) thickness,
BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER));
g.setColor(new Color(colorR & 0xFF, colorG & 0xFF, colorB & 0xFF,
colorA & 0xFF));
if (x1 == x2 && y1 == y2) {
// Always draw as arc to meet the behavior in the HTML5 Canvas.
Arc2D arc = new Arc2D.Double(x1, y1, 0, 0,
0d, 360d, Arc2D.OPEN);
g.draw(arc);
} else if (type == 1 || type == 2) {
// Draw a line.
Line2D line = new Line2D.Double(x1, y1, x2, y2);
g.draw(line);
} else if (type == 3 || type == 4) {
double x1 = this.x1, x2 = this.x2,
y1 = this.y1, y2 = this.y2;
if (x1 > x2) {
x1 = this.x2;
x2 = this.x1;
}
if (y1 > y2) {
y1 = this.y2;
y2 = this.y1;
}
// TODO: If (x1 == x2 || y1 == y2) draw as line.
if (type == 3) {
// Draw a rectangle.
Rectangle2D rect = new Rectangle2D.Double(x1, y1,
x2 - x1, y2 - y1);
g.draw(rect);
} else if (type == 4) {
// Draw an ellipse.
Arc2D arc = new Arc2D.Double(x1, y1, x2 - x1, y2 - y1,
0d, 360d, Arc2D.OPEN);
g.draw(arc);
}
}
}
/**
* Converts this message into a String representation that
* can be sent over WebSocket.<br>
* Since a DrawMessage consists only of numbers,
* we concatenate those numbers with a ",".
*/
@Override
public String toString() {
return type + "," + (colorR & 0xFF) + "," + (colorG & 0xFF) + ","
+ (colorB & 0xFF) + "," + (colorA & 0xFF) + "," + thickness
+ "," + x1 + "," + y1 + "," + x2 + "," + y2 + ","
+ (lastInChain ? "1" : "0");
}
public static DrawMessage parseFromString(String str)
throws ParseException {
int type;
byte[] colors = new byte[4];
double thickness;
double[] coords = new double[4];
boolean last;
try {
String[] elements = str.split(",");
type = Integer.parseInt(elements[0]);
if (!(type >= 1 && type <= 4))
throw new ParseException("Invalid type: " + type);
for (int i = 0; i < colors.length; i++) {
colors[i] = (byte) Integer.parseInt(elements[1 + i]);
}
thickness = Double.parseDouble(elements[5]);
if (Double.isNaN(thickness) || thickness < 0 || thickness > 100)
throw new ParseException("Invalid thickness: " + thickness);
for (int i = 0; i < coords.length; i++) {
coords[i] = Double.parseDouble(elements[6 + i]);
if (Double.isNaN(coords[i]))
throw new ParseException("Invalid coordinate: "
+ coords[i]);
}
last = !"0".equals(elements[10]);
} catch (RuntimeException ex) {
throw new ParseException(ex);
}
DrawMessage m = new DrawMessage(type, colors[0], colors[1],
colors[2], colors[3], thickness, coords[0], coords[2],
coords[1], coords[3], last);
return m;
}
public static class ParseException extends Exception {
private static final long serialVersionUID = -6651972769789842960L;
public ParseException(Throwable root) {
super(root);
}
public ParseException(String message) {
super(message);
}
}
}
| 3,667 |
335 | <reponame>Safal08/Hacktoberfest-1
{
"word": "Vivid",
"definitions": [
"Producing powerful feelings or strong, clear images in the mind.",
"(of a colour) intensely deep or bright.",
"(of a person or animal) lively and vigorous."
],
"parts-of-speech": "Adjective"
} | 120 |
443 | /*
* MIT License
*
* Copyright (c) [2018] [WangBoJing]
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*
*
**** ***** ************
*** * ** ** *
*** * * * ** **
* ** * * * ** *
* ** * * * ** *
* ** * ** **
* ** * *** **
* ** * *********** ***** ***** ** ***** * ****
* ** * ** ** ** ** *** * **** * **
* ** * ** ** * ** ** ** *** **
* ** * ** * * ** ** ** ** *
* ** * ** ** * ** ** ** ** **
* ** * ** * * ** ** ** **
* ** * ** ** * ** ** ** **
* ** * ** ** * ** ** ** **
* ** * ** * * ** ** ** **
* ** * ** ** * ** ** ** **
* *** ** * * ** ** * ** **
* *** ** * ** ** ** * ** **
* ** ** * ** ** ** * *** **
* ** ** * * ** ** * **** **
***** * **** * ****** ***** ** ****
* **
* **
***** **
**** ******
*
*/
#include "nty_api.h"
#include "nty_epoll.h"
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#define EPOLL_SIZE 5
#define BUFFER_LENGTH 1024
int main() {
nty_tcp_setup();
usleep(1);
int sockfd = nty_socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("socket");
return 1;
}
struct sockaddr_in addr;
memset(&addr, 0, sizeof(struct sockaddr_in));
addr.sin_family = AF_INET;
addr.sin_port = htons(9096);
addr.sin_addr.s_addr = INADDR_ANY;
if(nty_bind(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_in)) < 0) {
perror("bind");
return 2;
}
if (nty_listen(sockfd, 5) < 0) {
return 3;
}
int epoll_fd = nty_epoll_create(EPOLL_SIZE);
nty_epoll_event ev, events[EPOLL_SIZE];
ev.events = NTY_EPOLLIN;
ev.data = (uint64_t)sockfd;
nty_epoll_ctl(epoll_fd, NTY_EPOLL_CTL_ADD, sockfd, &ev);
while (1) {
int nready = nty_epoll_wait(epoll_fd, events, EPOLL_SIZE, -1);
if (nready == -1) {
printf("epoll_wait\n");
break;
}
printf("nready : %d\n", nready);
int i = 0;
for (i = 0;i < nready;i ++) {
if (events[i].data == (uint64_t)sockfd) {
struct sockaddr_in client_addr;
memset(&client_addr, 0, sizeof(struct sockaddr_in));
socklen_t client_len = sizeof(client_addr);
int clientfd = nty_accept(sockfd, (struct sockaddr*)&client_addr, &client_len);
if (clientfd <= 0) continue;
char str[INET_ADDRSTRLEN] = {0};
printf("recvived from %s at port %d, sockfd:%d, clientfd:%d\n", inet_ntop(AF_INET, &client_addr.sin_addr, str, sizeof(str)),
ntohs(client_addr.sin_port), sockfd, clientfd);
ev.events = NTY_EPOLLIN | NTY_EPOLLET;
ev.data = (uint64_t)clientfd;
nty_epoll_ctl(epoll_fd, NTY_EPOLL_CTL_ADD, clientfd, &ev);
} else {
int clientfd = (int)events[i].data;
char buffer[BUFFER_LENGTH] = {0};
int ret = nty_recv(clientfd, buffer, BUFFER_LENGTH, 0);
if (ret < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
printf("read all data");
}
nty_close(clientfd);
ev.events = NTY_EPOLLIN | NTY_EPOLLET;
ev.data = (uint64_t)clientfd;
nty_epoll_ctl(epoll_fd, NTY_EPOLL_CTL_DEL, clientfd, &ev);
} else if (ret == 0) {
printf(" disconnect %d\n", clientfd);
close(clientfd);
ev.events = NTY_EPOLLIN | NTY_EPOLLET;
ev.data = clientfd;
nty_epoll_ctl(epoll_fd, NTY_EPOLL_CTL_DEL, clientfd, &ev);
break;
} else {
printf("Recv: %s, %d Bytes\n", buffer, ret);
nty_send(clientfd, buffer, ret);
}
}
}
}
return 0;
}
| 3,474 |
319 | /**
* Copyright (c) 2011, The University of Southampton and the individual contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the University of Southampton nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openimaj.demos.sandbox.ml.regression;
import java.io.IOException;
import javax.swing.JFrame;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.time.Day;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.openimaj.io.Cache;
import org.openimaj.ml.timeseries.IncompatibleTimeSeriesException;
import org.openimaj.ml.timeseries.aggregator.MeanSquaredDifferenceAggregator;
import org.openimaj.ml.timeseries.processor.MovingAverageProcessor;
import org.openimaj.ml.timeseries.processor.WindowedLinearRegressionProcessor;
import org.openimaj.ml.timeseries.series.DoubleTimeSeries;
import org.openimaj.twitter.finance.YahooFinanceData;
import org.openimaj.util.pair.IndependentPair;
/**
* @author <NAME> (<EMAIL>)
*
*/
public class LinearRegressionPlayground {
/**
* @param args
* @throws IOException
* @throws IncompatibleTimeSeriesException
*/
public static void main(String[] args) throws IOException, IncompatibleTimeSeriesException {
final String stock = "AAPL";
final String start = "2010-01-01";
final String end = "2010-12-31";
final String learns = "2010-01-01";
final String learne = "2010-05-01";
final DateTimeFormatter parser = DateTimeFormat.forPattern("YYYY-MM-dd");
final long learnstart = parser.parseDateTime(learns).getMillis();
final long learnend = parser.parseDateTime(learne).getMillis();
YahooFinanceData data = new YahooFinanceData(stock, start, end, "YYYY-MM-dd");
data = Cache.load(data);
final DoubleTimeSeries highseries = data.seriesMap().get("High");
final DoubleTimeSeries yearFirstHalf = highseries.get(learnstart, learnend);
TimeSeriesCollection dataset = new TimeSeriesCollection();
dataset.addSeries(timeSeriesToChart("High Value", highseries));
final DoubleTimeSeries movingAverage = highseries.process(new MovingAverageProcessor(30l * 24l * 60l * 60l
* 1000l));
final DoubleTimeSeries halfYearMovingAverage = yearFirstHalf.process(new MovingAverageProcessor(30l * 24l * 60l
* 60l * 1000l));
dataset.addSeries(
timeSeriesToChart(
"High Value MA",
movingAverage
));
dataset.addSeries(
timeSeriesToChart(
"High Value MA Regressed (all seen)",
movingAverage.process(new WindowedLinearRegressionProcessor(10, 7))
));
dataset.addSeries(
timeSeriesToChart(
"High Value MA Regressed (latter half unseen)",
movingAverage.process(new WindowedLinearRegressionProcessor(halfYearMovingAverage, 10, 7))
));
displayTimeSeries(dataset, stock, "Date", "Price");
dataset = new TimeSeriesCollection();
dataset.addSeries(timeSeriesToChart("High Value", highseries));
// final DoubleTimeSeries linearRegression = highseries.process(new
// LinearRegressionProcessor());
// double lrmsd =
// MeanSquaredDifferenceAggregator.error(linearRegression,highseries);
// dataset.addSeries(timeSeriesToChart(String.format("OLR (MSE=%.2f)",lrmsd),linearRegression));
final DoubleTimeSeries windowedLinearRegression107 = highseries.process(new WindowedLinearRegressionProcessor(10,
7));
final DoubleTimeSeries windowedLinearRegression31 = highseries
.process(new WindowedLinearRegressionProcessor(3, 1));
final DoubleTimeSeries windowedLinearRegression107unseen = highseries
.process(new WindowedLinearRegressionProcessor(yearFirstHalf, 10, 7));
final double e107 = MeanSquaredDifferenceAggregator.error(windowedLinearRegression107, highseries);
final double e31 = MeanSquaredDifferenceAggregator.error(windowedLinearRegression31, highseries);
final double e107u = MeanSquaredDifferenceAggregator.error(windowedLinearRegression107unseen, highseries);
dataset.addSeries(timeSeriesToChart(String.format("OLR (m=7,n=10) (MSE=%.2f)", e107), windowedLinearRegression107));
dataset.addSeries(timeSeriesToChart(String.format("OLR (m=1,n=3) (MSE=%.2f)", e31), windowedLinearRegression31));
dataset.addSeries(timeSeriesToChart(String.format("OLR unseen (m=7,n=10) (MSE=%.2f)", e107u),
windowedLinearRegression107unseen));
displayTimeSeries(dataset, stock, "Date", "Price");
}
private static void displayTimeSeries(TimeSeriesCollection dataset, String name, String xname, String yname) {
final JFreeChart chart = ChartFactory.createTimeSeriesChart(name, xname, yname, dataset, true, false, false);
final ChartPanel panel = new ChartPanel(chart);
panel.setFillZoomRectangle(true);
final JFrame j = new JFrame();
j.setContentPane(panel);
j.pack();
j.setVisible(true);
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private static org.jfree.data.time.TimeSeries timeSeriesToChart(String name, DoubleTimeSeries highseries) {
final TimeSeries ret = new TimeSeries(name);
for (final IndependentPair<Long, Double> pair : highseries) {
final DateTime dt = new DateTime(pair.firstObject());
final Day d = new Day(dt.getDayOfMonth(), dt.getMonthOfYear(), dt.getYear());
ret.add(d, pair.secondObject());
}
return ret;
}
}
| 2,214 |
356 | #include "afio_pch.hpp"
int main(void)
{
//[filedir_example
using namespace BOOST_AFIO_V2_NAMESPACE;
using BOOST_AFIO_V2_NAMESPACE::rmdir;
std::shared_ptr<boost::afio::dispatcher> dispatcher =
boost::afio::make_dispatcher().get();
current_dispatcher_guard h(dispatcher);
// Free function
try
{
// Schedule creating a directory called testdir
auto mkdir(async_dir("testdir", boost::afio::file_flags::create));
// Schedule creating a file called testfile in testdir only when testdir has been created
auto mkfile(async_file(mkdir, "testfile", boost::afio::file_flags::create));
// Schedule creating a symbolic link called linktodir to the item referred to by the precondition
// i.e. testdir. Note that on Windows you can only symbolic link directories.
auto mklink(async_symlink(mkdir, "linktodir", mkdir, boost::afio::file_flags::create));
// Schedule deleting the symbolic link only after when it has been created
auto rmlink(async_rmsymlink(mklink));
// Schedule deleting the file only after when it has been created
auto rmfile(async_close(async_rmfile(mkfile)));
// Schedule waiting until both the preceding operations have finished
auto barrier(dispatcher->barrier({ rmlink, rmfile }));
// Schedule deleting the directory only after the barrier completes
auto rmdir(async_rmdir(depends(barrier.front(), mkdir)));
// Check ops for errors
boost::afio::when_all_p(mkdir, mkfile, mklink, rmlink, rmfile, rmdir).wait();
}
catch (...)
{
std::cerr << boost::current_exception_diagnostic_information(true) << std::endl;
throw;
}
// Batch
try
{
// Schedule creating a directory called testdir
auto mkdir(dispatcher->dir(std::vector<boost::afio::path_req>(1,
boost::afio::path_req("testdir", boost::afio::file_flags::create))).front());
// Schedule creating a file called testfile in testdir only when testdir has been created
auto mkfile(dispatcher->file(std::vector<boost::afio::path_req>(1,
boost::afio::path_req::relative(mkdir, "testfile",
boost::afio::file_flags::create))).front());
// Schedule creating a symbolic link called linktodir to the item referred to by the precondition
// i.e. testdir. Note that on Windows you can only symbolic link directories. Note that creating
// symlinks must *always* be as an absolute path, as that is how they are stored.
auto mklink(dispatcher->symlink(std::vector<boost::afio::path_req>(1,
boost::afio::path_req::absolute(mkdir, "testdir/linktodir",
boost::afio::file_flags::create))).front());
// Schedule deleting the symbolic link only after when it has been created
auto rmlink(dispatcher->close(std::vector<future<>>(1, dispatcher->rmsymlink(mklink))).front());
// Schedule deleting the file only after when it has been created
auto rmfile(dispatcher->close(std::vector<future<>>(1, dispatcher->rmfile(mkfile))).front());
// Schedule waiting until both the preceding operations have finished
auto barrier(dispatcher->barrier({rmlink, rmfile}));
// Schedule deleting the directory only after the barrier completes
auto rmdir(dispatcher->rmdir(std::vector<path_req>(1, dispatcher->depends(barrier.front(), mkdir))).front());
// Check ops for errors
boost::afio::when_all_p(mkdir, mkfile, mklink, rmlink, rmfile, rmdir).wait();
}
catch(...)
{
std::cerr << boost::current_exception_diagnostic_information(true) << std::endl;
throw;
}
//]
}
| 1,252 |
364 | // File implement/oglplus/enums/error_code_class.ipp
//
// Automatically generated file, DO NOT modify manually.
// Edit the source 'source/enums/oglplus/error_code.txt'
// or the 'source/enums/make_enum.py' script instead.
//
// Copyright 2010-2019 <NAME>.
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
namespace enums {
template <typename Base, template<ErrorCode> class Transform>
class EnumToClass<Base, ErrorCode, Transform>
: public Base
{
private:
Base& _base() { return *this; }
public:
#if defined GL_NO_ERROR
# if defined NoError
# pragma push_macro("NoError")
# undef NoError
Transform<ErrorCode::NoError> NoError;
# pragma pop_macro("NoError")
# else
Transform<ErrorCode::NoError> NoError;
# endif
#endif
#if defined GL_OUT_OF_MEMORY
# if defined OutOfMemory
# pragma push_macro("OutOfMemory")
# undef OutOfMemory
Transform<ErrorCode::OutOfMemory> OutOfMemory;
# pragma pop_macro("OutOfMemory")
# else
Transform<ErrorCode::OutOfMemory> OutOfMemory;
# endif
#endif
#if defined GL_INVALID_ENUM
# if defined InvalidEnum
# pragma push_macro("InvalidEnum")
# undef InvalidEnum
Transform<ErrorCode::InvalidEnum> InvalidEnum;
# pragma pop_macro("InvalidEnum")
# else
Transform<ErrorCode::InvalidEnum> InvalidEnum;
# endif
#endif
#if defined GL_INVALID_VALUE
# if defined InvalidValue
# pragma push_macro("InvalidValue")
# undef InvalidValue
Transform<ErrorCode::InvalidValue> InvalidValue;
# pragma pop_macro("InvalidValue")
# else
Transform<ErrorCode::InvalidValue> InvalidValue;
# endif
#endif
#if defined GL_INVALID_OPERATION
# if defined InvalidOperation
# pragma push_macro("InvalidOperation")
# undef InvalidOperation
Transform<ErrorCode::InvalidOperation> InvalidOperation;
# pragma pop_macro("InvalidOperation")
# else
Transform<ErrorCode::InvalidOperation> InvalidOperation;
# endif
#endif
#if defined GL_INVALID_FRAMEBUFFER_OPERATION
# if defined InvalidFramebufferOperation
# pragma push_macro("InvalidFramebufferOperation")
# undef InvalidFramebufferOperation
Transform<ErrorCode::InvalidFramebufferOperation> InvalidFramebufferOperation;
# pragma pop_macro("InvalidFramebufferOperation")
# else
Transform<ErrorCode::InvalidFramebufferOperation> InvalidFramebufferOperation;
# endif
#endif
#if defined GL_STACK_OVERFLOW
# if defined StackOverflow
# pragma push_macro("StackOverflow")
# undef StackOverflow
Transform<ErrorCode::StackOverflow> StackOverflow;
# pragma pop_macro("StackOverflow")
# else
Transform<ErrorCode::StackOverflow> StackOverflow;
# endif
#endif
#if defined GL_STACK_UNDERFLOW
# if defined StackUnderflow
# pragma push_macro("StackUnderflow")
# undef StackUnderflow
Transform<ErrorCode::StackUnderflow> StackUnderflow;
# pragma pop_macro("StackUnderflow")
# else
Transform<ErrorCode::StackUnderflow> StackUnderflow;
# endif
#endif
#if defined GL_TABLE_TOO_LARGE
# if defined TableTooLarge
# pragma push_macro("TableTooLarge")
# undef TableTooLarge
Transform<ErrorCode::TableTooLarge> TableTooLarge;
# pragma pop_macro("TableTooLarge")
# else
Transform<ErrorCode::TableTooLarge> TableTooLarge;
# endif
#endif
#if defined GL_CONTEXT_LOST
# if defined ContextLost
# pragma push_macro("ContextLost")
# undef ContextLost
Transform<ErrorCode::ContextLost> ContextLost;
# pragma pop_macro("ContextLost")
# else
Transform<ErrorCode::ContextLost> ContextLost;
# endif
#endif
EnumToClass() { }
EnumToClass(Base&& base)
: Base(std::move(base))
#if defined GL_NO_ERROR
# if defined NoError
# pragma push_macro("NoError")
# undef NoError
, NoError(_base())
# pragma pop_macro("NoError")
# else
, NoError(_base())
# endif
#endif
#if defined GL_OUT_OF_MEMORY
# if defined OutOfMemory
# pragma push_macro("OutOfMemory")
# undef OutOfMemory
, OutOfMemory(_base())
# pragma pop_macro("OutOfMemory")
# else
, OutOfMemory(_base())
# endif
#endif
#if defined GL_INVALID_ENUM
# if defined InvalidEnum
# pragma push_macro("InvalidEnum")
# undef InvalidEnum
, InvalidEnum(_base())
# pragma pop_macro("InvalidEnum")
# else
, InvalidEnum(_base())
# endif
#endif
#if defined GL_INVALID_VALUE
# if defined InvalidValue
# pragma push_macro("InvalidValue")
# undef InvalidValue
, InvalidValue(_base())
# pragma pop_macro("InvalidValue")
# else
, InvalidValue(_base())
# endif
#endif
#if defined GL_INVALID_OPERATION
# if defined InvalidOperation
# pragma push_macro("InvalidOperation")
# undef InvalidOperation
, InvalidOperation(_base())
# pragma pop_macro("InvalidOperation")
# else
, InvalidOperation(_base())
# endif
#endif
#if defined GL_INVALID_FRAMEBUFFER_OPERATION
# if defined InvalidFramebufferOperation
# pragma push_macro("InvalidFramebufferOperation")
# undef InvalidFramebufferOperation
, InvalidFramebufferOperation(_base())
# pragma pop_macro("InvalidFramebufferOperation")
# else
, InvalidFramebufferOperation(_base())
# endif
#endif
#if defined GL_STACK_OVERFLOW
# if defined StackOverflow
# pragma push_macro("StackOverflow")
# undef StackOverflow
, StackOverflow(_base())
# pragma pop_macro("StackOverflow")
# else
, StackOverflow(_base())
# endif
#endif
#if defined GL_STACK_UNDERFLOW
# if defined StackUnderflow
# pragma push_macro("StackUnderflow")
# undef StackUnderflow
, StackUnderflow(_base())
# pragma pop_macro("StackUnderflow")
# else
, StackUnderflow(_base())
# endif
#endif
#if defined GL_TABLE_TOO_LARGE
# if defined TableTooLarge
# pragma push_macro("TableTooLarge")
# undef TableTooLarge
, TableTooLarge(_base())
# pragma pop_macro("TableTooLarge")
# else
, TableTooLarge(_base())
# endif
#endif
#if defined GL_CONTEXT_LOST
# if defined ContextLost
# pragma push_macro("ContextLost")
# undef ContextLost
, ContextLost(_base())
# pragma pop_macro("ContextLost")
# else
, ContextLost(_base())
# endif
#endif
{ }
};
} // namespace enums
| 1,974 |
357 | <reponame>wfu8/lightwave
/*
* Copyright © 2012-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the “License”); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an “AS IS” BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#include "includes.h"
DWORD
VmDirQuerySecurityDescriptorInfo(
SECURITY_INFORMATION SecurityInformationNeeded,
PSECURITY_DESCRIPTOR_RELATIVE SecurityDescriptorInput,
PSECURITY_DESCRIPTOR_RELATIVE SecurityDescriptorOutput,
PULONG Length
)
{
return LwNtStatusToWin32Error(
RtlQuerySecurityDescriptorInfo(SecurityInformationNeeded,
SecurityDescriptorOutput,
Length,
SecurityDescriptorInput));
}
DWORD
VmDirSelfRelativeToAbsoluteSD(
PSECURITY_DESCRIPTOR_RELATIVE SelfRelativeSecurityDescriptor,
PSECURITY_DESCRIPTOR_ABSOLUTE AbsoluteSecurityDescriptor,
PULONG AbsoluteSecurityDescriptorSize,
PACL pDacl,
PULONG pDaclSize,
PACL pSacl,
PULONG pSaclSize,
PSID Owner,
PULONG pOwnerSize,
PSID PrimaryGroup,
PULONG pPrimaryGroupSize
)
{
return LwNtStatusToWin32Error(
RtlSelfRelativeToAbsoluteSD(SelfRelativeSecurityDescriptor,
AbsoluteSecurityDescriptor,
AbsoluteSecurityDescriptorSize,
pDacl,
pDaclSize,
pSacl,
pSaclSize,
Owner,
pOwnerSize,
PrimaryGroup,
pPrimaryGroupSize));
}
BOOLEAN
VmDirAccessCheck(
PSECURITY_DESCRIPTOR_ABSOLUTE SecurityDescriptor,
PACCESS_TOKEN AccessToken,
ACCESS_MASK DesiredAccess,
ACCESS_MASK PreviouslyGrantedAccess,
PGENERIC_MAPPING GenericMapping,
PACCESS_MASK GrantedAccess,
PDWORD pAccessError
)
{
BOOLEAN bRet = FALSE;
NTSTATUS ntStatus = STATUS_SUCCESS;
bRet = RtlAccessCheck(SecurityDescriptor,
AccessToken,
DesiredAccess,
PreviouslyGrantedAccess,
GenericMapping,
GrantedAccess,
&ntStatus);
*pAccessError = LwNtStatusToWin32Error(ntStatus);
return bRet;
}
DWORD
VmDirGetOwnerSecurityDescriptor(
PSECURITY_DESCRIPTOR_ABSOLUTE SecurityDescriptor,
PSID* Owner,
PBOOLEAN pIsOwnerDefaulted
)
{
return LwNtStatusToWin32Error(
RtlGetOwnerSecurityDescriptor(SecurityDescriptor,
Owner,
pIsOwnerDefaulted));
}
DWORD
VmDirGetGroupSecurityDescriptor(
PSECURITY_DESCRIPTOR_ABSOLUTE SecurityDescriptor,
PSID* Group,
PBOOLEAN pIsGroupDefaulted
)
{
return LwNtStatusToWin32Error(
RtlGetGroupSecurityDescriptor(SecurityDescriptor,
Group,
pIsGroupDefaulted));
}
DWORD
VmDirGetDaclSecurityDescriptor(
PSECURITY_DESCRIPTOR_ABSOLUTE SecurityDescriptor,
PBOOLEAN pIsDaclPresent,
PACL* Dacl,
PBOOLEAN pIsDaclDefaulted
)
{
return LwNtStatusToWin32Error(
RtlGetDaclSecurityDescriptor(SecurityDescriptor,
pIsDaclPresent,
Dacl,
pIsDaclDefaulted));
}
DWORD
VmDirGetSaclSecurityDescriptor(
PSECURITY_DESCRIPTOR_ABSOLUTE SecurityDescriptor,
PBOOLEAN pIsSaclPresent,
PACL* Sacl,
PBOOLEAN pIsSaclDefaulted
)
{
return LwNtStatusToWin32Error(
RtlGetSaclSecurityDescriptor(SecurityDescriptor,
pIsSaclPresent,
Sacl,
pIsSaclDefaulted));
}
BOOLEAN
VmDirValidRelativeSecurityDescriptor(
PSECURITY_DESCRIPTOR_RELATIVE SecurityDescriptor,
ULONG SecurityDescriptorLength,
SECURITY_INFORMATION RequiredInformation
)
{
return RtlValidRelativeSecurityDescriptor(SecurityDescriptor,
SecurityDescriptorLength,
RequiredInformation);
}
DWORD
VmDirSetSecurityDescriptorInfo(
SECURITY_INFORMATION SecurityInformation,
PSECURITY_DESCRIPTOR_RELATIVE InputSecurityDescriptor,
PSECURITY_DESCRIPTOR_RELATIVE ObjectSecurityDescriptor,
PSECURITY_DESCRIPTOR_RELATIVE NewObjectSecurityDescriptor,
PULONG NewObjectSecurityDescriptorLength,
PGENERIC_MAPPING GenericMapping
)
{
return LwNtStatusToWin32Error(RtlSetSecurityDescriptorInfo(SecurityInformation,
InputSecurityDescriptor,
ObjectSecurityDescriptor,
NewObjectSecurityDescriptor,
NewObjectSecurityDescriptorLength,
GenericMapping));
}
DWORD
VmDirCreateSecurityDescriptorAbsolute(
PSECURITY_DESCRIPTOR_ABSOLUTE *ppSecurityDescriptor
)
{
DWORD dwError = 0;
PSECURITY_DESCRIPTOR_ABSOLUTE SecurityDescriptor = NULL;
NTSTATUS Status = 0;
dwError = VmDirAllocateMemory(
SECURITY_DESCRIPTOR_ABSOLUTE_MIN_SIZE,
(PVOID*)&SecurityDescriptor);
BAIL_ON_VMDIR_ERROR(dwError);
Status = RtlCreateSecurityDescriptorAbsolute(
SecurityDescriptor,
SECURITY_DESCRIPTOR_REVISION);
dwError = LwNtStatusToWin32Error(Status);
BAIL_ON_VMDIR_ERROR(dwError);
*ppSecurityDescriptor = SecurityDescriptor;
SecurityDescriptor = NULL;
cleanup:
VMDIR_SAFE_FREE_MEMORY(SecurityDescriptor);
return dwError;
error:
goto cleanup;
}
VOID
VmDirReleaseAccessToken(
PACCESS_TOKEN* AccessToken
)
{
RtlReleaseAccessToken(AccessToken);
}
DWORD
VmDirSetOwnerSecurityDescriptor(
PSECURITY_DESCRIPTOR_ABSOLUTE SecurityDescriptor,
PSID Owner,
BOOLEAN IsOwnerDefaulted
)
{
return LwNtStatusToWin32Error(
RtlSetOwnerSecurityDescriptor(
SecurityDescriptor,
Owner,
IsOwnerDefaulted));
}
DWORD
VmDirSetGroupSecurityDescriptor(
PSECURITY_DESCRIPTOR_ABSOLUTE SecurityDescriptor,
PSID Group,
BOOLEAN IsGroupDefaulted
)
{
return LwNtStatusToWin32Error(
RtlSetGroupSecurityDescriptor(SecurityDescriptor, Group, IsGroupDefaulted));
}
ULONG
VmDirLengthSid(
PSID Sid
)
{
return RtlLengthSid(Sid);
}
DWORD
VmDirCreateAcl(
PACL Acl,
ULONG AclLength,
ULONG AclRevision
)
{
return LwNtStatusToWin32Error(RtlCreateAcl(Acl, AclLength, AclRevision));
}
DWORD
VmDirGetAce(
PACL pAcl,
ULONG dwIndex,
PACE_HEADER *ppAce
)
{
return LwNtStatusToWin32Error(RtlGetAce(pAcl, dwIndex, (PVOID*)ppAce));
}
DWORD
VmDirAddAccessAllowedAceEx(
PACL Acl,
ULONG AceRevision,
ULONG AceFlags,
ACCESS_MASK AccessMask,
PSID Sid
)
{
return LwNtStatusToWin32Error(RtlAddAccessAllowedAceEx(Acl,
AceRevision,
AceFlags,
AccessMask,
Sid));
}
DWORD
VmDirAddAccessDeniedAceEx(
PACL Acl,
ULONG AceRevision,
ULONG AceFlags,
ACCESS_MASK AccessMask,
PSID Sid
)
{
return LwNtStatusToWin32Error(RtlAddAccessDeniedAceEx(Acl,
AceRevision,
AceFlags,
AccessMask,
Sid));
}
DWORD
VmDirSetDaclSecurityDescriptor(
PSECURITY_DESCRIPTOR_ABSOLUTE SecurityDescriptor,
BOOLEAN IsDaclPresent,
PACL Dacl,
BOOLEAN IsDaclDefaulted
)
{
return LwNtStatusToWin32Error(
RtlSetDaclSecurityDescriptor(SecurityDescriptor,
IsDaclPresent,
Dacl,
IsDaclDefaulted));
}
BOOLEAN
VmDirValidSecurityDescriptor(
PSECURITY_DESCRIPTOR_ABSOLUTE SecurityDescriptor
)
{
return RtlValidSecurityDescriptor(SecurityDescriptor);
}
DWORD
VmDirAbsoluteToSelfRelativeSD(
PSECURITY_DESCRIPTOR_ABSOLUTE AbsoluteSecurityDescriptor,
PSECURITY_DESCRIPTOR_RELATIVE SelfRelativeSecurityDescriptor,
PULONG BufferLength
)
{
return LwNtStatusToWin32Error(RtlAbsoluteToSelfRelativeSD(
AbsoluteSecurityDescriptor,
SelfRelativeSecurityDescriptor,
BufferLength));
}
DWORD VmDirCreateWellKnownSid(
WELL_KNOWN_SID_TYPE wellKnownSidType,
PSID pDomainSid,
PSID pSid,
DWORD* pcbSid
)
{
DWORD dwError = ERROR_SUCCESS;
dwError = LwNtStatusToWin32Error(
RtlCreateWellKnownSid(
wellKnownSidType,
pDomainSid,
pSid,
pcbSid));
BAIL_ON_VMDIR_ERROR(dwError);
error:
return dwError;
}
VOID
VmDirMapGenericMask(
PDWORD pdwAccessMask,
PGENERIC_MAPPING pGenericMapping
)
{
RtlMapGenericMask(pdwAccessMask, pGenericMapping);
}
DWORD
VmDirQueryAccessTokenInformation(
HANDLE hTokenHandle,
TOKEN_INFORMATION_CLASS tokenInformationClass,
PVOID pTokenInformation,
DWORD dwTokenInformationLength,
PDWORD pdwReturnLength
)
{
DWORD dwError = ERROR_SUCCESS;
dwError = LwNtStatusToWin32Error(
RtlQueryAccessTokenInformation(
hTokenHandle,
tokenInformationClass,
pTokenInformation,
dwTokenInformationLength,
pdwReturnLength));
BAIL_ON_VMDIR_ERROR(dwError);
error:
return dwError;
}
DWORD
VmDirAllocateSddlCStringFromSecurityDescriptor(
PSECURITY_DESCRIPTOR_RELATIVE pSecurityDescriptor,
DWORD dwRequestedStringSDRevision,
SECURITY_INFORMATION securityInformation,
PSTR* ppStringSecurityDescriptor
)
{
DWORD dwError = ERROR_SUCCESS;
dwError = LwNtStatusToWin32Error(
RtlAllocateSddlCStringFromSecurityDescriptor(
ppStringSecurityDescriptor,
pSecurityDescriptor,
dwRequestedStringSDRevision,
securityInformation));
BAIL_ON_VMDIR_ERROR(dwError);
error:
return dwError;
}
DWORD
VmDirSetSecurityDescriptorControl(
PSECURITY_DESCRIPTOR_ABSOLUTE pSecurityDescriptor,
SECURITY_DESCRIPTOR_CONTROL BitsToChange,
SECURITY_DESCRIPTOR_CONTROL BitsToSet
)
{
return LwNtStatusToWin32Error(
RtlSetSecurityDescriptorControl(
pSecurityDescriptor,
BitsToChange,
BitsToSet));
}
| 6,395 |
515 | <reponame>kraehlit/CTK
/*=============================================================================
Library: CTK
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=============================================================================*/
#include "ctkCmdLineModuleExplorerDirectorySettings.h"
#include "ctkCmdLineModuleExplorerConstants.h"
#include <ctkPathListWidget.h>
#include <ctkCmdLineModuleDirectoryWatcher.h>
#include <QVBoxLayout>
ctkCmdLineModuleExplorerDirectorySettings::ctkCmdLineModuleExplorerDirectorySettings(ctkCmdLineModuleDirectoryWatcher *directoryWatcher)
: DirectoryWatcher(directoryWatcher)
{
this->setupUi(this);
this->PathListButtonsWidget->init(this->PathListWidget);
this->registerProperty(ctkCmdLineModuleExplorerConstants::KEY_SEARCH_PATHS,
this->PathListWidget, "paths", SIGNAL(pathsChanged(QStringList,QStringList)));
}
void ctkCmdLineModuleExplorerDirectorySettings::applySettings()
{
QVariant newSearchPaths = this->propertyValue(ctkCmdLineModuleExplorerConstants::KEY_SEARCH_PATHS);
this->DirectoryWatcher->setDirectories(newSearchPaths.toStringList());
ctkSettingsPanel::applySettings();
}
| 519 |
14,570 | <reponame>wwadge/swagger-codegen<gh_stars>1000+
package io.swagger.codegen.nodejs;
import io.swagger.codegen.AbstractOptionsTest;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.languages.NodeJSServerCodegen;
import io.swagger.codegen.options.NodeJSServerOptionsProvider;
import mockit.Expectations;
import mockit.Tested;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
public class NodeJSServerOptionsTest extends AbstractOptionsTest {
@Tested
private NodeJSServerCodegen clientCodegen;
public NodeJSServerOptionsTest() {
super(new NodeJSServerOptionsProvider());
}
@Override
protected CodegenConfig getCodegenConfig() {
return clientCodegen;
}
@SuppressWarnings("unused")
@Override
protected void setExpectations() {
new Expectations(clientCodegen) {{
clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(NodeJSServerOptionsProvider.SORT_PARAMS_VALUE));
clientCodegen.setGoogleCloudFunctions(Boolean.valueOf(NodeJSServerOptionsProvider.GOOGLE_CLOUD_FUNCTIONS));
clientCodegen.setExportedName(NodeJSServerOptionsProvider.EXPORTED_NAME);
times = 1;
}};
}
@Test
public void testCleanTitle() {
String dirtyTitle = "safe-title";
String clean = dirtyTitle.replaceAll("[^a-zA-Z0-9]", "-")
.replaceAll("^[-]*", "")
.replaceAll("[-]*$", "")
.replaceAll("[-]{2,}", "-");
assertEquals(clean, "safe-title");
}
@Test
public void testDirtyTitleCleansing() {
String dirtyTitle = "_it's-$ooo//////////---_//dirty!!!!";
String clean = dirtyTitle.replaceAll("[^a-zA-Z0-9]", "-")
.replaceAll("^[-]*", "")
.replaceAll("[-]*$", "")
.replaceAll("[-]{2,}", "-");
assertEquals(clean, "it-s-ooo-dirty");
}
}
| 839 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.