max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
575
// 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 <fuzzer/FuzzedDataProvider.h> #include "base/at_exit.h" #include "base/command_line.h" #include "content/browser/accessibility/browser_accessibility.h" #include "content/browser/accessibility/browser_accessibility_manager.h" #include "content/browser/accessibility/one_shot_accessibility_tree_search.h" #include "content/browser/accessibility/test_browser_accessibility_delegate.h" struct Env { Env() { base::CommandLine::Init(0, nullptr); } base::AtExitManager at_exit; }; namespace content { // Return an accessibility role to use in a tree to fuzz. Out of the // dozens of roles, these are the ones that tend to have special meaning // or otherwise affect the logic in BrowserAccessibility code. ax::mojom::Role GetInterestingRole(FuzzedDataProvider& fdp) { switch (fdp.ConsumeIntegralInRange(0, 12)) { default: case 0: return ax::mojom::Role::kIgnored; case 1: return ax::mojom::Role::kStaticText; case 2: return ax::mojom::Role::kInlineTextBox; case 3: return ax::mojom::Role::kParagraph; case 4: return ax::mojom::Role::kLineBreak; case 5: return ax::mojom::Role::kGenericContainer; case 6: return ax::mojom::Role::kButton; case 7: return ax::mojom::Role::kTextField; case 8: return ax::mojom::Role::kIframePresentational; case 9: return ax::mojom::Role::kIframe; case 10: return ax::mojom::Role::kHeading; case 11: return ax::mojom::Role::kPopUpButton; case 12: return ax::mojom::Role::kLink; } } // Add some states to the node based on the FuzzedDataProvider. // Currently we're messing with ignored and invisible because that // affects a lot of the tree walking code. void AddStates(FuzzedDataProvider& fdp, ui::AXNodeData* node) { if (fdp.ConsumeBool()) node->AddState(ax::mojom::State::kIgnored); if (fdp.ConsumeBool()) node->AddState(ax::mojom::State::kInvisible); } // Construct an accessibility tree. The shape of the tree is static, but // some of the properties of the nodes in the tree are determined by // the fuzz input. Once the tree is constructed, fuzz by calling some // functions that walk the tree in various ways to ensure they don't crash. extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { static Env env; FuzzedDataProvider fdp(data, size); // The tree structure is always the same, only the data changes. // // 1 // / \ // 2 3 4 // / \ / \ / \ // 5 6 7 8 9 10 // // In addition, there's a child tree that may be linked off one of // the nodes. ui::AXTreeID parent_tree_id = ui::AXTreeID::CreateNewAXTreeID(); ui::AXTreeID child_tree_id = ui::AXTreeID::CreateNewAXTreeID(); const int num_nodes = 10; ui::AXTreeUpdate tree; tree.root_id = 1; tree.tree_data.tree_id = parent_tree_id; tree.has_tree_data = true; tree.nodes.resize(10); tree.nodes[0].id = 1; tree.nodes[0].role = ax::mojom::Role::kRootWebArea; tree.nodes[0].child_ids = {2, 3, 4}; AddStates(fdp, &tree.nodes[0]); tree.nodes[1].id = 2; tree.nodes[1].role = GetInterestingRole(fdp); tree.nodes[1].child_ids = {5, 6}; AddStates(fdp, &tree.nodes[1]); tree.nodes[2].id = 3; tree.nodes[2].role = GetInterestingRole(fdp); tree.nodes[2].child_ids = {7, 8}; AddStates(fdp, &tree.nodes[2]); tree.nodes[3].id = 4; tree.nodes[3].role = GetInterestingRole(fdp); tree.nodes[3].child_ids = {9, 10}; AddStates(fdp, &tree.nodes[3]); for (int i = 4; i < num_nodes; i++) { tree.nodes[i].id = i + 1; tree.nodes[i].role = GetInterestingRole(fdp); AddStates(fdp, &tree.nodes[i]); } for (int i = 0; i < num_nodes; i++) tree.nodes[i].SetName(fdp.ConsumeRandomLengthString(5)); // Optionally, embed the child tree in the parent tree. int embedder_node = fdp.ConsumeIntegralInRange(0, num_nodes); if (embedder_node > 0) tree.nodes[embedder_node - 1].AddStringAttribute( ax::mojom::StringAttribute::kChildTreeId, child_tree_id.ToString()); VLOG(1) << tree.ToString(); // The child tree is trivial, just one node. That's still enough to exercise // a lot of paths. ui::AXTreeUpdate child_tree; child_tree.root_id = 1; child_tree.tree_data.tree_id = child_tree_id; child_tree.has_tree_data = true; child_tree.nodes.resize(1); child_tree.nodes[0].id = 1; child_tree.nodes[0].role = ax::mojom::Role::kRootWebArea; VLOG(1) << child_tree.ToString(); TestBrowserAccessibilityDelegate delegate; std::unique_ptr<BrowserAccessibilityManager> manager( BrowserAccessibilityManager::Create(tree, &delegate)); std::unique_ptr<BrowserAccessibilityManager> child_manager( BrowserAccessibilityManager::Create(child_tree, &delegate)); // We want to call a bunch of functions but we don't care what the // return values are. To ensure the compiler doesn't optimize the calls // away, push the return values onto a vector and make an assertion about // it at the end. std::vector<void*> results; // Test some tree-walking functions. BrowserAccessibility* root = manager->GetRoot(); results.push_back(root->PlatformDeepestFirstChild()); results.push_back(root->PlatformDeepestLastChild()); results.push_back(root->InternalDeepestFirstChild()); results.push_back(root->InternalDeepestLastChild()); // Test OneShotAccessibilityTreeSearch. OneShotAccessibilityTreeSearch search(manager->GetRoot()); search.SetDirection(fdp.ConsumeBool() ? OneShotAccessibilityTreeSearch::FORWARDS : OneShotAccessibilityTreeSearch::BACKWARDS); search.SetImmediateDescendantsOnly(fdp.ConsumeBool()); search.SetCanWrapToLastElement(fdp.ConsumeBool()); search.SetOnscreenOnly(fdp.ConsumeBool()); if (fdp.ConsumeBool()) search.AddPredicate(AccessibilityButtonPredicate); if (fdp.ConsumeBool()) search.SetSearchText(fdp.ConsumeRandomLengthString(5)); size_t matches = search.CountMatches(); for (size_t i = 0; i < matches; i++) { results.push_back(search.GetMatchAtIndex(i)); } // This is just to ensure that none of the above code gets optimized away. CHECK_NE(0U, results.size()); // Add a node, possibly clearing old children. int node_id = num_nodes + 1; int parent = fdp.ConsumeIntegralInRange(0, num_nodes); ui::AXTreeUpdate update; update.nodes.resize(2); update.nodes[0].id = parent; update.nodes[0].child_ids = {node_id}; update.nodes[1].id = node_id; update.nodes[1].role = GetInterestingRole(fdp); AddStates(fdp, &update.nodes[1]); AXEventNotificationDetails notification; notification.updates.resize(1); notification.updates[0] = update; CHECK(manager->OnAccessibilityEvents(notification)); return 0; } } // namespace content
2,578
1,056
<filename>java/jellytools.java/test/qa-functional/src/org/netbeans/jellytools/nodes/JavaNodeTest.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.jellytools.nodes; import java.awt.Toolkit; import java.io.IOException; import junit.framework.Test; import org.netbeans.jellytools.EditorOperator; import org.netbeans.jellytools.FilesTabOperator; import org.netbeans.jellytools.JellyTestCase; import org.netbeans.jellytools.SaveAsTemplateOperator; import org.netbeans.jellytools.testutils.JavaNodeUtils; /** * Test of org.netbeans.jellytools.nodes.JavaNode * * @author <NAME> * @author <NAME> */ public class JavaNodeTest extends JellyTestCase { public static String[] tests = new String[]{ "testVerifyPopup", "testOpen", "testCut", "testCopy", "testDelete", "testSaveAsTemplate", "testProperties" }; /** * constructor required by JUnit * * @param testName method name to be used as testcase */ public JavaNodeTest(String testName) { super(testName); } /** method used for explicit testsuite definition */ public static Test suite() { return createModuleTest(JavaNodeTest.class, tests); } protected static JavaNode javaNode = null; /** Finds node before each test case. */ @Override protected void setUp() throws IOException { System.out.println("### " + getName() + " ###"); openDataProjects("SampleProject"); if (javaNode == null) { javaNode = new JavaNode(new FilesTabOperator().getProjectNode("SampleProject"), "src|sample1|SampleClass1.java"); // NOI18N } } /** Test verifyPopup */ public void testVerifyPopup() { javaNode.verifyPopup(); } /** Test open */ public void testOpen() { javaNode.open(); new EditorOperator("SampleClass1.java").closeDiscard(); // NOI18N } /** Test cut */ public void testCut() { Object clipboard1 = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null); javaNode.cut(); JavaNodeUtils.testClipboard(clipboard1); } /** Test copy */ public void testCopy() { Object clipboard1 = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null); javaNode.copy(); JavaNodeUtils.testClipboard(clipboard1); } /** Test delete */ public void testDelete() { javaNode.delete(); JavaNodeUtils.closeSafeDeleteDialog(); } /** Test properties */ public void testProperties() { javaNode.properties(); JavaNodeUtils.closeProperties("SampleClass1.java"); // NOI18N } /** Test saveAsTemplate */ public void testSaveAsTemplate() { javaNode.saveAsTemplate(); new SaveAsTemplateOperator().close(); } }
1,305
4,459
/* * nixio - Linux I/O library for lua * * Copyright (C) 2009 <NAME> <<EMAIL>> * * 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 "nixio-tls.h" #include <stdlib.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <unistd.h> static int nixio_crypto_hash__init(lua_State *L, int hmac) { const char *type = luaL_checkstring(L, 1); nixio_hash *hash = lua_newuserdata(L, sizeof(nixio_hash)); if (!strcmp(type, "md5")) { hash->type = NIXIO_HASH_MD5; hash->digest_size = MD5_DIGEST_LENGTH; hash->block_size = 64; hash->ctx = malloc(sizeof(MD5_CTX)); if (!hash->ctx) { return luaL_error(L, NIXIO_OOM); } MD5_Init((MD5_CTX*)hash->ctx); hash->init = (nixio_hash_initcb)MD5_Init; hash->update = (nixio_hash_updatecb)MD5_Update; hash->final = (nixio_hash_finalcb)MD5_Final; } else if (!strcmp(type, "sha1")) { hash->type = NIXIO_HASH_SHA1; hash->digest_size = SHA_DIGEST_LENGTH; hash->block_size = 64; hash->ctx = malloc(sizeof(SHA_CTX)); if (!hash->ctx) { return luaL_error(L, NIXIO_OOM); } SHA1_Init((SHA_CTX*)hash->ctx); hash->init = (nixio_hash_initcb)SHA1_Init; hash->update = (nixio_hash_updatecb)SHA1_Update; hash->final = (nixio_hash_finalcb)SHA1_Final; } else { luaL_argerror(L, 1, "supported values: md5, sha1"); } luaL_getmetatable(L, NIXIO_CRYPTO_HASH_META); lua_setmetatable(L, -2); if (hmac) { const char *key = luaL_checklstring(L, 2, &hash->key_size); if (hash->key_size > hash->block_size) { hash->update(hash->ctx, key, hash->key_size); hash->final(hash->digest, hash->ctx); hash->init(hash->ctx); hash->key_size = hash->digest_size; memcpy(hash->key, hash->digest, hash->key_size); } else { memcpy(hash->key, key, hash->key_size); } unsigned char pad[NIXIO_CRYPTO_BLOCK_SIZE]; for (uint i = 0; i < hash->block_size; i++) { pad[i] = (i < hash->key_size) ? (0x36 ^ hash->key[i]) : 0x36; } hash->update(hash->ctx, pad, hash->block_size); hash->type |= NIXIO_HMAC_BIT; } return 1; } static int nixio_crypto_hash(lua_State *L) { return nixio_crypto_hash__init(L, 0); } static int nixio_crypto_hmac(lua_State *L) { return nixio_crypto_hash__init(L, 1); } static int nixio_crypto_hash_update(lua_State *L) { nixio_hash *hash = luaL_checkudata(L, 1, NIXIO_CRYPTO_HASH_META); if (hash->type) { size_t len; const char *chunk = luaL_checklstring(L, 2, &len); hash->update(hash->ctx, chunk, len); lua_pushvalue(L, 1); return 1; } else { return luaL_error(L, "Tried to update finalized hash object."); } } static int nixio_crypto_hash_final(lua_State *L) { nixio_hash *hash = luaL_checkudata(L, 1, NIXIO_CRYPTO_HASH_META); if (hash->type & NIXIO_HMAC_BIT) { hash->final(hash->digest, hash->ctx); hash->init(hash->ctx); unsigned char pad[NIXIO_CRYPTO_BLOCK_SIZE]; for (uint i = 0; i < hash->block_size; i++) { pad[i] = (i < hash->key_size) ? (0x5c ^ hash->key[i]) : 0x5c; } hash->update(hash->ctx, pad, hash->block_size); hash->update(hash->ctx, hash->digest, hash->digest_size); } if (hash->type) { hash->type = NIXIO_HASH_NONE; hash->final(hash->digest, hash->ctx); free(hash->ctx); } char hashdigest[NIXIO_DIGEST_SIZE*2]; for (uint i=0; i < hash->digest_size; i++) { hashdigest[2*i] = nixio__bin2hex[(hash->digest[i] & 0xf0) >> 4]; hashdigest[2*i+1] = nixio__bin2hex[(hash->digest[i] & 0x0f)]; } lua_pushlstring(L, hashdigest, hash->digest_size * 2); memcpy(hashdigest, hash->digest, hash->digest_size); lua_pushlstring(L, hashdigest, hash->digest_size); return 2; } static int nixio_crypto_hash__gc(lua_State *L) { nixio_hash *hash = luaL_checkudata(L, 1, NIXIO_CRYPTO_HASH_META); if (hash->type) { hash->final(hash->digest, hash->ctx); free(hash->ctx); hash->type = NIXIO_HASH_NONE; } return 0; } static int nixio_crypto_hash__tostring(lua_State *L) { nixio_hash *hash = luaL_checkudata(L, 1, NIXIO_CRYPTO_HASH_META); lua_pushfstring(L, "nixio hash object: %p", hash); return 1; } /* module table */ static const luaL_Reg R[] = { {"hash", nixio_crypto_hash}, {"hmac", nixio_crypto_hmac}, {NULL, NULL} }; /* hash table */ static const luaL_Reg M[] = { {"update", nixio_crypto_hash_update}, {"final", nixio_crypto_hash_final}, {"__gc", nixio_crypto_hash__gc}, {"__tostring", nixio_crypto_hash__tostring}, {NULL, NULL} }; void nixio_open_tls_crypto(lua_State *L) { luaL_newmetatable(L, NIXIO_CRYPTO_HASH_META); luaL_register(L, NULL, M); lua_pushvalue(L, -1); lua_setfield(L, -2, "__index"); lua_pop(L, 1); lua_newtable(L); luaL_register(L, NULL, R); lua_setfield(L, -2, "crypto"); }
2,324
2,211
// Copyright (c) 2013 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 "xwalk/extensions/renderer/xwalk_v8_utils.h" #include "base/strings/stringprintf.h" #include "v8/include/v8.h" namespace xwalk { namespace extensions { std::string ExceptionToString(const v8::TryCatch& try_catch) { std::string str; v8::HandleScope handle_scope(v8::Isolate::GetCurrent()); v8::String::Utf8Value exception(try_catch.Exception()); v8::Local<v8::Message> message(try_catch.Message()); if (message.IsEmpty()) { str.append(base::StringPrintf("%s\n", *exception)); } else { v8::String::Utf8Value filename(message->GetScriptResourceName()); int linenum = message->GetLineNumber(); int colnum = message->GetStartColumn(); str.append(base::StringPrintf( "%s:%i:%i %s\n", *filename, linenum, colnum, *exception)); v8::String::Utf8Value sourceline(message->GetSourceLine()); str.append(base::StringPrintf("%s\n", *sourceline)); } return str; } } // namespace extensions } // namespace xwalk
401
852
#ifndef EventFilter_L1TRawToDigi_Omtf_CscPacker_H #define EventFilter_L1TRawToDigi_Omtf_CscPacker_H #include <string> #include "DataFormats/CSCDigi/interface/CSCCorrelatedLCTDigiCollection.h" #include "DataFormats/L1TMuon/interface/OMTF/OmtfDataWord64.h" #include "EventFilter/L1TRawToDigi/interface/OmtfLinkMappingCsc.h" namespace edm { class EventSetup; } namespace omtf { class CscPacker { public: void init(); void pack(const CSCCorrelatedLCTDigiCollection* prod, FedAmcRawsMap& raws); private: MapCscDet2EleIndex theCsc2Omtf; }; } // namespace omtf #endif
250
799
from typing import List, Dict import demistomock as demisto from CommonServerPython import * from CommonServerUserPython import * def main(domains: str, urls: str) -> CommandResults: """Checks that the urls are in the domain in the domain name. Args: domains: A comma separated list of domains. urls: A comma separated list of urls. Returns: Results to display in CortexXSOAR """ urls = argToList(urls) domains = set(argToList(domains)) outputs: List[Dict] = list() for url in urls: results = demisto.executeCommand('ExtractDomainFromUrlAndEmail', {'input': url.lower()}) if is_error(results): demisto.debug(f'Could not get domain from url {url}') return_error(get_error(results)) else: domain_from_url = results[0]['Contents'] outputs.append({ 'URL': url, 'Domain': domain_from_url, 'IsInternal': (domain_from_url in domains) or url.startswith(('https://localhost', 'http://localhost')) }) return CommandResults('IsUrlPartOfDomain', outputs=outputs) if __name__ in ('builtins', '__builtin__'): return_results(main(**demisto.args()))
509
2,449
# Copyright 2016 Pinterest, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import tests from deployd.client.serverless_client import ServerlessClient from deployd.common.types import DeployStatus, AgentStatus from deployd.types.ping_report import PingReport class TestServerlessClient(tests.TestCase): def setUp(self): self.env_name = "test" self.stage = "prod" self.env_id = "12343434" self.build = '{"commit":"c5a7f50453fa70fefa41dc5b75e9b053fc5bba4b","id":"S2dUHIrFSMyDzdwO-6mgeA_c81d6b3","branch":"master","artifactUrl":"https://deployrepo.pinadmin.com/pinboard/pinboard-c5a7f50.tar.gz","repo":"P","name": "pinboard"}' self.script_variables = '{"IS_DOCKER": "True"}' self.client = ServerlessClient(env_name=self.env_name, stage=self.stage, build=self.build, script_variables=self.script_variables) def _new_report(self): report = PingReport() report.envName = self.env_name report.stageName = self.stage report.erroCode = 0 report.envId = self.env_id report.deployStage = None report.status = AgentStatus.SUCCEEDED return report def test_deploy_stage_trnasition(self): report = self._new_report() deploy_status = DeployStatus() deploy_status.report = report env_status = {self.env_name : deploy_status} deployStages = ['PRE_DOWNLOAD', 'DOWNLOADING', 'POST_DOWNLOAD', 'STAGING', 'PRE_RESTART', 'RESTARTING', 'POST_RESTART', 'SERVING_BUILD'] for i in range(0, len(deployStages)): response = self.client.send_reports(env_status) self.assertEqual(response.opCode, "DEPLOY") self.assertEqual(response.deployGoal.deployStage, deployStages[i]) report.deployStage = response.deployGoal.deployStage report.deployId = response.deployGoal.deployId # test ending case response = self.client.send_reports(env_status) self.assertEqual(response.deployGoal, None) def test_errorcode_stop_deployment(self): report = self._new_report() deploy_status = DeployStatus() deploy_status.report = report env_status = {self.env_name : deploy_status} # first try is allowed. report.errorCode = 123 response = self.client.send_reports(env_status) report.deployStage = response.deployGoal.deployStage report.deployId = response.deployGoal.deployId response = self.client.send_reports(env_status) self.assertEqual(response, None) def test_unknow_status_cause_retry(self): report = self._new_report() deploy_status = DeployStatus() deploy_status.report = report env_status = {self.env_name : deploy_status} report.status = AgentStatus.UNKNOWN response = self.client.send_reports(env_status) report.deployStage = response.deployGoal.deployStage report.deployId = response.deployGoal.deployId response = self.client.send_reports(env_status) self.assertEqual(response.deployGoal.deployStage, 'PRE_DOWNLOAD') if __name__ == '__main__': unittest.main()
1,524
783
<reponame>fakegit/douban.fm #!/usr/bin/env python2 # -*- coding: utf-8 -*- from __future__ import print_function from threading import Thread from six.moves import input from six.moves import cPickle as pickle from six.moves import configparser as ConfigParser import logging import time import os from doubanfm.API.login import request_token from doubanfm.check import is_latest, update_package, is_mplayer from doubanfm.exceptions import ConfigError is_mplayer() logger = logging.getLogger('doubanfm') # get logger THEME = ['default', 'larapaste', 'monokai', 'tomorrow'] PATH_CONFIG = os.path.expanduser("~/.doubanfm_config") PATH_HISTORY = os.path.expanduser('~/.doubanfm_history') PATH_TOKEN = os.path.expanduser('~/.doubanfm_token') CONFIG = ''' [key] UP = k DOWN = j TOP = g BOTTOM = G OPENURL = w RATE = r NEXT = n BYE = b QUIT = q PAUSE = p LOOP = l MUTE = m LRC = o HELP = h HIGH = i ''' KEYS = { 'UP': 'k', 'DOWN': 'j', 'TOP': 'g', 'BOTTOM': 'G', 'OPENURL': 'w', 'RATE': 'r', 'NEXT': 'n', 'BYE': 'b', 'QUIT': 'q', 'PAUSE': 'p', 'LOOP': 'l', 'MUTE': 'm', 'LRC': 'o', 'HELP': 'h', 'HIGH': 'i' } class Config(object): """ 提供默认值 """ def __init__(self): self.volume = 50 # 音量 self.channel = 0 # 频道 self.theme_id = 0 # 主题 self.user_name = '' # 用户名 self.netease = False # 是否使用网易320k音乐播放 self.run_times = 0 # 登陆次数 self.last_time = time.time() # 当前登陆时间戳 self.total_time = 0 # 总共登陆时间 self.liked = 0 # 加❤歌曲 self.banned = 0 # 不再播放 self.played = 0 # 累计播放 self.is_latest = True self.login_data = self.get_login_data() def output(args): def _deco(func): def _func(self): print('\033[31m♥\033[0m ' + args, end='') tmp = func(self) print(' [\033[32m OK \033[0m]') return tmp return _func return _deco def get_login_data(self): """ 提供登陆的认证 这里顺带增加了 volume, channel, theme_id , netease, run_times的默认值 """ login_data = None try: if os.path.exists(PATH_TOKEN): # 使用上次登录保存的token with open(PATH_TOKEN, 'rb') as f: login_data = pickle.load(f) if 'cookies' not in login_data: login_data = request_token() except Exception: pass if not login_data: # 未登陆 login_data = request_token() self.get_default_set(login_data) self.get_user_states(login_data) self.get_is_latest_version(login_data) Thread(target=self.check_version).start() # 这里每次异步检测, 下次打开时进行提示 return login_data def check_version(self): self.is_latest = is_latest('douban.fm') def get_is_latest_version(self, login_data): self.is_latest = login_data.get('is_latest', True) if not self.is_latest: if_update = input('检测到douban.fm有更新, 是否升级?(Y) ') if if_update.lower() == 'y': update_package('douban.fm') with open(PATH_TOKEN, 'w') as f: login_data['is_latest'] = True pickle.dump(login_data, f) print('请重新打开douban.fm(升级失败可能需要sudo权限, 试试sudo pip install --upgrade douban.fm)') os._exit(0) def get_default_set(self, login_data): """ 记录退出时的播放状态 """ self.cookies = login_data.get('cookies', '') self.user_name = login_data.get('user_name', '') print('\033[31m♥\033[0m Get local token - Username: \033[33m%s\033[0m' %\ login_data['user_name']) self.channel = login_data.get('channel', 0) print('\033[31m♥\033[0m Get channel [\033[32m OK \033[0m]') self.volume = login_data.get('volume', 50) print('\033[31m♥\033[0m Get volume [\033[32m OK \033[0m]') self.theme_id = login_data.get('theme_id', 0) print('\033[31m♥\033[0m Get theme [\033[32m OK \033[0m]') self.netease = login_data.get('netease', False) self.keys = self.get_keys() def get_user_states(self, login_data): """ 统计用户信息 """ self.run_times = login_data.get('run_times', 0) self.total_time = login_data.get('total_time', 0) @output('Get keys') def get_keys(self): ''' 获取配置并检查是否更改 ''' if not os.path.exists(PATH_CONFIG): with open(PATH_CONFIG, 'w') as F: F.write(CONFIG) else: config = ConfigParser.ConfigParser() with open(PATH_CONFIG, 'r') as cfgfile: config.readfp(cfgfile) options = config.options('key') for option in options: option = option.upper() if option in KEYS: KEYS[option] = config.get('key', option) return KEYS @property def history(self): try: with open(PATH_HISTORY, 'r') as f: history = pickle.load(f) except IOError: history = [] return history def save_config(self, volume, channel, theme, netease): """ 存储历史记录和登陆信息 """ self.login_data['cookies'] = self.cookies self.login_data['volume'] = volume self.login_data['channel'] = channel self.login_data['theme_id'] = theme self.login_data['netease'] = netease self.login_data['run_times'] = self.run_times + 1 self.login_data['last_time'] = self.last_time self.login_data['total_time'] = self.total_time +\ time.time() - self.last_time self.login_data['is_latest'] = self.is_latest with open(PATH_TOKEN, 'wb') as f: pickle.dump(self.login_data, f) # with open(PATH_HISTORY, 'w') as f: # pickle.dump(history, f) db_config = Config()
3,405
1,253
# -*- coding: utf-8 -*- """Analyzer result attribute container.""" from plaso.containers import interface from plaso.containers import manager class AnalyzerResult(interface.AttributeContainer): """Attribute container to store results of analyzers. Analyzers can produce results with different attribute names. For example, the 'hashing' analyzer could produce an attribute 'md5_hash', with a value of 'd41d8cd98f00b204e9800998ecf8427e'. Attributes: analyzer_name (str): name of the analyzer that produce the result. attribute_name (str): name of the attribute produced. attribute_value (str): value of the attribute produced. """ CONTAINER_TYPE = 'analyzer_result' def __init__(self): """Initializes an analyzer result.""" super(AnalyzerResult, self).__init__() self.analyzer_name = None self.attribute_name = None self.attribute_value = None manager.AttributeContainersManager.RegisterAttributeContainer(AnalyzerResult)
292
530
<filename>strongbox-commons/src/main/java/org/carlspring/strongbox/net/MediaType.java package org.carlspring.strongbox.net; /** * @author <NAME> */ @SuppressWarnings("PMD.ClassNamingConventions") public final class MediaType { public static final String APPLICATION_YML_VALUE = "application/yml"; public static final String APPLICATION_YAML_VALUE = "application/yaml"; public static final String APPLICATION_X_GZIP_VALUE = "application/x-gzip"; public static final String TEXT_EVENT_STREAM_UTF8_VALUE = "text/event-stream; charset=UTF-8"; public static final String TEXT_PLAIN_UTF8_VALUE = "text/plain; charset=UTF-8"; private MediaType() { } }
239
2,151
/* * Copyright (C) 2015 The Android Open Source Project * * 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 android.support.v4.content; import android.content.SharedPreferences; import android.os.Build; import android.support.annotation.NonNull; public final class SharedPreferencesCompat { public final static class EditorCompat { private static EditorCompat sInstance; private static class Helper { Helper() { } public void apply(@NonNull SharedPreferences.Editor editor) { try { editor.apply(); } catch (AbstractMethodError unused) { // The app injected its own pre-Gingerbread // SharedPreferences.Editor implementation without // an apply method. editor.commit(); } } } private final Helper mHelper; private EditorCompat() { mHelper = new Helper(); } public static EditorCompat getInstance() { if (sInstance == null) { sInstance = new EditorCompat(); } return sInstance; } public void apply(@NonNull SharedPreferences.Editor editor) { // Note that this redirection is needed to not break the public API chain // of getInstance().apply() calls. Otherwise this method could (and should) // be static. mHelper.apply(editor); } } private SharedPreferencesCompat() {} }
817
3,212
<filename>nifi-nar-bundles/nifi-accumulo-bundle/nifi-accumulo-processors/src/main/java/org/apache/nifi/accumulo/data/AccumuloRecordConfiguration.java /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nifi.accumulo.data; /** * Encapsulates configuring the session with some required parameters. * * Justification: Generally not a fan of this fluent API to configure other objects, but there is a lot encapsulated here * so it helps minimize what we pass between the current set of classes and the upcoming features. */ public class AccumuloRecordConfiguration { private String tableName; private String rowFieldName; private String columnFamily; private String columnFamilyField; private String timestampField; private String fieldDelimiter; private boolean encodeFieldDelimiter; private boolean qualifierInKey; private boolean deleteKeys; protected AccumuloRecordConfiguration(final String tableName, final String rowFieldName, final String columnFamily, final String columnFamilyField, final String timestampField, final String fieldDelimiter, final boolean encodeFieldDelimiter, final boolean qualifierInKey, final boolean deleteKeys) { this.tableName = tableName; this.rowFieldName = rowFieldName; this.columnFamily = columnFamily; this.columnFamilyField = columnFamilyField; this.timestampField = timestampField; this.fieldDelimiter = fieldDelimiter; this.encodeFieldDelimiter = encodeFieldDelimiter; this.qualifierInKey = qualifierInKey; this.deleteKeys = deleteKeys; } public String getTableName(){ return tableName; } public String getColumnFamily() { return columnFamily; } public String getColumnFamilyField() { return columnFamilyField; } public boolean getEncodeDelimiter(){ return encodeFieldDelimiter; } public String getTimestampField(){ return timestampField; } public String getFieldDelimiter(){ return fieldDelimiter; } public boolean getQualifierInKey(){ return qualifierInKey; } public boolean isDeleteKeys(){ return deleteKeys; } public String getRowField(){ return rowFieldName; } public static class Builder{ public static final Builder newBuilder(){ return new Builder(); } public Builder setRowField(final String rowFieldName){ this.rowFieldName = rowFieldName; return this; } public Builder setTableName(final String tableName){ this.tableName = tableName; return this; } public Builder setEncodeFieldDelimiter(final boolean encodeFieldDelimiter){ this.encodeFieldDelimiter = encodeFieldDelimiter; return this; } public Builder setColumnFamily(final String columnFamily){ this.columnFamily = columnFamily; return this; } public Builder setColumnFamilyField(final String columnFamilyField){ this.columnFamilyField = columnFamilyField; return this; } public Builder setTimestampField(final String timestampField){ this.timestampField = timestampField; return this; } public Builder setQualifierInKey(final boolean qualifierInKey){ this.qualifierInKey = qualifierInKey; return this; } public Builder setFieldDelimiter(final String fieldDelimiter){ this.fieldDelimiter = fieldDelimiter; return this; } public Builder setDelete(final boolean deleteKeys){ this.deleteKeys = deleteKeys; return this; } public AccumuloRecordConfiguration build(){ return new AccumuloRecordConfiguration(tableName,rowFieldName,columnFamily,columnFamilyField,timestampField,fieldDelimiter,encodeFieldDelimiter,qualifierInKey,deleteKeys); } private String tableName; private String rowFieldName; private String columnFamily; private String columnFamilyField; private String fieldDelimiter; private boolean qualifierInKey=false; private boolean encodeFieldDelimiter=false; private String timestampField; private boolean deleteKeys=false; } }
1,971
17,703
#include "source/exe/platform_impl.h" #include "test/mocks/common.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace Envoy { TEST(PlatformImpl, Basic) { PlatformImpl platform; #ifdef __linux__ EXPECT_EQ(true, platform.enableCoreDump()); #else EXPECT_EQ(false, platform.enableCoreDump()); #endif } } // namespace Envoy
149
663
<gh_stars>100-1000 # (C) Datadog, Inc. 2018-present # All rights reserved # Licensed under Simplified BSD License (see LICENSE) # flake8: noqa from ..base.utils.limiter import *
61
14,425
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn; import static org.junit.Assert.assertSame; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import org.apache.hadoop.util.ExitUtil; import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; import org.junit.Test; public class TestYarnUncaughtExceptionHandler { private static final YarnUncaughtExceptionHandler exHandler = new YarnUncaughtExceptionHandler(); /** * Throw {@code YarnRuntimeException} inside thread and * check {@code YarnUncaughtExceptionHandler} instance * * @throws InterruptedException */ @Test public void testUncaughtExceptionHandlerWithRuntimeException() throws InterruptedException { final YarnUncaughtExceptionHandler spyYarnHandler = spy(exHandler); final YarnRuntimeException yarnException = new YarnRuntimeException( "test-yarn-runtime-exception"); final Thread yarnThread = new Thread(new Runnable() { @Override public void run() { throw yarnException; } }); yarnThread.setUncaughtExceptionHandler(spyYarnHandler); assertSame(spyYarnHandler, yarnThread.getUncaughtExceptionHandler()); yarnThread.start(); yarnThread.join(); verify(spyYarnHandler).uncaughtException(yarnThread, yarnException); } /** * <p> * Throw {@code Error} inside thread and * check {@code YarnUncaughtExceptionHandler} instance * <p> * Used {@code ExitUtil} class to avoid jvm exit through * {@code System.exit(-1) } * * @throws InterruptedException */ @Test public void testUncaughtExceptionHandlerWithError() throws InterruptedException { ExitUtil.disableSystemExit(); final YarnUncaughtExceptionHandler spyErrorHandler = spy(exHandler); final java.lang.Error error = new java.lang.Error("test-error"); final Thread errorThread = new Thread(new Runnable() { @Override public void run() { throw error; } }); errorThread.setUncaughtExceptionHandler(spyErrorHandler); assertSame(spyErrorHandler, errorThread.getUncaughtExceptionHandler()); errorThread.start(); errorThread.join(); verify(spyErrorHandler).uncaughtException(errorThread, error); } /** * <p> * Throw {@code OutOfMemoryError} inside thread and * check {@code YarnUncaughtExceptionHandler} instance * <p> * Used {@code ExitUtil} class to avoid jvm exit through * {@code Runtime.getRuntime().halt(-1)} * * @throws InterruptedException */ @Test public void testUncaughtExceptionHandlerWithOutOfMemoryError() throws InterruptedException { ExitUtil.disableSystemHalt(); final YarnUncaughtExceptionHandler spyOomHandler = spy(exHandler); final OutOfMemoryError oomError = new OutOfMemoryError("out-of-memory-error"); final Thread oomThread = new Thread(new Runnable() { @Override public void run() { throw oomError; } }); oomThread.setUncaughtExceptionHandler(spyOomHandler); assertSame(spyOomHandler, oomThread.getUncaughtExceptionHandler()); oomThread.start(); oomThread.join(); verify(spyOomHandler).uncaughtException(oomThread, oomError); } }
1,315
340
package com.vincentbrison.openlibraries.android.dualcache; /** * This is the LRU cache used for the RAM layer when configured to used references. * @param <T> is the class of object stored in the cache. */ public class ReferenceLruCache<T> extends RamLruCache<String, T> { private SizeOf<T> mHandlerSizeOf; /** * @param maxSize for caches that do not override {@link #sizeOf}, this is * the maximum number of entries in the cache. For all other caches, * this is the maximum sum of the sizes of the entries in this cache. * * @param handler computes the size of each object stored in the RAM cache layer. */ public ReferenceLruCache(int maxSize, SizeOf<T> handler) { super(maxSize); mHandlerSizeOf = handler; } @Override protected int sizeOf(String key, T value) { return mHandlerSizeOf.sizeOf(value); } }
335
370
<gh_stars>100-1000 #pragma once #include <ml/util/workload_manager.hpp> #include <ml/util/data_loading.hpp> #include <ml/util/metafile_reader.hpp> #include <ml/util/math_util.hpp> #include <ml/util/fastapprox/fastapprox.hpp> #include <ml/feature/sparse_feature.hpp> #include <ml/feature/dense_feature.hpp> #include <ml/feature/abstract_feature.hpp>
147
14,668
<filename>chrome/browser/ui/views/extensions/extensions_toolbar_unittest.cc // 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. #include "chrome/browser/ui/views/extensions/extensions_toolbar_unittest.h" #include "build/build_config.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/test_extension_system.h" #include "chrome/browser/ui/toolbar/toolbar_action_view_controller.h" #include "components/crx_file/id_util.h" #include "extensions/common/extension.h" #include "extensions/common/extension_builder.h" #include "extensions/common/value_builder.h" #include "ui/events/base_event_utils.h" #include "ui/views/layout/animating_layout_manager_test_util.h" #include "ui/views/view_utils.h" namespace { std::unique_ptr<base::ListValue> ToListValue( const std::vector<std::string>& permissions) { extensions::ListBuilder builder; for (const std::string& permission : permissions) builder.Append(permission); return builder.Build(); } } // namespace void ExtensionsToolbarUnitTest::SetUp() { TestWithBrowserView::SetUp(); extensions::TestExtensionSystem* extension_system = static_cast<extensions::TestExtensionSystem*>( extensions::ExtensionSystem::Get(profile())); extension_system->CreateExtensionService( base::CommandLine::ForCurrentProcess(), base::FilePath(), false); extension_service_ = extensions::ExtensionSystem::Get(profile())->extension_service(); // Shorten delay on animations so tests run faster. views::test::ReduceAnimationDuration(extensions_container()); } scoped_refptr<const extensions::Extension> ExtensionsToolbarUnitTest::InstallExtension(const std::string& name) { return InstallExtensionWithHostPermissions(name, {}); } scoped_refptr<const extensions::Extension> ExtensionsToolbarUnitTest::InstallExtensionWithHostPermissions( const std::string& name, const std::vector<std::string>& host_permissions) { scoped_refptr<const extensions::Extension> extension = extensions::ExtensionBuilder(name) .SetManifestKey("manifest_version", 3) .SetManifestKey("host_permissions", ToListValue(host_permissions)) .SetID(crx_file::id_util::GenerateId(name)) .Build(); extension_service()->AddExtension(extension.get()); // Force the container to re-layout, since a new extension was added. LayoutContainerIfNecessary(); return extension; } void ExtensionsToolbarUnitTest::ReloadExtension( const extensions::ExtensionId& extension_id) { extension_service()->ReloadExtension(extension_id); } void ExtensionsToolbarUnitTest::UninstallExtension( const extensions::ExtensionId& extension_id) { extension_service()->UninstallExtension( extension_id, extensions::UninstallReason::UNINSTALL_REASON_FOR_TESTING, nullptr); } void ExtensionsToolbarUnitTest::EnableExtension( const extensions::ExtensionId& extension_id) { extension_service()->EnableExtension(extension_id); } void ExtensionsToolbarUnitTest::DisableExtension( const extensions::ExtensionId& extension_id) { extension_service()->DisableExtension( extension_id, extensions::disable_reason::DISABLE_USER_ACTION); } void ExtensionsToolbarUnitTest::ClickButton(views::Button* button) const { ui::MouseEvent press_event(ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(), ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, 0); button->OnMousePressed(press_event); ui::MouseEvent release_event(ui::ET_MOUSE_RELEASED, gfx::Point(), gfx::Point(), ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, 0); button->OnMouseReleased(release_event); } std::vector<ToolbarActionView*> ExtensionsToolbarUnitTest::GetPinnedExtensionViews() { std::vector<ToolbarActionView*> result; for (views::View* child : extensions_container()->children()) { // Ensure we don't downcast the ExtensionsToolbarButton. if (views::IsViewClass<ToolbarActionView>(child)) { ToolbarActionView* const action = static_cast<ToolbarActionView*>(child); #if defined(OS_MAC) // TODO(crbug.com/1045212): Use IsActionVisibleOnToolbar() because it // queries the underlying model and not GetVisible(), as that relies on an // animation running, which is not reliable in unit tests on Mac. const bool is_visible = extensions_container()->IsActionVisibleOnToolbar( action->view_controller()); #else const bool is_visible = action->GetVisible(); #endif if (is_visible) result.push_back(action); } } return result; } std::vector<std::string> ExtensionsToolbarUnitTest::GetPinnedExtensionNames() { std::vector<ToolbarActionView*> views = GetPinnedExtensionViews(); std::vector<std::string> result; result.resize(views.size()); std::transform( views.begin(), views.end(), result.begin(), [](ToolbarActionView* view) { return base::UTF16ToUTF8(view->view_controller()->GetActionName()); }); return result; } void ExtensionsToolbarUnitTest::WaitForAnimation() { #if defined(OS_MAC) // TODO(crbug.com/1045212): we avoid using animations on Mac due to the lack // of support in unit tests. Therefore this is a no-op. #else views::test::WaitForAnimatingLayoutManager(extensions_container()); #endif } void ExtensionsToolbarUnitTest::LayoutContainerIfNecessary() { extensions_container()->GetWidget()->LayoutRootViewIfNecessary(); } content::WebContentsTester* ExtensionsToolbarUnitTest::AddWebContentsAndGetTester() { std::unique_ptr<content::WebContents> contents( content::WebContentsTester::CreateTestWebContents(profile(), nullptr)); content::WebContents* raw_contents = contents.get(); browser()->tab_strip_model()->AppendWebContents(std::move(contents), true); EXPECT_EQ(browser()->tab_strip_model()->GetActiveWebContents(), raw_contents); return content::WebContentsTester::For(raw_contents); }
2,097
2,151
#include <stdint.h> #if 0 ../cube.vert Warning, version 400 is not yet complete; most version-specific features are present, but some are missing. Linked vertex stage: // Module Version 10000 // Generated by (magic number): 80001 // Id's are bound by 55 Capability Shader 1: ExtInstImport "GLSL.std.450" MemoryModel Logical GLSL450 EntryPoint Vertex 4 "main" 9 21 28 Source GLSL 400 SourceExtension "GL_ARB_separate_shader_objects" SourceExtension "GL_ARB_shading_language_420pack" Name 4 "main" Name 9 "texcoord" Name 15 "buf" MemberName 15(buf) 0 "MVP" MemberName 15(buf) 1 "position" MemberName 15(buf) 2 "attr" Name 17 "ubuf" Name 21 "gl_VertexIndex" Name 26 "gl_PerVertex" MemberName 26(gl_PerVertex) 0 "gl_Position" Name 28 "" Decorate 9(texcoord) Location 0 Decorate 13 ArrayStride 16 Decorate 14 ArrayStride 16 MemberDecorate 15(buf) 0 ColMajor MemberDecorate 15(buf) 0 Offset 0 MemberDecorate 15(buf) 0 MatrixStride 16 MemberDecorate 15(buf) 1 Offset 64 MemberDecorate 15(buf) 2 Offset 640 Decorate 15(buf) Block Decorate 17(ubuf) DescriptorSet 0 Decorate 17(ubuf) Binding 0 Decorate 21(gl_VertexIndex) BuiltIn VertexIndex MemberDecorate 26(gl_PerVertex) 0 BuiltIn Position Decorate 26(gl_PerVertex) Block 2: TypeVoid 3: TypeFunction 2 6: TypeFloat 32 7: TypeVector 6(float) 4 8: TypePointer Output 7(fvec4) 9(texcoord): 8(ptr) Variable Output 10: TypeMatrix 7(fvec4) 4 11: TypeInt 32 0 12: 11(int) Constant 36 13: TypeArray 7(fvec4) 12 14: TypeArray 7(fvec4) 12 15(buf): TypeStruct 10 13 14 16: TypePointer Uniform 15(buf) 17(ubuf): 16(ptr) Variable Uniform 18: TypeInt 32 1 19: 18(int) Constant 2 20: TypePointer Input 18(int) 21(gl_VertexIndex): 20(ptr) Variable Input 23: TypePointer Uniform 7(fvec4) 26(gl_PerVertex): TypeStruct 7(fvec4) 27: TypePointer Output 26(gl_PerVertex) 28: 27(ptr) Variable Output 29: 18(int) Constant 0 30: TypePointer Uniform 10 33: 18(int) Constant 1 39: 11(int) Constant 1 40: TypePointer Output 6(float) 45: 11(int) Constant 2 48: 11(int) Constant 3 52: 6(float) Constant 1073741824 4(main): 2 Function None 3 5: Label 22: 18(int) Load 21(gl_VertexIndex) 24: 23(ptr) AccessChain 17(ubuf) 19 22 25: 7(fvec4) Load 24 Store 9(texcoord) 25 31: 30(ptr) AccessChain 17(ubuf) 29 32: 10 Load 31 34: 18(int) Load 21(gl_VertexIndex) 35: 23(ptr) AccessChain 17(ubuf) 33 34 36: 7(fvec4) Load 35 37: 7(fvec4) MatrixTimesVector 32 36 38: 8(ptr) AccessChain 28 29 Store 38 37 41: 40(ptr) AccessChain 28 29 39 42: 6(float) Load 41 43: 6(float) FNegate 42 44: 40(ptr) AccessChain 28 29 39 Store 44 43 46: 40(ptr) AccessChain 28 29 45 47: 6(float) Load 46 49: 40(ptr) AccessChain 28 29 48 50: 6(float) Load 49 51: 6(float) FAdd 47 50 53: 6(float) FDiv 51 52 54: 40(ptr) AccessChain 28 29 45 Store 54 53 Return FunctionEnd #endif static const uint32_t cube_vert[396] = { 0x07230203, 0x00010000, 0x00080001, 0x00000037, 0x00000000, 0x00020011, 0x00000001, 0x0006000b, 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001, 0x0008000f, 0x00000000, 0x00000004, 0x6e69616d, 0x00000000, 0x00000009, 0x00000015, 0x0000001c, 0x00030003, 0x00000002, 0x00000190, 0x00090004, 0x415f4c47, 0x735f4252, 0x72617065, 0x5f657461, 0x64616873, 0x6f5f7265, 0x63656a62, 0x00007374, 0x00090004, 0x415f4c47, 0x735f4252, 0x69646168, 0x6c5f676e, 0x75676e61, 0x5f656761, 0x70303234, 0x006b6361, 0x00040005, 0x00000004, 0x6e69616d, 0x00000000, 0x00050005, 0x00000009, 0x63786574, 0x64726f6f, 0x00000000, 0x00030005, 0x0000000f, 0x00667562, 0x00040006, 0x0000000f, 0x00000000, 0x0050564d, 0x00060006, 0x0000000f, 0x00000001, 0x69736f70, 0x6e6f6974, 0x00000000, 0x00050006, 0x0000000f, 0x00000002, 0x72747461, 0x00000000, 0x00040005, 0x00000011, 0x66756275, 0x00000000, 0x00060005, 0x00000015, 0x565f6c67, 0x65747265, 0x646e4978, 0x00007865, 0x00060005, 0x0000001a, 0x505f6c67, 0x65567265, 0x78657472, 0x00000000, 0x00060006, 0x0000001a, 0x00000000, 0x505f6c67, 0x7469736f, 0x006e6f69, 0x00030005, 0x0000001c, 0x00000000, 0x00040047, 0x00000009, 0x0000001e, 0x00000000, 0x00040047, 0x0000000d, 0x00000006, 0x00000010, 0x00040047, 0x0000000e, 0x00000006, 0x00000010, 0x00040048, 0x0000000f, 0x00000000, 0x00000005, 0x00050048, 0x0000000f, 0x00000000, 0x00000023, 0x00000000, 0x00050048, 0x0000000f, 0x00000000, 0x00000007, 0x00000010, 0x00050048, 0x0000000f, 0x00000001, 0x00000023, 0x00000040, 0x00050048, 0x0000000f, 0x00000002, 0x00000023, 0x00000280, 0x00030047, 0x0000000f, 0x00000002, 0x00040047, 0x00000011, 0x00000022, 0x00000000, 0x00040047, 0x00000011, 0x00000021, 0x00000000, 0x00040047, 0x00000015, 0x0000000b, 0x0000002a, 0x00050048, 0x0000001a, 0x00000000, 0x0000000b, 0x00000000, 0x00030047, 0x0000001a, 0x00000002, 0x00020013, 0x00000002, 0x00030021, 0x00000003, 0x00000002, 0x00030016, 0x00000006, 0x00000020, 0x00040017, 0x00000007, 0x00000006, 0x00000004, 0x00040020, 0x00000008, 0x00000003, 0x00000007, 0x0004003b, 0x00000008, 0x00000009, 0x00000003, 0x00040018, 0x0000000a, 0x00000007, 0x00000004, 0x00040015, 0x0000000b, 0x00000020, 0x00000000, 0x0004002b, 0x0000000b, 0x0000000c, 0x00000024, 0x0004001c, 0x0000000d, 0x00000007, 0x0000000c, 0x0004001c, 0x0000000e, 0x00000007, 0x0000000c, 0x0005001e, 0x0000000f, 0x0000000a, 0x0000000d, 0x0000000e, 0x00040020, 0x00000010, 0x00000002, 0x0000000f, 0x0004003b, 0x00000010, 0x00000011, 0x00000002, 0x00040015, 0x00000012, 0x00000020, 0x00000001, 0x0004002b, 0x00000012, 0x00000013, 0x00000002, 0x00040020, 0x00000014, 0x00000001, 0x00000012, 0x0004003b, 0x00000014, 0x00000015, 0x00000001, 0x00040020, 0x00000017, 0x00000002, 0x00000007, 0x0003001e, 0x0000001a, 0x00000007, 0x00040020, 0x0000001b, 0x00000003, 0x0000001a, 0x0004003b, 0x0000001b, 0x0000001c, 0x00000003, 0x0004002b, 0x00000012, 0x0000001d, 0x00000000, 0x00040020, 0x0000001e, 0x00000002, 0x0000000a, 0x0004002b, 0x00000012, 0x00000021, 0x00000001, 0x0004002b, 0x0000000b, 0x00000027, 0x00000001, 0x00040020, 0x00000028, 0x00000003, 0x00000006, 0x0004002b, 0x0000000b, 0x0000002d, 0x00000002, 0x0004002b, 0x0000000b, 0x00000030, 0x00000003, 0x0004002b, 0x00000006, 0x00000034, 0x40000000, 0x00050036, 0x00000002, 0x00000004, 0x00000000, 0x00000003, 0x000200f8, 0x00000005, 0x0004003d, 0x00000012, 0x00000016, 0x00000015, 0x00060041, 0x00000017, 0x00000018, 0x00000011, 0x00000013, 0x00000016, 0x0004003d, 0x00000007, 0x00000019, 0x00000018, 0x0003003e, 0x00000009, 0x00000019, 0x00050041, 0x0000001e, 0x0000001f, 0x00000011, 0x0000001d, 0x0004003d, 0x0000000a, 0x00000020, 0x0000001f, 0x0004003d, 0x00000012, 0x00000022, 0x00000015, 0x00060041, 0x00000017, 0x00000023, 0x00000011, 0x00000021, 0x00000022, 0x0004003d, 0x00000007, 0x00000024, 0x00000023, 0x00050091, 0x00000007, 0x00000025, 0x00000020, 0x00000024, 0x00050041, 0x00000008, 0x00000026, 0x0000001c, 0x0000001d, 0x0003003e, 0x00000026, 0x00000025, 0x00060041, 0x00000028, 0x00000029, 0x0000001c, 0x0000001d, 0x00000027, 0x0004003d, 0x00000006, 0x0000002a, 0x00000029, 0x0004007f, 0x00000006, 0x0000002b, 0x0000002a, 0x00060041, 0x00000028, 0x0000002c, 0x0000001c, 0x0000001d, 0x00000027, 0x0003003e, 0x0000002c, 0x0000002b, 0x00060041, 0x00000028, 0x0000002e, 0x0000001c, 0x0000001d, 0x0000002d, 0x0004003d, 0x00000006, 0x0000002f, 0x0000002e, 0x00060041, 0x00000028, 0x00000031, 0x0000001c, 0x0000001d, 0x00000030, 0x0004003d, 0x00000006, 0x00000032, 0x00000031, 0x00050081, 0x00000006, 0x00000033, 0x0000002f, 0x00000032, 0x00050088, 0x00000006, 0x00000035, 0x00000033, 0x00000034, 0x00060041, 0x00000028, 0x00000036, 0x0000001c, 0x0000001d, 0x0000002d, 0x0003003e, 0x00000036, 0x00000035, 0x000100fd, 0x00010038, };
5,535
363
<reponame>yukihiko/hrm /* Author(s): <NAME> See LICENCE.txt for licensing information. */ #include "gl_includes.h" void *create_context (unsigned int imageWidth, unsigned int imageHeight, GLenum typ); // =GL_UNSIGNED_BYTE void set_current(void *ctx); void release_context(void *ctx);
99
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 COMPONENTS_POLICY_TEST_SUPPORT_REQUEST_HANDLER_FOR_PSM_AUTO_ENROLLMENT_H_ #define COMPONENTS_POLICY_TEST_SUPPORT_REQUEST_HANDLER_FOR_PSM_AUTO_ENROLLMENT_H_ #include "components/policy/test_support/embedded_policy_test_server.h" namespace policy { // Handler for request type `enterprise_psm_check`. class RequestHandlerForPsmAutoEnrollment : public EmbeddedPolicyTestServer::RequestHandler { public: enum PirResponse { kPirResponseHasMembership = 1, kPirResponseHasNoMembership = 2, }; RequestHandlerForPsmAutoEnrollment(ClientStorage* client_storage, PolicyStorage* policy_storage); RequestHandlerForPsmAutoEnrollment( RequestHandlerForPsmAutoEnrollment&& handler) = delete; RequestHandlerForPsmAutoEnrollment& operator=( RequestHandlerForPsmAutoEnrollment&& handler) = delete; ~RequestHandlerForPsmAutoEnrollment() override; // EmbeddedPolicyTestServer::RequestHandler: std::string RequestType() override; std::unique_ptr<net::test_server::HttpResponse> HandleRequest( const net::test_server::HttpRequest& request) override; }; } // namespace policy #endif // COMPONENTS_POLICY_TEST_SUPPORT_REQUEST_HANDLER_FOR_PSM_AUTO_ENROLLMENT_H_
486
1,836
#!/usr/bin/env python3 import http.client import json import os import subprocess import sys import time def circleci_command(method, url, body=None): token = os.environ['CIRCLE_TOKEN'] conn = http.client.HTTPSConnection('circleci.com') conn.request( method, '/api/v1.1/project/github/skiplang/skip' + url+'?circle-token=' + token, body, {'Accept': 'application/json'} ) res = conn.getresponse() return json.loads(res.read()) branch = os.environ['CIRCLE_BRANCH'] # Only do this optimization on pull request jobs if not branch.startswith('pull/'): sys.exit(0) while 1: output = subprocess.check_output( ['git', 'ls-remote', '<EMAIL>:skiplang/skip.git', 'refs/' + branch + '/head'] ) rev = output.split()[0] print(( "Found rev (%s) vs running rev (%s)" % (rev, os.environ['CIRCLE_SHA1']) )) if rev != os.environ['CIRCLE_SHA1']: print(("Canceling myself (build: %s)" % os.environ['CIRCLE_BUILD_NUM'])) circleci_command('POST', '/%s/cancel' % os.environ['CIRCLE_BUILD_NUM']) time.sleep(30)
441
573
<reponame>Esigodini/dynarmic<gh_stars>100-1000 /* This file is part of the mp project. * Copyright (c) 2017 MerryMage * SPDX-License-Identifier: 0BSD */ #pragma once #include <mp/metavalue/value.h> namespace mp { /// Does list L contain an element which is same as type T? template<class L, class T> struct contains; template<template<class...> class LT, class... Ts, class T> struct contains<LT<Ts...>, T> : bool_value<(false || ... || std::is_same_v<Ts, T>)> {}; /// Does list L contain an element which is same as type T? template<class L, class T> constexpr bool contains_v = contains<L, T>::value; } // namespace mp
223
370
/* * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.ndbench.core.resources; import com.google.inject.Inject; import com.netflix.ndbench.api.plugin.NdBenchAbstractClient; import com.netflix.ndbench.api.plugin.NdBenchClient; import com.netflix.ndbench.api.plugin.NdBenchMonitor; import com.netflix.ndbench.api.plugin.annotations.NdBenchClientPlugin; import com.netflix.ndbench.core.DataBackfill; import com.netflix.ndbench.core.NdBenchClientFactory; import com.netflix.ndbench.core.NdBenchDriver; import com.netflix.ndbench.core.config.IConfiguration; import com.netflix.ndbench.core.generators.KeyGenerator; import com.netflix.ndbench.core.util.LoadPattern; import com.netflix.ndbench.core.util.RestUtil; import com.sun.jersey.multipart.FormDataParam; import groovy.lang.GroovyClassLoader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import static com.netflix.ndbench.core.util.RestUtil.Result; import static com.netflix.ndbench.core.util.RestUtil.ErrorResponse; import static com.netflix.ndbench.core.util.RestUtil.SuccessResponse; /** * @author vchella, pencal */ @Path("/ndbench/driver") public class NdBenchResource { private static final Logger logger = LoggerFactory.getLogger(NdBenchResource.class); private final NdBenchClientFactory clientFactory; private final NdBenchDriver ndBenchDriver; private final DataBackfill dataBackfill; private final IConfiguration config; private final NdBenchMonitor ndBenchMonitor; @Inject public NdBenchResource(NdBenchClientFactory cFactory, NdBenchDriver ndBenchDriver, DataBackfill dataBackfill, IConfiguration config, NdBenchMonitor ndBenchMonitor) { this.clientFactory = cFactory; this.ndBenchDriver = ndBenchDriver; this.dataBackfill = dataBackfill; this.config = config; this.ndBenchMonitor = ndBenchMonitor; } @Path("/initfromscript") @POST @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.APPLICATION_JSON) public Response initfromscript(@FormDataParam("dynamicplugin") String dynamicPlugin) throws Exception { try { GroovyClassLoader gcl = new GroovyClassLoader(); Class classFromScript = gcl.parseClass(dynamicPlugin); Object objectFromScript = classFromScript.newInstance(); NdBenchClient client = (NdBenchClient) objectFromScript; ndBenchDriver.init(client); return sendSuccessResponse("NdBench client - dynamic plugin initiated with script!"); } catch (Exception e) { logger.error("Error initializing dynamic plugin from script", e); return sendErrorResponse("script initialization failed for dynamic plugin!", e); } } @Path("/startDataFill") @GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response startDataFill() throws Exception { logger.info("Starting NdBench data fill"); try { NdBenchAbstractClient<?> client = ndBenchDriver.getClient(); dataBackfill.backfill(client); return sendSuccessResponse("data fill done!"); } catch (Exception e) { logger.error("Error starting datafill", e); return sendErrorResponse("dataFill failed!", e); } } @Path("/startDataFillAsync") @GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response startDataFillAsync() throws Exception { logger.info("Starting NdBench data fill - Async"); try { NdBenchAbstractClient<?> client = ndBenchDriver.getClient(); dataBackfill.backfillAsync(client); return sendSuccessResponse( "Async data fill started !"); } catch (Exception e) { logger.error("Error starting datafill", e); return sendErrorResponse("Async dataFill failed to start!", e); } } @Path("/startConditionalDataFill") @GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response conditionalBackfill() throws Exception { logger.info("Starting NdBench data fill"); try { NdBenchAbstractClient<?> client = ndBenchDriver.getClient(); dataBackfill.conditionalBackfill(client); return sendSuccessResponse("data fill done!"); } catch (Exception e) { logger.error("Error starting datafill", e); return sendErrorResponse("dataFill failed!", e); } } @Path("/startVerifyDataFill") @GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response verifyBackfill() throws Exception { logger.info("Starting NdBench data fill"); try { NdBenchAbstractClient<?> client = ndBenchDriver.getClient(); dataBackfill.verifyBackfill(client); return sendSuccessResponse("data fill done!"); } catch (Exception e) { logger.error("Error starting datafill", e); return sendErrorResponse("dataFill failed!", e); } } @Path("/stopDataFill") @GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response stopDataFill() throws Exception { logger.info("Stop NdBench data fill"); try { dataBackfill.stopBackfill(); return sendSuccessResponse("data fill stop!" ); } catch (Exception e) { logger.error("Error stop datafill", e); return sendErrorResponse("dataFill failed!", e); } } @Path("/shutdownDataFill") @GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response shutdownDataFill() throws Exception { logger.info("Shutdown NdBench data fill"); try { dataBackfill.shutdown(); return sendSuccessResponse("data fill stop!" ); } catch (Exception e) { logger.error("Error shutdown datafill", e); return sendErrorResponse("dataFill failed!", e); } } @Path("/init/{client}") @GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response init(@PathParam("client") String clientName) throws Exception { try { NdBenchAbstractClient<?> client = clientFactory.getClient(clientName); ndBenchDriver.init(client); return sendSuccessResponse("NdBench client initiated!"); } catch (Exception e) { logger.error("Error initializing the client - "+clientName, e); return sendErrorResponse("Client initialization failed!", e); } } @Path("/start") @GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response start(@DefaultValue("random") @QueryParam("loadPattern") String loadPattern, @DefaultValue("-1") @QueryParam("windowSize") int windowSize, @DefaultValue("-1") @QueryParam("durationInSec") long durationInSec, @DefaultValue("1") @QueryParam("bulkSize") int bulkSize) throws Exception { try { LoadPattern loadPatternType = LoadPattern.fromString(loadPattern); Result validationResult = validateLoadPatternParams(loadPatternType, windowSize, durationInSec); if (validationResult.isSuccess) { ndBenchDriver.start(loadPatternType, windowSize, durationInSec, bulkSize); logger.info("Starting NdBench test"); return sendSuccessResponse("NDBench test started"); } else { return sendResult(validationResult); } } catch (Exception e) { logger.error("Error starting NdBench test", e); return sendErrorResponse("NdBench start failed! ", e); } } @Path("/startReads") @GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response startReads(@DefaultValue("random") @QueryParam("loadPattern") String loadPattern, @DefaultValue("-1") @QueryParam("windowSize") int windowSize, @DefaultValue("-1") @QueryParam("durationInSec") long durationInSec, @DefaultValue("1") @QueryParam("bulkSize") int bulkSize) throws Exception { try { LoadPattern loadPatternType = LoadPattern.fromString(loadPattern); Result validationResult = validateLoadPatternParams(loadPatternType, windowSize, durationInSec); if (validationResult.isSuccess) { ndBenchDriver.startReads(loadPatternType, windowSize, durationInSec, bulkSize); logger.info("Starting NdBench reads"); return sendSuccessResponse("NDBench reads started"); } else { return sendResult(validationResult); } } catch (Exception e) { logger.error("Error starting NdBench read test", e); return sendErrorResponse("NdBench startReads failed! ", e); } } @Path("/stopReads") @GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response stopReads() throws Exception { logger.info("stopping NdBenchread test"); try { ndBenchDriver.stopReads(); return sendSuccessResponse("NdBench reads stopped!"); } catch (Exception e) { logger.error("Error stopping NdBench reads", e); return sendErrorResponse("NdBench stopreads failed! ", e); } } @Path("/startWrites") @GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response startWrites(@DefaultValue("random") @QueryParam("loadPattern") String loadPattern, @DefaultValue("-1") @QueryParam("windowSize") int windowSize, @DefaultValue("-1") @QueryParam("durationInSec") long durationInSec, @DefaultValue("1") @QueryParam("bulkSize") int bulkSize) throws Exception { try { LoadPattern loadPatternType = LoadPattern.fromString(loadPattern); Result validationResult = validateLoadPatternParams(loadPatternType, windowSize, durationInSec); if (validationResult.isSuccess) { ndBenchDriver.startWrites(loadPatternType, windowSize, durationInSec, bulkSize); logger.info("Starting NdBench writes"); return sendSuccessResponse("NDBench writes started"); } else { return sendResult(validationResult); } } catch (Exception e) { logger.error("Error starting NdBench write test", e); return sendErrorResponse("NdBench startWrites failed! ", e); } } @Path("/stopWrites") @GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response stopWrites() throws Exception { logger.info("stopping NdBenchwrite test"); try { ndBenchDriver.stopWrites(); return sendSuccessResponse("NdBench writes stopped!"); } catch (Exception e) { logger.error("Error stopping NdBench writes", e); return sendErrorResponse("NdBench stopwrites failed! ", e); } } @Path("/stop") @GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response stop() throws Exception { logger.info("Stopping NdBench tests"); try { ndBenchDriver.stop(); return sendSuccessResponse("NdBench test stopped!"); } catch (Exception e) { logger.error("Error stopping NdBench test", e); return sendErrorResponse("NdBench stop failed! ", e); } } @Path("/readSingle/{key}") @GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response readSingle(@PathParam("key") String key) throws Exception { try { String value = ndBenchDriver.readSingle(key); return sendSuccessResponse(value); } catch (Exception e) { return sendErrorResponse("NdBench readSingle failed! ", e); } } @Path("/writeSingle/{key}") @GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response writeSingle(@PathParam("key") String key) throws Exception { try { String result = ndBenchDriver.writeSingle(key); return sendSuccessResponse(result); } catch (Exception e) { logger.error("ERROR: " + e.getMessage()); return sendErrorResponse("NdBench writeSingle failed! ", e); } } @Path("/stats") @GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response NdBenchStats() throws Exception { try { return sendJson(ndBenchMonitor); } catch (Exception e) { logger.error("Error getting NdBench stats", e); return sendErrorResponse("NdBench status failed! ", e); } } @Path("/getReadStatus") @GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response getReadStatus() throws Exception { try { if (ndBenchDriver.getIsReadRunning()) return sendSuccessResponse("Read process running"); else return sendSuccessResponse( "No Read process is running"); } catch (Exception e) { logger.error("Error getting NdBench getReadStatus", e); return sendErrorResponse("NdBench getReadStatus failed! ", e); } } @Path("/getWriteStatus") @GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response getWriteStatus() throws Exception { try { if (ndBenchDriver.getIsWriteRunning()) return sendSuccessResponse("Writes process running"); else return sendSuccessResponse("No Write process is running"); } catch (Exception e) { logger.error("Error getting NdBench getWriteStatus", e); return sendErrorResponse("NdBench getWriteStatus failed! ", e); } } @Path("/shutdownclient") @GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response shutdownClient() throws Exception { try { ndBenchDriver.stop(); ndBenchDriver.shutdownClient(); ndBenchMonitor.resetStats(); return sendSuccessResponse("NdBench client uninitialized"); } catch (Exception e) { logger.error("Error shutting down NdBench client", e); return sendErrorResponse("NdBench shutdownClient failed! ", e); } } @Path("/getdrivers") @GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response getDrivers() throws Exception { try { return sendJson(clientFactory.getClientDrivers()); } catch (Exception e) { logger.error("Error in getting Client drivers", e); return sendErrorResponse("NdBench getDrivers failed! ", e); } } @Path("/getserverstatus") @GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response getServerStatus() throws Exception { try { Map<String, Object> serverStatusJson = new HashMap<>(); serverStatusJson.put("ClientDrivers",clientFactory.getClientDrivers()); serverStatusJson.put("LoadPatterns", Arrays.asList(LoadPattern.values())); String currentRunningDriver="NA",connectionInfo="NA", currentWriteLoadPattern="NA", currentReadLoadPattern="NA"; NdBenchAbstractClient<?> NdBenchClient= ndBenchDriver.getClient(); if(NdBenchClient!=null) { if(NdBenchClient.getClass().getAnnotation(NdBenchClientPlugin.class)!=null) { currentRunningDriver=NdBenchClient.getClass().getAnnotation(NdBenchClientPlugin.class).value(); } else { currentRunningDriver=NdBenchClient.getClass().getSimpleName(); } connectionInfo=NdBenchClient.getConnectionInfo(); } KeyGenerator writeLoadPattern=ndBenchDriver.getWriteLoadPattern(); if(null!=writeLoadPattern) { currentWriteLoadPattern= writeLoadPattern.getClass().getSimpleName(); } KeyGenerator readLoadPattern=ndBenchDriver.getReadLoadPattern(); if(null!=readLoadPattern) { currentReadLoadPattern= readLoadPattern.getClass().getSimpleName(); } serverStatusJson.put("RunningDriver",currentRunningDriver); serverStatusJson.put("RunningWriteLoadPattern",currentWriteLoadPattern); serverStatusJson.put("RunningReadLoadPattern",currentReadLoadPattern); serverStatusJson.put("ConnectionInfo",connectionInfo); serverStatusJson.put("IsReadsRunning", ndBenchDriver.getIsReadRunning()); serverStatusJson.put("IsWritesRunning", ndBenchDriver.getIsWriteRunning()); serverStatusJson.put("Stats",ndBenchMonitor); serverStatusJson.put("DriverConfig",config); serverStatusJson.put("IsBackfillRunning",dataBackfill.getIsBackfillRunning()); return sendJson(serverStatusJson); } catch (Exception e) { logger.error("Error in getting getServerStatus", e); return sendErrorResponse("NdBench getServerStatus failed! ", e); } } @Path("/runworkflow") @GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response runWorkflow() throws Exception { try { NdBenchAbstractClient<?> client = ndBenchDriver.getClient(); return sendSuccessResponse(client.runWorkFlow()); } catch (Exception e) { logger.error("Error in running workflow", e); return sendErrorResponse("NdBench runworkflow failed! ", e); } } private Result validateLoadPatternParams(LoadPattern loadPattern, long windowSize, long durationInSec) { String returnMsg = "Input validation Failure:"; if(loadPattern==null) { returnMsg+="loadpattern parameter is not available"; logger.error(returnMsg); return new ErrorResponse(returnMsg); } if(loadPattern.equals(LoadPattern.SLIDING_WINDOW) && (windowSize < 1 || durationInSec < 1)) { returnMsg += "WindowSize and DurationInSeconds can not be less than 1, provided: windowSize: "+windowSize+", durationInSec: "+durationInSec; logger.error(returnMsg); return new ErrorResponse(returnMsg); } return new SuccessResponse(""); } private Response sendSuccessResponse(String returnMessage) { return RestUtil.sendSuccessResponse(returnMessage, this.config); } private Response sendErrorResponse(String errorMessage, Exception e) { return RestUtil.sendErrorResponse(errorMessage, e, this.config); } private Response sendResult(RestUtil.Result result) { return RestUtil.sendResult(result, this.config); } private <T> Response sendJson(T object) { return RestUtil.sendJson(object, this.config); } }
8,387
3,673
// ---------------------------------------------------------------------------- // - Open3D: www.open3d.org - // ---------------------------------------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2018-2021 www.open3d.org // // 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 "open3d/core/nns/FixedRadiusIndex.h" #include "open3d/core/Dispatch.h" #include "open3d/core/TensorCheck.h" #include "open3d/utility/Logging.h" namespace open3d { namespace core { namespace nns { FixedRadiusIndex::FixedRadiusIndex(){}; FixedRadiusIndex::FixedRadiusIndex(const Tensor &dataset_points, double radius) { AssertTensorDtypes(dataset_points, {Float32, Float64}); SetTensorData(dataset_points, radius); }; FixedRadiusIndex::~FixedRadiusIndex(){}; bool FixedRadiusIndex::SetTensorData(const Tensor &dataset_points, double radius) { const int64_t num_dataset_points = dataset_points.GetShape()[0]; Tensor points_row_splits(std::vector<int64_t>({0, num_dataset_points}), {2}, Int64); return SetTensorData(dataset_points, points_row_splits, radius); } bool FixedRadiusIndex::SetTensorData(const Tensor &dataset_points, const Tensor &points_row_splits, double radius) { AssertTensorDtypes(dataset_points, {Float32, Float64}); // AssertTensorDevice(points_row_splits, dataset_points.GetDevice()); AssertTensorDtype(points_row_splits, Int64); if (radius <= 0) { utility::LogError("radius should be positive."); } if (dataset_points.GetShape()[0] != points_row_splits[-1].Item<int64_t>()) { utility::LogError( "dataset_points and points_row_splits have incompatible " "shapes."); } dataset_points_ = dataset_points.Contiguous(); points_row_splits_ = points_row_splits.Contiguous(); const int64_t num_dataset_points = GetDatasetSize(); const int64_t num_batch = points_row_splits.GetShape()[0] - 1; const Device device = GetDevice(); const Dtype dtype = GetDtype(); std::vector<uint32_t> hash_table_splits(num_batch + 1, 0); for (int i = 0; i < num_batch; ++i) { int64_t num_dataset_points_i = points_row_splits_[i + 1].Item<int64_t>() - points_row_splits_[i].Item<int64_t>(); int64_t hash_table_size = std::min<int64_t>( std::max<int64_t>(hash_table_size_factor * num_dataset_points_i, 1), max_hash_tabls_size); hash_table_splits[i + 1] = hash_table_splits[i] + (uint32_t)hash_table_size; } hash_table_splits_ = Tensor(hash_table_splits, {num_batch + 1}, UInt32); hash_table_index_ = Tensor::Empty({num_dataset_points}, UInt32, device); hash_table_cell_splits_ = Tensor::Empty({hash_table_splits.back() + 1}, UInt32, device); #define BUILD_PARAMETERS \ dataset_points_, radius, points_row_splits_, hash_table_splits_, \ hash_table_index_, hash_table_cell_splits_ #define CALL_BUILD(type, fn) \ if (Dtype::FromType<type>() == dtype) { \ fn<type>(BUILD_PARAMETERS); \ return true; \ } if (device.GetType() == Device::DeviceType::CUDA) { #ifdef BUILD_CUDA_MODULE CALL_BUILD(float, BuildSpatialHashTableCUDA) CALL_BUILD(double, BuildSpatialHashTableCUDA) #else utility::LogError( "-DBUILD_CUDA_MODULE=OFF. Please compile Open3d with " "-DBUILD_CUDA_MODULE=ON."); #endif } else { CALL_BUILD(float, BuildSpatialHashTableCPU) CALL_BUILD(double, BuildSpatialHashTableCPU) } return false; }; std::tuple<Tensor, Tensor, Tensor> FixedRadiusIndex::SearchRadius( const Tensor &query_points, double radius, bool sort) const { const int64_t num_query_points = query_points.GetShape()[0]; Tensor queries_row_splits(std::vector<int64_t>({0, num_query_points}), {2}, Int64); return SearchRadius(query_points, queries_row_splits, radius, sort); } std::tuple<Tensor, Tensor, Tensor> FixedRadiusIndex::SearchRadius( const Tensor &query_points, const Tensor &queries_row_splits, double radius, bool sort) const { const Dtype dtype = GetDtype(); const Device device = GetDevice(); // Check device and dtype. AssertTensorDevice(query_points, device); AssertTensorDtype(query_points, dtype); // AssertTensorDevice(queries_row_splits, device); AssertTensorDtype(queries_row_splits, Int64); // Check shape. AssertTensorShape(query_points, {utility::nullopt, GetDimension()}); AssertTensorShape(queries_row_splits, points_row_splits_.GetShape()); const int64_t num_query_points = query_points.GetShape()[0]; if (num_query_points != queries_row_splits[-1].Item<int64_t>()) { utility::LogError( "query_points and queries_row_splits have incompatible " "shapes."); } if (radius <= 0) { utility::LogError("radius should be positive."); } Tensor query_points_ = query_points.Contiguous(); Tensor queries_row_splits_ = queries_row_splits.Contiguous(); Tensor neighbors_index, neighbors_distance; Tensor neighbors_row_splits = Tensor({num_query_points + 1}, Int64, device); #define RADIUS_PARAMETERS \ dataset_points_, query_points_, radius, points_row_splits_, \ queries_row_splits_, hash_table_splits_, hash_table_index_, \ hash_table_cell_splits_, Metric::L2, false, true, sort, \ neighbors_index, neighbors_row_splits, neighbors_distance #define CALL_RADIUS(type, fn) \ if (Dtype::FromType<type>() == dtype) { \ fn<type>(RADIUS_PARAMETERS); \ } if (device.GetType() == Device::DeviceType::CUDA) { #ifdef BUILD_CUDA_MODULE CALL_RADIUS(float, FixedRadiusSearchCUDA) CALL_RADIUS(double, FixedRadiusSearchCUDA) #else utility::LogError( "-DBUILD_CUDA_MODULE=OFF. Please compile Open3d with " "-DBUILD_CUDA_MODULE=ON."); #endif } else { CALL_RADIUS(float, FixedRadiusSearchCPU) CALL_RADIUS(double, FixedRadiusSearchCPU) } return std::make_tuple(neighbors_index, neighbors_distance, neighbors_row_splits); }; std::tuple<Tensor, Tensor, Tensor> FixedRadiusIndex::SearchHybrid( const Tensor &query_points, double radius, int max_knn) const { const int64_t num_query_points = query_points.GetShape()[0]; Tensor queries_row_splits(std::vector<int64_t>({0, num_query_points}), {2}, Int64); return SearchHybrid(query_points, queries_row_splits, radius, max_knn); } std::tuple<Tensor, Tensor, Tensor> FixedRadiusIndex::SearchHybrid( const Tensor &query_points, const Tensor &queries_row_splits, double radius, int max_knn) const { const Dtype dtype = GetDtype(); const Device device = GetDevice(); // Check device and dtype. AssertTensorDevice(query_points, device); AssertTensorDtype(query_points, dtype); // AssertTensorDevice(queries_row_splits, device); AssertTensorDtype(queries_row_splits, Int64); // Check shape. AssertTensorShape(query_points, {utility::nullopt, GetDimension()}); AssertTensorShape(queries_row_splits, points_row_splits_.GetShape()); const int64_t num_query_points = query_points.GetShape()[0]; if (num_query_points != queries_row_splits[-1].Item<int64_t>()) { utility::LogError( "query_points and queries_row_splits have incompatible " "shapes."); } if (radius <= 0) { utility::LogError("radius should be positive."); } Tensor query_points_ = query_points.Contiguous(); Tensor queries_row_splits_ = queries_row_splits.Contiguous(); Tensor neighbors_index, neighbors_distance, neighbors_count; #define HYBRID_PARAMETERS \ dataset_points_, query_points_, radius, max_knn, points_row_splits_, \ queries_row_splits_, hash_table_splits_, hash_table_index_, \ hash_table_cell_splits_, Metric::L2, neighbors_index, \ neighbors_count, neighbors_distance #define CALL_HYBRID(type, fn) \ if (Dtype::FromType<type>() == dtype) { \ fn<type>(HYBRID_PARAMETERS); \ } if (device.GetType() == Device::DeviceType::CUDA) { #ifdef BUILD_CUDA_MODULE CALL_HYBRID(float, HybridSearchCUDA) CALL_HYBRID(double, HybridSearchCUDA) #else utility::LogError( "-DBUILD_CUDA_MODULE=OFF. Please compile Open3d with " "-DBUILD_CUDA_MODULE=ON."); #endif } else { CALL_HYBRID(float, HybridSearchCPU) CALL_HYBRID(double, HybridSearchCPU) } return std::make_tuple(neighbors_index.View({num_query_points, max_knn}), neighbors_distance.View({num_query_points, max_knn}), neighbors_count.View({num_query_points})); } } // namespace nns } // namespace core } // namespace open3d
4,644
630
<reponame>oussemanaffetyy/letter-shell /** * @file main.c * @author Letter (<EMAIL>) * @brief * @version 0.1 * @date 2020-07-12 * * @copyright (c) 2019 Letter * */ #include "shell_port.h" #include <stdlib.h> #include <signal.h> static int demoExit(int value) { system("stty icanon"); system("stty echo"); exit(value); return value; } SHELL_EXPORT_CMD(SHELL_CMD_PERMISSION(0)|SHELL_CMD_TYPE(SHELL_TYPE_CMD_FUNC)|SHELL_CMD_PARAM_NUM(1), exit, demoExit, exit); SHELL_EXPORT_KEY_AGENCY(SHELL_CMD_PERMISSION(0), 0x03000000, exit, demoExit, 0); static void signalHandler(int signal) { demoExit(0); } int main(void) { signal(SIGINT, signalHandler); system("stty -echo"); system("stty -icanon"); userShellInit(); shellTask(&shell); return 0; }
345
333
<filename>enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/openshift/ImageChangeTriggerEnricher.java /** * Copyright 2016 Red Hat, Inc. * * Red Hat 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 io.fabric8.maven.enricher.standard.openshift; import io.fabric8.kubernetes.api.builder.TypedVisitor; import io.fabric8.kubernetes.api.model.Container; import io.fabric8.kubernetes.api.model.KubernetesListBuilder; import io.fabric8.kubernetes.api.model.PodSpec; import io.fabric8.kubernetes.api.model.PodTemplateSpec; import io.fabric8.maven.core.config.PlatformMode; import io.fabric8.maven.core.util.Configs; import io.fabric8.maven.docker.util.ImageName; import io.fabric8.maven.enricher.api.BaseEnricher; import io.fabric8.maven.enricher.api.MavenEnricherContext; import io.fabric8.openshift.api.model.DeploymentConfigSpecBuilder; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; public class ImageChangeTriggerEnricher extends BaseEnricher { static final String ENRICHER_NAME = "fmp-openshift-imageChangeTrigger"; private Boolean enableAutomaticTrigger; private Boolean enableImageChangeTrigger; private Boolean trimImageInContainerSpecFlag; private enum Config implements Configs.Key { containers {{ d = ""; }}; public String def() { return d; } protected String d; } public ImageChangeTriggerEnricher(MavenEnricherContext context) { super(context, ENRICHER_NAME); this.enableAutomaticTrigger = getValueFromConfig(OPENSHIFT_ENABLE_AUTOMATIC_TRIGGER, true); this.enableImageChangeTrigger = getValueFromConfig(IMAGE_CHANGE_TRIGGERS, true); this.trimImageInContainerSpecFlag = getValueFromConfig(OPENSHIFT_TRIM_IMAGE_IN_CONTAINER_SPEC, false); } @Override public void create(PlatformMode platformMode, KubernetesListBuilder builder) { if(platformMode.equals(PlatformMode.kubernetes)) return; builder.accept(new TypedVisitor<DeploymentConfigSpecBuilder>() { @Override public void visit(DeploymentConfigSpecBuilder builder) { Map<String, String> containerToImageMap = new HashMap<>(); PodTemplateSpec template = builder.buildTemplate(); if (template != null) { PodSpec podSpec = template.getSpec(); Objects.requireNonNull(podSpec, "No PodSpec for PodTemplate:" + template); List<Container> containers = podSpec.getContainers(); for(Container container : containers) { if(container.getName() != null && container.getImage() != null) { containerToImageMap.put(container.getName(), container.getImage()); } } } // add a new image change trigger for the build stream if (containerToImageMap.size() != 0) { if(enableImageChangeTrigger && isOpenShiftMode()) { for (Map.Entry<String, String> entry : containerToImageMap.entrySet()) { String containerName = entry.getKey(); if(!isImageChangeTriggerNeeded(containerName)) continue; ImageName image = new ImageName(entry.getValue()); String tag = image.getTag() != null ? image.getTag() : "latest"; builder.addNewTrigger() .withType("ImageChange") .withNewImageChangeParams() .withAutomatic(enableAutomaticTrigger) .withNewFrom() .withKind("ImageStreamTag") .withName(image.getSimpleName() + ":" + tag) .withNamespace(image.getUser()) .endFrom() .withContainerNames(containerName) .endImageChangeParams() .endTrigger(); } if(trimImageInContainerSpecFlag) { builder.editTemplate().editSpec().withContainers(trimImagesInContainers(template)).endSpec().endTemplate(); } } } } }); } private Boolean isImageChangeTriggerNeeded(String containerName) { String containersFromConfig = Configs.asString(getConfig(Config.containers)); Boolean enrichAll = getValueFromConfig(ENRICH_ALL_WITH_IMAGE_TRIGGERS, false); if(enrichAll) { return true; } if(!(getProcessingInstructionViaKey(FABRIC8_GENERATED_CONTAINERS).contains(containerName) || getProcessingInstructionViaKey(NEED_IMAGECHANGE_TRIGGERS).contains(containerName) || Arrays.asList(containersFromConfig.split(",")).contains(containerName))) { return false; } return true; } private List<Container> trimImagesInContainers(PodTemplateSpec template) { List<Container> containers = template.getSpec().getContainers(); containers.forEach(container -> container.setImage("")); return containers; } }
2,898
363
#include <cppfs/posix/LocalFileSystem.h> #include <cppfs/FileHandle.h> #include <cppfs/FileWatcher.h> #include <cppfs/AbstractFileWatcherBackend.h> #include <cppfs/posix/LocalFileHandle.h> #ifdef SYSTEM_LINUX #include <cppfs/linux/LocalFileWatcher.h> #endif namespace cppfs { LocalFileSystem::LocalFileSystem() { } LocalFileSystem::~LocalFileSystem() { } FileHandle LocalFileSystem::open(const std::string & path) { return open(std::string(path)); } FileHandle LocalFileSystem::open(std::string && path) { return FileHandle( std::unique_ptr<AbstractFileHandleBackend>( new LocalFileHandle(shared_from_this(), std::move(path)) ) ); } std::unique_ptr<AbstractFileWatcherBackend> LocalFileSystem::createFileWatcher(FileWatcher & fileWatcher) { #ifdef SYSTEM_LINUX return std::unique_ptr<AbstractFileWatcherBackend>( new LocalFileWatcher(&fileWatcher, shared_from_this()) ); #else return nullptr; #endif } } // namespace cppfs
386
6,036
<filename>onnxruntime/core/providers/cuda/tensor/gather.h // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "core/providers/shared_library/provider_api.h" #include "core/providers/cuda/cuda_kernel.h" #include "core/providers/cpu/tensor/gatherbase.h" namespace onnxruntime { namespace cuda { class Gather final : public CudaKernel, public GatherBase { public: Gather(const OpKernelInfo& info) : CudaKernel(info), GatherBase(info) {} Status ComputeInternal(OpKernelContext* context) const override; }; } // namespace cuda } // namespace onnxruntime
205
3,793
<gh_stars>1000+ /* This file is part of: NoahFrame https://github.com/ketoo/NoahGameFrame Copyright 2009 - 2021 NoahFrame(NoahGameFrame) File creator: lvsheng.huang NoahFrame is open-source software and you can redistribute it and/or modify it under the terms of the License; besides, anyone who use this file/software must include this copyright announcement. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef NFI_HTTP_NET_MODULE_H #define NFI_HTTP_NET_MODULE_H #include "NFComm/NFPluginModule/NFPlatform.h" #include "NFComm/NFPluginModule/NFIModule.h" #include "NFComm/NFNetPlugin/NFIHttpServer.h" class NFIHttpServerModule : public NFIModule { public: virtual ~NFIHttpServerModule() {}; // register msg callback template<typename BaseType> bool AddRequestHandler(const std::string& strPath, const NFHttpType eRequestType, BaseType* pBase, bool (BaseType::*handleReceiver)(NF_SHARE_PTR<NFHttpRequest> req)) { HTTP_RECEIVE_FUNCTOR functor = std::bind(handleReceiver, pBase, std::placeholders::_1); HTTP_RECEIVE_FUNCTOR_PTR functorPtr(new HTTP_RECEIVE_FUNCTOR(functor)); return AddMsgCB(strPath, eRequestType, functorPtr); } template<typename BaseType> bool AddNetFilter(const std::string& strPath, BaseType* pBase, NFWebStatus(BaseType::*handleFilter)(NF_SHARE_PTR<NFHttpRequest> req)) { HTTP_FILTER_FUNCTOR functor = std::bind(handleFilter, pBase, std::placeholders::_1); HTTP_FILTER_FUNCTOR_PTR functorPtr(new HTTP_FILTER_FUNCTOR(functor)); return AddFilterCB(strPath, functorPtr); } public: virtual int InitServer(const unsigned short nPort) = 0; virtual bool ResponseMsg(NF_SHARE_PTR<NFHttpRequest> req, const std::string& msg, NFWebStatus code = NFWebStatus::WEB_OK, const std::string& reason = "OK") = 0; private: virtual bool AddMsgCB(const std::string& strPath, const NFHttpType eRequestType, const HTTP_RECEIVE_FUNCTOR_PTR& cb) = 0; virtual bool AddFilterCB(const std::string& strPath, const HTTP_FILTER_FUNCTOR_PTR& cb) = 0; }; #endif
874
1,334
<gh_stars>1000+ package org.mockserver.dashboard.serializers; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.std.StdSerializer; import com.google.common.collect.ImmutableMap; import org.mockserver.dashboard.model.DashboardLogEntryDTO; import org.mockserver.model.NottableString; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.apache.commons.lang3.StringUtils.isNotBlank; /** * @author jamesdbloom */ public class DashboardLogEntryDTOSerializer extends StdSerializer<DashboardLogEntryDTO> { public DashboardLogEntryDTOSerializer() { super(DashboardLogEntryDTO.class); } @Override public void serialize(DashboardLogEntryDTO logEntry, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException { jsonGenerator.writeStartObject(); jsonGenerator.writeObjectField("key", logEntry.getId() + "_log"); jsonGenerator.writeObjectFieldStart("value"); if (logEntry.getDescription() != null) { jsonGenerator.writeObjectField("description", logEntry.getDescription()); } if (logEntry.getType() != null) { jsonGenerator.writeObjectField("style", logStyle(logEntry)); } if (logEntry.getMessageFormat() != null) { String[] messageFormatParts = isNotBlank(logEntry.getMessageFormat()) ? logEntry.getMessageFormat().split("\\{}") : new String[]{""}; Object[] arguments = logEntry.getArguments(); List<Object> messageParts = new ArrayList<>(); for (int i = 0; i < messageFormatParts.length; i++) { messageParts.add(ImmutableMap.of( "key", logEntry.getId() + "_" + i + "msg", "value", messageFormatParts[i] )); if (arguments != null && i < arguments.length) { if (arguments[i] instanceof String || arguments[i] instanceof NottableString) { String[] split = String.valueOf(arguments[i]).split("\n"); if (arguments[i].equals(logEntry.getBecause())) { messageParts.add(ImmutableMap.of( "key", logEntry.getId() + "_" + i + "arg", "because", true, "argument", true, "value", split )); } else { messageParts.add(ImmutableMap.of( "key", logEntry.getId() + "_" + i + "arg", "multiline", split.length > 1, "argument", true, "value", split.length > 1 ? split : "\"" + split[0] + "\"" )); } } else { messageParts.add(ImmutableMap.of( "key", logEntry.getId() + "_" + i + "arg", "json", true, "argument", true, "value", arguments[i] != null ? arguments[i] : "\"\"" )); } } } if (logEntry.getThrowable() != null) { messageParts.add(ImmutableMap.of( "key", logEntry.getId() + "_throwable_msg", "value", "exception:" )); messageParts.add(ImmutableMap.of( "key", logEntry.getId() + "_throwable_value", "multiline", true, "argument", true, "value", logEntry.getThrowable() )); } jsonGenerator.writeObjectField("messageParts", messageParts); } jsonGenerator.writeEndObject(); // end value jsonGenerator.writeEndObject(); // end log entry } public Map<String, String> logStyle(DashboardLogEntryDTO logEntry) { Map<String, String> style = new HashMap<>(); style.put("paddingTop", "4px"); style.put("paddingBottom", "4px"); style.put("whiteSpace", "nowrap"); style.put("overflow", "auto"); switch (logEntry.getType()) { case RUNNABLE: break; case TRACE: style.put("color", "rgb(215, 216, 154)"); style.put("style.whiteSpace", "pre-wrap"); break; case DEBUG: style.put("color", "rgb(178,132,190)"); style.put("style.whiteSpace", "pre-wrap"); break; case INFO: style.put("color", "rgb(59,122,87)"); style.put("style.whiteSpace", "pre-wrap"); break; case WARN: style.put("color", "rgb(245, 95, 105)"); style.put("style.whiteSpace", "pre-wrap"); break; case ERROR: style.put("color", "rgb(179, 97, 122)"); style.put("style.whiteSpace", "pre-wrap"); break; case EXCEPTION: style.put("color", "rgb(211,33,45)"); style.put("style.whiteSpace", "pre-wrap"); break; case CLEARED: style.put("color", "rgb(139, 146, 52)"); break; case RETRIEVED: style.put("color", "rgb(222, 147, 95)"); break; case UPDATED_EXPECTATION: style.put("color", "rgb(176,191,26)"); break; case CREATED_EXPECTATION: style.put("color", "rgb(216,199,166)"); break; case REMOVED_EXPECTATION: style.put("color", "rgb(124,185,232)"); break; case RECEIVED_REQUEST: style.put("color", "rgb(114,160,193)"); break; case EXPECTATION_RESPONSE: style.put("color", "rgb(161,208,231)"); break; case NO_MATCH_RESPONSE: style.put("color", "rgb(196,98,16)"); break; case EXPECTATION_MATCHED: style.put("color", "rgb(117,185,186)"); break; case EXPECTATION_NOT_MATCHED: style.put("color", "rgb(204,165,163)"); break; case VERIFICATION: style.put("color", "rgb(178, 148, 187)"); break; case VERIFICATION_FAILED: style.put("color", "rgb(234, 67, 106)"); break; case FORWARDED_REQUEST: style.put("color", "rgb(152, 208, 255)"); break; case TEMPLATE_GENERATED: style.put("color", "rgb(241, 186, 27)"); break; case SERVER_CONFIGURATION: style.put("color", "rgb(138, 175, 136)"); break; default: style.put("color", "rgb(201, 125, 240)"); } return style; } }
4,025
4,812
// compile & generate coverage data using: // clang++ -g -o test-linux_x86_64 -fsanitize=address -fsanitize-coverage=bb test.cpp ../Inputs/foo.cpp // ASAN_OPTIONS="coverage=1" ./test-linux_x86_64 && mv test-linux_x86_64.??*.sancov test-linux_x86_64.0.sancov // ASAN_OPTIONS="coverage=1" ./test-linux_x86_64 1 && mv test-linux_x86_64.??*.sancov test-linux_x86_64.1.sancov #include <stdio.h> #include <string> void foo(); __attribute__((noinline)) std::string bar(std::string str) { printf("bar\n"); return str; } int main(int argc, char **argv) { if (argc == 2) foo(); bar("str"); printf("main\n"); }
271
468
<gh_stars>100-1000 #define GLI_INCLUDE_GL_NV_BINDLESS_MULTI_DRAW_INDIRECT void glMultiDrawArraysIndirectBindlessNV(GLenum[Main] mode, const void *indirect, GLsizei drawCount, GLsizei stride, GLint vertexBufferCount); void glMultiDrawElementsIndirectBindlessNV(GLenum[Main] mode, GLenum[Main] type, const void *indirect, GLsizei drawCount, GLsizei stride, GLint vertexBufferCount);
132
28,056
package com.alibaba.json.bvtVO.ae; import com.alibaba.fastjson.annotation.JSONType; /** * Created by huangliang on 17/4/12. */ public interface Area { public static final String TYPE_FLOOR = "floor"; public static final String TYPE_ITEM = "item"; String getName(); }
101
732
/* Copyright 2014 Adobe Systems Incorporated (http://www.adobe.com/). All Rights Reserved. This software is licensed as OpenSource, under the Apache License, Version 2.0. This license is available at: http://opensource.org/licenses/Apache-2.0. */ #ifndef SPOTMSGS_H #define SPOTMSGS_H #include "numtypes.h" extern const Byte8 *spotMsg(IntX msgId); /* Message IDs */ #define SPOT_MSG_BASEUNKCOORD 1 #define SPOT_MSG_CFFPARSING 2 #define SPOT_MSG_GIDTOOLARGE 3 #define SPOT_MSG_BOPTION 4 #define SPOT_MSG_ENCOUNKENCOD 5 #define SPOT_MSG_GPOSUNKSINGL 6 #define SPOT_MSG_GPOSUNKPAIR 7 #define SPOT_MSG_GPOSUNKANCH 8 #define SPOT_MSG_GPOSUNKMARKB 9 #define SPOT_MSG_GPOSUNSRLOOK 10 #define SPOT_MSG_GPOSUNKRLOOK 11 #define SPOT_MSG_GPOSNULFEAT 12 #define SPOT_MSG_GPOSUNSDLOOK 13 #define SPOT_MSG_GPOSUNKDLOOK 14 #define SPOT_MSG_GSUBUNKSINGL 15 #define SPOT_MSG_GSUBUNKMULT 16 #define SPOT_MSG_GSUBUNKALT 17 #define SPOT_MSG_GSUBUNKLIG 18 #define SPOT_MSG_GSUBUNKCTX 19 #define SPOT_MSG_GSUBUNKCCTX 20 #define SPOT_MSG_GSUBUNKRLOOK 21 #define SPOT_MSG_GSUBCTXDEF 22 #define SPOT_MSG_GSUBCTXCNT 23 #define SPOT_MSG_GSUBCTXNYI 24 #define SPOT_MSG_GSUBCCTXCNT 25 #define SPOT_MSG_GSUBINPUTCNT 26 #define SPOT_MSG_GSUBNULFEAT 27 #define SPOT_MSG_GSUBEVALCNT 28 #define SPOT_MSG_GSUBNOCOVG 29 #define SPOT_MSG_GSUBEUNKLOOK 30 #define SPOT_MSG_GSUBESUBCNT 31 #define SPOT_MSG_cmapBADMSFMT 32 #define SPOT_MSG_EARLYEOF 33 #define SPOT_MSG_BADREADSIZE 34 #define SPOT_MSG_TABLEMISSING 35 #define SPOT_MSG_NOMOREMEM 36 #define SPOT_MSG_UNKNGLYPHS 37 #define SPOT_MSG_glyfBADLOCA 38 #define SPOT_MSG_glyfMAXCMP 39 #define SPOT_MSG_glyfUNSCOMP 40 #define SPOT_MSG_glyfUNSDCOMP 41 #define SPOT_MSG_glyfUNSCANCH 42 #define SPOT_MSG_glyfLSBXMIN 43 #define SPOT_MSG_kernUNSTAB 44 #define SPOT_MSG_locaBADFMT 45 #define SPOT_MSG_BADFILE 46 #define SPOT_MSG_pathNOPELT 47 #define SPOT_MSG_pathNOSUBP 48 #define SPOT_MSG_pathMTMT 49 #define SPOT_MSG_pathNOOSA 50 #define SPOT_MSG_postNONGLYPH 51 #define SPOT_MSG_postBADVERS 52 #define SPOT_MSG_prufSTR2BIG 53 #define SPOT_MSG_prufWRTFAIL 54 #define SPOT_MSG_prufPROGRESS 55 #define SPOT_MSG_prufNUMPAGES 56 #define SPOT_MSG_prufOFILNAME 57 #define SPOT_MSG_prufPLSCLEAN 58 #define SPOT_MSG_prufSPOOLTO 59 #define SPOT_MSG_prufNOOPENF 60 #define SPOT_MSG_prufPREPPS 61 #define SPOT_MSG_prufCANTPS 62 #define SPOT_MSG_prufNOBUFMEM 63 #define SPOT_MSG_prufNOSHAPES 64 #define SPOT_MSG_prufNOTPSDEV 65 #define SPOT_MSG_NOSUCHSFNT 66 #define SPOT_MSG_BADTAGSTR 67 #define SPOT_MSG_BADFEATSTR 68 #define SPOT_MSG_sysIOERROR 69 #define SPOT_MSG_sysEOFERROR 70 #define SPOT_MSG_sysNOSUCHF 71 #define SPOT_MSG_sysMACFERROR 72 #define SPOT_MSG_sysFERRORSTR 73 #define SPOT_MSG_BADSCRIPTFILE 74 #define SPOT_MSG_ECHOSCRIPTFILE 75 #define SPOT_MSG_ECHOSCRIPTCMD 76 #define SPOT_MSG_RAWSTRING 77 #define SPOT_MSG_EOLN 78 #define SPOT_MSG_MACSELECTOTF 79 #define SPOT_MSG_MACSELECTSCRIPT 80 #define SPOT_MSG_MISSINGFILENAME 81 #define SPOT_MSG_TABLETOOBIG 82 #define SPOT_MSG_BADUNKCOVERAGE 83 #define SPOT_MSG_BADUNKCLASS 84 #define SPOT_MSG_BADINDEX 85 #define SPOT_MSG_cmapBADTBL 86 #define SPOT_MSG_DONE 87 #define SPOT_MSG_GPOS_DUPKRN 88 #define SPOT_MSG_FILEFERR 89 #define SPOT_MSG_GPOSUNKCTX 90 #define SPOT_MSG_GPOSUNKCCTX 91 #define SPOT_MSG_GPOSCTXDEF 92 #define SPOT_MSG_GPOSCTXCNT 93 #define SPOT_MSG_GPOSCTXNYI 94 #define SPOT_MSG_GPOSCCTXCNT 95 #define SPOT_MSG_GPOSUFMTCTX 96 #define SPOT_MSG_GPOSUFMTCCTX 97 #define SPOT_MSG_GPOSUFMTCCTX3 98 #define SPOT_MSG_GPOSUFMTDEV 99 #define SPOT_MSG_GSUBUFMTCTX 100 #define SPOT_MSG_GSUBUFMTCCTX 101 #define SPOT_MSG_CNTX_RECURSION 102 #define SPOT_MSG_DUP_IN_COV 103 #define SPOT_MSG_GSUBMULTIPLEINPUTS 104 #define SPOT_MSG_ENDSENTINEL SPOT_MSG_GSUBMULTIPLEINPUTS #endif
2,510
1,604
<gh_stars>1000+ package org.bouncycastle.tls.crypto.impl.bc; import org.bouncycastle.tls.crypto.TlsAgreement; import org.bouncycastle.tls.crypto.TlsECDomain; public class BcX448Domain implements TlsECDomain { protected final BcTlsCrypto crypto; public BcX448Domain(BcTlsCrypto crypto) { this.crypto = crypto; } public TlsAgreement createECDH() { return new BcX448(crypto); } }
185
2,542
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #pragma once namespace Api { typedef ComPointer<IFabricTransportMessage> ComFabricTransportMessageCPtr; class ComProxyFabricTransportMessageHandler : public Common::ComponentRoot, public IServiceCommunicationMessageHandler { DENY_COPY(ComProxyFabricTransportMessageHandler); public: ComProxyFabricTransportMessageHandler(Common::ComPointer<IFabricTransportMessageHandler> const & comImpl, Common::ComPointer<IFabricTransportMessageDisposer> const & comDisposerImpl); virtual ~ComProxyFabricTransportMessageHandler(); virtual Common::AsyncOperationSPtr BeginProcessRequest( std::wstring const & clientId, Transport::MessageUPtr && message, Common::TimeSpan const & timeout, Common::AsyncCallback const & callback, Common::AsyncOperationSPtr const & parent); virtual Common::ErrorCode EndProcessRequest( Common::AsyncOperationSPtr const & operation, Transport::MessageUPtr & reply); virtual Common::ErrorCode HandleOneWay( std::wstring const & clientId, Transport::MessageUPtr && message); virtual void Initialize(); virtual void Release() { } private: class ProcessRequestAsyncOperation; std::unique_ptr<Common::BatchJobQueue<ComFabricTransportMessageCPtr, Common::ComponentRoot>> disposeQueue_; Common::ComPointer<IFabricTransportMessageHandler> comImpl_; Common::ComPointer<IFabricTransportMessageDisposer> comDisposerImpl_; }; }
666
763
<reponame>pranavbj-amzn/batfish package org.batfish.common.traceroute; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.collect.ImmutableList; import java.util.List; import java.util.Stack; import java.util.stream.Stream; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.batfish.datamodel.Flow; import org.batfish.datamodel.FlowDisposition; import org.batfish.datamodel.flow.FirewallSessionTraceInfo; import org.batfish.datamodel.flow.Hop; import org.batfish.datamodel.flow.Trace; import org.batfish.datamodel.flow.TraceAndReverseFlow; /** * A DAG representation of a collection of {@link TraceAndReverseFlow traces}. Every path through * the DAG from a root to a leaf is a valid {@link TraceAndReverseFlow trace}, i.e. one that {@link * org.batfish.common.plugin.TracerouteEngine} would create. */ public final class TraceDagImpl implements TraceDag { /** A node in the DAG contains everything needed to reconstruct traces through the node. */ public static final class Node { private final @Nonnull Hop _hop; private final @Nullable FirewallSessionTraceInfo _firewallSessionTraceInfo; private final @Nullable FlowDisposition _flowDisposition; private final @Nullable Flow _returnFlow; private final List<Integer> _successors; public Node( Hop hop, @Nullable FirewallSessionTraceInfo firewallSessionTraceInfo, @Nullable FlowDisposition flowDisposition, @Nullable Flow returnFlow, List<Integer> successors) { checkArgument( (flowDisposition != null && flowDisposition.isSuccessful()) == (returnFlow != null), "returnFlow is present iff disposition is successful"); checkArgument( (flowDisposition != null) == successors.isEmpty(), "flowDisposition is present iff successors is empty"); _hop = hop; _firewallSessionTraceInfo = firewallSessionTraceInfo; _flowDisposition = flowDisposition; _returnFlow = returnFlow; _successors = ImmutableList.copyOf(successors); } public @Nonnull Hop getHop() { return _hop; } public @Nullable FirewallSessionTraceInfo getFirewallSessionTraceInfo() { return _firewallSessionTraceInfo; } public @Nullable FlowDisposition getFlowDisposition() { return _flowDisposition; } public @Nullable Flow getReturnFlow() { return _returnFlow; } public @Nonnull List<Integer> getSuccessors() { return _successors; } } private final List<Node> _nodes; private final List<Integer> _rootIds; public TraceDagImpl(List<Node> nodes, List<Integer> rootIds) { _nodes = nodes; _rootIds = rootIds; } public @Nonnull List<Node> getNodes() { return _nodes; } @Override public int size() { return new SizeComputer().size(); } /** Efficiently compute the number of traces in the DAG. */ private class SizeComputer { private final Integer[] _cache; SizeComputer() { _cache = new Integer[_nodes.size()]; } int size(int nodeId) { @Nullable Integer cachedSize = _cache[nodeId]; if (cachedSize != null) { return cachedSize; } Node node = _nodes.get(nodeId); if (node._successors.isEmpty()) { // leaf _cache[nodeId] = 1; } else { _cache[nodeId] = node._successors.stream().mapToInt(this::size).sum(); } return _cache[nodeId]; } int size() { return _rootIds.stream().mapToInt(this::size).sum(); } } private Stream<TraceAndReverseFlow> getTraces( List<Hop> hopsInput, List<FirewallSessionTraceInfo> sessionsInput, int rootId) { Node node = _nodes.get(rootId); List<Hop> hops = ImmutableList.<Hop>builderWithExpectedSize(hopsInput.size() + 1) .addAll(hopsInput) .add(node._hop) .build(); List<FirewallSessionTraceInfo> sessions; FirewallSessionTraceInfo firewallSessionTraceInfo = node._firewallSessionTraceInfo; if (firewallSessionTraceInfo != null) { sessions = ImmutableList.<FirewallSessionTraceInfo>builderWithExpectedSize(sessionsInput.size() + 1) .addAll(sessionsInput) .add(firewallSessionTraceInfo) .build(); } else { sessions = sessionsInput; } List<Integer> successors = node._successors; if (successors.isEmpty()) { FlowDisposition disposition = checkNotNull(node._flowDisposition, "failed to determine disposition from hop"); Trace trace = new Trace(disposition, hops); return Stream.of(new TraceAndReverseFlow(trace, node._returnFlow, sessions)); } else { return successors.stream().flatMap(successorId -> getTraces(hops, sessions, successorId)); } } @Override public int countEdges() { return _nodes.stream().map(node -> node._successors).mapToInt(List::size).sum(); } @Override public int countNodes() { return _nodes.size(); } private Stream<TraceAndReverseFlow> getTraces(int rootId) { return getTraces(ImmutableList.of(), new Stack<>(), rootId); } @Override public Stream<TraceAndReverseFlow> getTraces() { return _rootIds.stream().flatMap(this::getTraces); } }
1,995
32,544
<filename>gradle/junit5/src/test/java/com/example/CalculatorJUnit5Test.java package com.example; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test;; public class CalculatorJUnit5Test { @Tag("fast") @Test public void testAdd() { assertEquals(42, Integer.sum(19, 23)); } @Tag("slow") @Test public void testAddMaxInteger() { assertEquals(2147483646, Integer.sum(2147183646, 300000)); } @Tag("fast") @Test public void testAddZero() { assertEquals(21, Integer.sum(21, 0)); } @Tag("fast") @Test public void testDivide() { assertThrows(ArithmeticException.class, () -> { Integer.divideUnsigned(42, 0); }); } }
371
675
/* * Copyright 2016 The Bazel 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 com.google.idea.blaze.base.lang.buildfile.completion; import com.google.idea.blaze.base.lang.buildfile.psi.BuildFile; import com.google.idea.blaze.base.lang.buildfile.psi.StringLiteral; import com.intellij.codeInsight.AutoPopupController; import com.intellij.codeInsight.editorActions.TypedHandlerDelegate; import com.intellij.codeInsight.lookup.LookupManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; /** * Supplements {@link com.intellij.codeInsight.editorActions.CompletionAutoPopupHandler}, triggering * auto-complete pop-up on some non-letter characters when typing in build files. */ public class BuildCompletionAutoPopupHandler extends TypedHandlerDelegate { @Override public Result checkAutoPopup( char charTyped, final Project project, final Editor editor, final PsiFile file) { if (!(file instanceof BuildFile)) { return Result.CONTINUE; } if (LookupManager.getActiveLookup(editor) != null) { return Result.CONTINUE; } if (charTyped != '/' && charTyped != ':') { return Result.CONTINUE; } PsiElement psi = file.findElementAt(editor.getCaretModel().getOffset()); if (psi != null && psi.getParent() instanceof StringLiteral) { AutoPopupController.getInstance(project).scheduleAutoPopup(editor); return Result.STOP; } return Result.CONTINUE; } }
677
1,405
<filename>sample4/recompiled_java/sources/tms/ft.java<gh_stars>1000+ package tms; import android.content.IntentFilter; import com.lenovo.safecenter.net.cache.NetConstant; import com.tencent.tmsecure.common.ManagerCreator; import com.tencent.tmsecure.common.TMSApplication; import com.tencent.tmsecure.module.wupsession.WupSessionManager; /* access modifiers changed from: package-private */ public final class ft extends Thread { final /* synthetic */ af a; ft(af afVar) { this.a = afVar; } public final void run() { if (h.b) { TMSApplication.getApplicaionContext().unregisterReceiver(h.c); boolean unused = h.b = false; } try { Thread.sleep(NetConstant.SLEEP_SECONDS_TEN); } catch (InterruptedException e) { e.printStackTrace(); } if (((WupSessionManager) ManagerCreator.getManager(WupSessionManager.class)).reportChannelInfo() == 0) { this.a.a("reportlc", true, true); } else if (!(h.b)) { TMSApplication.getApplicaionContext().registerReceiver(h.c, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE")); boolean unused2 = h.b = true; } boolean unused3 = h.a = false; } }
540
1,088
/* Copyright 2020 Alibaba Group Holding Limited. 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. ==============================================================================*/ #ifndef GRAPHLEARN_COMMON_RPC_NOTIFICATION_H_ #define GRAPHLEARN_COMMON_RPC_NOTIFICATION_H_ #include <functional> #include <string> #include "graphlearn/include/status.h" namespace graphlearn { class RpcNotificationImpl; class RpcNotification { public: typedef std::function<void(const std::string& req_type, const Status& status)> Callback; RpcNotification(); ~RpcNotification(); // Set notification request type and reserve size. void Init(const std::string& req_type, int32_t size); // Add an rpc task to remote_id to tasks. // Returns: // task id. int32_t AddRpcTask(int32_t remote_id); // Set notification callback. // This callback will be invoked when all rpcs are done or any rpc is failed. void SetCallback(Callback cb); // An rpc task to remote_id is finished. void Notify(int32_t remote_id); // An rpc task to remote_id is failed. void NotifyFail(int32_t remote_id, const Status& status); // Wait for sync notification. void Wait(int64_t timeout_ms = -1); private: RpcNotificationImpl* impl_; }; } // namespace graphlearn #endif // GRAPHLEARN_COMMON_RPC_NOTIFICATION_H_
583
308
#include "init.hpp" #include "bugged.hpp" #include <vpp/buffer.hpp> // this should not give any warnings in the debug layer // used to make sure move/copy initialization works correctly // and does not leak resources TEST(copy) { auto& dev = *globals.device; vk::BufferCreateInfo bufInfo; bufInfo.size = 1024; bufInfo.usage = vk::BufferUsageBits::uniformBuffer; auto buffer = vpp::Buffer(dev.devMemAllocator(), bufInfo); buffer = {dev.devMemAllocator(), bufInfo}; buffer = {dev.devMemAllocator(), bufInfo}; buffer = {dev.devMemAllocator(), bufInfo}; }
193
381
from pypy.objspace.fake.checkmodule import checkmodule def test_checkmodule(): checkmodule('array')
34
1,091
/* * Copyright 2021-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.kubevirtnetworking.api; import org.onlab.packet.IpAddress; import java.util.Set; /** * Representation of load balancer. */ public interface KubevirtLoadBalancer { /** * Returns the load balancer name. * * @return load balancer name */ String name(); /** * Returns the load balancer description. * * @return load balancer description */ String description(); /** * Returns the network identifier. * * @return network identifier */ String networkId(); /** * Returns the load balancer virtual IP address. * * @return load balancer virtual IP address */ IpAddress vip(); /** * Returns the IP address of members. * * @return IP addresses */ Set<IpAddress> members(); /** * Returns the load balancer rules. * * @return load balancer rules */ Set<KubevirtLoadBalancerRule> rules(); /** * A default builder interface. */ interface Builder { /** * Builds an immutable load balancer instance. * * @return kubevirt load balancer */ KubevirtLoadBalancer build(); /** * Returns kubevirt load balancer builder with supplied load balancer name. * * @param name load balancer name * @return load balancer builder */ Builder name(String name); /** * Returns kubevirt load balancer builder with supplied load balancer description. * * @param description load balancer description * @return load balancer builder */ Builder description(String description); /** * Returns kubevirt load balancer builder with supplied load balancer network identifier. * * @param networkId load balancer network identifier * @return load balancer builder */ Builder networkId(String networkId); /** * Returns kubevirt load balancer builder with supplied load balancer vip. * * @param vip load balancer vip * @return load balancer builder */ Builder vip(IpAddress vip); /** * Returns kubevirt load balancer builder with supplied load balancer members. * * @param members load balancer members * @return load balancer builder */ Builder members(Set<IpAddress> members); /** * Returns kubevirt load balancer builder with supplied load balancer rules. * * @param rules load balancer rules * @return load balancer builder */ Builder rules(Set<KubevirtLoadBalancerRule> rules); } }
1,290
1,127
<filename>src/tests/functional/plugin/shared/include/behavior/ov_infer_request/inference.hpp // Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include <gtest/gtest.h> #include <string> #include "functional_test_utils/ov_plugin_cache.hpp" #include <base/behavior_test_utils.hpp> namespace ov { namespace test { namespace behavior { struct OVInferReqInferParam { ov::Shape m_shape; ov::Tensor m_input_tensor; std::vector<float> m_expected; std::string m_test_name; }; using OVInferRequestInferenceTestsParams = std::tuple<OVInferReqInferParam, std::string>; namespace tensor_roi { inline OVInferReqInferParam roi_nchw() { OVInferReqInferParam res; res.m_test_name = "roi_nchw"; res.m_shape = Shape{1, 2, 3, 3}; auto in_tensor = ov::Tensor(element::f32, Shape{1, 2, 5, 5}); auto in_data = std::vector<float>{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4 }; memcpy(in_tensor.data(), in_data.data(), in_data.size() * sizeof(float)); res.m_input_tensor = ov::Tensor(in_tensor, Coordinate{0, 0, 1, 1}, Coordinate{1, 2, 4, 4}); // Extracted 3x3 boxes, add 1 to each element res.m_expected = std::vector<float>{ 7, 8, 9, 2, 3, 4, 7, 8, 9, 9, 8, 7, 2, 3, 4, 7, 8, 9, }; return res; } inline OVInferReqInferParam roi_1d() { OVInferReqInferParam res; res.m_test_name = "roi_1d"; res.m_shape = Shape{3}; auto in_tensor = ov::Tensor(element::f32, Shape{5}); auto in_data = std::vector<float>{10, 20, 30, 40, 50}; memcpy(in_tensor.data(), in_data.data(), in_data.size() * sizeof(float)); res.m_input_tensor = ov::Tensor(in_tensor, Coordinate{1}, Coordinate{4}); res.m_expected = std::vector<float>{21, 31, 41}; return res; } } // namespace tensor_roi class OVInferRequestInferenceTests : public testing::WithParamInterface<OVInferRequestInferenceTestsParams>, public CommonTestUtils::TestsCommon { public: static std::string getTestCaseName(const testing::TestParamInfo<OVInferRequestInferenceTestsParams>& device_name); protected: void SetUp() override; void TearDown() override; static std::shared_ptr<Model> create_n_inputs(size_t num, element::Type type, const PartialShape& shape); std::shared_ptr<ov::Core> ie = utils::PluginCache::get().core(); OVInferReqInferParam m_param; std::string m_device_name; }; } // namespace behavior } // namespace test } // namespace ov
1,353
305
<reponame>securityscorecard/aws-big-data-blog<filename>aws-blog-real-time-in-memory-oltp-and-analytics-with-apache-ignite/sample/ddbStreamstoFirehose.py from __future__ import print_function import base64 import json import boto3 print('Loading function') client = boto3.client('firehose') def lambda_handler(event, context): #print("Received event: " + json.dumps(event, indent=2)) for record in event['Records']: # Kinesis data is base64 encoded so decode here #print(json.dumps(record['dynamodb'], indent=2)) payload = json.loads(json.dumps(record['dynamodb'], indent=2)) csvrecord = '' if payload['NewImage'].get('OrderId') != None: csvrecord = csvrecord+str(payload['NewImage']['OrderId']['S'])+',' if payload['NewImage'].get('OrderDate') != None: csvrecord = csvrecord+str(payload['NewImage']['OrderDate']['N'])+',' if payload['NewImage'].get('ShipMethod') != None: csvrecord = csvrecord+str(payload['NewImage']['ShipMethod']['S'])+',' if payload['NewImage'].get('BillAddress') != None: csvrecord = csvrecord+str(payload['NewImage']['BillAddress']['S']).replace('\n',' ')+',' if payload['NewImage'].get('BillCity') != None: csvrecord = csvrecord+str(payload['NewImage']['BillCity']['S'])+',' if payload['NewImage'].get('BillPostalCode') != None: csvrecord = csvrecord+str(payload['NewImage']['BillPostalCode']['N'])+',' if payload['NewImage'].get('OrderQty') != None: csvrecord = csvrecord+str(payload['NewImage']['OrderQty']['N'])+',' if payload['NewImage'].get('UnitPrice') != None: csvrecord = csvrecord+str(payload['NewImage']['UnitPrice']['N'])+',' if payload['NewImage'].get('ProductCategory') != None: csvrecord = csvrecord+str(payload['NewImage']['ProductCategory']['S'])+',' csvrecord = csvrecord[:-1]+'\n' response = client.put_record( DeliveryStreamName='<Firehose_Delivery_Stream_Name>', Record={ 'Data': csvrecord } ) return response
951
683
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package io.opentelemetry.javaagent.instrumentation.cxf; import org.apache.cxf.message.Message; import org.apache.cxf.phase.AbstractPhaseInterceptor; import org.apache.cxf.phase.Phase; public class TracingStartInInterceptor extends AbstractPhaseInterceptor<Message> { public TracingStartInInterceptor() { super(Phase.PRE_INVOKE); } @Override public void handleMessage(Message message) { CxfHelper.start(message); } }
169
360
""" Copyright (c) 2020 Huawei Technologies Co.,Ltd. openGauss is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v2 for more details. """ import datetime import logging import os import re import sys import shlex import subprocess import requests import config from datetime import timedelta from threading import Thread, Event import psycopg2 import sqlparse from sqlparse.sql import Identifier, IdentifierList from sqlparse.tokens import Keyword, DML from global_vars import DATE_FORMAT split_flag = ('!=', '<=', '>=', '==', '<', '>', '=', ',', '*', ';', '%', '+', ',', ';', '/') class RepeatTimer(Thread): """ This class inherits from threading.Thread, it is used for periodic execution function at a specified time interval. """ def __init__(self, interval, function, *args, **kwargs): Thread.__init__(self) self._interval = interval self._function = function self._args = args self._kwargs = kwargs self._finished = Event() def run(self): while not self._finished.is_set(): # Execute first, wait later. self._function(*self._args, **self._kwargs) self._finished.wait(self._interval) self._finished.set() def cancel(self): self._finished.set() class StdStreamSuppressor: """ This class suppress standard stream object 'stdout' and 'stderr' in context. """ def __init__(self): self.default_stdout_fd = sys.stdout.fileno() self.default_stderr_fd = sys.stderr.fileno() self.null_device_fd = [os.open(os.devnull, os.O_WRONLY), os.open(os.devnull, os.O_WRONLY)] self.standard_stream_fd = (os.dup(self.default_stdout_fd), os.dup(self.default_stderr_fd)) def __enter__(self): os.dup2(self.null_device_fd[0], self.default_stdout_fd) os.dup2(self.null_device_fd[1], self.default_stderr_fd) def __exit__(self, *args): os.dup2(self.standard_stream_fd[0], self.default_stdout_fd) os.dup2(self.standard_stream_fd[1], self.default_stderr_fd) os.close(self.null_device_fd[0]) os.close(self.null_device_fd[1]) class TimeString: TIMEDELTA_MAPPER = {'W': timedelta(weeks=1), 'D': timedelta(days=1), 'H': timedelta(hours=1), 'M': timedelta(minutes=1), 'S': timedelta(seconds=1)} SECOND_MAPPER = {'W': 7 * 24 * 3600, 'D': 24 * 3600, 'H': 3600, 'M': 60, 'S': 1} def __init__(self, time_string): """ Transform time string to timedelta or second, only support 'weeks(W), days(D), hours(H), minutes(M), seconds(S) :param time_string: string, time string like '10S', '20H', '3W'. """ self._str = time_string num, self._unit = re.match(r'(\d+)?([WDHMS])', time_string).groups() if self._unit is None: raise ValueError('Incorrect format %s.' % time_string) if num is None: self._val = 1 else: self._val = int(num) def to_second(self): return TimeString.SECOND_MAPPER.get(self._unit) * self._val def to_timedelta(self): return TimeString.TIMEDELTA_MAPPER.get(self._unit) * self._val @property def standard(self): return '%dS' % self.to_second() class DBAgent: def __init__(self, port, host=None, user=None, password=<PASSWORD>, database=None): self.host = host self.port = port self.user = user self.database = database self.password = password self.conn = None self.cursor = None self.connect() def __enter__(self): self.connect() return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() def connect(self): self.conn = psycopg2.connect(host=self.host, user=self.user, password=<PASSWORD>, database=self.database, port=self.port) self.conn.set_client_encoding('latin9') self.cursor = self.conn.cursor() def fetch_all_result(self, sql): try: self.cursor.execute(sql) result = list(self.cursor.fetchall()) return result except Exception as e: logging.getLogger('agent').warning(str(e)) def close(self): self.cursor.close() self.conn.close() def remove_comment(sql): sql = re.sub(r'\n', r' ', sql) sql = re.sub(r'/\s*\*[\w\W]*?\*\s*/\s*', r'', sql) sql = re.sub(r'^--.*\s?', r'', sql) return sql def unify_sql(sql): index = 0 sql = remove_comment(sql) while index < len(sql): if sql[index] in split_flag: if sql[index:index + 2] in split_flag: sql = sql[:index].strip() + ' ' + sql[index:index + 2] + ' ' + sql[index + 2:].strip() index = index + 3 else: sql = sql[:index].strip() + ' ' + sql[index] + ' ' + sql[index + 1:].strip() index = index + 2 else: index = index + 1 new_sql = list() for word in sql.split(): new_sql.append(word.upper()) sql = ' '.join(new_sql) return sql.strip() def input_sql_processing(sql): """ SQL desensitization """ if not sql: return '' standard_sql = unify_sql(sql) if standard_sql.startswith('INSERT'): standard_sql = re.sub(r'VALUES (\(.*\))', r'VALUES', standard_sql) # remove digital like 12, 12.565 standard_sql = re.sub(r'[\s]+\d+(\.\d+)?', r' ?', standard_sql) # remove '$n' in sql standard_sql = re.sub(r'\$\d+', r'?', standard_sql) # remove single quotes content standard_sql = re.sub(r'\'.*?\'', r'?', standard_sql) # remove double quotes content standard_sql = re.sub(r'".*?"', r'?', standard_sql) # remove '(1' format standard_sql = re.sub(r'\(\d+(\.\d+)?', r'(?', standard_sql) # remove '`' in sql standard_sql = re.sub(r'`', r'', standard_sql) # remove ; in sql standard_sql = re.sub(r';', r'', standard_sql) return standard_sql.strip() def wdr_sql_processing(sql): standard_sql = unify_sql(sql) standard_sql = re.sub(r';', r'', standard_sql) standard_sql = re.sub(r'VALUES (\(.*\))', r'VALUES', standard_sql) standard_sql = re.sub(r'\$\d+?', r'?', standard_sql) return standard_sql def convert_to_mb(volume_str): """ Transfer unit of K、M、G、T、P to M :param volume_str: string, byte information like '100M', '2K', '30G'. :return: int, bytes size in unit of M, like '400M' -> 400. """ convtbl = {'K': 1 / 1024, 'M': 1, 'G': 1024, 'T': 1024 * 1024, 'P': 1024 * 1024 * 1024} volume_str = volume_str.upper() num, unit = re.match(r'^(\d+|\d+\.\d+)([KMGTP])', volume_str).groups() if (num is None) or (unit is None) or (unit not in 'KMGTP'): raise ValueError('cannot parse format of {bytes}'.format(bytes=volume_str)) return convtbl[unit] * int(float(num)) def fatal_exit(msg=None): if msg: print("FATAL: %s." % msg, file=sys.stderr) logging.getLogger('service').fatal("A fatal problem has occurred, and the process will exit.") raise SystemExit(2) def abnormal_exit(msg=None): if msg: print("ERROR: %s." % msg, file=sys.stderr) logging.getLogger('service').fatal("An abnormal has occurred, and the process will exit.") raise SystemExit(1) def check_select(parsed_sql): if not parsed_sql.is_group: return False for token in parsed_sql.tokens: if token.ttype is DML and token.value.upper() == 'SELECT': return True return False def get_table_token_list(parsed_sql, token_list): flag = False for token in parsed_sql.tokens: if not flag: if token.ttype is Keyword and token.value.upper() == 'FROM': flag = True else: if check_select(token): get_table_token_list(token, token_list) elif token.ttype is Keyword: return else: token_list.append(token) def extract_table_from_select(sql): tables = [] table_token_list = [] sql_parsed = sqlparse.parse(sql)[0] get_table_token_list(sql_parsed, table_token_list) for table_token in table_token_list: if isinstance(table_token, Identifier): tables.append(table_token.get_name()) elif isinstance(table_token, IdentifierList): for identifier in table_token.get_identifiers(): tables.append(identifier.get_name()) else: if table_token.ttype is Keyword: tables.append(table_token.value) return tables def extract_table_from_sql(sql): """ Function: get table name in sql has many problems in code, especially in 'delete', 'update', 'insert into' sql """ if not sql.strip(): return [] delete_pattern_1 = re.compile(r'FROM\s+([^\s]*)[;\s ]?', re.IGNORECASE) delete_pattern_2 = re.compile(r'FROM\s+([^\s]*)\s+WHERE', re.IGNORECASE) update_pattern = re.compile(r'UPDATE\s+([^\s]*)\s+SET', re.IGNORECASE) insert_pattern = re.compile(r'INSERT\s+INTO\s+([^\s]*)\s+VALUES', re.IGNORECASE) if sql.upper().strip().startswith('SELECT'): tables = extract_table_from_select(sql) elif sql.upper().strip().startswith('DELETE'): if 'WHERE' not in sql: tables = delete_pattern_1.findall(sql) else: tables = delete_pattern_2.findall(sql) elif sql.upper().strip().startswith('UPDATE'): tables = update_pattern.findall(sql) elif sql.upper().strip().startswith('INSERT INTO'): sql = re.sub(r'\(.*?\)', r' ', sql) tables = insert_pattern.findall(sql) else: tables = [] return tables def check_time_legality(time_string): try: datetime.datetime.strptime(time_string, DATE_FORMAT) return True except ValueError: return False def check_port_occupancy(port): if not port.isdigit(): raise RuntimeError("The port should be digit: '{port}'".format(port=port)) child = subprocess.Popen(shlex.split('lsof -i:{port}'.format(port=port)), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False) stream = child.communicate() if stream[0]: raise RuntimeError("The port {port} is occupied.".format(port=port)) def read_pid_file(filepath): """ Return the pid of the running process recorded in the file, and return 0 if the acquisition fails. """ if not os.path.exists(filepath): return 0 try: with open(filepath, mode='r') as f: pid = int(f.read()) if os.path.exists('/proc/%d' % pid): return pid else: return 0 except PermissionError: return 0 except ValueError: return 0 def check_db_alive(port, database='postgres'): try: with DBAgent(port=port, database=database) as db: sql = "select pg_sleep(0.1)" result = db.fetch_all_result(sql) return True except Exception as e: return False def check_collector(): agent_logger = logging.getLogger('agent') try: req_url = 'http://{host}:{port}/sink'.format(host=config.get('server', 'host'), port=config.get('server', 'listen_port')) response = requests.get(req_url) return True except Exception as e: agent_logger.error("{error}".format(error=str(e))) return False def check_tls_protocol(): try: context = config.getboolean('security', 'tls') if context: protocol = 'https' else: protocol = 'http' return protocol except Exception as e: agent_logger.error("[security] part must exists in configure file.") raise
5,592
892
{ "schema_version": "1.2.0", "id": "GHSA-7m9x-8qgr-fwq3", "modified": "2022-05-13T01:02:19Z", "published": "2022-05-13T01:02:19Z", "aliases": [ "CVE-2014-5110" ], "details": "Cross-site scripting (XSS) vulnerability in user/help/html/index.php in Fonality trixbox allows remote attackers to inject arbitrary web script or HTML via the id_nodo parameter.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2014-5110" }, { "type": "WEB", "url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/94719" }, { "type": "WEB", "url": "http://packetstormsecurity.com/files/127522/Trixbox-XSS-LFI-SQL-Injection-Code-Execution.html" } ], "database_specific": { "cwe_ids": [ "CWE-79" ], "severity": "MODERATE", "github_reviewed": false } }
425
1,738
<filename>dev/Code/Sandbox/Editor/TrackView/TrackViewUndo.cpp /* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #include "StdAfx.h" #include <AzToolsFramework/API/ComponentEntityObjectBus.h> #include <Maestro/Bus/EditorSequenceComponentBus.h> #include <AzCore/Component/ComponentBus.h> #include "TrackViewUndo.h" #include "TrackViewSequenceManager.h" #include "TrackViewSequence.h" #include "TrackViewTrack.h" #include "Objects/ObjectLayer.h" #include "Objects/EntityObject.h" #include <Maestro/Types/AnimNodeType.h> #include <Maestro/Types/AnimParamType.h> #include <Maestro/Types/SequenceType.h> #include <AnimationContext.h> ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// CUndoComponentEntityTrackObject::CUndoComponentEntityTrackObject(CTrackViewTrack* track) { AZ_Assert(track, "Expected a valid track"); if (track) { m_trackName = track->GetName(); AZ_Assert(!m_trackName.empty(), "Expected a valid track name"); CTrackViewAnimNode* animNode = track->GetAnimNode(); AZ_Assert(animNode, "Expected a valid anim node"); if (animNode) { m_trackComponentId = animNode->GetComponentId(); AZ_Assert(m_trackComponentId != AZ::InvalidComponentId, "Expected a valid track component id"); CTrackViewSequence* sequence = track->GetSequence(); AZ_Assert(sequence, "Expected to find the sequence"); if (sequence) { m_sequenceId = sequence->GetSequenceComponentEntityId(); AZ_Assert(m_sequenceId.IsValid(), "Expected a valid sequence id"); AnimNodeType nodeType = animNode->GetType(); AZ_Assert(nodeType == AnimNodeType::Component, "Expected a this node to be a AnimNodeType::Component type"); if (nodeType == AnimNodeType::Component) { CTrackViewAnimNode* parentAnimNode = static_cast<CTrackViewAnimNode*>(animNode->GetParentNode()); AZ_Assert(parentAnimNode, "Expected a valid parent node"); if (parentAnimNode) { m_entityId = parentAnimNode->GetAzEntityId(); AZ_Assert(m_entityId.IsValid(), "Expected a valid sequence id"); // Store undo info. m_undo = track->GetMemento(); CObjectLayer* objectLayer = sequence->GetSequenceObjectLayer(); if (objectLayer) { objectLayer->SetModified(); } } } } } } } ////////////////////////////////////////////////////////////////////////// CTrackViewTrack* CUndoComponentEntityTrackObject::FindTrack(CTrackViewSequence* sequence) { AZ_Assert(sequence, "Expected to find the sequence"); CTrackViewTrack* track = nullptr; CTrackViewTrackBundle allTracks = sequence->GetAllTracks(); for (int trackIndex = 0; trackIndex < allTracks.GetCount(); trackIndex++) { CTrackViewTrack* curTrack = allTracks.GetTrack(trackIndex); if (curTrack->GetAnimNode() && curTrack->GetAnimNode()->GetComponentId() == m_trackComponentId) { if (0 == azstricmp(curTrack->GetName(), m_trackName.c_str())) { CTrackViewAnimNode* parentAnimNode = static_cast<CTrackViewAnimNode*>(curTrack->GetAnimNode()->GetParentNode()); if (parentAnimNode && parentAnimNode->GetAzEntityId() == m_entityId) { track = curTrack; break; } } } } return track; } ////////////////////////////////////////////////////////////////////////// void CUndoComponentEntityTrackObject::Undo(bool bUndo) { CTrackViewSequence* sequence = CTrackViewSequence::LookUpSequenceByEntityId(m_sequenceId); AZ_Assert(sequence, "Expected to find the sequence"); if (sequence) { CTrackViewTrack* track = FindTrack(sequence); AZ_Assert(track, "Expected to find track"); { CTrackViewSequenceNoNotificationContext context(sequence); if (bUndo) { m_redo = track->GetMemento(); } // Undo track state. track->RestoreFromMemento(m_undo); CObjectLayer* objectLayer = sequence->GetSequenceObjectLayer(); AZ_Assert(objectLayer, "Expected a valid layer object"); if (objectLayer && bUndo) { objectLayer->SetModified(); } } if (bUndo) { sequence->OnKeysChanged(); } else { sequence->ForceAnimation(); } } } ////////////////////////////////////////////////////////////////////////// void CUndoComponentEntityTrackObject::Redo() { CTrackViewSequence* sequence = CTrackViewSequence::LookUpSequenceByEntityId(m_sequenceId); AZ_Assert(sequence, "Expected to find the sequence"); if (sequence) { CTrackViewTrack* track = FindTrack(sequence); AZ_Assert(track, "Expected to find track"); // Redo track state. track->RestoreFromMemento(m_redo); CObjectLayer* objectLayer = sequence->GetSequenceObjectLayer(); AZ_Assert(objectLayer, "Expected a valid layer object"); if (objectLayer) { objectLayer->SetModified(); } sequence->OnKeysChanged(); } }
2,607
313
<filename>YBL365/Comment/ReuseView/CustomView/YBLNetWorkHudBar.h // // YBLNetWorkHudBar.h // YC168 // // Created by 乔同新 on 2017/5/1. // Copyright © 2017年 乔同新. All rights reserved. // #import <UIKit/UIKit.h> @interface YBLNetWorkHudBar : UIView + (void)startMonitorWithVc:(UIViewController *)selfVc; + (void)dismissHudView; + (void)setHudViewHidden:(BOOL)isHidden; @end
173
575
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_TEST_STUB_RENDER_WIDGET_HOST_OWNER_DELEGATE_H_ #define CONTENT_TEST_STUB_RENDER_WIDGET_HOST_OWNER_DELEGATE_H_ #include "content/browser/renderer_host/render_widget_host_owner_delegate.h" namespace content { class StubRenderWidgetHostOwnerDelegate : public RenderWidgetHostOwnerDelegate { public: void RenderWidgetDidFirstVisuallyNonEmptyPaint() override {} void RenderWidgetGotFocus() override {} void RenderWidgetLostFocus() override {} void RenderWidgetDidForwardMouseEvent( const blink::WebMouseEvent& mouse_event) override {} bool MayRenderWidgetForwardKeyboardEvent( const NativeWebKeyboardEvent& key_event) override; bool ShouldContributePriorityToProcess() override; void SetBackgroundOpaque(bool opaque) override {} bool IsMainFrameActive() override; bool IsNeverComposited() override; blink::web_pref::WebPreferences GetWebkitPreferencesForWidget() override; }; } // namespace content #endif // CONTENT_TEST_STUB_RENDER_WIDGET_HOST_OWNER_DELEGATE_H_
375
535
<reponame>tt1pjm/mynewt-core /* * 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. */ #include <assert.h> #include <string.h> #include <bsp.h> #include "uart/uart.h" #include "mcu/da1469x_pd.h" #include "mcu/da1469x_hal.h" #include "hal/hal_gpio.h" #include "uart_da1469x/uart_da1469x.h" static void da1469x_uart_uart_isr(void); static void da1469x_uart_uart2_isr(void); static void da1469x_uart_uart3_isr(void); struct da1469x_uart_hw_data { UART2_Type *regs; IRQn_Type irqn; mcu_gpio_func rx_pin_func; mcu_gpio_func tx_pin_func; mcu_gpio_func rts_pin_func; mcu_gpio_func cts_pin_func; /* Mask for (RE)SET_CLK_COM_REG */ uint8_t clk_com_mask; void (*isr)(void); }; static const struct da1469x_uart_hw_data da1469x_uart0_hw = { .regs = (UART2_Type *)UART, .irqn = UART_IRQn, .rx_pin_func = MCU_GPIO_FUNC_UART_RX, .tx_pin_func = MCU_GPIO_FUNC_UART_TX, .rts_pin_func = MCU_GPIO_FUNC_GPIO, .cts_pin_func = MCU_GPIO_FUNC_GPIO, .clk_com_mask = CRG_COM_RESET_CLK_COM_REG_UART_ENABLE_Msk, .isr = da1469x_uart_uart_isr, }; static const struct da1469x_uart_hw_data da1469x_uart1_hw = { .regs = (UART2_Type *)UART2, .irqn = UART2_IRQn, .rx_pin_func = MCU_GPIO_FUNC_UART2_RX, .tx_pin_func = MCU_GPIO_FUNC_UART2_TX, .rts_pin_func = MCU_GPIO_FUNC_UART2_RTSN, .cts_pin_func = MCU_GPIO_FUNC_UART2_CTSN, .clk_com_mask = CRG_COM_RESET_CLK_COM_REG_UART2_ENABLE_Msk, .isr = da1469x_uart_uart2_isr, }; static const struct da1469x_uart_hw_data da1469x_uart2_hw = { .regs = (UART2_Type *)UART3, .irqn = UART3_IRQn, .rx_pin_func = MCU_GPIO_FUNC_UART3_RX, .tx_pin_func = MCU_GPIO_FUNC_UART3_TX, .rts_pin_func = MCU_GPIO_FUNC_UART3_RTSN, .cts_pin_func = MCU_GPIO_FUNC_UART3_CTSN, .clk_com_mask = CRG_COM_RESET_CLK_COM_REG_UART3_ENABLE_Msk, .isr = da1469x_uart_uart3_isr, }; static struct da1469x_uart_dev *da1469x_dev0; static struct da1469x_uart_dev *da1469x_dev1; static struct da1469x_uart_dev *da1469x_dev2; static void da1469x_uart_uart_configure(struct da1469x_uart_dev *dev); static void da1469x_uart_uart_shutdown(struct da1469x_uart_dev *dev); static void da1469x_uart_on_wakeup_callout_cb(struct os_event *ev) { struct da1469x_uart_dev *dev = ev->ev_arg; da1469x_uart_uart_configure(dev); } static void da1469x_uart_on_wakeup_gpio_cb(void *arg) { struct da1469x_uart_dev *dev = arg; hal_gpio_irq_disable(dev->da1469x_cfg.pin_rx); hal_gpio_irq_release(dev->da1469x_cfg.pin_rx); os_callout_reset(&dev->wakeup_callout, os_time_ms_to_ticks32(MYNEWT_VAL(UART_DA1469X_WAKEUP_DELAY_MS))); } static void da1469x_uart_on_setup_wakeup_cb(struct os_event *ev) { struct da1469x_uart_dev *dev = ev->ev_arg; hal_gpio_irq_init(dev->da1469x_cfg.pin_rx, da1469x_uart_on_wakeup_gpio_cb, dev, HAL_GPIO_TRIG_RISING, HAL_GPIO_PULL_NONE); hal_gpio_irq_enable(dev->da1469x_cfg.pin_rx); } static void da1469x_uart_setup_wakeup(struct da1469x_uart_dev *dev) { os_eventq_put(os_eventq_dflt_get(), &dev->setup_wakeup_event); } static inline void da1469x_uart_tx_intr_enable(struct da1469x_uart_dev *dev) { dev->hw->regs->UART2_IER_DLH_REG |= UART2_UART2_IER_DLH_REG_PTIME_DLH7_Msk | UART2_UART2_IER_DLH_REG_ETBEI_DLH1_Msk; } static inline void da1469x_uart_tx_intr_disable(struct da1469x_uart_dev *dev) { dev->hw->regs->UART2_IER_DLH_REG &= ~(UART2_UART2_IER_DLH_REG_PTIME_DLH7_Msk | UART2_UART2_IER_DLH_REG_ETBEI_DLH1_Msk); } static inline void da1469x_uart_lsr_intr_enable(struct da1469x_uart_dev *dev) { dev->hw->regs->UART2_IER_DLH_REG |= UART2_UART2_IER_DLH_REG_ELSI_DLH2_Msk; } static inline void da1469x_uart_rx_intr_enable(struct da1469x_uart_dev *dev) { dev->hw->regs->UART2_IER_DLH_REG |= UART2_UART2_IER_DLH_REG_ERBFI_DLH0_Msk; } static inline void da1469x_uart_rx_intr_disable(struct da1469x_uart_dev *dev) { dev->hw->regs->UART2_IER_DLH_REG &= ~UART2_UART2_IER_DLH_REG_ERBFI_DLH0_Msk; } static void da1469x_uart_isr_thr_empty(struct da1469x_uart_dev *dev) { struct uart_conf *uc = &dev->uc; int ch; while (dev->hw->regs->UART2_USR_REG & UART2_UART2_USR_REG_UART_TFNF_Msk) { ch = uc->uc_tx_char(uc->uc_cb_arg); if (ch < 0) { da1469x_uart_tx_intr_disable(dev); dev->tx_started = 0; if (uc->uc_tx_done) { uc->uc_tx_done(uc->uc_cb_arg); } break; } dev->hw->regs->UART2_RBR_THR_DLL_REG = ch; } } static void da1469x_uart_isr_recv_data(struct da1469x_uart_dev *dev) { int ch; dev->rx_data = dev->hw->regs->UART2_RBR_THR_DLL_REG; ch = dev->uc.uc_rx_char(dev->uc.uc_cb_arg, dev->rx_data); if (ch < 0) { da1469x_uart_rx_intr_disable(dev); dev->rx_stalled = 1; } } static void da1469x_uart_isr(struct da1469x_uart_dev *dev) { UART2_Type *uart = dev->hw->regs; bool no_intr = false; os_trace_isr_enter(); while (!no_intr) { /* * NOTE: should be UART2_UART2_IIR_FCR_REG_IIR_FCR_Msk below but this is * defined (incorrectly) as 0xFF so incorrect value is read. */ switch (uart->UART2_IIR_FCR_REG & 0x0F) { case 0x01: /* no interrupt pending */ no_intr = true; break; case 0x02: /* THR empty */ da1469x_uart_isr_thr_empty(dev); break; case 0x04: /* received data available */ da1469x_uart_isr_recv_data(dev); break; case 0x06: /* receiver line status */ if (uart->UART2_LSR_REG & UART2_UART2_LSR_REG_UART_BI_Msk) { da1469x_uart_uart_shutdown(dev); da1469x_uart_setup_wakeup(dev); no_intr = true; } break; case 0x07: /* busy detect */ (void)uart->UART2_USR_REG; da1469x_uart_uart_shutdown(dev); da1469x_uart_setup_wakeup(dev); no_intr = true; break; case 0x0c: /* character timeout */ break; default: assert(0); break; } } os_trace_isr_exit(); } static void da1469x_uart_uart_isr(void) { da1469x_uart_isr(da1469x_dev0); } static void da1469x_uart_uart2_isr(void) { da1469x_uart_isr(da1469x_dev1); } static void da1469x_uart_uart3_isr(void) { da1469x_uart_isr(da1469x_dev2); } static void da1469x_uart_uart_configure(struct da1469x_uart_dev *dev) { struct uart_conf *uc = &dev->uc; uint32_t baudrate_cfg; uint32_t reg; UART2_Type *uart = dev->hw->regs; IRQn_Type irqn = dev->hw->irqn; da1469x_pd_acquire(MCU_PD_DOMAIN_COM); NVIC_DisableIRQ(irqn); if (dev->da1469x_cfg.pin_rx >= 0) { /* Turn RX pin to GPIO input during configuration to avoid busy state */ mcu_gpio_set_pin_function(dev->da1469x_cfg.pin_rx, MCU_GPIO_MODE_INPUT, MCU_GPIO_FUNC_GPIO); } /* Reset UART */ CRG_COM->RESET_CLK_COM_REG = dev->hw->clk_com_mask; CRG_COM->SET_CLK_COM_REG = dev->hw->clk_com_mask; uart->UART2_SRR_REG = UART2_UART2_SRR_REG_UART_UR_Msk | UART2_UART2_SRR_REG_UART_RFR_Msk | UART2_UART2_SRR_REG_UART_XFR_Msk; /* Configure baudrate */ baudrate_cfg = (32000000 - 1 + (uc->uc_speed / 2)) / uc->uc_speed; uart->UART2_LCR_REG |= UART2_UART2_LCR_REG_UART_DLAB_Msk; uart->UART2_IER_DLH_REG = (baudrate_cfg >> 12) & 0xff; uart->UART2_RBR_THR_DLL_REG = (baudrate_cfg >> 4) & 0xff; uart->UART2_DLF_REG = baudrate_cfg & 0x0f; uart->UART2_LCR_REG &= ~UART2_UART2_LCR_REG_UART_DLAB_Msk; /* Configure frame */ reg = 0; switch (uc->uc_parity) { case UART_PARITY_NONE: break; case UART_PARITY_EVEN: reg |= UART2_UART2_LCR_REG_UART_EPS_Msk; /* no break */ case UART_PARITY_ODD: reg |= UART2_UART2_LCR_REG_UART_PEN_Msk; break; } reg |= (uc->uc_stopbits - 1) << UART2_UART2_LCR_REG_UART_STOP_Pos; reg |= (uc->uc_databits - 5) << UART2_UART2_LCR_REG_UART_DLS_Pos; uart->UART2_LCR_REG = reg; /* Enable flow-control if requested and supported */ if (uc->uc_flow_ctl == UART_FLOW_CTL_RTS_CTS) { uart->UART2_MCR_REG |= UART2_UART2_MCR_REG_UART_AFCE_Msk | UART2_UART2_MCR_REG_UART_RTS_Msk; } /* Enable hardware FIFO */ uart->UART2_SFE_REG = UART2_UART2_SFE_REG_UART_SHADOW_FIFO_ENABLE_Msk; uart->UART2_SRT_REG = 0; uart->UART2_STET_REG = 0; dev->active = 1; dev->rx_stalled = 0; dev->tx_started = 0; da1469x_uart_lsr_intr_enable(dev); mcu_gpio_set_pin_function(dev->da1469x_cfg.pin_tx, MCU_GPIO_MODE_OUTPUT, dev->hw->tx_pin_func); if (dev->da1469x_cfg.pin_rx >= 0) { mcu_gpio_set_pin_function(dev->da1469x_cfg.pin_rx, dev->da1469x_cfg.rx_pullup ? MCU_GPIO_MODE_INPUT_PULLUP : MCU_GPIO_MODE_INPUT, dev->hw->rx_pin_func); da1469x_uart_rx_intr_enable(dev); } if (dev->da1469x_cfg.pin_rts >= 0) { mcu_gpio_set_pin_function(dev->da1469x_cfg.pin_rts, MCU_GPIO_MODE_OUTPUT, dev->hw->rts_pin_func); } if (dev->da1469x_cfg.pin_cts >= 0) { mcu_gpio_set_pin_function(dev->da1469x_cfg.pin_cts, MCU_GPIO_MODE_INPUT, dev->hw->cts_pin_func); } NVIC_ClearPendingIRQ(irqn); NVIC_EnableIRQ(irqn); } static void da1469x_uart_uart_shutdown(struct da1469x_uart_dev *dev) { dev->active = 0; /* * Reset UART before disabling clock to avoid any unexpected behavior after * clock is enabled again. */ dev->hw->regs->UART2_SRR_REG = UART2_UART2_SRR_REG_UART_UR_Msk | UART2_UART2_SRR_REG_UART_RFR_Msk | UART2_UART2_SRR_REG_UART_XFR_Msk; NVIC_DisableIRQ(dev->hw->irqn); NVIC_ClearPendingIRQ(dev->hw->irqn); CRG_COM->RESET_CLK_COM_REG = dev->hw->clk_com_mask; da1469x_pd_release(MCU_PD_DOMAIN_COM); } static int da1469x_uart_open(struct os_dev *odev, uint32_t wait, void *arg) { struct da1469x_uart_dev *dev = (struct da1469x_uart_dev *)odev; struct uart_conf *uc = (struct uart_conf *)arg; (void)wait; if (!uc) { return OS_EINVAL; } if (odev->od_flags & OS_DEV_F_STATUS_OPEN) { return OS_EBUSY; } dev->uc = *uc; if (uc->uc_speed < 1200 || uc->uc_speed > 1000000) { return OS_INVALID_PARM; } if ((uc->uc_databits < 5) || (uc->uc_databits > 8) || (uc->uc_stopbits < 1) || (uc->uc_stopbits > 2)) { return OS_INVALID_PARM; } if ((uc->uc_parity != UART_PARITY_NONE) && (uc->uc_parity != UART_PARITY_ODD) && (uc->uc_parity != UART_PARITY_EVEN)) { return OS_INVALID_PARM; } if (uc->uc_flow_ctl == UART_FLOW_CTL_RTS_CTS) { #if MYNEWT_VAL(UART_0) if (dev->hw->regs == (UART2_Type *)UART) { return OS_INVALID_PARM; } #endif if (dev->da1469x_cfg.pin_rts < 0 || dev->da1469x_cfg.pin_cts < 0) { return OS_INVALID_PARM; } } da1469x_uart_uart_configure(dev); return OS_OK; } static int da1469x_uart_close(struct os_dev *odev) { struct da1469x_uart_dev *dev = (struct da1469x_uart_dev *)odev; da1469x_uart_uart_shutdown(dev); return OS_OK; } static void da1469x_uart_drain_tx(struct da1469x_uart_dev *dev) { struct uart_conf *uc = &dev->uc; int ch; while (1) { ch = uc->uc_tx_char(uc->uc_cb_arg); if (ch < 0) { if (uc->uc_tx_done) { uc->uc_tx_done(uc->uc_cb_arg); } break; } } } static void da1469x_uart_start_tx(struct uart_dev *udev) { struct da1469x_uart_dev *dev = (struct da1469x_uart_dev *)udev; os_sr_t sr; if (!dev->active) { da1469x_uart_drain_tx(dev); return; } OS_ENTER_CRITICAL(sr); if (dev->tx_started == 0) { dev->tx_started = 1; da1469x_uart_tx_intr_enable(dev); } OS_EXIT_CRITICAL(sr); } static void da1469x_uart_start_rx(struct uart_dev *udev) { struct da1469x_uart_dev *dev = (struct da1469x_uart_dev *)udev; int ch; os_sr_t sr; OS_ENTER_CRITICAL(sr); if (dev->rx_stalled) { ch = dev->uc.uc_rx_char(dev->uc.uc_cb_arg, dev->rx_data); if (ch >= 0) { dev->rx_stalled = 0; da1469x_uart_rx_intr_enable(dev); } } OS_EXIT_CRITICAL(sr); } static void da1469x_uart_blocking_tx(struct uart_dev *udev, uint8_t byte) { struct da1469x_uart_dev *dev = (struct da1469x_uart_dev *)udev; UART2_Type *uart = dev->hw->regs; if (!dev->active) { return; } while (!(uart->UART2_USR_REG & UART2_UART2_USR_REG_UART_TFNF_Msk)) { /* Wait until FIFO has free space */ } uart->UART2_RBR_THR_DLL_REG = byte; while (!(uart->UART2_USR_REG & UART2_UART2_USR_REG_UART_TFE_Msk) || (uart->UART2_USR_REG & UART2_UART2_USR_REG_UART_BUSY_Msk)) { /* Wait until FIFO is empty and UART finished tx */ } } static int da1469x_uart_init(struct os_dev *odev, void *arg) { struct da1469x_uart_dev *dev = (struct da1469x_uart_dev *)odev; struct da1469x_uart_cfg *cfg = arg; if (cfg->pin_rx >= 0) { os_callout_init(&dev->wakeup_callout, os_eventq_dflt_get(), da1469x_uart_on_wakeup_callout_cb, dev); dev->setup_wakeup_event.ev_cb = da1469x_uart_on_setup_wakeup_cb; dev->setup_wakeup_event.ev_arg = dev; } OS_DEV_SETHANDLERS(odev, da1469x_uart_open, da1469x_uart_close); dev->dev.ud_funcs.uf_start_tx = da1469x_uart_start_tx; dev->dev.ud_funcs.uf_start_rx = da1469x_uart_start_rx; dev->dev.ud_funcs.uf_blocking_tx = da1469x_uart_blocking_tx; dev->da1469x_cfg = *cfg; NVIC_DisableIRQ(dev->hw->irqn); NVIC_SetPriority(dev->hw->irqn, (1 << __NVIC_PRIO_BITS) - 1); NVIC_SetVector(dev->hw->irqn, (uint32_t)dev->hw->isr); return OS_OK; } int da1469x_uart_dev_create(struct da1469x_uart_dev *dev, const char *name, uint8_t priority, const struct da1469x_uart_cfg *da1469x_cfg) { size_t uart_num_idx; int uart_num; if (dev == NULL || name == NULL || da1469x_cfg == NULL) { return OS_EINVAL; } /* Get UART number from device name last character. */ uart_num_idx = strlen(name) - 1; uart_num = name[uart_num_idx] - '0'; if (MYNEWT_VAL(UART_0) && uart_num == 0) { dev->hw = &da1469x_uart0_hw; assert(da1469x_dev0 == NULL); da1469x_dev0 = dev; } else if (MYNEWT_VAL(UART_1) && uart_num == 1) { dev->hw = &da1469x_uart1_hw; assert(da1469x_dev1 == NULL); da1469x_dev1 = dev; } else if (MYNEWT_VAL(UART_2) && uart_num == 2) { dev->hw = &da1469x_uart2_hw; assert(da1469x_dev2 == NULL); da1469x_dev2 = dev; } else { return OS_ENOENT; } return os_dev_create((struct os_dev *)dev, name, OS_DEV_INIT_PRIMARY, priority, da1469x_uart_init, (void *)da1469x_cfg); }
8,652
312
/* Copyright (c) 2014-2015, <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: 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 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. */ #ifndef INDEX_BUFFER_DECOMPRESSION_H__ #define INDEX_BUFFER_DECOMPRESSION_H__ #pragma once #include <stdint.h> #include "readbitstream.h" // Compress an index buffer, writing the results out to a bitstream and providing a vertex remapping (which will be in pre-transform cache optimised // order. // Parameters: // [out] triangles - Triangle list index buffer (3 indices to vertices per triangle), output from the decompression - 16bit indices // [in] triangle count - The number of triangles to decompress. // [in] input - The bit stream that the compressed data will be read from. void DecompressIndexBuffer( uint16_t* triangles, uint32_t triangleCount, ReadBitstream& input ); // Same as above but 32 bit indices. void DecompressIndexBuffer( uint32_t* triangles, uint32_t triangleCount, ReadBitstream& input ); #endif // -- INDEX_BUFFER_DECOMPRESSION_H__
641
310
{ "name": "PowerTower Pro 250", "description": "A PowerPC-based Mac clone.", "url": "http://www.everymac.com/systems/powercc/powertower_pro/powertower_pro250.html" }
63
1,039
#if !defined(SIMDE_TEST_MIPS_TEST_MSA_H) #define SIMDE_TEST_MIPS_TEST_MSA_H #include "../../../simde/mips/msa.h" #include "../../test.h" #if !defined(SIMDE_TEST_BARE) #define SIMDE_TEST_DECLARE_SUITE(name) SIMDE_TEST_SUITE_DECLARE_GETTERS(HEDLEY_CONCAT(simde_test_mips_msa_simd_get_suite_,name)) #include <test/mips/msa/declare-suites.h> #undef SIMDE_TEST_DECLARE_SUITE #endif #define SIMDE_TEST_MIPS_MSA_GENERATE_INT_FUNCS_(Element_Width, Element_Count, Variant_Name) \ static int \ simde_test_msa_v##Element_Count##i##Element_Width##_assert_equal_( \ simde_v##Element_Count##i##Element_Width a, simde_v##Element_Count##i##Element_Width b, \ const char* filename, int line, const char* astr, const char* bstr) { \ int##Element_Width##_t a_[sizeof(a) / sizeof(int##Element_Width##_t)]; \ int##Element_Width##_t b_[sizeof(a) / sizeof(int##Element_Width##_t)]; \ simde_memcpy(a_, &a, sizeof(a)); \ simde_memcpy(b_, &b, sizeof(b)); \ return simde_assert_equal_vi##Element_Width##_(sizeof(a_) / sizeof(a_[0]), a_, b_, filename, line, astr, bstr); \ } \ \ static int \ simde_test_msa_v##Element_Count##u##Element_Width##_assert_equal_( \ simde_v##Element_Count##u##Element_Width a, simde_v##Element_Count##u##Element_Width b, \ const char* filename, int line, const char* astr, const char* bstr) { \ uint##Element_Width##_t a_[sizeof(a) / sizeof(uint##Element_Width##_t)]; \ uint##Element_Width##_t b_[sizeof(a) / sizeof(uint##Element_Width##_t)]; \ simde_memcpy(a_, &a, sizeof(a)); \ simde_memcpy(b_, &b, sizeof(b)); \ return simde_assert_equal_vu##Element_Width##_(sizeof(a_) / sizeof(a_[0]), a_, b_, filename, line, astr, bstr); \ } \ \ static void \ simde_test_msa_v##Element_Count##i##Element_Width##_write(int indent, simde_v##Element_Count##i##Element_Width v, SimdeTestVecPos pos) { \ int##Element_Width##_t v_[sizeof(v) / sizeof(int##Element_Width##_t)]; \ simde_memcpy(v_, &v, sizeof(v)); \ simde_test_codegen_write_vi##Element_Width(indent, sizeof(v_) / sizeof(v_[0]), v_, pos); \ } \ \ static void \ simde_test_msa_v##Element_Count##u##Element_Width##_write(int indent, simde_v##Element_Count##u##Element_Width v, SimdeTestVecPos pos) { \ uint##Element_Width##_t v_[sizeof(v) / sizeof(int##Element_Width##_t)]; \ simde_memcpy(v_, &v, sizeof(v)); \ simde_test_codegen_write_vu##Element_Width(indent, sizeof(v_) / sizeof(v_[0]), v_, pos); \ } \ \ static simde_v##Element_Count##i##Element_Width \ simde_test_msa_v##Element_Count##i##Element_Width##_random(void) { \ simde_v##Element_Count##i##Element_Width r; \ simde_test_codegen_random_memory(sizeof(r), HEDLEY_REINTERPRET_CAST(uint8_t*, &r)); \ return r; \ } \ \ static simde_v##Element_Count##u##Element_Width \ simde_test_msa_v##Element_Count##u##Element_Width##_random(void) { \ simde_v##Element_Count##u##Element_Width r; \ simde_test_codegen_random_memory(sizeof(r), HEDLEY_REINTERPRET_CAST(uint8_t*, &r)); \ return r; \ } #define SIMDE_TEST_MIPS_MSA_GENERATE_FLOAT_FUNCS_(Element_Width, Element_Count, Variant_Name) \ static int \ simde_test_msa_v##Element_Count##f##Element_Width##_assert_equal_( \ simde_v##Element_Count##f##Element_Width a, simde_v##Element_Count##f##Element_Width b, simde_float##Element_Width slop, \ const char* filename, int line, const char* astr, const char* bstr) { \ simde_float##Element_Width a_[sizeof(a) / sizeof(simde_float##Element_Width)]; \ simde_float##Element_Width b_[sizeof(a) / sizeof(simde_float##Element_Width)]; \ simde_memcpy(a_, &a, sizeof(a)); \ simde_memcpy(b_, &b, sizeof(b)); \ return simde_assert_equal_vf##Element_Width##_(sizeof(a_) / sizeof(a_[0]), a_, b_, slop, filename, line, astr, bstr); \ } \ \ static void \ simde_test_msa_v##Element_Count##f##Element_Width##_write(int indent, simde_v##Element_Count##f##Element_Width v, SimdeTestVecPos pos) { \ simde_float##Element_Width v_[sizeof(v) / sizeof(simde_float##Element_Width)]; \ simde_memcpy(v_, &v, sizeof(v)); \ simde_test_codegen_write_vf##Element_Width(indent, sizeof(v_) / sizeof(v_[0]), v_, pos); \ } \ \ static simde_v##Element_Count##f##Element_Width \ simde_test_msa_v##Element_Count##f##Element_Width##_random(simde_float##Element_Width min, simde_float##Element_Width max) { \ simde_float##Element_Width r_[sizeof(simde_v##Element_Count##f##Element_Width) / sizeof(simde_float##Element_Width)]; \ simde_v##Element_Count##f##Element_Width r; \ simde_test_codegen_random_vf##Element_Width(sizeof(simde_v##Element_Count##f##Element_Width) / sizeof(simde_float##Element_Width), r_, min, max); \ simde_memcpy(&r, r_, sizeof(r)); \ return r; \ } \ \ static void \ simde_test_msa_v##Element_Count##f##Element_Width##_random_full( \ size_t test_sets, size_t vectors_per_set, \ simde_float##Element_Width v[HEDLEY_ARRAY_PARAM(test_sets * vectors_per_set * (sizeof(simde_v##Element_Count##f##Element_Width) / sizeof(simde_float##Element_Width)))], \ simde_float##Element_Width min, simde_float##Element_Width max, \ SimdeTestVecFloatType vec_type) { \ simde_test_codegen_random_vf##Element_Width##_full(test_sets, vectors_per_set, (sizeof(simde_v##Element_Count##f##Element_Width) / sizeof(simde_float##Element_Width)), v, min, max, vec_type); \ } \ \ static simde_v##Element_Count##f##Element_Width \ simde_test_msa_f##Element_Width##x##Element_Count##_random_full_extract( \ size_t vectors_per_set, \ simde_float##Element_Width v[], \ size_t set_n, size_t vec_n) { \ simde_v##Element_Count##f##Element_Width r; \ simde_memcpy(&r, &(v[((vectors_per_set * set_n) + vec_n) * (sizeof(simde_v##Element_Count##f##Element_Width) / sizeof(simde_float##Element_Width))]), sizeof(r)); \ return r; \ } SIMDE_TEST_MIPS_MSA_GENERATE_INT_FUNCS_( 8, 16, b) SIMDE_TEST_MIPS_MSA_GENERATE_INT_FUNCS_(16, 8, h) SIMDE_TEST_MIPS_MSA_GENERATE_INT_FUNCS_(32, 4, w) SIMDE_TEST_MIPS_MSA_GENERATE_INT_FUNCS_(64, 2, d) SIMDE_TEST_MIPS_MSA_GENERATE_FLOAT_FUNCS_(32, 4, w) SIMDE_TEST_MIPS_MSA_GENERATE_FLOAT_FUNCS_(64, 2, d) #define simde_test_msa_v16i8_assert_equal(a, b) do { if (simde_test_msa_v16i8_assert_equal_(a, b, __FILE__, __LINE__, #a, #b)) return 1; } while (0) #define simde_test_msa_v8i16_assert_equal(a, b) do { if (simde_test_msa_v8i16_assert_equal_(a, b, __FILE__, __LINE__, #a, #b)) return 1; } while (0) #define simde_test_msa_v4i32_assert_equal(a, b) do { if (simde_test_msa_v4i32_assert_equal_(a, b, __FILE__, __LINE__, #a, #b)) return 1; } while (0) #define simde_test_msa_v2i64_assert_equal(a, b) do { if (simde_test_msa_v2i64_assert_equal_(a, b, __FILE__, __LINE__, #a, #b)) return 1; } while (0) #define simde_test_msa_v16u8_assert_equal(a, b) do { if (simde_test_msa_v16u8_assert_equal_(a, b, __FILE__, __LINE__, #a, #b)) return 1; } while (0) #define simde_test_msa_v8u16_assert_equal(a, b) do { if (simde_test_msa_v8u16_assert_equal_(a, b, __FILE__, __LINE__, #a, #b)) return 1; } while (0) #define simde_test_msa_v4u32_assert_equal(a, b) do { if (simde_test_msa_v4u32_assert_equal_(a, b, __FILE__, __LINE__, #a, #b)) return 1; } while (0) #define simde_test_msa_v2u64_assert_equal(a, b) do { if (simde_test_msa_v2u64_assert_equal_(a, b, __FILE__, __LINE__, #a, #b)) return 1; } while (0) #define simde_test_msa_v4f32_assert_equal(a, b, precision) do { if (simde_test_msa_v4f32_assert_equal_(a, b, simde_test_f32_precision_to_slop(precision), __FILE__, __LINE__, #a, #b)) return 1; } while (0) #define simde_test_msa_v2f64_assert_equal(a, b, precision) do { if (simde_test_msa_v2f64_assert_equal_(a, b, simde_test_f64_precision_to_slop(precision), __FILE__, __LINE__, #a, #b)) return 1; } while (0) #endif /* !defined(SIMDE_TEST_MIPS_TEST_MSA_H) */
3,479
1,350
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.compute.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.compute.fluent.models.GalleryProperties; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Map; /** Specifies information about the Shared Image Gallery that you want to update. */ @Fluent public final class GalleryUpdate extends UpdateResourceDefinition { @JsonIgnore private final ClientLogger logger = new ClientLogger(GalleryUpdate.class); /* * Describes the properties of a Shared Image Gallery. */ @JsonProperty(value = "properties") private GalleryProperties innerProperties; /** * Get the innerProperties property: Describes the properties of a Shared Image Gallery. * * @return the innerProperties value. */ private GalleryProperties innerProperties() { return this.innerProperties; } /** {@inheritDoc} */ @Override public GalleryUpdate withTags(Map<String, String> tags) { super.withTags(tags); return this; } /** * Get the description property: The description of this Shared Image Gallery resource. This property is updatable. * * @return the description value. */ public String description() { return this.innerProperties() == null ? null : this.innerProperties().description(); } /** * Set the description property: The description of this Shared Image Gallery resource. This property is updatable. * * @param description the description value to set. * @return the GalleryUpdate object itself. */ public GalleryUpdate withDescription(String description) { if (this.innerProperties() == null) { this.innerProperties = new GalleryProperties(); } this.innerProperties().withDescription(description); return this; } /** * Get the identifier property: Describes the gallery unique name. * * @return the identifier value. */ public GalleryIdentifier identifier() { return this.innerProperties() == null ? null : this.innerProperties().identifier(); } /** * Set the identifier property: Describes the gallery unique name. * * @param identifier the identifier value to set. * @return the GalleryUpdate object itself. */ public GalleryUpdate withIdentifier(GalleryIdentifier identifier) { if (this.innerProperties() == null) { this.innerProperties = new GalleryProperties(); } this.innerProperties().withIdentifier(identifier); return this; } /** * Get the provisioningState property: The current state of the gallery. The provisioning state, which only appears * in the response. * * @return the provisioningState value. */ public GalleryPropertiesProvisioningState provisioningState() { return this.innerProperties() == null ? null : this.innerProperties().provisioningState(); } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ @Override public void validate() { super.validate(); if (innerProperties() != null) { innerProperties().validate(); } } }
1,204
844
<reponame>iprinceroyy/Hacktoberfest-2020 { "github-username": "Himanshu_Gour", "favourite-emoji": "😂", "favourite-music": "https://soundcloud.com/dinojames/loser", "favourite-color": "#2e2e2e" }
103
1,273
<filename>src/test/java/org/broadinstitute/hellbender/tools/spark/pipelines/metrics/MeanQualityHistogramGeneratorUnitTest.java package org.broadinstitute.hellbender.tools.spark.pipelines.metrics; import htsjdk.samtools.SAMTag; import htsjdk.samtools.SAMUtils; import org.broadinstitute.hellbender.utils.read.ArtificialReadUtils; import org.broadinstitute.hellbender.utils.read.GATKRead; import org.broadinstitute.hellbender.GATKBaseTest; import org.testng.Assert; import org.testng.annotations.Test; public final class MeanQualityHistogramGeneratorUnitTest extends GATKBaseTest { @Test public void testUsingQualities() throws Exception { final MeanQualityByCycleSpark.HistogramGenerator hg = new MeanQualityByCycleSpark.HistogramGenerator(false); Assert.assertEquals(hg.useOriginalQualities, false); GATKRead read1 = ArtificialReadUtils.createArtificialRead("aa".getBytes(), new byte[]{50, 50}, "2M"); hg.addRead(read1); Assert.assertEquals(hg.firstReadCountsByCycle, new long[]{0, 1, 1}); assertEqualsDoubleArray(hg.firstReadTotalsByCycle, new double[]{0, 50, 50}, 1e-05); Assert.assertEquals(hg.secondReadCountsByCycle, new long[]{0, 0, 0}); assertEqualsDoubleArray(hg.secondReadTotalsByCycle, new double[]{0, 0, 0}, 1e-05); GATKRead read2 = ArtificialReadUtils.createArtificialRead("aaa".getBytes(), new byte[]{11, 12, 13}, "3M"); hg.addRead(read2); Assert.assertEquals(hg.firstReadCountsByCycle, new long[]{0, 2, 2, 1}); assertEqualsDoubleArray(hg.firstReadTotalsByCycle, new double[]{0, 61, 62, 13}, 1e-05); Assert.assertEquals(hg.secondReadCountsByCycle, new long[]{0, 0, 0, 0}); assertEqualsDoubleArray(hg.secondReadTotalsByCycle, new double[]{0, 0, 0, 0}, 1e-05); GATKRead read3 = ArtificialReadUtils.createArtificialRead("aa".getBytes(), new byte[]{50, 60}, "2M"); read3.setIsReverseStrand(true); hg.addRead(read3); Assert.assertEquals(hg.firstReadCountsByCycle, new long[]{0, 3, 3, 1}); assertEqualsDoubleArray(hg.firstReadTotalsByCycle, new double[]{0, 121, 112, 13}, 1e-05); Assert.assertEquals(hg.secondReadCountsByCycle, new long[]{0, 0, 0, 0}); assertEqualsDoubleArray(hg.secondReadTotalsByCycle, new double[]{0, 0, 0, 0}, 1e-05); GATKRead read4 = ArtificialReadUtils.createArtificialRead("aaa".getBytes(), new byte[]{11, 13, 15}, "3M"); read4.setIsReverseStrand(true); hg.addRead(read4); Assert.assertEquals(hg.firstReadCountsByCycle, new long[]{0, 4, 4, 2}); assertEqualsDoubleArray(hg.firstReadTotalsByCycle, new double[]{0, 121 + 15, 112 + 13, 13 + 11}, 1e-05); Assert.assertEquals(hg.secondReadCountsByCycle, new long[]{0, 0, 0, 0}); assertEqualsDoubleArray(hg.secondReadTotalsByCycle, new double[]{0, 0, 0, 0}, 1e-05); GATKRead read5 = ArtificialReadUtils.createArtificialRead("aaa".getBytes(), new byte[]{11, 12, 13}, "3M"); read5.setIsSecondOfPair(); hg.addRead(read5); Assert.assertEquals(hg.firstReadCountsByCycle, new long[]{0, 4, 4, 2}); assertEqualsDoubleArray(hg.firstReadTotalsByCycle, new double[]{0, 121 + 15, 112 + 13, 13 + 11}, 1e-05); Assert.assertEquals(hg.secondReadCountsByCycle, new long[]{0, 1, 1, 1}); assertEqualsDoubleArray(hg.secondReadTotalsByCycle, new double[]{0, 11, 12, 13}, 1e-05); final MeanQualityByCycleSpark.HistogramGenerator hg2 = new MeanQualityByCycleSpark.HistogramGenerator(false); GATKRead read1b = ArtificialReadUtils.createArtificialRead("aaaaa".getBytes(), new byte[]{51, 52, 53, 54, 55}, "5M"); hg2.addRead(read1b); final MeanQualityByCycleSpark.HistogramGenerator hg2Plus1 = hg2.merge(hg); //add short to long Assert.assertTrue(hg2 == hg2Plus1); Assert.assertEquals(hg2Plus1.firstReadCountsByCycle, new long[]{0, 5, 5, 3, 1, 1}); assertEqualsDoubleArray(hg2Plus1.firstReadTotalsByCycle, new double[]{0, 121 + 15 + 51, 112 + 13 + 52, 13 + 11 + 53, 54, 55}, 1e-05); Assert.assertEquals(hg2Plus1.secondReadCountsByCycle, new long[]{0, 1, 1, 1, 0, 0}); assertEqualsDoubleArray(hg2Plus1.secondReadTotalsByCycle, new double[]{0, 11, 12, 13, 0, 0}, 1e-05); final MeanQualityByCycleSpark.HistogramGenerator hg2_copy = new MeanQualityByCycleSpark.HistogramGenerator(false); hg2_copy.addRead(read1b); final MeanQualityByCycleSpark.HistogramGenerator hg1Plus2 = hg.merge(hg2_copy); //add long to short Assert.assertTrue(hg == hg1Plus2); Assert.assertEquals(hg1Plus2.firstReadCountsByCycle, new long[]{0, 5, 5, 3, 1, 1}); assertEqualsDoubleArray(hg1Plus2.firstReadTotalsByCycle, new double[]{0, 121 + 15 + 51, 112 + 13 + 52, 13 + 11 + 53, 54, 55}, 1e-05); Assert.assertEquals(hg1Plus2.secondReadCountsByCycle, new long[]{0, 1, 1, 1, 0, 0}); assertEqualsDoubleArray(hg1Plus2.secondReadTotalsByCycle, new double[]{0, 11, 12, 13, 0, 0}, 1e-05); } @Test public void testUsingOriginalQualities() throws Exception { final MeanQualityByCycleSpark.HistogramGenerator hg = new MeanQualityByCycleSpark.HistogramGenerator(true); Assert.assertEquals(hg.useOriginalQualities, true); GATKRead read1 = ArtificialReadUtils.createArtificialRead("aa".getBytes(), new byte[]{50, 50}, "2M"); hg.addRead(read1); Assert.assertEquals(hg.firstReadCountsByCycle, new long[0]); assertEqualsDoubleArray(hg.firstReadTotalsByCycle, new double[0], 1e-05); Assert.assertEquals(hg.secondReadCountsByCycle, new long[0]); assertEqualsDoubleArray(hg.secondReadTotalsByCycle, new double[0], 1e-05); GATKRead read2 = ArtificialReadUtils.createArtificialRead("aa".getBytes(), new byte[]{50, 50}, "2M"); read2.setAttribute(SAMTag.OQ.name(), SAMUtils.phredToFastq(new byte[]{30, 40})); hg.addRead(read2); Assert.assertEquals(hg.firstReadCountsByCycle, new long[]{0, 1, 1}); assertEqualsDoubleArray(hg.firstReadTotalsByCycle, new double[]{0, 30, 40}, 1e-05); Assert.assertEquals(hg.secondReadCountsByCycle, new long[]{0, 0, 0}); assertEqualsDoubleArray(hg.secondReadTotalsByCycle, new double[]{0, 0, 0}, 1e-05); } @Test(expectedExceptions = IllegalArgumentException.class) public void testInvalidMerge() throws Exception { final MeanQualityByCycleSpark.HistogramGenerator oq = new MeanQualityByCycleSpark.HistogramGenerator(true); final MeanQualityByCycleSpark.HistogramGenerator q = new MeanQualityByCycleSpark.HistogramGenerator(false); oq.merge(q); } @Test(expectedExceptions = IllegalArgumentException.class) public void testInvalidMergeNull() throws Exception { final MeanQualityByCycleSpark.HistogramGenerator oq = new MeanQualityByCycleSpark.HistogramGenerator(true); oq.merge(null); } }
2,936
1,909
package org.knowm.xchange.idex.service; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import org.knowm.xchange.idex.annotations.Api; import org.knowm.xchange.idex.annotations.ApiOperation; import org.knowm.xchange.idex.annotations.ApiResponse; import org.knowm.xchange.idex.annotations.ApiResponses; import org.knowm.xchange.idex.dto.OrderBookReq; import org.knowm.xchange.idex.dto.ReturnOrderBookResponse; @Path("/returnOrderBook") @Api(description = "the returnOrderBook API") @Consumes("application/json") @Produces("application/json") public interface ReturnOrderBookApi { @POST @Consumes("application/json") @Produces("application/json") @ApiOperation( value = "Returns the orderbook for a given market, or returns an object of the entire orderbook keyed by\\ market if the market parameter is omitted.", notes = "", tags = "market") @ApiResponses(@ApiResponse(code = 200, message = "", response = ReturnOrderBookResponse.class)) ReturnOrderBookResponse orderBook(OrderBookReq orderBookReq); }
392
878
<reponame>fansaien/parallec<gh_stars>100-1000 package io.parallec.core.main.ssh; import io.parallec.core.ParallecResponseHandler; import io.parallec.core.ParallelClient; import io.parallec.core.ResponseOnSingleTask; import io.parallec.core.TestBase; import java.util.HashMap; import java.util.Map; import org.apache.http.util.Asserts; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; public class ParallelClientSshTest extends TestBase { private static ParallelClient pc; @BeforeClass public static void setUp() throws Exception { pc = new ParallelClient(); } @AfterClass public static void shutdown() throws Exception { pc.releaseExternalResources(); } @Test public void sshWorkerFakeVmPasswordTest() { Map<String, Object> responseContext = new HashMap<String, Object>(); pc.prepareSsh().setConcurrency(500) .setTargetHostsFromString(hostIpSample) .setSshCommandLine("df -h; ds; ").setSshUserName(userName) .setSshPassword(<PASSWORD>).setSshConnectionTimeoutMillis(5000) .setResponseContext(responseContext) .execute(new ParallecResponseHandler() { @Override public void onCompleted(ResponseOnSingleTask res, Map<String, Object> responseContext) { logger.info("Responose:" + res.toString() + " host: " + res.getHost() + " errmsg: " + res.getErrorMessage()); responseContext.put("errorMessage", res.getErrorMessage()); } }); String errMessage = (String) responseContext.get("errorMessage"); Asserts.check(errMessage.contains("socket is not established"), "fail. error is not expected. not sure if ssh flow was executed"); }// end func @Test public void sshWorkerFakeVmPasswordInvalidPollerTest() { Map<String, Object> responseContext = new HashMap<String, Object>(); pc.prepareSsh().setConcurrency(300) .setTargetHostsFromString(hostIpSample) .setSshCommandLine("df -h; ds; ").setSshUserName(userName) .setHttpPollable(true).setSshPassword(<PASSWORD>) .setResponseContext(responseContext) .execute(new ParallecResponseHandler() { @Override public void onCompleted(ResponseOnSingleTask res, Map<String, Object> responseContext) { logger.info("Responose:" + res.toString() + " host: " + res.getHost() + " errmsg: " + res.getErrorMessage()); } }); }// end func // @Test @Ignore public void sshWorkerRealVmPasswordTest() { pc.prepareSsh().setConcurrency(300) .setTargetHostsFromString(SshProviderRealTest.vmIp) .setSshCommandLine("df -h; ds; ").setSshUserName("parallec") .setSshPassword("<PASSWORD>") .execute(new ParallecResponseHandler() { @Override public void onCompleted(ResponseOnSingleTask res, Map<String, Object> responseContext) { logger.info("Responose:" + res.toString() + " host: " + res.getHost() + " errmsg: " + res.getErrorMessage()); } }); } }
1,836
5,169
<filename>Specs/b/9/2/SimpleRefresh/0.0.7/SimpleRefresh.podspec.json { "name": "SimpleRefresh", "version": "0.0.7", "summary": "So simple pull to refresh framework in iOS written by Swift5", "description": "A simple pull to refresh lib with highly customizable animation.", "homepage": "https://github.com/qiuncheng/SimpleRefresh", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "qiuncheng": "<EMAIL>" }, "source": { "git": "https://github.com/qiuncheng/SimpleRefresh.git", "tag": "0.0.7" }, "social_media_url": "https://twitter.com/vsccw", "platforms": { "ios": "8.0" }, "swift_version": "5.0", "source_files": "SimpleRefresh/Classes/**/*", "resources": [ "SimpleRefresh/Assets/*.xcassets" ] }
314
1,483
/* * Copyright Lealone Database Group. * Licensed under the Server Side Public License, v 1. * Initial Developer: zhh */ package org.lealone.test.db.auth; import org.junit.Test; import org.lealone.db.Constants; import org.lealone.db.api.ErrorCode; import org.lealone.db.auth.Role; import org.lealone.db.result.SearchRow; import org.lealone.test.db.DbObjectTestBase; public class RoleTest extends DbObjectTestBase { private void asserts(String roleName) { Role role = findRole(roleName); int id = role.getId(); assertTrue(id > 0); assertEquals(roleName, role.getName()); assertTrue(!role.isTemporary()); SearchRow row = findMeta(id); assertNotNull(row); assertEquals(id, row.getValue(0).getInt()); } @Test public void run() { create(); drop(); } void create() { executeUpdate("CREATE ROLE IF NOT EXISTS r1"); asserts("r1"); // 虽然r1存在了,但是使用了IF NOT EXISTS executeUpdate("CREATE ROLE IF NOT EXISTS r1"); asserts("r1"); try { // 没有使用IF NOT EXISTS时就抛错 executeUpdate("CREATE ROLE r1"); fail(); } catch (Exception e) { assertException(e, ErrorCode.ROLE_ALREADY_EXISTS_1); } executeUpdate("CREATE USER IF NOT EXISTS RoleTest_u1 PASSWORD 'abc'"); try { // 角色名不能和前面的用户名一样 executeUpdate("CREATE ROLE IF NOT EXISTS RoleTest_u1"); fail(); } catch (Exception e) { assertException(e, ErrorCode.USER_ALREADY_EXISTS_1); } finally { executeUpdate("DROP USER IF EXISTS RoleTest_u1"); } } void drop() { Role role = findRole("r1"); int id = role.getId(); assertNotNull(role); executeUpdate("DROP ROLE r1"); role = findRole("r1"); assertNull(role); SearchRow row = findMeta(id); assertNull(row); try { executeUpdate("DROP ROLE r1"); fail(); } catch (Exception e) { assertException(e, ErrorCode.ROLE_NOT_FOUND_1); } try { executeUpdate("DROP ROLE " + Constants.PUBLIC_ROLE_NAME); fail(); } catch (Exception e) { assertException(e, ErrorCode.ROLE_CAN_NOT_BE_DROPPED_1); } } }
1,176
875
/* * src/element.c Elements * * Copyright (c) 2001-2013 <NAME> <<EMAIL>> * Copyright (c) 2013 Red Hat, Inc. * * 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 <bmon/bmon.h> #include <bmon/conf.h> #include <bmon/element.h> #include <bmon/element_cfg.h> #include <bmon/group.h> #include <bmon/input.h> #include <bmon/utils.h> static LIST_HEAD(allowed); static LIST_HEAD(denied); static int match_mask(const struct policy *p, const char *str) { int i, n; char c; if (!p || !str) return 0; for (i = 0, n = 0; p->p_rule[i] != '\0'; i++) { if (p->p_rule[i] == '*') { c = tolower(p->p_rule[i + 1]); if (c == '\0') return 1; while (tolower(str[n]) != c) if (str[n++] == '\0') return 0; } else if (tolower(p->p_rule[i]) != tolower(str[n++])) return 0; } return str[n] == '\0' ? 1 : 0; } int element_allowed(const char *name, struct element_cfg *cfg) { struct policy *p; if (cfg) { if (cfg->ec_flags & ELEMENT_CFG_HIDE) return 0; else if (cfg->ec_flags & ELEMENT_CFG_SHOW) return 1; } list_for_each_entry(p, &denied, p_list) if (match_mask(p, name)) return 0; if (!list_empty(&allowed)) { list_for_each_entry(p, &allowed, p_list) if (match_mask(p, name)) return 1; return 0; } return 1; } void element_parse_policy(const char *policy) { char *start, *copy, *save = NULL, *tok; struct policy *p; if (!policy) return; copy = strdup(policy); start = copy; while ((tok = strtok_r(start, ",", &save)) != NULL) { start = NULL; p = xcalloc(1, sizeof(*p)); if (*tok == '!') { p->p_rule = strdup(++tok); list_add_tail(&p->p_list, &denied); } else { p->p_rule = strdup(tok); list_add_tail(&p->p_list, &allowed); } } xfree(copy); } static struct element *__lookup_element(struct element_group *group, const char *name, uint32_t id, struct element *parent) { struct list_head *list; struct element *e; if (parent) list = &parent->e_childs; else list = &group->g_elements; list_for_each_entry(e, list, e_list) if (!strcmp(name, e->e_name) && e->e_id == id) return e; return NULL; } struct element *element_lookup(struct element_group *group, const char *name, uint32_t id, struct element *parent, int flags) { struct element_cfg *cfg; struct element *e; int i; if (!group) BUG(); if ((e = __lookup_element(group, name, id, parent))) return e; if (!(flags & ELEMENT_CREAT)) return NULL; cfg = element_cfg_lookup(name); if (!element_allowed(name, cfg)) return NULL; DBG("Creating element %d \"%s\"", id, name); e = xcalloc(1, sizeof(*e)); init_list_head(&e->e_list); init_list_head(&e->e_childs); init_list_head(&e->e_info_list); init_list_head(&e->e_attr_sorted); for (i = 0; i < ATTR_HASH_SIZE; i++) init_list_head(&e->e_attrhash[i]); e->e_name = strdup(name); e->e_id = id; e->e_parent = parent; e->e_group = group; e->e_lifecycles = get_lifecycles(); e->e_flags = ELEMENT_FLAG_CREATED; e->e_cfg = cfg; if (e->e_cfg) { if (e->e_cfg->ec_description) element_update_info(e, "Description", e->e_cfg->ec_description); element_set_rxmax(e, e->e_cfg->ec_rxmax); element_set_txmax(e, e->e_cfg->ec_txmax); } if (parent) { DBG("Attached to parent %d \"%s\"", parent->e_id, parent->e_name); list_add_tail(&e->e_list, &parent->e_childs); } else { DBG("Attached to group %s", group->g_name); list_add_tail(&e->e_list, &group->g_elements); } group->g_nelements++; return e; } void element_free(struct element *e) { struct info *info, *ninfo; struct element *c, *cnext; struct attr *a, *an; int i; list_for_each_entry_safe(c, cnext, &e->e_childs, e_list) element_free(c); list_for_each_entry_safe(info, ninfo, &e->e_info_list, i_list) { xfree(info->i_name); xfree(info->i_value); list_del(&info->i_list); xfree(info); } for (i = 0; i < ATTR_HASH_SIZE; i++) list_for_each_entry_safe(a, an, &e->e_attrhash[i], a_list) attr_free(a); if (e->e_group->g_current == e) { element_select_prev(); if (e->e_group->g_current == e) e->e_group->g_current = NULL; } list_del(&e->e_list); e->e_group->g_nelements--; xfree(e->e_name); xfree(e); } #if 0 if (item->i_group->g_selected == item) { if (item_select_prev() == END_OF_LIST) { if (group_select_prev() == END_OF_LIST) { if (node_select_prev() != END_OF_LIST) item_select_last(); } else item_select_last(); } } #endif #if 0 void item_delete(struct item *item) { int m; struct item *child; for (m = 0; m < ATTR_HASH_MAX; m++) { struct attr *a, *next; for (a = item->i_attrs[m]; a; a = next) { next = a->a_next; xfree(a); } } if (item->i_group->g_selected == item) { if (item_select_prev() == END_OF_LIST) { if (group_select_prev() == END_OF_LIST) { if (node_select_prev() != END_OF_LIST) item_select_last(); } else item_select_last(); } } unlink_item(item); item->i_group->g_nitems--; for (child = item->i_childs; child; child = child->i_next) item_delete(child); if (item->i_path) xfree(item->i_path); xfree(item); } #endif void element_reset_update_flag(struct element_group *g, struct element *e, void *arg) { DBG("Reseting update flag of %s", e->e_name); e->e_flags &= ~ELEMENT_FLAG_UPDATED; } /** * Needs to be called after updating all attributes of an element */ void element_notify_update(struct element *e, timestamp_t *ts) { struct attr *a; int i; e->e_flags |= ELEMENT_FLAG_UPDATED; if (ts == NULL) ts = &rtiming.rt_last_read; for (i = 0; i < ATTR_HASH_SIZE; i++) list_for_each_entry(a, &e->e_attrhash[i], a_list) attr_notify_update(a, ts); if (e->e_usage_attr && e->e_cfg && (a = attr_lookup(e, e->e_usage_attr->ad_id))) { attr_calc_usage(a, &e->e_rx_usage, &e->e_tx_usage, e->e_cfg->ec_rxmax, e->e_cfg->ec_txmax); } else { e->e_rx_usage = FLT_MAX; e->e_tx_usage = FLT_MAX; } } void element_lifesign(struct element *e, int n) { e->e_lifecycles = n * get_lifecycles(); } void element_check_if_dead(struct element_group *g, struct element *e, void *arg) { if (--(e->e_lifecycles) <= 0) { element_free(e); DBG("Deleting dead element %s", e->e_name); } } void element_foreach_attr(struct element *e, void (*cb)(struct element *e, struct attr *, void *), void *arg) { struct attr *a; list_for_each_entry(a, &e->e_attr_sorted, a_sort_list) cb(e, a, arg); } int element_set_key_attr(struct element *e, const char *major, const char * minor) { if (!(e->e_key_attr[GT_MAJOR] = attr_def_lookup(major))) return -ENOENT; if (!(e->e_key_attr[GT_MINOR] = attr_def_lookup(minor))) return -ENOENT; return 0; } int element_set_usage_attr(struct element *e, const char *usage) { if (!(e->e_usage_attr = attr_def_lookup(usage))) return -ENOENT; return 0; } void element_pick_from_policy(struct element_group *g) { if (!list_empty(&allowed)) { struct policy *p; list_for_each_entry(p, &allowed, p_list) { struct element *e; list_for_each_entry(e, &g->g_elements, e_list) { if (match_mask(p, e->e_name)) { g->g_current = e; return; } } } } element_select_first(); } struct element *element_current(void) { struct element_group *g; if (!(g = group_current())) return NULL; /* * If no element is picked yet, pick a default interface according to * the selection policy. */ if (!g->g_current) element_pick_from_policy(g); return g->g_current; } struct element *element_select_first(void) { struct element_group *g; if (!(g = group_current())) return NULL; if (list_empty(&g->g_elements)) g->g_current = NULL; else g->g_current = list_first_entry(&g->g_elements, struct element, e_list); return g->g_current; } struct element *element_select_last(void) { struct element_group *g; if (!(g = group_current())) return NULL; if (list_empty(&g->g_elements)) g->g_current = NULL; else { struct element *e; e = list_entry(g->g_elements.prev, struct element, e_list); while (!list_empty(&e->e_childs)) e = list_entry(e->e_childs.prev, struct element, e_list); g->g_current = e; } return g->g_current; } struct element *element_select_next(void) { struct element_group *g; struct element *e; if (!(g = group_current())) return NULL; if (!(e = g->g_current)) return element_select_first(); if (!list_empty(&e->e_childs)) e = list_first_entry(&e->e_childs, struct element, e_list); else { /* * move upwards until we have no parent or there is a next * entry in the list */ while (e->e_parent && e->e_list.next == &e->e_parent->e_childs) e = e->e_parent; if (!e->e_parent && e->e_list.next == &g->g_elements) { group_select_next(); return element_select_first(); } else e = list_entry(e->e_list.next, struct element, e_list); } g->g_current = e; return e; } struct element *element_select_prev(void) { struct element_group *g; struct element *e; if (!(g = group_current())) return NULL; if (!(e = g->g_current)) return element_select_last(); if (!e->e_parent && e->e_list.prev == &g->g_elements) { group_select_prev(); return element_select_last(); } if (e->e_parent && e->e_list.prev == &e->e_parent->e_childs) e = e->e_parent; else { e = list_entry(e->e_list.prev, struct element, e_list); while (!list_empty(&e->e_childs)) e = list_entry(e->e_childs.prev, struct element, e_list); } g->g_current = e; return e; } static struct info *element_info_lookup(struct element *e, const char *name) { struct info *i; list_for_each_entry(i, &e->e_info_list, i_list) if (!strcmp(i->i_name, name)) return i; return NULL; } void element_update_info(struct element *e, const char *name, const char *value) { struct info *i; if ((i = element_info_lookup(e, name))) { xfree(i->i_value); i->i_value = strdup(value); return; } DBG("Created element info %s (\"%s\")", name, value); i = xcalloc(1, sizeof(*i)); i->i_name = strdup(name); i->i_value = strdup(value); e->e_ninfo++; list_add_tail(&i->i_list, &e->e_info_list); } void element_set_txmax(struct element *e, uint64_t max) { char buf[32]; if (!e->e_cfg) e->e_cfg = element_cfg_create(e->e_name); if (e->e_cfg->ec_txmax != max) e->e_cfg->ec_txmax = max; unit_bit2str(e->e_cfg->ec_txmax * 8, buf, sizeof(buf)); element_update_info(e, "TxMax", buf); } void element_set_rxmax(struct element *e, uint64_t max) { char buf[32]; if (!e->e_cfg) e->e_cfg = element_cfg_create(e->e_name); if (e->e_cfg->ec_rxmax != max) e->e_cfg->ec_rxmax = max; unit_bit2str(e->e_cfg->ec_rxmax * 8, buf, sizeof(buf)); element_update_info(e, "RxMax", buf); }
5,108
407
package com.alibaba.sreworks.job.master.jobtrigger; import lombok.Data; @Data public abstract class AbstractJobTriggerConf { }
43
623
<filename>tools/reviewer/aa/commands/PatchCommand.java /* * Copyright 2018 The StartupOS 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 * * https://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.google.startupos.tools.reviewer.aa.commands; import com.google.startupos.common.FileUtils; import com.google.startupos.common.flags.Flag; import com.google.startupos.common.flags.FlagDesc; import com.google.startupos.common.flags.Flags; import com.google.startupos.common.repo.GitRepo; import com.google.startupos.common.repo.GitRepoFactory; import java.io.IOException; import javax.inject.Inject; import javax.inject.Named; public class PatchCommand implements AaCommand { private FileUtils fileUtils; private GitRepoFactory gitRepoFactory; private String workspacePath; @FlagDesc(name = "diff_number", description = "Diff number to apply patch from", required = true) public static Flag<Integer> diffNumber = Flag.create(-1); @Inject public PatchCommand( FileUtils utils, GitRepoFactory repoFactory, @Named("Workspace path") String workspacePath) { this.fileUtils = utils; this.gitRepoFactory = repoFactory; this.workspacePath = workspacePath; } @Override public boolean run(String[] args) { for (int i = 0; i < args.length; i++) { if (args[i].equals("-d")) { args[i] = "--diff_number"; } } Flags.parseCurrentPackage(args); String branchName = String.format("D%d", diffNumber.get()); try { fileUtils .listContents(workspacePath) .stream() .map(path -> fileUtils.joinToAbsolutePath(workspacePath, path)) .filter(path -> fileUtils.folderExists(path)) .forEach( path -> { GitRepo repo = this.gitRepoFactory.create(path); String currentBranchName = repo.currentBranch(); if (!currentBranchName.startsWith("D")) { System.err.println( String.format( "Currently (%s) not on a diff branch, unable to apply changes from %s", ANSI_YELLOW + ANSI_BOLD + currentBranchName + ANSI_RESET, branchName)); } else { repo.merge(branchName, true); } }); } catch (IOException e) { e.printStackTrace(); } return false; } }
1,114
430
# 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. import time import traceback from typing import Any, List import requests from lib.error_logger import ErrorLogger from lib.io import pbar _LIMIT = 500_000 _MAX_RETRIES = 4 _INIT_WAIT_TIME = 8 _WD_TIMEOUT = 60 * 5 _WD_URL = "http://query.wikidata.org/bigdata/namespace/wdq/sparql" _WD_QUERY = "SELECT ?pid ?prop WHERE {{ ?pid wdt:{prop} ?prop. }}" _REQUEST_HEADER = {"User-Agent": "covid-19-open-data/0.0 (linux-gnu)"} def wikidata_property( prop: str, entities: List[str], query_template: str = _WD_QUERY, logger: ErrorLogger = ErrorLogger(), offset: int = 0, **tqdm_kwargs, ) -> Any: """ Query a single property from Wikidata, and return all entities which are part of the provided list which contain that property. Arguments: prop: Wikidata property, for example P1082 for population. entities: List of Wikidata identifiers to query the desired property. query: [Optional] SPARQL query used to retrieve `prop`. logger: [Optional] ErrorLogger instance to use for logging. offset: [Optional] Number of items to skip in the result set. Returns: Iterable[Tuple[str, Any]]: Iterable of <Wikidata ID, property value> """ # Time to wait before retry in case of failure wait_time = _INIT_WAIT_TIME # Build the query from template tpl = query_template + " LIMIT {limit} OFFSET {offset}" query = tpl.format(prop=prop, limit=_LIMIT, offset=offset) # Keep trying request until succeeds, or _max_retries is reached for i in range(_MAX_RETRIES): response = None try: start_time = time.monotonic() params = {"query": query, "format": "json"} req_opts = dict(headers=_REQUEST_HEADER, params=params, timeout=_WD_TIMEOUT) response = requests.get(_WD_URL, **req_opts) elapsed_time = time.monotonic() - start_time log_opts = dict(status=response.status_code, url=_WD_URL, time=elapsed_time, **params) logger.log_info(f"Wikidata SPARQL server response", **log_opts) data = response.json() # Return the first binding available (there should be only one) for item in pbar(data["results"]["bindings"], **tqdm_kwargs): pid = item["pid"]["value"].split("/")[-1] if pid in entities: yield pid, item["prop"]["value"] # Unless we got `_LIMIT` results, keep adding offset until we run our of results if len(data["results"]["bindings"]) == _LIMIT: yield from wikidata_property( prop, entities, query_template=query_template, logger=logger, offset=offset + _LIMIT, **tqdm_kwargs, ) # If no exceptions were thrown, we have reached the end logger.log_info(f"Wikidata SPARQL results end reached") return except Exception as exc: # If we have reached the error limit, log and re-raise the error if i + 1 >= _MAX_RETRIES: msg = response.text if response is not None else "Unknown error" logger.log_error(msg, exc=exc, traceback=traceback.format_exc()) raise exc # Use exponential backoff in case of error logger.log_info(f"({i + 1}) Request error. Retry in {wait_time} seconds...", exc=exc) time.sleep(wait_time) wait_time *= 2
1,713
369
<reponame>bitigchi/MuditaOS<gh_stars>100-1000 // Copyright (c) 2017-2021, Mudit<NAME>.o.o. All rights reserved. // For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md #pragma once #include <chrono> #include <service-desktop/DesktopEvent.hpp> namespace sdesktop::developerMode { class ATResponseEvent : public Event { std::string command; std::chrono::milliseconds timeout; public: explicit ATResponseEvent(std::string command, std::chrono::milliseconds timeout); void setResponse(const std::vector<std::string> &response); [[nodiscard]] const auto &getCommand() const noexcept { return command; } [[nodiscard]] auto getTimeout() const noexcept { return timeout; } }; } // namespace sdesktop::developerMode
344
892
{ "schema_version": "1.2.0", "id": "GHSA-gcg2-fp7f-g9vc", "modified": "2022-05-13T01:22:02Z", "published": "2022-05-13T01:22:02Z", "aliases": [ "CVE-2019-2438" ], "details": "Vulnerability in the Oracle Web Cache component of Oracle Fusion Middleware (subcomponent: ESI/Partial Page Caching). The supported version that is affected is 172.16.17.32.0. Difficult to exploit vulnerability allows unauthenticated attacker with network access via HTTP to compromise Oracle Web Cache. Successful attacks require human interaction from a person other than the attacker and while the vulnerability is in Oracle Web Cache, attacks may significantly impact additional products. Successful attacks of this vulnerability can result in unauthorized access to critical data or complete access to all Oracle Web Cache accessible data as well as unauthorized update, insert or delete access to some of Oracle Web Cache accessible data. CVSS 3.0 Base Score 6.9 (Confidentiality and Integrity impacts). CVSS Vector: (CVSS:3.0/AV:N/AC:H/PR:N/UI:R/S:C/C:H/I:L/A:N).", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.0/AV:N/AC:H/PR:N/UI:R/S:C/C:H/I:L/A:N" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2019-2438" }, { "type": "WEB", "url": "http://www.oracle.com/technetwork/security-advisory/cpujan2019-5072801.html" }, { "type": "WEB", "url": "http://www.securityfocus.com/bid/106612" } ], "database_specific": { "cwe_ids": [ ], "severity": "MODERATE", "github_reviewed": false } }
627
1,056
<gh_stars>1000+ /* * 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.openide.loaders; import java.io.File; import java.util.List; import java.util.logging.Level; import org.netbeans.junit.NbTestCase; import org.openide.cookies.InstanceCookie; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.nodes.Node; /** * * @author <NAME> <<EMAIL>> */ public class InstanceCookieViaNodeTest extends NbTestCase { private static final int CNT = 100; private File wd; private FileObject fo; public InstanceCookieViaNodeTest(String name) { super(name); } @Override protected Level logLevel() { return Level.SEVERE; } @Override protected boolean runInEQ() { return true; } @Override protected void setUp() throws Exception { clearWorkDir(); wd = getWorkDir(); for (int i = 0; i < CNT; i++) { File f = new File(wd, "i" + i + ".instance"); f.createNewFile(); } fo = FileUtil.toFileObject(wd); } public void testAllTheNodesHaveInstanceDataObject() throws Exception { InstanceCookie ic; Node nd = DataFolder.findFolder(fo).getNodeDelegate(); for (int round = 0; ; round++) { List<Node> s = nd.getChildren().snapshot(); for (int i = 0; i < s.size(); i++) { final Node n = s.get(i); ic = n.getLookup().lookup(InstanceDataObject.class); if (ic == null) { fail("No InstanceCookie for " + i + "th node in round " + round + ": " + n); } } if (s.size() == CNT) { break; } Thread.sleep(10); } clearWorkDir(); } }
1,073
2,406
<gh_stars>1000+ // Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "default_opset.hpp" #include "ngraph/node.hpp" #include "onnx_import/core/node.hpp" namespace ngraph { namespace onnx_import { namespace op { namespace set_1 { OutputVector experimental_detectron_detection_output(const Node& node) { using DetectionOutput = ngraph::op::v6::ExperimentalDetectronDetectionOutput; auto inputs = node.get_ng_inputs(); auto rois = inputs[0]; auto deltas = inputs[1]; auto scores = inputs[2]; auto im_info = inputs[3]; DetectionOutput::Attributes attrs{}; attrs.score_threshold = node.get_attribute_value<float>("score_threshold", 0.05); attrs.nms_threshold = node.get_attribute_value<float>("nms_threshold", 0.5); attrs.max_delta_log_wh = node.get_attribute_value<float>("max_delta_log_wh", std::log(1000.0f / 16.0f)); attrs.num_classes = node.get_attribute_value<std::int64_t>("num_classes", 81); attrs.post_nms_count = node.get_attribute_value<std::int64_t>("post_nms_count", 2000); attrs.max_detections_per_image = node.get_attribute_value<std::int64_t>("max_detections_per_image", 100); attrs.class_agnostic_box_regression = static_cast<bool>(node.get_attribute_value<std::int64_t>("class_agnostic_box_regression", 0)); attrs.deltas_weights = node.get_attribute_value<std::vector<float>>("deltas_weights", {10.0f, 10.0f, 5.0f, 5.0f}); auto detection_output = std::make_shared<DetectionOutput>(rois, deltas, scores, im_info, attrs); return {detection_output->output(0), detection_output->output(1), detection_output->output(2)}; } } // namespace set_1 } // namespace op } // namespace onnx_import } // namespace ngraph
679
1,473
<filename>profiler-test/src/main/java/com/navercorp/pinpoint/test/util/BiHashMap.java<gh_stars>1000+ package com.navercorp.pinpoint.test.util; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * copy & modify org.redisson.misc.BiHashMap * https://github.com/redisson/redisson/blob/master/redisson/src/main/java/org/redisson/misc/BiHashMap.java * @param <K> * @param <V> */ public class BiHashMap<K, V> { private final Map<K, V> keyValueMap = new HashMap<>(); private final Map<V, K> valueKeyMap = new HashMap<>(); public int size() { return this.keyValueMap.size(); } public boolean isEmpty() { return this.keyValueMap.isEmpty(); } public boolean containsKey(Object key) { return this.keyValueMap.containsKey(key); } public boolean containsValue(Object value) { return this.valueKeyMap.containsKey(value); } public V get(Object key) { return this.keyValueMap.get(key); } public K reverseGet(Object key) { return this.valueKeyMap.get(key); } public V put(K key, V value) { // modify // replace key if (this.keyValueMap.containsKey(key)) { this.valueKeyMap.remove(this.keyValueMap.get(key)); return put0(key, value); } // replace value if (this.valueKeyMap.containsKey(value)) { this.keyValueMap.remove(this.valueKeyMap.get(value)); return put0(key, value); } return put0(key, value); } private V put0(K key, V value) { this.valueKeyMap.put(value, key); return this.keyValueMap.put(key, value); } public V remove(Object key) { V removed = this.keyValueMap.remove(key); if (removed != null) { this.valueKeyMap.remove(removed); } return removed; } public void putAll(Map<? extends K, ? extends V> m) { Iterator var2 = m.entrySet().iterator(); while(var2.hasNext()) { Map.Entry<? extends K, ? extends V> entry = (Map.Entry)var2.next(); this.put(entry.getKey(), entry.getValue()); } } public void clear() { this.keyValueMap.clear(); this.valueKeyMap.clear(); } public Set<K> keySet() { return this.keyValueMap.keySet(); } public Set<V> valueSet() { return this.valueKeyMap.keySet(); } public Collection<V> values() { return this.keyValueMap.values(); } public Collection<K> keys() { return this.valueKeyMap.values(); } public Set<Map.Entry<K, V>> entrySet() { return this.keyValueMap.entrySet(); } public Set<Map.Entry<V, K>> reverseEntrySet() { return this.valueKeyMap.entrySet(); } }
1,242
527
<filename>tests/performance/agents/metrics_collector.py #!/usr/bin/env python3 # Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. # Licensed under the Apache License, Version 2.0 (the "License"). # You may not use this file except in compliance with the License. # A copy of the License is located at # http://www.apache.org/licenses/LICENSE-2.0 # or in the "license" file accompanying this file. This file is distributed # on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either # express or implied. See the License for the specific language governing # permissions and limitations under the License. """ Server metrics collector """ # pylint: disable=redefined-builtin, broad-except, unused-variable import argparse import logging import os import sys import tempfile import time import gevent import psutil from utils.process import get_process_pid_from_file, get_child_processes, \ get_server_processes, get_server_pidfile from metrics import AVAILABLE_METRICS, get_metrics import configuration logger = logging.getLogger(__name__) logging.basicConfig(stream=sys.stdout, format="%(message)s", level=logging.INFO) TMP_DIR = tempfile.gettempdir() METRICS_LOG_FILE = os.path.join(TMP_DIR, "server_metrics_{}.log".format(int(time.time()))) METRICS_COLLECTOR_PID_FILE = os.path.join(TMP_DIR, "metrics_collector.pid") PID_FILE = configuration.get('server', 'pid_file', 'model_server.pid') MONITOR_INTERVAL = 1 def store_pid(pid_file): """ Store the current process id to pid_file""" process = psutil.Process() pid_file = os.path.join(pid_file) with open(pid_file, "w") as pf: pf.write(str(process.pid)) def stop_process(pid_file): """This will stop already running process . Note at a time only one pid file will be available. """ pid = get_process_pid_from_file(pid_file) if pid: try: process = psutil.Process(pid) if process.is_running(): logger.info("Process with pid %s is running. Killing it.", process.pid) process.kill() except Exception as e: pass else: logger.info("Dead process with pid %s found in '%s'.", process.pid, pid_file) logger.info("Removing pid file '%s'.", pid_file) os.remove(pid_file) def check_is_running(pid_file): """check if pid is running""" pid = get_process_pid_from_file(pid_file) if pid: try: perf_mon_process = psutil.Process(pid) except Exception as e: stop_process(pid_file) else: if perf_mon_process.is_running(): logger.error("Performance monitoring script already running. " "Stop it using stop option.") sys.exit() def store_metrics_collector_pid(): """ Store the process id of metrics collector process""" store_pid(METRICS_COLLECTOR_PID_FILE) def stop_metrics_collector_process(): """This will stop already running metrics collector process. Note at a time only one pid file will be available. """ stop_process(METRICS_COLLECTOR_PID_FILE) def monitor_processes(server_process, metrics, interval, socket): """ Monitor the metrics of server_process and its child processes """ while True: message = [] collected_metrics = get_metrics(server_process, get_child_processes(server_process), logger) metrics_msg = [] for metric in metrics: message.append(str(collected_metrics.get(metric, 0))) if collected_metrics.get(metric) is not None: metrics_msg.append("{0} : {1}".format(metric, collected_metrics.get(metric, 0))) message = "\t".join(message) + "\t\n" logger.info("%s", " -- ".join(metrics_msg)) if socket: try: socket.send(message.encode("latin-1")) except BrokenPipeError: logger.info("Stopping monitoring as socket connection is closed.") break # TODO - log metrics to a file METRICS_LOG_FILE if METRICS_LOG_FILE is provided gevent.sleep(interval) def start_metric_collection(server_process, metrics, interval, socket): bad_metrics = set(metrics) - set(AVAILABLE_METRICS) if bad_metrics: raise Exception("Metrics not available for monitoring {}.".format(bad_metrics)) logger.info("Started metric collection for target server processes.....") thread = gevent.spawn(monitor_processes, server_process, metrics, interval, socket) gevent.joinall([thread]) def start_metric_collector_process(): """Spawn a metric collection process and keep on monitoring """ check_is_running(METRICS_COLLECTOR_PID_FILE) store_metrics_collector_pid() server_pid = get_process_pid_from_file(get_server_pidfile(PID_FILE)) server_process = get_server_processes(server_pid) start_metric_collection(server_process, AVAILABLE_METRICS, MONITOR_INTERVAL, None) if __name__ == "__main__": logging.basicConfig(stream=sys.stdout, format="%(message)s", level=logging.INFO) parser = argparse.ArgumentParser(prog='metric-collector', description='System Performance Metrics collector') sub_parse = parser.add_mutually_exclusive_group(required=True) sub_parse.add_argument('--start', action='store_true', help='Start the metric-collector') sub_parse.add_argument('--stop', action='store_true', help='Stop the metric-collector') args = parser.parse_args() if args.start: start_metric_collector_process() elif args.stop: stop_metrics_collector_process()
2,153
4,054
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #pragma once #include "fieldsearcher.h" namespace vsm { class IntFieldSearcher : public FieldSearcher { public: std::unique_ptr<FieldSearcher> duplicate() const override; IntFieldSearcher(FieldIdT fId=0); ~IntFieldSearcher(); void prepare(search::streaming::QueryTermList & qtl, const SharedSearcherBuf & buf) override; void onValue(const document::FieldValue & fv) override; protected: class IntInfo { public: IntInfo(int64_t low, int64_t high, bool v) : _lower(low), _upper(high), _valid(v) { if (low > high) { _lower = high; _upper = low; } } bool cmp(int64_t key) const { return (_lower <= key) && (key <= _upper); } bool valid() const { return _valid; } private: int64_t _lower; int64_t _upper; bool _valid; }; typedef std::vector<IntInfo> IntInfoListT; IntInfoListT _intTerm; }; }
397
2,180
package com.xiaojukeji.kafka.manager.bpm.common.entry.detail; import java.util.List; /** * @author zhongyuankai * @date 2020/5/18 */ public class OrderDetailApplyTopicDTO extends AbstractOrderDetailData { private String appId; private String appName; private String appPrincipals; private Long physicalClusterId; private String physicalClusterName; private Long logicalClusterId; private String logicalClusterName; private List<Long> regionIdList; private String topicName; private Long peakBytesIn; public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId; } public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } public String getAppPrincipals() { return appPrincipals; } public void setAppPrincipals(String appPrincipals) { this.appPrincipals = appPrincipals; } public Long getPhysicalClusterId() { return physicalClusterId; } public void setPhysicalClusterId(Long physicalClusterId) { this.physicalClusterId = physicalClusterId; } public String getPhysicalClusterName() { return physicalClusterName; } public void setPhysicalClusterName(String physicalClusterName) { this.physicalClusterName = physicalClusterName; } public Long getLogicalClusterId() { return logicalClusterId; } public void setLogicalClusterId(Long logicalClusterId) { this.logicalClusterId = logicalClusterId; } public String getLogicalClusterName() { return logicalClusterName; } public void setLogicalClusterName(String logicalClusterName) { this.logicalClusterName = logicalClusterName; } public List<Long> getRegionIdList() { return regionIdList; } public void setRegionIdList(List<Long> regionIdList) { this.regionIdList = regionIdList; } public String getTopicName() { return topicName; } public void setTopicName(String topicName) { this.topicName = topicName; } public Long getPeakBytesIn() { return peakBytesIn; } public void setPeakBytesIn(Long peakBytesIn) { this.peakBytesIn = peakBytesIn; } @Override public String toString() { return "OrderDetailApplyTopicDTO{" + "appId='" + appId + '\'' + ", appName='" + appName + '\'' + ", appPrincipals='" + appPrincipals + '\'' + ", physicalClusterId=" + physicalClusterId + ", physicalClusterName='" + physicalClusterName + '\'' + ", logicalClusterId=" + logicalClusterId + ", logicalClusterName='" + logicalClusterName + '\'' + ", regionIdList=" + regionIdList + ", topicName='" + topicName + '\'' + ", peakBytesIn=" + peakBytesIn + '}'; } }
1,259
1,248
<reponame>pajowu/pretix # Generated by Django 2.1 on 2018-09-12 10:35 import django.db.models.deletion from django.db import migrations, models import pretix.base.models.devices class Migration(migrations.Migration): dependencies = [ ('pretixbase', '0098_auto_20180731_1243_squashed_0100_item_require_approval'), ] operations = [ migrations.CreateModel( name='Device', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('device_id', models.PositiveIntegerField()), ('unique_serial', models.CharField(default=pretix.base.models.devices.generate_serial, max_length=190, unique=True)), ('initialization_token', models.CharField(default=pretix.base.models.devices.generate_initialization_token, max_length=190, unique=True)), ('api_token', models.CharField(max_length=190, null=True, unique=True)), ('all_events', models.BooleanField(default=False, verbose_name='All events (including newly created ones)')), ('name', models.CharField(max_length=190, verbose_name='Name')), ('created', models.DateTimeField(auto_now_add=True, verbose_name='Setup date')), ('initialized', models.DateTimeField(null=True, verbose_name='Initialization date')), ('hardware_brand', models.CharField(blank=True, max_length=190, null=True)), ('hardware_model', models.CharField(blank=True, max_length=190, null=True)), ('software_brand', models.CharField(blank=True, max_length=190, null=True)), ('software_version', models.CharField(blank=True, max_length=190, null=True)), ('limit_events', models.ManyToManyField(blank=True, to='pretixbase.Event', verbose_name='Limit to events')), ('organizer', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='devices', to='pretixbase.Organizer')), ], ), migrations.AlterUniqueTogether( name='device', unique_together={('organizer', 'device_id')}, ), migrations.AddField( model_name='logentry', name='device', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='pretixbase.Device'), ), ]
1,048
964
# -*- coding: utf-8 -*- # Copyright (c) 2010-2016, MIT Probabilistic Computing Project # # 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. from collections import namedtuple from bayeslite.exception import BQLParseError from bayeslite.util import casefold from bayeslite.backends.cgpm_schema.parse import flatten from bayeslite.backends.cgpm_schema.parse import intersperse import grammar ''' grep -o 'K_[A-Z][A-Z0-9_]*' < grammar.y | sort -u | awk ' { sub("^K_", "", $1); printf(" '\''%s'\'': grammar.K_%s,\n", tolower($1), $1); }' ''' KEYWORDS = { 'cluster': grammar.K_CLUSTER, 'context': grammar.K_CONTEXT, 'concentration': grammar.K_CONCENTRATION, 'dependent': grammar.K_DEPENDENT, 'ensure': grammar.K_ENSURE, 'in': grammar.K_IN, 'independent': grammar.K_INDEPENDENT, 'of': grammar.K_OF, 'parameter': grammar.K_PARAMETER, 'row': grammar.K_ROW, 'rows': grammar.K_ROWS, 'set': grammar.K_SET, 'singleton': grammar.K_SINGLETON, 'to': grammar.K_TO, 'variable': grammar.K_VARIABLE, 'variables': grammar.K_VARIABLES, 'view': grammar.K_VIEW, 'within': grammar.K_WITHIN, } PUNCTUATION = { '(': grammar.T_LROUND, ')': grammar.T_RROUND, '*': grammar.T_STAR, ',': grammar.T_COMMA, } def parse(tokens): semantics = CGpmAlterSemantics() parser = grammar.Parser(semantics) for token in tokenize(tokens): semantics.context.append(token) if len(semantics.context) > 10: semantics.context.pop(0) parser.feed(token) if semantics.errors: raise BQLParseError(semantics.errors) if semantics.failed: raise BQLParseError(['parse failed mysteriously']) assert semantics.phrases is not None return semantics.phrases def tokenize(tokenses): for token in intersperse(',', [flatten(tokens) for tokens in tokenses]): if isinstance(token, str): if casefold(token) in KEYWORDS: yield KEYWORDS[casefold(token)], token elif token in PUNCTUATION: yield PUNCTUATION[token], token else: # XXX check for alphanumeric/_ yield grammar.L_NAME, token elif isinstance(token, (int, float)): yield grammar.L_NUMBER, token else: raise IOError('Invalid token: %r' % (token,)) yield 0, '' # EOF class CGpmAlterSemantics(object): def __init__(self): self.context = [] self.errors = [] self.failed = False self.phrases = None def accept(self): pass def parse_failed(self): self.failed = True def syntax_error(self, (token, text)): if token == -1: # error self.errors.append('Bad token: %r' % (text,)) else: self.errors.append("Syntax error near [%s] after [%s]" % ( text, ' '.join([str(t) for (_t, t) in self.context[:-1]]))) def p_alter_start(self, ps): self.phrases = ps def p_phrases_one(self, p): return [p] if p else [] def p_phrases_many(self, ps, p): if p: ps.append(p) return ps def p_phrase_none(self,): return None def p_phrase_set_var_dependency(self, cols, dep): return SetVarDependency(cols, dep) def p_phrase_set_var_cluster(self, cols0, col1): return SetVarCluster(cols0, col1) def p_phrase_set_var_cluster_singleton(self, cols): return SetVarCluster(cols, SingletonCluster) def p_phrase_set_var_cluster_conc(self, conc): return SetVarClusterConc(conc) def p_phrase_set_row_cluster(self, rows0, row1, col): return SetRowCluster(rows0, row1, col) def p_phrase_set_row_cluster_singleton(self, rows0, col): return SetRowCluster(rows0, SingletonCluster, col) def p_phrase_set_row_cluster_conc(self, col, conc): return SetRowClusterConc(col, conc) def p_dependency_independent(self): return EnsureIndependent def p_dependency_dependent(self): return EnsureDependent def p_columns_one(self, col): return [col] def p_columns_all(self): return SqlAll def p_columns_many(self, cols): return cols def p_column_list_one(self, col): return [col] def p_column_list_many(self, cols, col): cols.append(col); return cols def p_column_name_n(self, n): return n def p_rows_one(self, row): return [row] def p_rows_all(self): return SqlAll def p_rows_many(self, rows): return rows def p_row_list_one(self, row): return [row] def p_row_list_many(self, rows, row): rows.append(row); return rows def p_row_index_n(self, n): return n def p_concentration_c(self, n): return n SetVarDependency = namedtuple('SetVarCluster', [ 'columns', # columns to modify 'dependency' # INDEPENDENT or DEPENDENT ]) SetVarCluster = namedtuple('SetVarCluster', [ 'columns0', # columns to modify 'column1' # context column ]) SetVarClusterConc = namedtuple('SetVarClusterConc', [ 'concentration' # real valued concentration parameter ]) SetRowCluster = namedtuple('SetRowCluster', [ 'rows0', # rows to modify 'row1', # row whose cluster to move rows0 to 'column' # context column ]) SetRowClusterConc = namedtuple('SetRowClusterConc', [ 'column', # context column 'concentration' # real valued concentration parameter ]) SqlAll = 'SqlAll' EnsureDependent = 'EnsureDependent' EnsureIndependent = 'EnsureIndependent' SingletonCluster = 'SingletonCluster'
2,844
552
<filename>Engine/source/EtRendering/SceneStructure/Skybox.h #pragma once #include <EtCore/Content/AssetPointer.h> #include <EtRendering/GraphicsTypes/EnvironmentMap.h> namespace et { namespace render { //---------------------- // Skybox // // Data required to draw a skybox in a scene // struct Skybox { float m_Roughness = 0.2f; AssetPtr<EnvironmentMap> m_EnvironmentMap; }; } // namespace render } // namespace et
145
8,657
<filename>deps/brotli/research/sieve.cc #include "./sieve.h" typedef struct Slot { uint32_t next; uint32_t offset; uint16_t presence; uint16_t mark; } Slot; static size_t dryRun(size_t sliceLen, Slot* map, uint32_t* shortcut, size_t end, size_t middle, uint16_t minPresence, uint16_t iteration) { int from = -2; int to = -1; size_t result = 0; uint16_t targetPresence = minPresence; for (uint32_t i = 0; i < end; ++i) { if (i == middle) { targetPresence++; } Slot& item = map[shortcut[i]]; if (item.mark != iteration) { item.mark = iteration; if (item.presence >= targetPresence) { if (to < i) { if (from > 0) { result += to - from; } from = i; } to = i + sliceLen; } } } if (from > 0) { result += to - from; } return result; } static std::string createDictionary(const uint8_t* data, size_t sliceLen, Slot* map, uint32_t* shortcut, size_t end, size_t middle, uint16_t minPresence, uint16_t iteration) { std::string output; int from = -2; int to = -1; uint16_t targetPresence = minPresence; for (uint32_t i = 0; i < end; ++i) { if (i == middle) { targetPresence++; } Slot& item = map[shortcut[i]]; if (item.mark != iteration) { item.mark = iteration; if (item.presence >= targetPresence) { if (to < i) { if (from > 0) { output.insert(output.end(), &data[from], &data[to]); } from = i; } to = i + sliceLen; } } } if (from > 0) { output.insert(output.end(), &data[from], &data[to]); } return output; } std::string sieve_generate(size_t dictionary_size_limit, size_t slice_len, const std::vector<size_t>& sample_sizes, const uint8_t* sample_data) { /* Parameters aliasing */ size_t targetSize = dictionary_size_limit; size_t sliceLen = slice_len; const uint8_t* data = sample_data; size_t total = 0; std::vector<size_t> offsets; for (size_t i = 0; i < sample_sizes.size(); ++i) { total += sample_sizes[i]; offsets.push_back(total); } /***************************************************************************** * Build coverage map. ****************************************************************************/ std::vector<Slot> map; std::vector<uint32_t> shortcut; map.push_back({0, 0, 0, 0}); size_t end = total - sliceLen; int hashLen = 8; while ((1 << hashLen) < end) { hashLen += 3; } hashLen -= 3; uint32_t hashMask = (1u << hashLen) - 1u; std::vector<uint32_t> hashHead(1 << hashLen); uint32_t hashSlot = 1; uint16_t piece = 0; uint32_t hash = 0; int lShift = 3; int rShift = hashLen - lShift; for (int i = 0; i < sliceLen - 1; ++i) { uint32_t v = data[i]; hash = (((hash << lShift) | (hash >> rShift)) & hashMask) ^ v; } int lShiftX = (lShift * (sliceLen - 1)) % hashLen; int rShiftX = hashLen - lShiftX; for (uint32_t i = 0; i < end; ++i) { uint32_t v = data[i + sliceLen - 1]; hash = (((hash << lShift) | (hash >> rShift)) & hashMask) ^ v; if (offsets[piece] == i) { piece++; } uint32_t slot = hashHead[hash]; while (slot != 0) { Slot& item = map[slot]; int start = item.offset; bool miss = false; for (size_t j = 0; j < sliceLen; ++j) { if (data[i + j] != data[start + j]) { miss = true; break; } } if (!miss) { if (item.mark != piece) { item.mark = piece; item.presence++; } shortcut.push_back(slot); break; } slot = item.next; } if (slot == 0) { map.push_back({hashHead[hash], i, 1, piece}); hashHead[hash] = hashSlot; shortcut.push_back(hashSlot); hashSlot++; } v = data[i]; hash ^= ((v << lShiftX) | (v >> rShiftX)) & hashMask; } /***************************************************************************** * Build dictionary of specified size. ****************************************************************************/ size_t a = 1; size_t size = dryRun( sliceLen, map.data(), shortcut.data(), end, end, a, ++piece); /* Maximal output is smaller than target. */ if (size <= targetSize) { return createDictionary( data, sliceLen, map.data(), shortcut.data(), end, end, a, ++piece); } size_t b = offsets.size(); size = dryRun(sliceLen, map.data(), shortcut.data(), end, end, b, ++piece); if (size == targetSize) { return createDictionary( data, sliceLen, map.data(), shortcut.data(), end, end, b, ++piece); } /* Run binary search. */ if (size < targetSize) { /* size(a) > targetSize > size(b) && a < m < b */ while (a + 1 < b) { size_t m = (a + b) / 2; size = dryRun( sliceLen, map.data(), shortcut.data(), end, end, m, ++piece); if (size < targetSize) { b = m; } else if (size > targetSize) { a = m; } else { return createDictionary( data, sliceLen, map.data(), shortcut.data(), end, end, b, ++piece); } } } else { a = b; } /* size(minPresence) > targetSize > size(minPresence + 1) */ size_t minPresence = a; a = 0; b = end; /* size(a) < targetSize < size(b) && a < m < b */ while (a + 1 < b) { size_t m = (a + b) / 2; size = dryRun( sliceLen, map.data(), shortcut.data(), end, m, minPresence, ++piece); if (size < targetSize) { a = m; } else if (size > targetSize) { b = m; } else { return createDictionary(data, sliceLen, map.data(), shortcut.data(), end, m, minPresence, ++piece); } } bool unrestricted = false; if (minPresence <= 2 && !unrestricted) { minPresence = 2; a = end; } return createDictionary(data, sliceLen, map.data(), shortcut.data(), end, a, minPresence, ++piece); }
2,550
405
<reponame>msakai/soft-dtw import numpy as np from scipy.optimize import approx_fprime from sklearn.metrics.pairwise import euclidean_distances from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_array_almost_equal from sdtw.path import gen_all_paths from sdtw.distance import SquaredEuclidean from sdtw import SoftDTW # Generate two inputs randomly. rng = np.random.RandomState(0) X = rng.randn(5, 4) Y = rng.randn(6, 4) D = euclidean_distances(X, Y, squared=True) def _softmax(z): max_val = np.max(z) return max_val + np.log(np.exp(z - max_val).sum()) def _softmin(z, gamma): z = np.array(z) return -gamma * _softmax(-z / gamma) def _soft_dtw_bf(D, gamma): costs = [np.sum(A * D) for A in gen_all_paths(D.shape[0], D.shape[1])] return _softmin(costs, gamma) def test_soft_dtw(): for gamma in (0.001, 0.01, 0.1, 1, 10, 100, 1000): assert_almost_equal(SoftDTW(D, gamma).compute(), _soft_dtw_bf(D, gamma=gamma)) def test_soft_dtw_grad(): def make_func(gamma): def func(d): D_ = d.reshape(*D.shape) return SoftDTW(D_, gamma).compute() return func for gamma in (0.001, 0.01, 0.1, 1, 10, 100, 1000): sdtw = SoftDTW(D, gamma) sdtw.compute() E = sdtw.grad() func = make_func(gamma) E_num = approx_fprime(D.ravel(), func, 1e-6).reshape(*E.shape) assert_array_almost_equal(E, E_num, 5) def test_soft_dtw_grad_X(): def make_func(gamma): def func(x): X_ = x.reshape(*X.shape) D_ = SquaredEuclidean(X_, Y) return SoftDTW(D_, gamma).compute() return func for gamma in (0.001, 0.01, 0.1, 1, 10, 100, 1000): dist = SquaredEuclidean(X, Y) sdtw = SoftDTW(dist, gamma) sdtw.compute() E = sdtw.grad() G = dist.jacobian_product(E) func = make_func(gamma) G_num = approx_fprime(X.ravel(), func, 1e-6).reshape(*G.shape) assert_array_almost_equal(G, G_num, 5)
1,012
10,876
{ "name": "nifticlib", "version-string": "2020-04-30", "port-version": 1, "description": "Nifticlib is a C I/O library for reading and writing files in the nifti-1 data format.", "homepage": "NIFTI-Imaging/nifti_clib", "supports": "!uwp", "dependencies": [ "zlib" ], "default-features": [ "nifti2", "nifticdf" ], "features": { "cifti": { "description": "Build cifti libraries and tools" }, "fsl": { "description": "Build fsl libraries and tools" }, "nifti2": { "description": "Build nifti2 libraries and tools" }, "nifticdf": { "description": "Build nifticdf libraries and tools" }, "tests": { "description": "Build tests" }, "tools": { "description": "Build tools" } } }
346
458
__author__ = '<NAME>'
10
5,133
/* * Copyright MapStruct Authors. * * Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package org.mapstruct.ap.test.collection.wildcard; import java.math.BigDecimal; import java.util.List; import org.mapstruct.Mapper; /** * * @author <NAME> */ @Mapper public interface ErroneousIterableTypeVarBoundMapperOnMethod { <T extends BigDecimal> List<T> map(List<BigDecimal> in); }
152
1,114
<reponame>3096/libnx #define NX_SERVICE_ASSUME_NON_DOMAIN #include "service_guard.h" #include "services/fan.h" #include "runtime/hosversion.h" static Service g_fanSrv; NX_GENERATE_SERVICE_GUARD(fan); Result _fanInitialize(void) { return smGetService(&g_fanSrv, "fan"); } void _fanCleanup(void) { serviceClose(&g_fanSrv); } Result fanOpenController(FanController *out, u32 device_code) { return serviceDispatchIn(&g_fanSrv, 0, device_code, .out_num_objects = 1, .out_objects = &out->s, ); } Service* fanGetServiceSession(void) { return &g_fanSrv; } void fanControllerClose(FanController *controller) { serviceClose(&controller->s); } Result fanControllerSetRotationSpeedLevel(FanController *controller, float level) { return serviceDispatchIn(&controller->s, 0, level); } Result fanControllerGetRotationSpeedLevel(FanController *controller, float *level) { return serviceDispatchOut(&controller->s, 2, *level); }
363
1,742
<gh_stars>1000+ from .sudoku import Sudoku, sudoku from .hexad import Minimog
30
716
<filename>envi/tests/msp430/iclr.py from envi.archs.msp430.regs import * checks = [ # CLR ( 'CLR R15', { 'regs': [(REG_R15, 0xffff)], 'flags': [(SR_N, 0), (SR_Z, 0), (SR_C, 0), (SR_V, 0)], 'code': "0f43", 'data': "" }, { 'regs': [(REG_R15, 0x0)], 'flags': [(SR_N, 0), (SR_Z, 0), (SR_C, 0), (SR_V, 0)], 'code': "0f43", 'data': "" } ), ( 'CLR @R15', { 'regs': [(REG_R15, 0x1000)], 'flags': [(SR_N, 0), (SR_Z, 0), (SR_C, 0), (SR_V, 0)], 'code': "8f430000", 'data': "11223344" }, { 'regs': [(REG_R15, 0x1000)], 'flags': [(SR_N, 0), (SR_Z, 0), (SR_C, 0), (SR_V, 0)], 'code': "8f430000", 'data': "00003344" } ), # CLR.b ( 'CLR.b R15', { 'regs': [(REG_R15, 0xffff)], 'flags': [(SR_N, 0), (SR_Z, 0), (SR_C, 0), (SR_V, 0)], 'code': "4f43", 'data': "" }, { 'regs': [(REG_R15, 0x0)], 'flags': [(SR_N, 0), (SR_Z, 0), (SR_C, 0), (SR_V, 0)], 'code': "4f43", 'data': "" } ), ( 'CLR @R15', { 'regs': [(REG_R15, 0x1000)], 'flags': [(SR_N, 0), (SR_Z, 0), (SR_C, 0), (SR_V, 0)], 'code': "cf430000", 'data': "11223344" }, { 'regs': [(REG_R15, 0x1000)], 'flags': [(SR_N, 0), (SR_Z, 0), (SR_C, 0), (SR_V, 0)], 'code': "cf430000", 'data': "00223344" } ), ]
724
892
<gh_stars>100-1000 { "schema_version": "1.2.0", "id": "GHSA-6px6-cgv7-v9vp", "modified": "2022-05-13T01:15:59Z", "published": "2022-05-13T01:15:59Z", "aliases": [ "CVE-2013-2556" ], "details": "Unspecified vulnerability in Microsoft Windows Vista SP2, Windows Server 2008 SP2 and R2 SP1, and Windows 7 through SP1 allows attackers to bypass the ASLR protection mechanism via unknown vectors, as demonstrated against Adobe Flash Player by VUPEN during a Pwn2Own competition at CanSecWest 2013, aka \"ASLR Security Feature Bypass Vulnerability.\"", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2013-2556" }, { "type": "WEB", "url": "https://docs.microsoft.com/en-us/security-updates/securitybulletins/2013/ms13-063" }, { "type": "WEB", "url": "https://oval.cisecurity.org/repository/search/definition/oval%3Aorg.mitre.oval%3Adef%3A18132" }, { "type": "WEB", "url": "http://h30499.www3.hp.com/t5/HP-Security-Research-Blog/Pwn2Own-2013/ba-p/5981157" }, { "type": "WEB", "url": "http://twitter.com/VUPEN/statuses/309713355466227713" }, { "type": "WEB", "url": "http://twitter.com/thezdi/statuses/309756927301283840" }, { "type": "WEB", "url": "http://www.us-cert.gov/ncas/alerts/TA13-225A" } ], "database_specific": { "cwe_ids": [ ], "severity": "HIGH", "github_reviewed": false } }
700
697
<reponame>mahak/opsmop # Copyright 2018 <NAME> LLC, <<EMAIL>> # # 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. from opsmop.core.field import Field from opsmop.core.fields import Fields from opsmop.core.resource import Resource from opsmop.core.resources import Resources class Handlers(Resources): def __init__(self, **kwargs): handlers = [] for (k,v) in kwargs.items(): v.handles = k handlers.append(v) self.setup(items=handlers) def fields(self): return Fields( self, items = Field(kind=list, of=Resource), )
384
929
# -*- coding: utf-8 -*- # Generated by Django 1.11.22 on 2019-08-16 16:54 from __future__ import unicode_literals from django.db import migrations from django.db.models import OuterRef, Exists def change_locale_bn_bd_to_bn_forwards(apps, schema_editor): Document = apps.get_model('wiki', 'Document') DraftRevision = apps.get_model('wiki', 'DraftRevision') Locale = apps.get_model('wiki', 'Locale') # Change the locale of the documents that does not have bn-BD translation bn_bd_document = (Document.objects.only('id').all() .filter(parent=OuterRef('parent'), locale='bn-BD')) bn_in_documents = (Document.objects.all().filter(locale='bn-IN') .annotate(has_bn_bd=Exists(bn_bd_document)) .exclude(has_bn_bd=True) .values_list('id', flat=True)) Document.objects.all().filter(locale='bn-IN', id__in=list(bn_in_documents)).update(locale='bn') Document.objects.all().filter(locale='bn-BD').update(locale='bn') DraftRevision.objects.all().filter(locale='bn-BD').update(locale='bn') Locale.objects.all().filter(locale='bn-BD').update(locale='bn') def change_locale_bn_to_bn_bd_backwards(apps, schema_editor): pass class Migration(migrations.Migration): dependencies = [ ('wiki', '0009_auto_20190507_1052'), ] operations = [ migrations.RunPython(change_locale_bn_bd_to_bn_forwards, change_locale_bn_to_bn_bd_backwards) ]
711
2,706
/* Copyright (c) 2013-2015 <NAME> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "gl.h" #include <mgba-util/math.h> static const GLint _glVertices[] = { 0, 0, 256, 0, 256, 256, 0, 256 }; static const GLint _glTexCoords[] = { 0, 0, 1, 0, 1, 1, 0, 1 }; static void mGLContextInit(struct VideoBackend* v, WHandle handle) { UNUSED(handle); struct mGLContext* context = (struct mGLContext*) v; glGenTextures(1, &context->tex); glBindTexture(GL_TEXTURE_2D, context->tex); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); #ifndef _WIN32 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); #endif } static void mGLContextSetDimensions(struct VideoBackend* v, unsigned width, unsigned height) { struct mGLContext* context = (struct mGLContext*) v; v->width = width; v->height = height; glBindTexture(GL_TEXTURE_2D, context->tex); #ifdef COLOR_16_BIT #ifdef COLOR_5_6_5 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, toPow2(width), toPow2(height), 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, 0); #else glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, toPow2(width), toPow2(height), 0, GL_RGBA, GL_UNSIGNED_SHORT_1_5_5_5_REV, 0); #endif #elif defined(__BIG_ENDIAN__) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, toPow2(width), toPow2(height), 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV, 0); #else glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, toPow2(width), toPow2(height), 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); #endif } static void mGLContextDeinit(struct VideoBackend* v) { struct mGLContext* context = (struct mGLContext*) v; glDeleteTextures(1, &context->tex); } static void mGLContextResized(struct VideoBackend* v, unsigned w, unsigned h) { unsigned drawW = w; unsigned drawH = h; if (v->lockAspectRatio) { if (w * v->height > h * v->width) { drawW = h * v->width / v->height; } else if (w * v->height < h * v->width) { drawH = w * v->height / v->width; } } if (v->lockIntegerScaling) { drawW -= drawW % v->width; drawH -= drawH % v->height; } glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT); glViewport((w - drawW) / 2, (h - drawH) / 2, drawW, drawH); } static void mGLContextClear(struct VideoBackend* v) { UNUSED(v); glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT); } void mGLContextDrawFrame(struct VideoBackend* v) { struct mGLContext* context = (struct mGLContext*) v; glEnable(GL_TEXTURE_2D); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(2, GL_INT, 0, _glVertices); glTexCoordPointer(2, GL_INT, 0, _glTexCoords); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, v->width, v->height, 0, 0, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glBindTexture(GL_TEXTURE_2D, context->tex); if (v->filter) { glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } else { glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); } glDrawArrays(GL_TRIANGLE_FAN, 0, 4); } void mGLContextPostFrame(struct VideoBackend* v, const void* frame) { struct mGLContext* context = (struct mGLContext*) v; glBindTexture(GL_TEXTURE_2D, context->tex); #ifdef COLOR_16_BIT #ifdef COLOR_5_6_5 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, v->width, v->height, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, frame); #else glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, v->width, v->height, GL_RGBA, GL_UNSIGNED_SHORT_1_5_5_5_REV, frame); #endif #elif defined(__BIG_ENDIAN__) glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, v->width, v->height, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV, frame); #else glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, v->width, v->height, GL_RGBA, GL_UNSIGNED_BYTE, frame); #endif } void mGLContextCreate(struct mGLContext* context) { context->d.init = mGLContextInit; context->d.deinit = mGLContextDeinit; context->d.setDimensions = mGLContextSetDimensions; context->d.resized = mGLContextResized; context->d.swap = 0; context->d.clear = mGLContextClear; context->d.postFrame = mGLContextPostFrame; context->d.drawFrame = mGLContextDrawFrame; context->d.setMessage = 0; context->d.clearMessage = 0; }
1,912
1,405
<gh_stars>1000+ package android.support.v4.view.accessibility; import android.graphics.Rect; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.view.accessibility.AccessibilityNodeInfoCompatApi21; import android.support.v4.view.accessibility.AccessibilityNodeInfoCompatKitKat; import android.view.View; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class AccessibilityNodeInfoCompat { public static final int ACTION_ACCESSIBILITY_FOCUS = 64; public static final String ACTION_ARGUMENT_COLUMN_INT = "android.view.accessibility.action.ARGUMENT_COLUMN_INT"; public static final String ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN = "ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN"; public static final String ACTION_ARGUMENT_HTML_ELEMENT_STRING = "ACTION_ARGUMENT_HTML_ELEMENT_STRING"; public static final String ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT = "ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT"; public static final String ACTION_ARGUMENT_PROGRESS_VALUE = "android.view.accessibility.action.ARGUMENT_PROGRESS_VALUE"; public static final String ACTION_ARGUMENT_ROW_INT = "android.view.accessibility.action.ARGUMENT_ROW_INT"; public static final String ACTION_ARGUMENT_SELECTION_END_INT = "ACTION_ARGUMENT_SELECTION_END_INT"; public static final String ACTION_ARGUMENT_SELECTION_START_INT = "ACTION_ARGUMENT_SELECTION_START_INT"; public static final String ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE = "ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE"; public static final int ACTION_CLEAR_ACCESSIBILITY_FOCUS = 128; public static final int ACTION_CLEAR_FOCUS = 2; public static final int ACTION_CLEAR_SELECTION = 8; public static final int ACTION_CLICK = 16; public static final int ACTION_COLLAPSE = 524288; public static final int ACTION_COPY = 16384; public static final int ACTION_CUT = 65536; public static final int ACTION_DISMISS = 1048576; public static final int ACTION_EXPAND = 262144; public static final int ACTION_FOCUS = 1; public static final int ACTION_LONG_CLICK = 32; public static final int ACTION_NEXT_AT_MOVEMENT_GRANULARITY = 256; public static final int ACTION_NEXT_HTML_ELEMENT = 1024; public static final int ACTION_PASTE = 32768; public static final int ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY = 512; public static final int ACTION_PREVIOUS_HTML_ELEMENT = 2048; public static final int ACTION_SCROLL_BACKWARD = 8192; public static final int ACTION_SCROLL_FORWARD = 4096; public static final int ACTION_SELECT = 4; public static final int ACTION_SET_SELECTION = 131072; public static final int ACTION_SET_TEXT = 2097152; public static final int FOCUS_ACCESSIBILITY = 2; public static final int FOCUS_INPUT = 1; static final AccessibilityNodeInfoImpl IMPL; public static final int MOVEMENT_GRANULARITY_CHARACTER = 1; public static final int MOVEMENT_GRANULARITY_LINE = 4; public static final int MOVEMENT_GRANULARITY_PAGE = 16; public static final int MOVEMENT_GRANULARITY_PARAGRAPH = 8; public static final int MOVEMENT_GRANULARITY_WORD = 2; private final Object mInfo; /* access modifiers changed from: package-private */ public interface AccessibilityNodeInfoImpl { void addAction(Object obj, int i); void addAction(Object obj, Object obj2); void addChild(Object obj, View view); void addChild(Object obj, View view, int i); boolean canOpenPopup(Object obj); List<Object> findAccessibilityNodeInfosByText(Object obj, String str); List<Object> findAccessibilityNodeInfosByViewId(Object obj, String str); Object findFocus(Object obj, int i); Object focusSearch(Object obj, int i); int getAccessibilityActionId(Object obj); CharSequence getAccessibilityActionLabel(Object obj); Object getActionContextClick(); List<Object> getActionList(Object obj); Object getActionScrollDown(); Object getActionScrollLeft(); Object getActionScrollRight(); Object getActionScrollToPosition(); Object getActionScrollUp(); Object getActionSetProgress(); Object getActionShowOnScreen(); int getActions(Object obj); void getBoundsInParent(Object obj, Rect rect); void getBoundsInScreen(Object obj, Rect rect); Object getChild(Object obj, int i); int getChildCount(Object obj); CharSequence getClassName(Object obj); Object getCollectionInfo(Object obj); int getCollectionInfoColumnCount(Object obj); int getCollectionInfoRowCount(Object obj); int getCollectionInfoSelectionMode(Object obj); int getCollectionItemColumnIndex(Object obj); int getCollectionItemColumnSpan(Object obj); Object getCollectionItemInfo(Object obj); int getCollectionItemRowIndex(Object obj); int getCollectionItemRowSpan(Object obj); CharSequence getContentDescription(Object obj); int getDrawingOrder(Object obj); CharSequence getError(Object obj); Bundle getExtras(Object obj); int getInputType(Object obj); Object getLabelFor(Object obj); Object getLabeledBy(Object obj); int getLiveRegion(Object obj); int getMaxTextLength(Object obj); int getMovementGranularities(Object obj); CharSequence getPackageName(Object obj); Object getParent(Object obj); Object getRangeInfo(Object obj); CharSequence getRoleDescription(Object obj); CharSequence getText(Object obj); int getTextSelectionEnd(Object obj); int getTextSelectionStart(Object obj); Object getTraversalAfter(Object obj); Object getTraversalBefore(Object obj); String getViewIdResourceName(Object obj); Object getWindow(Object obj); int getWindowId(Object obj); boolean isAccessibilityFocused(Object obj); boolean isCheckable(Object obj); boolean isChecked(Object obj); boolean isClickable(Object obj); boolean isCollectionInfoHierarchical(Object obj); boolean isCollectionItemHeading(Object obj); boolean isCollectionItemSelected(Object obj); boolean isContentInvalid(Object obj); boolean isContextClickable(Object obj); boolean isDismissable(Object obj); boolean isEditable(Object obj); boolean isEnabled(Object obj); boolean isFocusable(Object obj); boolean isFocused(Object obj); boolean isImportantForAccessibility(Object obj); boolean isLongClickable(Object obj); boolean isMultiLine(Object obj); boolean isPassword(Object obj); boolean isScrollable(Object obj); boolean isSelected(Object obj); boolean isVisibleToUser(Object obj); Object newAccessibilityAction(int i, CharSequence charSequence); Object obtain(); Object obtain(View view); Object obtain(View view, int i); Object obtain(Object obj); Object obtainCollectionInfo(int i, int i2, boolean z); Object obtainCollectionInfo(int i, int i2, boolean z, int i3); Object obtainCollectionItemInfo(int i, int i2, int i3, int i4, boolean z); Object obtainCollectionItemInfo(int i, int i2, int i3, int i4, boolean z, boolean z2); Object obtainRangeInfo(int i, float f, float f2, float f3); boolean performAction(Object obj, int i); boolean performAction(Object obj, int i, Bundle bundle); void recycle(Object obj); boolean refresh(Object obj); boolean removeAction(Object obj, Object obj2); boolean removeChild(Object obj, View view); boolean removeChild(Object obj, View view, int i); void setAccessibilityFocused(Object obj, boolean z); void setBoundsInParent(Object obj, Rect rect); void setBoundsInScreen(Object obj, Rect rect); void setCanOpenPopup(Object obj, boolean z); void setCheckable(Object obj, boolean z); void setChecked(Object obj, boolean z); void setClassName(Object obj, CharSequence charSequence); void setClickable(Object obj, boolean z); void setCollectionInfo(Object obj, Object obj2); void setCollectionItemInfo(Object obj, Object obj2); void setContentDescription(Object obj, CharSequence charSequence); void setContentInvalid(Object obj, boolean z); void setContextClickable(Object obj, boolean z); void setDismissable(Object obj, boolean z); void setDrawingOrder(Object obj, int i); void setEditable(Object obj, boolean z); void setEnabled(Object obj, boolean z); void setError(Object obj, CharSequence charSequence); void setFocusable(Object obj, boolean z); void setFocused(Object obj, boolean z); void setImportantForAccessibility(Object obj, boolean z); void setInputType(Object obj, int i); void setLabelFor(Object obj, View view); void setLabelFor(Object obj, View view, int i); void setLabeledBy(Object obj, View view); void setLabeledBy(Object obj, View view, int i); void setLiveRegion(Object obj, int i); void setLongClickable(Object obj, boolean z); void setMaxTextLength(Object obj, int i); void setMovementGranularities(Object obj, int i); void setMultiLine(Object obj, boolean z); void setPackageName(Object obj, CharSequence charSequence); void setParent(Object obj, View view); void setParent(Object obj, View view, int i); void setPassword(Object obj, boolean z); void setRangeInfo(Object obj, Object obj2); void setRoleDescription(Object obj, CharSequence charSequence); void setScrollable(Object obj, boolean z); void setSelected(Object obj, boolean z); void setSource(Object obj, View view); void setSource(Object obj, View view, int i); void setText(Object obj, CharSequence charSequence); void setTextSelection(Object obj, int i, int i2); void setTraversalAfter(Object obj, View view); void setTraversalAfter(Object obj, View view, int i); void setTraversalBefore(Object obj, View view); void setTraversalBefore(Object obj, View view, int i); void setViewIdResourceName(Object obj, String str); void setVisibleToUser(Object obj, boolean z); } public static class AccessibilityActionCompat { public static final AccessibilityActionCompat ACTION_ACCESSIBILITY_FOCUS = new AccessibilityActionCompat(64, null); public static final AccessibilityActionCompat ACTION_CLEAR_ACCESSIBILITY_FOCUS = new AccessibilityActionCompat(128, null); public static final AccessibilityActionCompat ACTION_CLEAR_FOCUS = new AccessibilityActionCompat(2, null); public static final AccessibilityActionCompat ACTION_CLEAR_SELECTION = new AccessibilityActionCompat(8, null); public static final AccessibilityActionCompat ACTION_CLICK = new AccessibilityActionCompat(16, null); public static final AccessibilityActionCompat ACTION_COLLAPSE = new AccessibilityActionCompat(524288, null); public static final AccessibilityActionCompat ACTION_CONTEXT_CLICK = new AccessibilityActionCompat(AccessibilityNodeInfoCompat.IMPL.getActionContextClick()); public static final AccessibilityActionCompat ACTION_COPY = new AccessibilityActionCompat(16384, null); public static final AccessibilityActionCompat ACTION_CUT = new AccessibilityActionCompat(65536, null); public static final AccessibilityActionCompat ACTION_DISMISS = new AccessibilityActionCompat(1048576, null); public static final AccessibilityActionCompat ACTION_EXPAND = new AccessibilityActionCompat(262144, null); public static final AccessibilityActionCompat ACTION_FOCUS = new AccessibilityActionCompat(1, null); public static final AccessibilityActionCompat ACTION_LONG_CLICK = new AccessibilityActionCompat(32, null); public static final AccessibilityActionCompat ACTION_NEXT_AT_MOVEMENT_GRANULARITY = new AccessibilityActionCompat(256, null); public static final AccessibilityActionCompat ACTION_NEXT_HTML_ELEMENT = new AccessibilityActionCompat(1024, null); public static final AccessibilityActionCompat ACTION_PASTE = new AccessibilityActionCompat(32768, null); public static final AccessibilityActionCompat ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY = new AccessibilityActionCompat(512, null); public static final AccessibilityActionCompat ACTION_PREVIOUS_HTML_ELEMENT = new AccessibilityActionCompat(2048, null); public static final AccessibilityActionCompat ACTION_SCROLL_BACKWARD = new AccessibilityActionCompat(8192, null); public static final AccessibilityActionCompat ACTION_SCROLL_DOWN = new AccessibilityActionCompat(AccessibilityNodeInfoCompat.IMPL.getActionScrollDown()); public static final AccessibilityActionCompat ACTION_SCROLL_FORWARD = new AccessibilityActionCompat(4096, null); public static final AccessibilityActionCompat ACTION_SCROLL_LEFT = new AccessibilityActionCompat(AccessibilityNodeInfoCompat.IMPL.getActionScrollLeft()); public static final AccessibilityActionCompat ACTION_SCROLL_RIGHT = new AccessibilityActionCompat(AccessibilityNodeInfoCompat.IMPL.getActionScrollRight()); public static final AccessibilityActionCompat ACTION_SCROLL_TO_POSITION = new AccessibilityActionCompat(AccessibilityNodeInfoCompat.IMPL.getActionScrollToPosition()); public static final AccessibilityActionCompat ACTION_SCROLL_UP = new AccessibilityActionCompat(AccessibilityNodeInfoCompat.IMPL.getActionScrollUp()); public static final AccessibilityActionCompat ACTION_SELECT = new AccessibilityActionCompat(4, null); public static final AccessibilityActionCompat ACTION_SET_PROGRESS = new AccessibilityActionCompat(AccessibilityNodeInfoCompat.IMPL.getActionSetProgress()); public static final AccessibilityActionCompat ACTION_SET_SELECTION = new AccessibilityActionCompat(131072, null); public static final AccessibilityActionCompat ACTION_SET_TEXT = new AccessibilityActionCompat(2097152, null); public static final AccessibilityActionCompat ACTION_SHOW_ON_SCREEN = new AccessibilityActionCompat(AccessibilityNodeInfoCompat.IMPL.getActionShowOnScreen()); final Object mAction; public AccessibilityActionCompat(int actionId, CharSequence label) { this(AccessibilityNodeInfoCompat.IMPL.newAccessibilityAction(actionId, label)); } AccessibilityActionCompat(Object action) { this.mAction = action; } public int getId() { return AccessibilityNodeInfoCompat.IMPL.getAccessibilityActionId(this.mAction); } public CharSequence getLabel() { return AccessibilityNodeInfoCompat.IMPL.getAccessibilityActionLabel(this.mAction); } } public static class CollectionInfoCompat { public static final int SELECTION_MODE_MULTIPLE = 2; public static final int SELECTION_MODE_NONE = 0; public static final int SELECTION_MODE_SINGLE = 1; final Object mInfo; public static CollectionInfoCompat obtain(int rowCount, int columnCount, boolean hierarchical, int selectionMode) { return new CollectionInfoCompat(AccessibilityNodeInfoCompat.IMPL.obtainCollectionInfo(rowCount, columnCount, hierarchical, selectionMode)); } public static CollectionInfoCompat obtain(int rowCount, int columnCount, boolean hierarchical) { return new CollectionInfoCompat(AccessibilityNodeInfoCompat.IMPL.obtainCollectionInfo(rowCount, columnCount, hierarchical)); } CollectionInfoCompat(Object info) { this.mInfo = info; } public int getColumnCount() { return AccessibilityNodeInfoCompat.IMPL.getCollectionInfoColumnCount(this.mInfo); } public int getRowCount() { return AccessibilityNodeInfoCompat.IMPL.getCollectionInfoRowCount(this.mInfo); } public boolean isHierarchical() { return AccessibilityNodeInfoCompat.IMPL.isCollectionInfoHierarchical(this.mInfo); } public int getSelectionMode() { return AccessibilityNodeInfoCompat.IMPL.getCollectionInfoSelectionMode(this.mInfo); } } public static class CollectionItemInfoCompat { final Object mInfo; public static CollectionItemInfoCompat obtain(int rowIndex, int rowSpan, int columnIndex, int columnSpan, boolean heading, boolean selected) { return new CollectionItemInfoCompat(AccessibilityNodeInfoCompat.IMPL.obtainCollectionItemInfo(rowIndex, rowSpan, columnIndex, columnSpan, heading, selected)); } public static CollectionItemInfoCompat obtain(int rowIndex, int rowSpan, int columnIndex, int columnSpan, boolean heading) { return new CollectionItemInfoCompat(AccessibilityNodeInfoCompat.IMPL.obtainCollectionItemInfo(rowIndex, rowSpan, columnIndex, columnSpan, heading)); } CollectionItemInfoCompat(Object info) { this.mInfo = info; } public int getColumnIndex() { return AccessibilityNodeInfoCompat.IMPL.getCollectionItemColumnIndex(this.mInfo); } public int getColumnSpan() { return AccessibilityNodeInfoCompat.IMPL.getCollectionItemColumnSpan(this.mInfo); } public int getRowIndex() { return AccessibilityNodeInfoCompat.IMPL.getCollectionItemRowIndex(this.mInfo); } public int getRowSpan() { return AccessibilityNodeInfoCompat.IMPL.getCollectionItemRowSpan(this.mInfo); } public boolean isHeading() { return AccessibilityNodeInfoCompat.IMPL.isCollectionItemHeading(this.mInfo); } public boolean isSelected() { return AccessibilityNodeInfoCompat.IMPL.isCollectionItemSelected(this.mInfo); } } public static class RangeInfoCompat { public static final int RANGE_TYPE_FLOAT = 1; public static final int RANGE_TYPE_INT = 0; public static final int RANGE_TYPE_PERCENT = 2; final Object mInfo; public static RangeInfoCompat obtain(int type, float min, float max, float current) { return new RangeInfoCompat(AccessibilityNodeInfoCompat.IMPL.obtainRangeInfo(type, min, max, current)); } RangeInfoCompat(Object info) { this.mInfo = info; } public float getCurrent() { return AccessibilityNodeInfoCompatKitKat.RangeInfo.getCurrent(this.mInfo); } public float getMax() { return AccessibilityNodeInfoCompatKitKat.RangeInfo.getMax(this.mInfo); } public float getMin() { return AccessibilityNodeInfoCompatKitKat.RangeInfo.getMin(this.mInfo); } public int getType() { return AccessibilityNodeInfoCompatKitKat.RangeInfo.getType(this.mInfo); } } static class AccessibilityNodeInfoStubImpl implements AccessibilityNodeInfoImpl { AccessibilityNodeInfoStubImpl() { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public Object newAccessibilityAction(int actionId, CharSequence label) { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public Object obtain() { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public Object obtain(View source) { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public Object obtain(View root, int virtualDescendantId) { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public Object obtain(Object info) { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void addAction(Object info, int action) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void addAction(Object info, Object action) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public boolean removeAction(Object info, Object action) { return false; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public int getAccessibilityActionId(Object action) { return 0; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public CharSequence getAccessibilityActionLabel(Object action) { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void addChild(Object info, View child) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void addChild(Object info, View child, int virtualDescendantId) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public boolean removeChild(Object info, View child) { return false; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public boolean removeChild(Object info, View root, int virtualDescendantId) { return false; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public List<Object> findAccessibilityNodeInfosByText(Object info, String text) { return Collections.emptyList(); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public int getActions(Object info) { return 0; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void getBoundsInParent(Object info, Rect outBounds) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void getBoundsInScreen(Object info, Rect outBounds) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public Object getChild(Object info, int index) { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public int getChildCount(Object info) { return 0; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public CharSequence getClassName(Object info) { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public CharSequence getContentDescription(Object info) { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public CharSequence getPackageName(Object info) { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public Object getParent(Object info) { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public CharSequence getText(Object info) { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public int getWindowId(Object info) { return 0; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public boolean isCheckable(Object info) { return false; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public boolean isChecked(Object info) { return false; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public boolean isClickable(Object info) { return false; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public boolean isEnabled(Object info) { return false; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public boolean isFocusable(Object info) { return false; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public boolean isFocused(Object info) { return false; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public boolean isVisibleToUser(Object info) { return false; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public boolean isAccessibilityFocused(Object info) { return false; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public boolean isLongClickable(Object info) { return false; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public boolean isPassword(Object info) { return false; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public boolean isScrollable(Object info) { return false; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public boolean isSelected(Object info) { return false; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public boolean performAction(Object info, int action) { return false; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public boolean performAction(Object info, int action, Bundle arguments) { return false; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setMovementGranularities(Object info, int granularities) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public int getMovementGranularities(Object info) { return 0; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setBoundsInParent(Object info, Rect bounds) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setBoundsInScreen(Object info, Rect bounds) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setCheckable(Object info, boolean checkable) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setChecked(Object info, boolean checked) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setClassName(Object info, CharSequence className) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setClickable(Object info, boolean clickable) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setContentDescription(Object info, CharSequence contentDescription) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setEnabled(Object info, boolean enabled) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setFocusable(Object info, boolean focusable) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setFocused(Object info, boolean focused) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setVisibleToUser(Object info, boolean visibleToUser) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setAccessibilityFocused(Object info, boolean focused) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setLongClickable(Object info, boolean longClickable) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setPackageName(Object info, CharSequence packageName) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setParent(Object info, View parent) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setPassword(Object info, boolean password) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setScrollable(Object info, boolean scrollable) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setSelected(Object info, boolean selected) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setSource(Object info, View source) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setSource(Object info, View root, int virtualDescendantId) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public Object findFocus(Object info, int focus) { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public Object focusSearch(Object info, int direction) { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setText(Object info, CharSequence text) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void recycle(Object info) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setParent(Object info, View root, int virtualDescendantId) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public String getViewIdResourceName(Object info) { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setViewIdResourceName(Object info, String viewId) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public int getLiveRegion(Object info) { return 0; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setLiveRegion(Object info, int mode) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public Object getCollectionInfo(Object info) { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setCollectionInfo(Object info, Object collectionInfo) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public Object getCollectionItemInfo(Object info) { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setCollectionItemInfo(Object info, Object collectionItemInfo) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public Object getRangeInfo(Object info) { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setRangeInfo(Object info, Object rangeInfo) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public List<Object> getActionList(Object info) { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public Object obtainCollectionInfo(int rowCount, int columnCount, boolean hierarchical, int selectionMode) { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public Object obtainCollectionInfo(int rowCount, int columnCount, boolean hierarchical) { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public int getCollectionInfoColumnCount(Object info) { return 0; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public int getCollectionInfoRowCount(Object info) { return 0; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public boolean isCollectionInfoHierarchical(Object info) { return false; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public Object obtainCollectionItemInfo(int rowIndex, int rowSpan, int columnIndex, int columnSpan, boolean heading, boolean selected) { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public Object obtainCollectionItemInfo(int rowIndex, int rowSpan, int columnIndex, int columnSpan, boolean heading) { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public int getCollectionItemColumnIndex(Object info) { return 0; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public int getCollectionItemColumnSpan(Object info) { return 0; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public int getCollectionItemRowIndex(Object info) { return 0; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public int getCollectionItemRowSpan(Object info) { return 0; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public boolean isCollectionItemHeading(Object info) { return false; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public boolean isCollectionItemSelected(Object info) { return false; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public Object obtainRangeInfo(int type, float min, float max, float current) { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public Object getTraversalBefore(Object info) { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setTraversalBefore(Object info, View view) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setTraversalBefore(Object info, View root, int virtualDescendantId) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public Object getTraversalAfter(Object info) { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setTraversalAfter(Object info, View view) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setTraversalAfter(Object info, View root, int virtualDescendantId) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setContentInvalid(Object info, boolean contentInvalid) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public boolean isContentInvalid(Object info) { return false; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setError(Object info, CharSequence error) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public CharSequence getError(Object info) { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setLabelFor(Object info, View labeled) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setLabelFor(Object info, View root, int virtualDescendantId) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public Object getLabelFor(Object info) { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setLabeledBy(Object info, View labeled) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setLabeledBy(Object info, View root, int virtualDescendantId) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public Object getLabeledBy(Object info) { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public boolean canOpenPopup(Object info) { return false; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setCanOpenPopup(Object info, boolean opensPopup) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public List<Object> findAccessibilityNodeInfosByViewId(Object info, String viewId) { return Collections.emptyList(); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public Bundle getExtras(Object info) { return new Bundle(); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public int getInputType(Object info) { return 0; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setInputType(Object info, int inputType) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setMaxTextLength(Object info, int max) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public int getMaxTextLength(Object info) { return -1; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setTextSelection(Object info, int start, int end) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public int getTextSelectionStart(Object info) { return -1; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public int getTextSelectionEnd(Object info) { return -1; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public Object getWindow(Object info) { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public boolean isDismissable(Object info) { return false; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setDismissable(Object info, boolean dismissable) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public boolean isEditable(Object info) { return false; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setEditable(Object info, boolean editable) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public boolean isMultiLine(Object info) { return false; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setMultiLine(Object info, boolean multiLine) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public boolean refresh(Object info) { return false; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public CharSequence getRoleDescription(Object info) { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setRoleDescription(Object info, CharSequence roleDescription) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public Object getActionScrollToPosition() { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public Object getActionSetProgress() { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public boolean isContextClickable(Object info) { return false; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setContextClickable(Object info, boolean contextClickable) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public Object getActionShowOnScreen() { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public Object getActionScrollUp() { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public Object getActionScrollDown() { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public Object getActionScrollLeft() { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public Object getActionScrollRight() { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public Object getActionContextClick() { return null; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public int getCollectionInfoSelectionMode(Object info) { return 0; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public int getDrawingOrder(Object info) { return 0; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setDrawingOrder(Object info, int drawingOrderInParent) { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public boolean isImportantForAccessibility(Object info) { return true; } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl public void setImportantForAccessibility(Object info, boolean importantForAccessibility) { } } static class AccessibilityNodeInfoIcsImpl extends AccessibilityNodeInfoStubImpl { AccessibilityNodeInfoIcsImpl() { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public Object obtain() { return AccessibilityNodeInfoCompatIcs.obtain(); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public Object obtain(View source) { return AccessibilityNodeInfoCompatIcs.obtain(source); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public Object obtain(Object info) { return AccessibilityNodeInfoCompatIcs.obtain(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void addAction(Object info, int action) { AccessibilityNodeInfoCompatIcs.addAction(info, action); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void addChild(Object info, View child) { AccessibilityNodeInfoCompatIcs.addChild(info, child); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public List<Object> findAccessibilityNodeInfosByText(Object info, String text) { return AccessibilityNodeInfoCompatIcs.findAccessibilityNodeInfosByText(info, text); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public int getActions(Object info) { return AccessibilityNodeInfoCompatIcs.getActions(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void getBoundsInParent(Object info, Rect outBounds) { AccessibilityNodeInfoCompatIcs.getBoundsInParent(info, outBounds); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void getBoundsInScreen(Object info, Rect outBounds) { AccessibilityNodeInfoCompatIcs.getBoundsInScreen(info, outBounds); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public Object getChild(Object info, int index) { return AccessibilityNodeInfoCompatIcs.getChild(info, index); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public int getChildCount(Object info) { return AccessibilityNodeInfoCompatIcs.getChildCount(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public CharSequence getClassName(Object info) { return AccessibilityNodeInfoCompatIcs.getClassName(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public CharSequence getContentDescription(Object info) { return AccessibilityNodeInfoCompatIcs.getContentDescription(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public CharSequence getPackageName(Object info) { return AccessibilityNodeInfoCompatIcs.getPackageName(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public Object getParent(Object info) { return AccessibilityNodeInfoCompatIcs.getParent(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public CharSequence getText(Object info) { return AccessibilityNodeInfoCompatIcs.getText(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public int getWindowId(Object info) { return AccessibilityNodeInfoCompatIcs.getWindowId(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public boolean isCheckable(Object info) { return AccessibilityNodeInfoCompatIcs.isCheckable(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public boolean isChecked(Object info) { return AccessibilityNodeInfoCompatIcs.isChecked(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public boolean isClickable(Object info) { return AccessibilityNodeInfoCompatIcs.isClickable(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public boolean isEnabled(Object info) { return AccessibilityNodeInfoCompatIcs.isEnabled(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public boolean isFocusable(Object info) { return AccessibilityNodeInfoCompatIcs.isFocusable(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public boolean isFocused(Object info) { return AccessibilityNodeInfoCompatIcs.isFocused(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public boolean isLongClickable(Object info) { return AccessibilityNodeInfoCompatIcs.isLongClickable(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public boolean isPassword(Object info) { return AccessibilityNodeInfoCompatIcs.isPassword(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public boolean isScrollable(Object info) { return AccessibilityNodeInfoCompatIcs.isScrollable(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public boolean isSelected(Object info) { return AccessibilityNodeInfoCompatIcs.isSelected(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public boolean performAction(Object info, int action) { return AccessibilityNodeInfoCompatIcs.performAction(info, action); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setBoundsInParent(Object info, Rect bounds) { AccessibilityNodeInfoCompatIcs.setBoundsInParent(info, bounds); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setBoundsInScreen(Object info, Rect bounds) { AccessibilityNodeInfoCompatIcs.setBoundsInScreen(info, bounds); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setCheckable(Object info, boolean checkable) { AccessibilityNodeInfoCompatIcs.setCheckable(info, checkable); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setChecked(Object info, boolean checked) { AccessibilityNodeInfoCompatIcs.setChecked(info, checked); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setClassName(Object info, CharSequence className) { AccessibilityNodeInfoCompatIcs.setClassName(info, className); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setClickable(Object info, boolean clickable) { AccessibilityNodeInfoCompatIcs.setClickable(info, clickable); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setContentDescription(Object info, CharSequence contentDescription) { AccessibilityNodeInfoCompatIcs.setContentDescription(info, contentDescription); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setEnabled(Object info, boolean enabled) { AccessibilityNodeInfoCompatIcs.setEnabled(info, enabled); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setFocusable(Object info, boolean focusable) { AccessibilityNodeInfoCompatIcs.setFocusable(info, focusable); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setFocused(Object info, boolean focused) { AccessibilityNodeInfoCompatIcs.setFocused(info, focused); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setLongClickable(Object info, boolean longClickable) { AccessibilityNodeInfoCompatIcs.setLongClickable(info, longClickable); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setPackageName(Object info, CharSequence packageName) { AccessibilityNodeInfoCompatIcs.setPackageName(info, packageName); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setParent(Object info, View parent) { AccessibilityNodeInfoCompatIcs.setParent(info, parent); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setPassword(Object info, boolean password) { AccessibilityNodeInfoCompatIcs.setPassword(info, password); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setScrollable(Object info, boolean scrollable) { AccessibilityNodeInfoCompatIcs.setScrollable(info, scrollable); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setSelected(Object info, boolean selected) { AccessibilityNodeInfoCompatIcs.setSelected(info, selected); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setSource(Object info, View source) { AccessibilityNodeInfoCompatIcs.setSource(info, source); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setText(Object info, CharSequence text) { AccessibilityNodeInfoCompatIcs.setText(info, text); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void recycle(Object info) { AccessibilityNodeInfoCompatIcs.recycle(info); } } static class AccessibilityNodeInfoJellybeanImpl extends AccessibilityNodeInfoIcsImpl { AccessibilityNodeInfoJellybeanImpl() { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public Object obtain(View root, int virtualDescendantId) { return AccessibilityNodeInfoCompatJellyBean.obtain(root, virtualDescendantId); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public Object findFocus(Object info, int focus) { return AccessibilityNodeInfoCompatJellyBean.findFocus(info, focus); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public Object focusSearch(Object info, int direction) { return AccessibilityNodeInfoCompatJellyBean.focusSearch(info, direction); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void addChild(Object info, View child, int virtualDescendantId) { AccessibilityNodeInfoCompatJellyBean.addChild(info, child, virtualDescendantId); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setSource(Object info, View root, int virtualDescendantId) { AccessibilityNodeInfoCompatJellyBean.setSource(info, root, virtualDescendantId); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public boolean isVisibleToUser(Object info) { return AccessibilityNodeInfoCompatJellyBean.isVisibleToUser(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setVisibleToUser(Object info, boolean visibleToUser) { AccessibilityNodeInfoCompatJellyBean.setVisibleToUser(info, visibleToUser); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public boolean isAccessibilityFocused(Object info) { return AccessibilityNodeInfoCompatJellyBean.isAccessibilityFocused(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setAccessibilityFocused(Object info, boolean focused) { AccessibilityNodeInfoCompatJellyBean.setAccesibilityFocused(info, focused); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public boolean performAction(Object info, int action, Bundle arguments) { return AccessibilityNodeInfoCompatJellyBean.performAction(info, action, arguments); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setMovementGranularities(Object info, int granularities) { AccessibilityNodeInfoCompatJellyBean.setMovementGranularities(info, granularities); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public int getMovementGranularities(Object info) { return AccessibilityNodeInfoCompatJellyBean.getMovementGranularities(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setParent(Object info, View root, int virtualDescendantId) { AccessibilityNodeInfoCompatJellyBean.setParent(info, root, virtualDescendantId); } } static class AccessibilityNodeInfoJellybeanMr1Impl extends AccessibilityNodeInfoJellybeanImpl { AccessibilityNodeInfoJellybeanMr1Impl() { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setLabelFor(Object info, View labeled) { AccessibilityNodeInfoCompatJellybeanMr1.setLabelFor(info, labeled); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setLabelFor(Object info, View root, int virtualDescendantId) { AccessibilityNodeInfoCompatJellybeanMr1.setLabelFor(info, root, virtualDescendantId); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public Object getLabelFor(Object info) { return AccessibilityNodeInfoCompatJellybeanMr1.getLabelFor(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setLabeledBy(Object info, View labeled) { AccessibilityNodeInfoCompatJellybeanMr1.setLabeledBy(info, labeled); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setLabeledBy(Object info, View root, int virtualDescendantId) { AccessibilityNodeInfoCompatJellybeanMr1.setLabeledBy(info, root, virtualDescendantId); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public Object getLabeledBy(Object info) { return AccessibilityNodeInfoCompatJellybeanMr1.getLabeledBy(info); } } static class AccessibilityNodeInfoJellybeanMr2Impl extends AccessibilityNodeInfoJellybeanMr1Impl { AccessibilityNodeInfoJellybeanMr2Impl() { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public String getViewIdResourceName(Object info) { return AccessibilityNodeInfoCompatJellybeanMr2.getViewIdResourceName(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setViewIdResourceName(Object info, String viewId) { AccessibilityNodeInfoCompatJellybeanMr2.setViewIdResourceName(info, viewId); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public List<Object> findAccessibilityNodeInfosByViewId(Object info, String viewId) { return AccessibilityNodeInfoCompatJellybeanMr2.findAccessibilityNodeInfosByViewId(info, viewId); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setTextSelection(Object info, int start, int end) { AccessibilityNodeInfoCompatJellybeanMr2.setTextSelection(info, start, end); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public int getTextSelectionStart(Object info) { return AccessibilityNodeInfoCompatJellybeanMr2.getTextSelectionStart(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public int getTextSelectionEnd(Object info) { return AccessibilityNodeInfoCompatJellybeanMr2.getTextSelectionEnd(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public boolean isEditable(Object info) { return AccessibilityNodeInfoCompatJellybeanMr2.isEditable(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setEditable(Object info, boolean editable) { AccessibilityNodeInfoCompatJellybeanMr2.setEditable(info, editable); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public boolean refresh(Object info) { return AccessibilityNodeInfoCompatJellybeanMr2.refresh(info); } } static class AccessibilityNodeInfoKitKatImpl extends AccessibilityNodeInfoJellybeanMr2Impl { AccessibilityNodeInfoKitKatImpl() { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public int getLiveRegion(Object info) { return AccessibilityNodeInfoCompatKitKat.getLiveRegion(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setLiveRegion(Object info, int mode) { AccessibilityNodeInfoCompatKitKat.setLiveRegion(info, mode); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public Object getCollectionInfo(Object info) { return AccessibilityNodeInfoCompatKitKat.getCollectionInfo(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setCollectionInfo(Object info, Object collectionInfo) { AccessibilityNodeInfoCompatKitKat.setCollectionInfo(info, collectionInfo); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public Object obtainCollectionInfo(int rowCount, int columnCount, boolean hierarchical, int selectionMode) { return AccessibilityNodeInfoCompatKitKat.obtainCollectionInfo(rowCount, columnCount, hierarchical, selectionMode); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public Object obtainCollectionInfo(int rowCount, int columnCount, boolean hierarchical) { return AccessibilityNodeInfoCompatKitKat.obtainCollectionInfo(rowCount, columnCount, hierarchical); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public Object obtainCollectionItemInfo(int rowIndex, int rowSpan, int columnIndex, int columnSpan, boolean heading, boolean selected) { return AccessibilityNodeInfoCompatKitKat.obtainCollectionItemInfo(rowIndex, rowSpan, columnIndex, columnSpan, heading); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public Object obtainCollectionItemInfo(int rowIndex, int rowSpan, int columnIndex, int columnSpan, boolean heading) { return AccessibilityNodeInfoCompatKitKat.obtainCollectionItemInfo(rowIndex, rowSpan, columnIndex, columnSpan, heading); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public int getCollectionInfoColumnCount(Object info) { return AccessibilityNodeInfoCompatKitKat.CollectionInfo.getColumnCount(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public int getCollectionInfoRowCount(Object info) { return AccessibilityNodeInfoCompatKitKat.CollectionInfo.getRowCount(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public boolean isCollectionInfoHierarchical(Object info) { return AccessibilityNodeInfoCompatKitKat.CollectionInfo.isHierarchical(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public Object getCollectionItemInfo(Object info) { return AccessibilityNodeInfoCompatKitKat.getCollectionItemInfo(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public Object getRangeInfo(Object info) { return AccessibilityNodeInfoCompatKitKat.getRangeInfo(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setRangeInfo(Object info, Object rangeInfo) { AccessibilityNodeInfoCompatKitKat.setRangeInfo(info, rangeInfo); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public int getCollectionItemColumnIndex(Object info) { return AccessibilityNodeInfoCompatKitKat.CollectionItemInfo.getColumnIndex(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public int getCollectionItemColumnSpan(Object info) { return AccessibilityNodeInfoCompatKitKat.CollectionItemInfo.getColumnSpan(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public int getCollectionItemRowIndex(Object info) { return AccessibilityNodeInfoCompatKitKat.CollectionItemInfo.getRowIndex(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public int getCollectionItemRowSpan(Object info) { return AccessibilityNodeInfoCompatKitKat.CollectionItemInfo.getRowSpan(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public boolean isCollectionItemHeading(Object info) { return AccessibilityNodeInfoCompatKitKat.CollectionItemInfo.isHeading(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setCollectionItemInfo(Object info, Object collectionItemInfo) { AccessibilityNodeInfoCompatKitKat.setCollectionItemInfo(info, collectionItemInfo); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public Object obtainRangeInfo(int type, float min, float max, float current) { return AccessibilityNodeInfoCompatKitKat.obtainRangeInfo(type, min, max, current); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setContentInvalid(Object info, boolean contentInvalid) { AccessibilityNodeInfoCompatKitKat.setContentInvalid(info, contentInvalid); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public boolean isContentInvalid(Object info) { return AccessibilityNodeInfoCompatKitKat.isContentInvalid(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public boolean canOpenPopup(Object info) { return AccessibilityNodeInfoCompatKitKat.canOpenPopup(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setCanOpenPopup(Object info, boolean opensPopup) { AccessibilityNodeInfoCompatKitKat.setCanOpenPopup(info, opensPopup); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public Bundle getExtras(Object info) { return AccessibilityNodeInfoCompatKitKat.getExtras(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public int getInputType(Object info) { return AccessibilityNodeInfoCompatKitKat.getInputType(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setInputType(Object info, int inputType) { AccessibilityNodeInfoCompatKitKat.setInputType(info, inputType); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public boolean isDismissable(Object info) { return AccessibilityNodeInfoCompatKitKat.isDismissable(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setDismissable(Object info, boolean dismissable) { AccessibilityNodeInfoCompatKitKat.setDismissable(info, dismissable); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public boolean isMultiLine(Object info) { return AccessibilityNodeInfoCompatKitKat.isMultiLine(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setMultiLine(Object info, boolean multiLine) { AccessibilityNodeInfoCompatKitKat.setMultiLine(info, multiLine); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public CharSequence getRoleDescription(Object info) { return AccessibilityNodeInfoCompatKitKat.getRoleDescription(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setRoleDescription(Object info, CharSequence roleDescription) { AccessibilityNodeInfoCompatKitKat.setRoleDescription(info, roleDescription); } } static class AccessibilityNodeInfoApi21Impl extends AccessibilityNodeInfoKitKatImpl { AccessibilityNodeInfoApi21Impl() { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public Object newAccessibilityAction(int actionId, CharSequence label) { return AccessibilityNodeInfoCompatApi21.newAccessibilityAction(actionId, label); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public List<Object> getActionList(Object info) { return AccessibilityNodeInfoCompatApi21.getActionList(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoKitKatImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public Object obtainCollectionInfo(int rowCount, int columnCount, boolean hierarchical, int selectionMode) { return AccessibilityNodeInfoCompatApi21.obtainCollectionInfo(rowCount, columnCount, hierarchical, selectionMode); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void addAction(Object info, Object action) { AccessibilityNodeInfoCompatApi21.addAction(info, action); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public boolean removeAction(Object info, Object action) { return AccessibilityNodeInfoCompatApi21.removeAction(info, action); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public int getAccessibilityActionId(Object action) { return AccessibilityNodeInfoCompatApi21.getAccessibilityActionId(action); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public CharSequence getAccessibilityActionLabel(Object action) { return AccessibilityNodeInfoCompatApi21.getAccessibilityActionLabel(action); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoKitKatImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public Object obtainCollectionItemInfo(int rowIndex, int rowSpan, int columnIndex, int columnSpan, boolean heading, boolean selected) { return AccessibilityNodeInfoCompatApi21.obtainCollectionItemInfo(rowIndex, rowSpan, columnIndex, columnSpan, heading, selected); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public boolean isCollectionItemSelected(Object info) { return AccessibilityNodeInfoCompatApi21.CollectionItemInfo.isSelected(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public CharSequence getError(Object info) { return AccessibilityNodeInfoCompatApi21.getError(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setError(Object info, CharSequence error) { AccessibilityNodeInfoCompatApi21.setError(info, error); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setMaxTextLength(Object info, int max) { AccessibilityNodeInfoCompatApi21.setMaxTextLength(info, max); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public int getMaxTextLength(Object info) { return AccessibilityNodeInfoCompatApi21.getMaxTextLength(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public Object getWindow(Object info) { return AccessibilityNodeInfoCompatApi21.getWindow(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public boolean removeChild(Object info, View child) { return AccessibilityNodeInfoCompatApi21.removeChild(info, child); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public boolean removeChild(Object info, View root, int virtualDescendantId) { return AccessibilityNodeInfoCompatApi21.removeChild(info, root, virtualDescendantId); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public int getCollectionInfoSelectionMode(Object info) { return AccessibilityNodeInfoCompatApi21.CollectionInfo.getSelectionMode(info); } } static class AccessibilityNodeInfoApi22Impl extends AccessibilityNodeInfoApi21Impl { AccessibilityNodeInfoApi22Impl() { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public Object getTraversalBefore(Object info) { return AccessibilityNodeInfoCompatApi22.getTraversalBefore(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setTraversalBefore(Object info, View view) { AccessibilityNodeInfoCompatApi22.setTraversalBefore(info, view); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setTraversalBefore(Object info, View root, int virtualDescendantId) { AccessibilityNodeInfoCompatApi22.setTraversalBefore(info, root, virtualDescendantId); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public Object getTraversalAfter(Object info) { return AccessibilityNodeInfoCompatApi22.getTraversalAfter(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setTraversalAfter(Object info, View view) { AccessibilityNodeInfoCompatApi22.setTraversalAfter(info, view); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setTraversalAfter(Object info, View root, int virtualDescendantId) { AccessibilityNodeInfoCompatApi22.setTraversalAfter(info, root, virtualDescendantId); } } static class AccessibilityNodeInfoApi23Impl extends AccessibilityNodeInfoApi22Impl { AccessibilityNodeInfoApi23Impl() { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public Object getActionScrollToPosition() { return AccessibilityNodeInfoCompatApi23.getActionScrollToPosition(); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public Object getActionShowOnScreen() { return AccessibilityNodeInfoCompatApi23.getActionShowOnScreen(); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public Object getActionScrollUp() { return AccessibilityNodeInfoCompatApi23.getActionScrollUp(); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public Object getActionScrollDown() { return AccessibilityNodeInfoCompatApi23.getActionScrollDown(); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public Object getActionScrollLeft() { return AccessibilityNodeInfoCompatApi23.getActionScrollLeft(); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public Object getActionScrollRight() { return AccessibilityNodeInfoCompatApi23.getActionScrollRight(); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public Object getActionContextClick() { return AccessibilityNodeInfoCompatApi23.getActionContextClick(); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public boolean isContextClickable(Object info) { return AccessibilityNodeInfoCompatApi23.isContextClickable(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setContextClickable(Object info, boolean contextClickable) { AccessibilityNodeInfoCompatApi23.setContextClickable(info, contextClickable); } } static class AccessibilityNodeInfoApi24Impl extends AccessibilityNodeInfoApi23Impl { AccessibilityNodeInfoApi24Impl() { } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public Object getActionSetProgress() { return AccessibilityNodeInfoCompatApi24.getActionSetProgress(); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public int getDrawingOrder(Object info) { return AccessibilityNodeInfoCompatApi24.getDrawingOrder(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setDrawingOrder(Object info, int drawingOrderInParent) { AccessibilityNodeInfoCompatApi24.setDrawingOrder(info, drawingOrderInParent); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public boolean isImportantForAccessibility(Object info) { return AccessibilityNodeInfoCompatApi24.isImportantForAccessibility(info); } @Override // android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoImpl, android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityNodeInfoStubImpl public void setImportantForAccessibility(Object info, boolean importantForAccessibility) { AccessibilityNodeInfoCompatApi24.setImportantForAccessibility(info, importantForAccessibility); } } static { if (Build.VERSION.SDK_INT >= 24) { IMPL = new AccessibilityNodeInfoApi24Impl(); } else if (Build.VERSION.SDK_INT >= 23) { IMPL = new AccessibilityNodeInfoApi23Impl(); } else if (Build.VERSION.SDK_INT >= 22) { IMPL = new AccessibilityNodeInfoApi22Impl(); } else if (Build.VERSION.SDK_INT >= 21) { IMPL = new AccessibilityNodeInfoApi21Impl(); } else if (Build.VERSION.SDK_INT >= 19) { IMPL = new AccessibilityNodeInfoKitKatImpl(); } else if (Build.VERSION.SDK_INT >= 18) { IMPL = new AccessibilityNodeInfoJellybeanMr2Impl(); } else if (Build.VERSION.SDK_INT >= 17) { IMPL = new AccessibilityNodeInfoJellybeanMr1Impl(); } else if (Build.VERSION.SDK_INT >= 16) { IMPL = new AccessibilityNodeInfoJellybeanImpl(); } else if (Build.VERSION.SDK_INT >= 14) { IMPL = new AccessibilityNodeInfoIcsImpl(); } else { IMPL = new AccessibilityNodeInfoStubImpl(); } } static AccessibilityNodeInfoCompat wrapNonNullInstance(Object object) { if (object != null) { return new AccessibilityNodeInfoCompat(object); } return null; } public AccessibilityNodeInfoCompat(Object info) { this.mInfo = info; } public Object getInfo() { return this.mInfo; } public static AccessibilityNodeInfoCompat obtain(View source) { return wrapNonNullInstance(IMPL.obtain(source)); } public static AccessibilityNodeInfoCompat obtain(View root, int virtualDescendantId) { return wrapNonNullInstance(IMPL.obtain(root, virtualDescendantId)); } public static AccessibilityNodeInfoCompat obtain() { return wrapNonNullInstance(IMPL.obtain()); } public static AccessibilityNodeInfoCompat obtain(AccessibilityNodeInfoCompat info) { return wrapNonNullInstance(IMPL.obtain(info.mInfo)); } public void setSource(View source) { IMPL.setSource(this.mInfo, source); } public void setSource(View root, int virtualDescendantId) { IMPL.setSource(this.mInfo, root, virtualDescendantId); } public AccessibilityNodeInfoCompat findFocus(int focus) { return wrapNonNullInstance(IMPL.findFocus(this.mInfo, focus)); } public AccessibilityNodeInfoCompat focusSearch(int direction) { return wrapNonNullInstance(IMPL.focusSearch(this.mInfo, direction)); } public int getWindowId() { return IMPL.getWindowId(this.mInfo); } public int getChildCount() { return IMPL.getChildCount(this.mInfo); } public AccessibilityNodeInfoCompat getChild(int index) { return wrapNonNullInstance(IMPL.getChild(this.mInfo, index)); } public void addChild(View child) { IMPL.addChild(this.mInfo, child); } public void addChild(View root, int virtualDescendantId) { IMPL.addChild(this.mInfo, root, virtualDescendantId); } public boolean removeChild(View child) { return IMPL.removeChild(this.mInfo, child); } public boolean removeChild(View root, int virtualDescendantId) { return IMPL.removeChild(this.mInfo, root, virtualDescendantId); } public int getActions() { return IMPL.getActions(this.mInfo); } public void addAction(int action) { IMPL.addAction(this.mInfo, action); } public void addAction(AccessibilityActionCompat action) { IMPL.addAction(this.mInfo, action.mAction); } public boolean removeAction(AccessibilityActionCompat action) { return IMPL.removeAction(this.mInfo, action.mAction); } public boolean performAction(int action) { return IMPL.performAction(this.mInfo, action); } public boolean performAction(int action, Bundle arguments) { return IMPL.performAction(this.mInfo, action, arguments); } public void setMovementGranularities(int granularities) { IMPL.setMovementGranularities(this.mInfo, granularities); } public int getMovementGranularities() { return IMPL.getMovementGranularities(this.mInfo); } public List<AccessibilityNodeInfoCompat> findAccessibilityNodeInfosByText(String text) { List<AccessibilityNodeInfoCompat> result = new ArrayList<>(); List<Object> infos = IMPL.findAccessibilityNodeInfosByText(this.mInfo, text); int infoCount = infos.size(); for (int i = 0; i < infoCount; i++) { result.add(new AccessibilityNodeInfoCompat(infos.get(i))); } return result; } public AccessibilityNodeInfoCompat getParent() { return wrapNonNullInstance(IMPL.getParent(this.mInfo)); } public void setParent(View parent) { IMPL.setParent(this.mInfo, parent); } public void setParent(View root, int virtualDescendantId) { IMPL.setParent(this.mInfo, root, virtualDescendantId); } public void getBoundsInParent(Rect outBounds) { IMPL.getBoundsInParent(this.mInfo, outBounds); } public void setBoundsInParent(Rect bounds) { IMPL.setBoundsInParent(this.mInfo, bounds); } public void getBoundsInScreen(Rect outBounds) { IMPL.getBoundsInScreen(this.mInfo, outBounds); } public void setBoundsInScreen(Rect bounds) { IMPL.setBoundsInScreen(this.mInfo, bounds); } public boolean isCheckable() { return IMPL.isCheckable(this.mInfo); } public void setCheckable(boolean checkable) { IMPL.setCheckable(this.mInfo, checkable); } public boolean isChecked() { return IMPL.isChecked(this.mInfo); } public void setChecked(boolean checked) { IMPL.setChecked(this.mInfo, checked); } public boolean isFocusable() { return IMPL.isFocusable(this.mInfo); } public void setFocusable(boolean focusable) { IMPL.setFocusable(this.mInfo, focusable); } public boolean isFocused() { return IMPL.isFocused(this.mInfo); } public void setFocused(boolean focused) { IMPL.setFocused(this.mInfo, focused); } public boolean isVisibleToUser() { return IMPL.isVisibleToUser(this.mInfo); } public void setVisibleToUser(boolean visibleToUser) { IMPL.setVisibleToUser(this.mInfo, visibleToUser); } public boolean isAccessibilityFocused() { return IMPL.isAccessibilityFocused(this.mInfo); } public void setAccessibilityFocused(boolean focused) { IMPL.setAccessibilityFocused(this.mInfo, focused); } public boolean isSelected() { return IMPL.isSelected(this.mInfo); } public void setSelected(boolean selected) { IMPL.setSelected(this.mInfo, selected); } public boolean isClickable() { return IMPL.isClickable(this.mInfo); } public void setClickable(boolean clickable) { IMPL.setClickable(this.mInfo, clickable); } public boolean isLongClickable() { return IMPL.isLongClickable(this.mInfo); } public void setLongClickable(boolean longClickable) { IMPL.setLongClickable(this.mInfo, longClickable); } public boolean isEnabled() { return IMPL.isEnabled(this.mInfo); } public void setEnabled(boolean enabled) { IMPL.setEnabled(this.mInfo, enabled); } public boolean isPassword() { return IMPL.isPassword(this.mInfo); } public void setPassword(boolean password) { IMPL.setPassword(this.mInfo, password); } public boolean isScrollable() { return IMPL.isScrollable(this.mInfo); } public void setScrollable(boolean scrollable) { IMPL.setScrollable(this.mInfo, scrollable); } public boolean isImportantForAccessibility() { return IMPL.isImportantForAccessibility(this.mInfo); } public void setImportantForAccessibility(boolean important) { IMPL.setImportantForAccessibility(this.mInfo, important); } public CharSequence getPackageName() { return IMPL.getPackageName(this.mInfo); } public void setPackageName(CharSequence packageName) { IMPL.setPackageName(this.mInfo, packageName); } public CharSequence getClassName() { return IMPL.getClassName(this.mInfo); } public void setClassName(CharSequence className) { IMPL.setClassName(this.mInfo, className); } public CharSequence getText() { return IMPL.getText(this.mInfo); } public void setText(CharSequence text) { IMPL.setText(this.mInfo, text); } public CharSequence getContentDescription() { return IMPL.getContentDescription(this.mInfo); } public void setContentDescription(CharSequence contentDescription) { IMPL.setContentDescription(this.mInfo, contentDescription); } public void recycle() { IMPL.recycle(this.mInfo); } public void setViewIdResourceName(String viewId) { IMPL.setViewIdResourceName(this.mInfo, viewId); } public String getViewIdResourceName() { return IMPL.getViewIdResourceName(this.mInfo); } public int getLiveRegion() { return IMPL.getLiveRegion(this.mInfo); } public void setLiveRegion(int mode) { IMPL.setLiveRegion(this.mInfo, mode); } public int getDrawingOrder() { return IMPL.getDrawingOrder(this.mInfo); } public void setDrawingOrder(int drawingOrderInParent) { IMPL.setDrawingOrder(this.mInfo, drawingOrderInParent); } public CollectionInfoCompat getCollectionInfo() { Object info = IMPL.getCollectionInfo(this.mInfo); if (info == null) { return null; } return new CollectionInfoCompat(info); } public void setCollectionInfo(Object collectionInfo) { IMPL.setCollectionInfo(this.mInfo, ((CollectionInfoCompat) collectionInfo).mInfo); } public void setCollectionItemInfo(Object collectionItemInfo) { IMPL.setCollectionItemInfo(this.mInfo, ((CollectionItemInfoCompat) collectionItemInfo).mInfo); } public CollectionItemInfoCompat getCollectionItemInfo() { Object info = IMPL.getCollectionItemInfo(this.mInfo); if (info == null) { return null; } return new CollectionItemInfoCompat(info); } public RangeInfoCompat getRangeInfo() { Object info = IMPL.getRangeInfo(this.mInfo); if (info == null) { return null; } return new RangeInfoCompat(info); } public void setRangeInfo(RangeInfoCompat rangeInfo) { IMPL.setRangeInfo(this.mInfo, rangeInfo.mInfo); } public List<AccessibilityActionCompat> getActionList() { List<Object> actions = IMPL.getActionList(this.mInfo); if (actions == null) { return Collections.emptyList(); } List<AccessibilityActionCompat> result = new ArrayList<>(); int actionCount = actions.size(); for (int i = 0; i < actionCount; i++) { result.add(new AccessibilityActionCompat(actions.get(i))); } return result; } public void setContentInvalid(boolean contentInvalid) { IMPL.setContentInvalid(this.mInfo, contentInvalid); } public boolean isContentInvalid() { return IMPL.isContentInvalid(this.mInfo); } public boolean isContextClickable() { return IMPL.isContextClickable(this.mInfo); } public void setContextClickable(boolean contextClickable) { IMPL.setContextClickable(this.mInfo, contextClickable); } public void setError(CharSequence error) { IMPL.setError(this.mInfo, error); } public CharSequence getError() { return IMPL.getError(this.mInfo); } public void setLabelFor(View labeled) { IMPL.setLabelFor(this.mInfo, labeled); } public void setLabelFor(View root, int virtualDescendantId) { IMPL.setLabelFor(this.mInfo, root, virtualDescendantId); } public AccessibilityNodeInfoCompat getLabelFor() { return wrapNonNullInstance(IMPL.getLabelFor(this.mInfo)); } public void setLabeledBy(View label) { IMPL.setLabeledBy(this.mInfo, label); } public void setLabeledBy(View root, int virtualDescendantId) { IMPL.setLabeledBy(this.mInfo, root, virtualDescendantId); } public AccessibilityNodeInfoCompat getLabeledBy() { return wrapNonNullInstance(IMPL.getLabeledBy(this.mInfo)); } public boolean canOpenPopup() { return IMPL.canOpenPopup(this.mInfo); } public void setCanOpenPopup(boolean opensPopup) { IMPL.setCanOpenPopup(this.mInfo, opensPopup); } public List<AccessibilityNodeInfoCompat> findAccessibilityNodeInfosByViewId(String viewId) { List<Object> nodes = IMPL.findAccessibilityNodeInfosByViewId(this.mInfo, viewId); if (nodes == null) { return Collections.emptyList(); } List<AccessibilityNodeInfoCompat> result = new ArrayList<>(); for (Object node : nodes) { result.add(new AccessibilityNodeInfoCompat(node)); } return result; } public Bundle getExtras() { return IMPL.getExtras(this.mInfo); } public int getInputType() { return IMPL.getInputType(this.mInfo); } public void setInputType(int inputType) { IMPL.setInputType(this.mInfo, inputType); } public void setMaxTextLength(int max) { IMPL.setMaxTextLength(this.mInfo, max); } public int getMaxTextLength() { return IMPL.getMaxTextLength(this.mInfo); } public void setTextSelection(int start, int end) { IMPL.setTextSelection(this.mInfo, start, end); } public int getTextSelectionStart() { return IMPL.getTextSelectionStart(this.mInfo); } public int getTextSelectionEnd() { return IMPL.getTextSelectionEnd(this.mInfo); } public AccessibilityNodeInfoCompat getTraversalBefore() { return wrapNonNullInstance(IMPL.getTraversalBefore(this.mInfo)); } public void setTraversalBefore(View view) { IMPL.setTraversalBefore(this.mInfo, view); } public void setTraversalBefore(View root, int virtualDescendantId) { IMPL.setTraversalBefore(this.mInfo, root, virtualDescendantId); } public AccessibilityNodeInfoCompat getTraversalAfter() { return wrapNonNullInstance(IMPL.getTraversalAfter(this.mInfo)); } public void setTraversalAfter(View view) { IMPL.setTraversalAfter(this.mInfo, view); } public void setTraversalAfter(View root, int virtualDescendantId) { IMPL.setTraversalAfter(this.mInfo, root, virtualDescendantId); } public AccessibilityWindowInfoCompat getWindow() { return AccessibilityWindowInfoCompat.wrapNonNullInstance(IMPL.getWindow(this.mInfo)); } public boolean isDismissable() { return IMPL.isDismissable(this.mInfo); } public void setDismissable(boolean dismissable) { IMPL.setDismissable(this.mInfo, dismissable); } public boolean isEditable() { return IMPL.isEditable(this.mInfo); } public void setEditable(boolean editable) { IMPL.setEditable(this.mInfo, editable); } public boolean isMultiLine() { return IMPL.isMultiLine(this.mInfo); } public void setMultiLine(boolean multiLine) { IMPL.setMultiLine(this.mInfo, multiLine); } public boolean refresh() { return IMPL.refresh(this.mInfo); } @Nullable public CharSequence getRoleDescription() { return IMPL.getRoleDescription(this.mInfo); } public void setRoleDescription(@Nullable CharSequence roleDescription) { IMPL.setRoleDescription(this.mInfo, roleDescription); } public int hashCode() { if (this.mInfo == null) { return 0; } return this.mInfo.hashCode(); } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } AccessibilityNodeInfoCompat other = (AccessibilityNodeInfoCompat) obj; return this.mInfo == null ? other.mInfo == null : this.mInfo.equals(other.mInfo); } public String toString() { StringBuilder builder = new StringBuilder(); builder.append(super.toString()); Rect bounds = new Rect(); getBoundsInParent(bounds); builder.append("; boundsInParent: " + bounds); getBoundsInScreen(bounds); builder.append("; boundsInScreen: " + bounds); builder.append("; packageName: ").append(getPackageName()); builder.append("; className: ").append(getClassName()); builder.append("; text: ").append(getText()); builder.append("; contentDescription: ").append(getContentDescription()); builder.append("; viewId: ").append(getViewIdResourceName()); builder.append("; checkable: ").append(isCheckable()); builder.append("; checked: ").append(isChecked()); builder.append("; focusable: ").append(isFocusable()); builder.append("; focused: ").append(isFocused()); builder.append("; selected: ").append(isSelected()); builder.append("; clickable: ").append(isClickable()); builder.append("; longClickable: ").append(isLongClickable()); builder.append("; enabled: ").append(isEnabled()); builder.append("; password: ").append(isPassword()); builder.append("; scrollable: " + isScrollable()); builder.append("; ["); int actionBits = getActions(); while (actionBits != 0) { int action = 1 << Integer.numberOfTrailingZeros(actionBits); actionBits &= action ^ -1; builder.append(getActionSymbolicName(action)); if (actionBits != 0) { builder.append(", "); } } builder.append("]"); return builder.toString(); } private static String getActionSymbolicName(int action) { switch (action) { case 1: return "ACTION_FOCUS"; case 2: return "ACTION_CLEAR_FOCUS"; case 4: return "ACTION_SELECT"; case 8: return "ACTION_CLEAR_SELECTION"; case 16: return "ACTION_CLICK"; case 32: return "ACTION_LONG_CLICK"; case 64: return "ACTION_ACCESSIBILITY_FOCUS"; case 128: return "ACTION_CLEAR_ACCESSIBILITY_FOCUS"; case 256: return "ACTION_NEXT_AT_MOVEMENT_GRANULARITY"; case 512: return "ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY"; case 1024: return "ACTION_NEXT_HTML_ELEMENT"; case 2048: return "ACTION_PREVIOUS_HTML_ELEMENT"; case 4096: return "ACTION_SCROLL_FORWARD"; case 8192: return "ACTION_SCROLL_BACKWARD"; case 16384: return "ACTION_COPY"; case 32768: return "ACTION_PASTE"; case 65536: return "ACTION_CUT"; case 131072: return "ACTION_SET_SELECTION"; default: return "ACTION_UNKNOWN"; } } }
43,776
1,724
<reponame>Rix565/skiftos-dailybuild { "name": "Terminal", "comment": "An ansi capable terminal emulator.", "icon": "console", "command": "terminal" }
66
548
# Copyright 2019 ZTE corporation. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 from typing import Any, Mapping, NamedTuple, Optional, Sequence import onnx import onnx.utils from . import repository from .. import utilities from ..models.data_format import DataFormat from ..models.irs.onnx_model import OnnxModel from ..models.sources.onnx_model_file import ONNXModelFile class Config(NamedTuple): input_formats: Sequence[Optional[DataFormat]] @staticmethod def from_json(value: Mapping[str, Any]) -> 'Config': return Config(input_formats=utilities.get_data_formats(value.get('input_formats'))) @staticmethod def from_env(env: Mapping[str, str]) -> 'Config': return Config(input_formats=utilities.get_data_formats(utilities.split_by(env.get('INPUT_FORMATS'), ','))) @repository.REPOSITORY.register(source_type=ONNXModelFile, target_type=OnnxModel, config_type=Config) def compile_source(source: ONNXModelFile, config: Config) -> OnnxModel: model = onnx.load(source.model_path) graph = model.graph # pylint: disable=no-member return OnnxModel(model_proto=model, input_data_formats=utilities.get_onnx_model_input_data_formats(graph, config.input_formats))
456
1,544
<gh_stars>1000+ """ Scripts for the in-game Python system. """ from datetime import datetime, timedelta from queue import Queue import re import sys import traceback from django.conf import settings from evennia import DefaultObject, DefaultScript, ChannelDB, ScriptDB from evennia import logger, ObjectDB from evennia.utils.ansi import raw from evennia.utils.create import create_channel from evennia.utils.dbserialize import dbserialize from evennia.utils.utils import all_from_module, delay, pypath_to_realpath from evennia.contrib.ingame_python.callbackhandler import CallbackHandler from evennia.contrib.ingame_python.utils import get_next_wait, EVENTS, InterruptEvent # Constants RE_LINE_ERROR = re.compile(r'^ File "\<string\>", line (\d+)') class EventHandler(DefaultScript): """ The event handler that contains all events in a global script. This script shouldn't be created more than once. It contains event (in a non-persistent attribute) and callbacks (in a persistent attribute). The script method would help adding, editing and deleting these events and callbacks. """ def at_script_creation(self): """Hook called when the script is created.""" self.key = "event_handler" self.desc = "Global event handler" self.persistent = True # Permanent data to be stored self.db.callbacks = {} self.db.to_valid = [] self.db.locked = [] # Tasks self.db.tasks = {} def at_start(self): """Set up the event system when starting. Note that this hook is called every time the server restarts (including when it's reloaded). This hook performs the following tasks: - Create temporarily stored events. - Generate locals (individual events' namespace). - Load eventfuncs, including user-defined ones. - Re-schedule tasks that aren't set to fire anymore. - Effectively connect the handler to the main script. """ self.ndb.events = {} for typeclass, name, variables, help_text, custom_call, custom_add in EVENTS: self.add_event(typeclass, name, variables, help_text, custom_call, custom_add) # Generate locals self.ndb.current_locals = {} self.ndb.fresh_locals = {} addresses = ["evennia.contrib.ingame_python.eventfuncs"] addresses.extend(getattr(settings, "EVENTFUNCS_LOCATIONS", ["world.eventfuncs"])) for address in addresses: if pypath_to_realpath(address): self.ndb.fresh_locals.update(all_from_module(address)) # Restart the delayed tasks now = datetime.now() for task_id, definition in tuple(self.db.tasks.items()): future, obj, event_name, locals = definition seconds = (future - now).total_seconds() if seconds < 0: seconds = 0 delay(seconds, complete_task, task_id) # Place the script in the CallbackHandler from evennia.contrib.ingame_python import typeclasses CallbackHandler.script = self DefaultObject.callbacks = typeclasses.EventObject.callbacks # Create the channel if non-existent try: self.ndb.channel = ChannelDB.objects.get(db_key="everror") except ChannelDB.DoesNotExist: self.ndb.channel = create_channel( "everror", desc="Event errors", locks="control:false();listen:perm(Builders);send:false()", ) def get_events(self, obj): """ Return a dictionary of events on this object. Args: obj (Object or typeclass): the connected object or a general typeclass. Returns: A dictionary of the object's events. Notes: Events would define what the object can have as callbacks. Note, however, that chained callbacks will not appear in events and are handled separately. You can also request the events of a typeclass, not a connected object. This is useful to get the global list of events for a typeclass that has no object yet. """ events = {} all_events = self.ndb.events classes = Queue() if isinstance(obj, type): classes.put(obj) else: classes.put(type(obj)) invalid = [] while not classes.empty(): typeclass = classes.get() typeclass_name = typeclass.__module__ + "." + typeclass.__name__ for key, etype in all_events.get(typeclass_name, {}).items(): if key in invalid: continue if etype[0] is None: # Invalidate invalid.append(key) continue if key not in events: events[key] = etype # Look for the parent classes for parent in typeclass.__bases__: classes.put(parent) return events def get_variable(self, variable_name): """ Return the variable defined in the locals. This can be very useful to check the value of a variable that can be modified in an event, and whose value will be used in code. This system allows additional customization. Args: variable_name (str): the name of the variable to return. Returns: The variable if found in the locals. None if not found in the locals. Note: This will return the variable from the current locals. Keep in mind that locals are shared between events. As every event is called one by one, this doesn't pose additional problems if you get the variable right after an event has been executed. If, however, you differ, there's no guarantee the variable will be here or will mean the same thing. """ return self.ndb.current_locals.get(variable_name) def get_callbacks(self, obj): """ Return a dictionary of the object's callbacks. Args: obj (Object): the connected objects. Returns: A dictionary of the object's callbacks. Note: This method can be useful to override in some contexts, when several objects would share callbacks. """ obj_callbacks = self.db.callbacks.get(obj, {}) callbacks = {} for callback_name, callback_list in obj_callbacks.items(): new_list = [] for i, callback in enumerate(callback_list): callback = dict(callback) callback["obj"] = obj callback["name"] = callback_name callback["number"] = i new_list.append(callback) if new_list: callbacks[callback_name] = new_list return callbacks def add_callback(self, obj, callback_name, code, author=None, valid=False, parameters=""): """ Add the specified callback. Args: obj (Object): the Evennia typeclassed object to be extended. callback_name (str): the name of the callback to add. code (str): the Python code associated with this callback. author (Character or Account, optional): the author of the callback. valid (bool, optional): should the callback be connected? parameters (str, optional): optional parameters. Note: This method doesn't check that the callback type exists. """ obj_callbacks = self.db.callbacks.get(obj, {}) if not obj_callbacks: self.db.callbacks[obj] = {} obj_callbacks = self.db.callbacks[obj] callbacks = obj_callbacks.get(callback_name, []) if not callbacks: obj_callbacks[callback_name] = [] callbacks = obj_callbacks[callback_name] # Add the callback in the list callbacks.append( { "created_on": datetime.now(), "author": author, "valid": valid, "code": code, "parameters": parameters, } ) # If not valid, set it in 'to_valid' if not valid: self.db.to_valid.append((obj, callback_name, len(callbacks) - 1)) # Call the custom_add if needed custom_add = self.get_events(obj).get(callback_name, [None, None, None, None])[3] if custom_add: custom_add(obj, callback_name, len(callbacks) - 1, parameters) # Build the definition to return (a dictionary) definition = dict(callbacks[-1]) definition["obj"] = obj definition["name"] = callback_name definition["number"] = len(callbacks) - 1 return definition def edit_callback(self, obj, callback_name, number, code, author=None, valid=False): """ Edit the specified callback. Args: obj (Object): the Evennia typeclassed object to be edited. callback_name (str): the name of the callback to edit. number (int): the callback number to be changed. code (str): the Python code associated with this callback. author (Character or Account, optional): the author of the callback. valid (bool, optional): should the callback be connected? Raises: RuntimeError if the callback is locked. Note: This method doesn't check that the callback type exists. """ obj_callbacks = self.db.callbacks.get(obj, {}) if not obj_callbacks: self.db.callbacks[obj] = {} obj_callbacks = self.db.callbacks[obj] callbacks = obj_callbacks.get(callback_name, []) if not callbacks: obj_callbacks[callback_name] = [] callbacks = obj_callbacks[callback_name] # If locked, don't edit it if (obj, callback_name, number) in self.db.locked: raise RuntimeError("this callback is locked.") # Edit the callback callbacks[number].update( {"updated_on": datetime.now(), "updated_by": author, "valid": valid, "code": code} ) # If not valid, set it in 'to_valid' if not valid and (obj, callback_name, number) not in self.db.to_valid: self.db.to_valid.append((obj, callback_name, number)) elif valid and (obj, callback_name, number) in self.db.to_valid: self.db.to_valid.remove((obj, callback_name, number)) # Build the definition to return (a dictionary) definition = dict(callbacks[number]) definition["obj"] = obj definition["name"] = callback_name definition["number"] = number return definition def del_callback(self, obj, callback_name, number): """ Delete the specified callback. Args: obj (Object): the typeclassed object containing the callback. callback_name (str): the name of the callback to delete. number (int): the number of the callback to delete. Raises: RuntimeError if the callback is locked. """ obj_callbacks = self.db.callbacks.get(obj, {}) callbacks = obj_callbacks.get(callback_name, []) # If locked, don't edit it if (obj, callback_name, number) in self.db.locked: raise RuntimeError("this callback is locked.") # Delete the callback itself try: code = callbacks[number]["code"] except IndexError: return else: logger.log_info( "Deleting callback {} {} of {}:\n{}".format(callback_name, number, obj, code) ) del callbacks[number] # Change IDs of callbacks to be validated i = 0 while i < len(self.db.to_valid): t_obj, t_callback_name, t_number = self.db.to_valid[i] if obj is t_obj and callback_name == t_callback_name: if t_number == number: # Strictly equal, delete the callback del self.db.to_valid[i] i -= 1 elif t_number > number: # Change the ID for this callback self.db.to_valid.insert(i, (t_obj, t_callback_name, t_number - 1)) del self.db.to_valid[i + 1] i += 1 # Update locked callback for i, line in enumerate(self.db.locked): t_obj, t_callback_name, t_number = line if obj is t_obj and callback_name == t_callback_name: if number < t_number: self.db.locked[i] = (t_obj, t_callback_name, t_number - 1) # Delete time-related callbacks associated with this object for script in obj.scripts.all(): if isinstance(script, TimecallbackScript): if script.obj is obj and script.db.callback_name == callback_name: if script.db.number == number: script.stop() elif script.db.number > number: script.db.number -= 1 def accept_callback(self, obj, callback_name, number): """ Valid a callback. Args: obj (Object): the object containing the callback. callback_name (str): the name of the callback. number (int): the number of the callback. """ obj_callbacks = self.db.callbacks.get(obj, {}) callbacks = obj_callbacks.get(callback_name, []) # Accept and connect the callback callbacks[number].update({"valid": True}) if (obj, callback_name, number) in self.db.to_valid: self.db.to_valid.remove((obj, callback_name, number)) def call(self, obj, callback_name, *args, **kwargs): """ Call the connected callbacks. Args: obj (Object): the Evennia typeclassed object. callback_name (str): the callback name to call. *args: additional variables for this callback. Keyword Args: number (int, optional): call just a specific callback. parameters (str, optional): call a callback with parameters. locals (dict, optional): a locals replacement. Returns: True to report the callback was called without interruption, False otherwise. """ # First, look for the callback type corresponding to this name number = kwargs.get("number") parameters = kwargs.get("parameters") locals = kwargs.get("locals") # Errors should not pass silently allowed = ("number", "parameters", "locals") if any(k for k in kwargs if k not in allowed): raise TypeError( "Unknown keyword arguments were specified " "to call callbacks: {}".format(kwargs) ) event = self.get_events(obj).get(callback_name) if locals is None and not event: logger.log_err( "The callback {} for the object {} (typeclass " "{}) can't be found".format(callback_name, obj, type(obj)) ) return False # Prepare the locals if necessary if locals is None: locals = self.ndb.fresh_locals.copy() for i, variable in enumerate(event[0]): try: locals[variable] = args[i] except IndexError: logger.log_trace( "callback {} of {} ({}): need variable " "{} in position {}".format(callback_name, obj, type(obj), variable, i) ) return False else: locals = {key: value for key, value in locals.items()} callbacks = self.get_callbacks(obj).get(callback_name, []) if event: custom_call = event[2] if custom_call: callbacks = custom_call(callbacks, parameters) # Now execute all the valid callbacks linked at this address self.ndb.current_locals = locals for i, callback in enumerate(callbacks): if not callback["valid"]: continue if number is not None and callback["number"] != number: continue try: exec(callback["code"], locals, locals) except InterruptEvent: return False except Exception: etype, evalue, tb = sys.exc_info() trace = traceback.format_exception(etype, evalue, tb) self.handle_error(callback, trace) return True def handle_error(self, callback, trace): """ Handle an error in a callback. Args: callback (dict): the callback representation. trace (list): the traceback containing the exception. Notes: This method can be useful to override to change the default handling of errors. By default, the error message is sent to the character who last updated the callback, if connected. If not, display to the everror channel. """ callback_name = callback["name"] number = callback["number"] obj = callback["obj"] oid = obj.id logger.log_err( "An error occurred during the callback {} of " "{} (#{}), number {}\n{}".format(callback_name, obj, oid, number + 1, "\n".join(trace)) ) # Create the error message line = "|runknown|n" lineno = "|runknown|n" for error in trace: if error.startswith(' File "<string>", line '): res = RE_LINE_ERROR.search(error) if res: lineno = int(res.group(1)) # Try to extract the line try: line = raw(callback["code"].splitlines()[lineno - 1]) except IndexError: continue else: break exc = raw(trace[-1].strip("\n").splitlines()[-1]) err_msg = "Error in {} of {} (#{})[{}], line {}:" " {}\n{}".format( callback_name, obj, oid, number + 1, lineno, line, exc ) # Inform the last updater if connected updater = callback.get("updated_by") if updater is None: updater = callback["created_by"] if updater and updater.sessions.all(): updater.msg(err_msg) else: err_msg = "Error in {} of {} (#{})[{}], line {}:" " {}\n {}".format( callback_name, obj, oid, number + 1, lineno, line, exc ) self.ndb.channel.msg(err_msg) def add_event(self, typeclass, name, variables, help_text, custom_call, custom_add): """ Add a new event for a defined typeclass. Args: typeclass (str): the path leading to the typeclass. name (str): the name of the event to add. variables (list of str): list of variable names for this event. help_text (str): the long help text of the event. custom_call (callable or None): the function to be called when the event fires. custom_add (callable or None): the function to be called when a callback is added. """ if typeclass not in self.ndb.events: self.ndb.events[typeclass] = {} events = self.ndb.events[typeclass] if name not in events: events[name] = (variables, help_text, custom_call, custom_add) def set_task(self, seconds, obj, callback_name): """ Set and schedule a task to run. Args: seconds (int, float): the delay in seconds from now. obj (Object): the typecalssed object connected to the event. callback_name (str): the callback's name. Notes: This method allows to schedule a "persistent" task. 'utils.delay' is called, but a copy of the task is kept in the event handler, and when the script restarts (after reload), the differed delay is called again. The dictionary of locals is frozen and will be available again when the task runs. This feature, however, is limited by the database: all data cannot be saved. Lambda functions, class methods, objects inside an instance and so on will not be kept in the locals dictionary. """ now = datetime.now() delta = timedelta(seconds=seconds) # Choose a free task_id used_ids = list(self.db.tasks.keys()) task_id = 1 while task_id in used_ids: task_id += 1 # Collect and freeze current locals locals = {} for key, value in self.ndb.current_locals.items(): try: dbserialize(value) except TypeError: continue else: locals[key] = value self.db.tasks[task_id] = (now + delta, obj, callback_name, locals) delay(seconds, complete_task, task_id) # Script to call time-related events class TimeEventScript(DefaultScript): """Gametime-sensitive script.""" def at_script_creation(self): """The script is created.""" self.start_delay = True self.persistent = True # Script attributes self.db.time_format = None self.db.event_name = "time" self.db.number = None def at_repeat(self): """ Call the event and reset interval. It is necessary to restart the script to reset its interval only twice after a reload. When the script has undergone down time, there's usually a slight shift in game time. Once the script restarts once, it will set the average time it needs for all its future intervals and should not need to be restarted. In short, a script that is created shouldn't need to restart more than once, and a script that is reloaded should restart only twice. """ if self.db.time_format: # If the 'usual' time is set, use it seconds = self.ndb.usual if seconds is None: seconds, usual, details = get_next_wait(self.db.time_format) self.ndb.usual = usual if self.interval != seconds: self.restart(interval=seconds) if self.db.event_name and self.db.number is not None: obj = self.obj if not obj.callbacks: return event_name = self.db.event_name number = self.db.number obj.callbacks.call(event_name, obj, number=number) # Functions to manipulate tasks def complete_task(task_id): """ Mark the task in the event handler as complete. Args: task_id (int): the task ID. Note: This function should be called automatically for individual tasks. """ try: script = ScriptDB.objects.get(db_key="event_handler") except ScriptDB.DoesNotExist: logger.log_trace("Can't get the event handler.") return if task_id not in script.db.tasks: logger.log_err("The task #{} was scheduled, but it cannot be " "found".format(task_id)) return delta, obj, callback_name, locals = script.db.tasks.pop(task_id) script.call(obj, callback_name, locals=locals)
10,540
391
# # Copyright (C) 2020 IBM. All Rights Reserved. # # See LICENSE.txt file in the root directory # of this source tree for licensing information. # from unittest import mock from unittest.mock import Mock from test.mock_executor import MockExecutor from test.state_mother import clai_plugins_state, clai_select_state, command_state, COMMAND_AGENT_STATE, \ COMMAND_NAME_AGENT_STATE import pytest from clai.server.message_handler import MessageHandler from clai.datasource.server_status_datasource import ServerStatusDatasource from clai.server.clai_message_builder import create_error_select from clai.server.command_runner.agent_descriptor import AgentDescriptor from clai.datasource.config_storage import ConfigStorage from clai.datasource.model.plugin_config import PluginConfig from clai.server.agent import Agent from clai.server.agent_datasource import AgentDatasource from clai.server.command_message import Action, NOOP_COMMAND from clai.tools.colorize_console import Colorize NO_SELECTED = PluginConfig(default_orchestrator="max_orchestrator") ALL_PLUGINS = [AgentDescriptor(pkg_name="demo_agent", name="demo_agent"), AgentDescriptor(pkg_name="nlc2cmd", name="nlc2cmd")] ALL_PLUGINS_WITH_TAR_INSTALLED = [ AgentDescriptor(pkg_name="demo_agent", name="demo_agent", installed=True), AgentDescriptor(pkg_name="nlc2cmd", name="nlc2cmd", installed=True)] def get_printable_name(plugin: AgentDescriptor): composed_name = f"{plugin.name} " if plugin.installed: composed_name = composed_name + "(Installed)" else: composed_name = composed_name + "(Not Installed)" return composed_name def expected_description(all_plugins, selected) -> str: text = 'Available Skills:\n' for plugin in all_plugins: if plugin.pkg_name in selected: text += Colorize().emoji(Colorize.EMOJI_CHECK).complete() \ .append(f" {get_printable_name(plugin)}\n") \ .to_console() else: text += Colorize().emoji(Colorize.EMOJI_BOX) \ .append(f' {get_printable_name(plugin)}\n') \ .to_console() return text def create_mock_agent() -> Agent: agent = Mock(spec=Agent) agent.agent_name = "demo_agent" return agent @pytest.yield_fixture(scope='session', autouse=True) def mock_executor(): with mock.patch('clai.server.agent_runner.agent_executor', MockExecutor()) as _fixture: yield _fixture def test_should_return_the_list_of_plugins_with_default_selected_when_the_server_received_plugins_no_selected(mocker): mock_agent = create_mock_agent() mocker.patch.object(AgentDatasource, 'get_instances', return_value=[mock_agent], autospec=True) mocker.patch.object(ConfigStorage, 'read_config', return_value=NO_SELECTED, autospec=True) mocker.patch.object(AgentDatasource, 'all_plugins', return_value=ALL_PLUGINS, autospec=True) message_handler = MessageHandler(ServerStatusDatasource(), AgentDatasource()) action = message_handler.process_message(clai_plugins_state()) assert action.suggested_command == NOOP_COMMAND assert action.origin_command == 'clai skills' assert action.execute assert action.description == expected_description(ALL_PLUGINS, NO_SELECTED.default) def test_should_return_the_list_of_plugins_with_selected_when_the_server_received_plugins(mocker): mock_agent = create_mock_agent() mocker.patch.object(AgentDatasource, 'get_instances', return_value=[mock_agent], autospec=True) agent_selected = 'nlc2cmd' mocker.patch.object(AgentDatasource, 'all_plugins', return_value=ALL_PLUGINS, autospec=True) mocker.patch.object(ConfigStorage, 'read_all_user_config', return_value=None, autospec=True) mocker.patch.object( ConfigStorage, 'read_config', return_value=PluginConfig( selected=[agent_selected], default_orchestrator="max_orchestrator"), autospec=True) message_handler = MessageHandler(ServerStatusDatasource(), AgentDatasource()) action = message_handler.process_message(clai_plugins_state()) assert action.suggested_command == NOOP_COMMAND assert action.origin_command == 'clai skills' assert action.execute assert action.description == expected_description(ALL_PLUGINS, agent_selected) def test_should_return_the_list_without_any_selected_plugin_when_default_doesnt_exist(mocker): mock_agent = create_mock_agent() mocker.patch.object(AgentDatasource, 'get_instances', return_value=[mock_agent], autospec=True) mocker.patch.object(AgentDatasource, 'all_plugins', return_value=ALL_PLUGINS, autospec=True) mocker.patch.object(ConfigStorage, 'read_config', return_value=PluginConfig( default="", default_orchestrator="max_orchestrator"), autospec=True) message_handler = MessageHandler(ServerStatusDatasource(), AgentDatasource()) action = message_handler.process_message(clai_plugins_state()) assert action.suggested_command == NOOP_COMMAND assert action.origin_command == 'clai skills' assert action.execute assert action.description == expected_description(ALL_PLUGINS, '') def test_should_return_the_install_command_when_the_new_plugin_is_not_installed_yet(mocker): mock_agent = create_mock_agent() mocker.patch.object(AgentDatasource, 'get_instances', return_value=[mock_agent], autospec=True) mocker.patch.object(ConfigStorage, 'read_config', return_value=PluginConfig( selected=["nlc2cmd"], default_orchestrator="max_orchestrator"), autospec=True) mocker.patch.object(ConfigStorage, 'store_config', return_value=None, autospec=True) mocker.patch.object(AgentDatasource, 'all_plugins', return_value=ALL_PLUGINS, autospec=True) message_handler = MessageHandler(ServerStatusDatasource(), AgentDatasource()) select_agent = clai_select_state('nlc2cmd') action = message_handler.process_message(select_agent) assert action.suggested_command == "$CLAI_PATH/fileExist.sh nlc2cmd $CLAI_PATH" assert action.origin_command == select_agent.command assert message_handler.agent_datasource.get_current_plugin_name(select_agent.user_name) == ['nlc2cmd'] def test_should_return_the_list_with_the_new_selected_values_if_exists_and_is_installed(mocker): mock_agent = create_mock_agent() mocker.patch.object(AgentDatasource, 'get_instances', return_value=[mock_agent], autospec=True) mocker.patch.object(ConfigStorage, 'read_config', return_value=PluginConfig( selected=["demo_agent"], default_orchestrator="max_orchestrator"), autospec=True) mocker.patch.object(ConfigStorage, 'store_config', return_value=None, autospec=True) mocker.patch.object(AgentDatasource, 'all_plugins', return_value=ALL_PLUGINS_WITH_TAR_INSTALLED, autospec=True) message_handler = MessageHandler(ServerStatusDatasource(), AgentDatasource()) select_agent = clai_select_state('nlc2cmd') action = message_handler.process_message(select_agent) assert action.suggested_command == NOOP_COMMAND assert action.origin_command == select_agent.command assert action.execute assert message_handler.agent_datasource.get_current_plugin_name(select_agent.user_name) == ['nlc2cmd'] def test_should_return_an_error_when_agent_doesnt_exist(mocker): mock_agent = create_mock_agent() mocker.patch.object(AgentDatasource, 'get_instances', return_value=[mock_agent], autospec=True) mocker.patch.object(AgentDatasource, 'all_plugins', return_value=ALL_PLUGINS, autospec=True) mocker.patch.object(ConfigStorage, 'read_config', return_value=PluginConfig( selected=["nlc2cmd"], default_orchestrator="max_orchestrator"), autospec=True) mocker.patch.object(ConfigStorage, 'store_config', return_value=None, autospec=True) message_handler = MessageHandler(ServerStatusDatasource(), AgentDatasource()) select_agent = clai_select_state('wrong_agent') action = message_handler.process_message(select_agent) assert action.suggested_command == NOOP_COMMAND assert action.origin_command == select_agent.command assert action.execute assert action.description == create_error_select('wrong_agent').description assert message_handler.agent_datasource.get_current_plugin_name(select_agent.user_name) == ['nlc2cmd'] def test_should_return_an_error_when_selected_is_empty(mocker): mock_agent = create_mock_agent() mocker.patch.object(AgentDatasource, 'get_instances', return_value=[mock_agent], autospec=True) mocker.patch.object(AgentDatasource, 'all_plugins', return_value=ALL_PLUGINS, autospec=True) mocker.patch.object(ConfigStorage, 'read_config', return_value=PluginConfig( selected=["nlc2cmd"], default_orchestrator="max_orchestrator"), autospec=True) mocker.patch.object(ConfigStorage, 'store_config', return_value=None, autospec=True) message_handler = MessageHandler(ServerStatusDatasource(), AgentDatasource()) select_agent = clai_select_state('') action = message_handler.process_message(select_agent) assert action.suggested_command == NOOP_COMMAND assert action.origin_command == select_agent.command assert action.execute assert action.description == create_error_select('').description assert message_handler.agent_datasource.get_current_plugin_name(select_agent.user_name) == ['nlc2cmd'] # @patch('clai.server.agent_executor.thread_executor', MockExecutor()) def test_should_return_the_action_from_selected_agent_when_the_command_goes_to_the_agent_and_threshold_is_ok(mocker): mock_agent = create_mock_agent() mocker.patch.object(AgentDatasource, 'get_instances', return_value=[mock_agent], autospec=True) action_to_execute = Action(suggested_command="command", confidence=1.0) mock_agent.execute.return_value = action_to_execute mocker.patch.object(ConfigStorage, 'read_config', return_value=PluginConfig( selected=["demo_agent"], default_orchestrator="max_orchestrator"), autospec=True) message_handler = MessageHandler(ServerStatusDatasource(), AgentDatasource()) action = message_handler.process_message(command_state()) assert action.suggested_command == action_to_execute.suggested_command assert action.origin_command == command_state().command assert not action.execute assert not action.description # @patch('clai.server.agent_executor.thread_executor', MockExecutor()) def test_should_return_empty_action_from_selected_agent_when_the_command_goes_to_the_agent_and_not_confidence(mocker): mock_agent = create_mock_agent() mocker.patch.object(AgentDatasource, 'get_instances', return_value=[mock_agent], autospec=True) action_to_execute = Action(suggested_command="command", confidence=0.1) mock_agent.execute.return_value = action_to_execute mocker.patch.object(ConfigStorage, 'read_config', return_value=PluginConfig( selected=["demo_agent"], default_orchestrator="max_orchestrator"), autospec=True) message_handler = MessageHandler(ServerStatusDatasource(), AgentDatasource()) action = message_handler.process_message(command_state()) assert action.suggested_command is action.origin_command assert action.origin_command == command_state().command assert not action.execute assert not action.description # @patch('clai.server.agent_executor.thread_executor', MockExecutor()) def test_should_return_the_suggestion_from_agent_ignoring_confidence_if_is_clai_command(mocker): mock_agent = create_mock_agent() mocker.patch.object(AgentDatasource, 'get_instances', return_value=[mock_agent], autospec=True) action_to_execute = Action(suggested_command="command", confidence=0.0) mock_agent.execute.return_value = action_to_execute mocker.patch.object(ConfigStorage, 'read_config', return_value=PluginConfig( selected=["demo_agent"], default_orchestrator="max_orchestrator"), autospec=True) message_handler = MessageHandler(ServerStatusDatasource(), AgentDatasource()) action = message_handler.process_message(COMMAND_AGENT_STATE) assert action.suggested_command == action_to_execute.suggested_command assert action.origin_command == command_state().command assert not action.execute assert not action.description # @patch('clai.server.agent_executor.thread_executor', MockExecutor()) def test_should_return_the_suggestion_from_agent_ignoring_confidence_if_is_name_agent_command(mocker): mock_agent = create_mock_agent() mocker.patch.object(AgentDatasource, 'get_instances', return_value=[mock_agent], autospec=True) action_to_execute = Action(suggested_command="command", confidence=0.0) mock_agent.execute.return_value = action_to_execute mocker.patch.object(ConfigStorage, 'read_config', return_value=PluginConfig( selected=["demo_agent"], default_orchestrator="max_orchestrator"), autospec=True) message_handler = MessageHandler(ServerStatusDatasource(), AgentDatasource()) action = message_handler.process_message(COMMAND_NAME_AGENT_STATE) assert action.suggested_command == action_to_execute.suggested_command assert action.origin_command == command_state().command assert not action.execute assert not action.description def test_should_return_valid_action_if_the_select_agent_return_none(mocker): mock_agent = create_mock_agent() mocker.patch.object(AgentDatasource, 'get_instances', return_value=[mock_agent], autospec=True) mock_agent.execute.return_value = None mocker.patch.object(ConfigStorage, 'read_config', return_value=PluginConfig( selected=["demo_agent"], default_orchestrator="max_orchestrator"), autospec=True) message_handler = MessageHandler(ServerStatusDatasource(), AgentDatasource()) action = message_handler.process_message(command_state()) assert action.suggested_command is action.origin_command assert action.origin_command == command_state().command assert not action.execute assert not action.description
4,784
598
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from enum import Enum from typing import Callable, Dict, List, Tuple, Union import numpy as np from maro.utils import clone from maro.utils.exception.rl_toolkit_exception import StoreMisalignment from .abs_store import AbsStore class OverwriteType(Enum): ROLLING = "rolling" RANDOM = "random" class SimpleStore(AbsStore): """ An implementation of ``AbsStore`` for experience storage in RL. This implementation uses a dictionary of lists as the internal data structure. The objects for each key are stored in a list. To be useful for experience storage in RL, uniformity checks are performed during put operations to ensure that the list lengths stay the same for all keys at all times. Both unlimited and limited storage are supported. Args: keys (list): List of keys identifying each column. capacity (int): If negative, the store is of unlimited capacity. Defaults to -1. overwrite_type (OverwriteType): If storage capacity is bounded, this specifies how existing entries are overwritten when the capacity is exceeded. Two types of overwrite behavior are supported: - Rolling, where overwrite occurs sequentially with wrap-around. - Random, where overwrite occurs randomly among filled positions. Alternatively, the user may also specify overwrite positions (see ``put``). """ def __init__(self, keys: list, capacity: int = -1, overwrite_type: OverwriteType = None): super().__init__() self._keys = keys self._capacity = capacity self._overwrite_type = overwrite_type self._store = {key: [] if self._capacity < 0 else [None] * self._capacity for key in keys} self._size = 0 self._iter_index = 0 def __len__(self): return self._size def __iter__(self): return self def __next__(self): if self._iter_index >= self._size: self._iter_index = 0 raise StopIteration index = self._iter_index self._iter_index += 1 return {k: lst[index] for k, lst in self._store.items()} def __getitem__(self, index: int): return {k: lst[index] for k, lst in self._store.items()} @property def keys(self): return self._keys @property def capacity(self): """Store capacity. If negative, the store grows without bound. Otherwise, the number of items in the store will not exceed this capacity. """ return self._capacity @property def overwrite_type(self): """An ``OverwriteType`` member indicating the overwrite behavior when the store capacity is exceeded.""" return self._overwrite_type def get(self, indexes: [int]) -> dict: return {k: [self._store[k][i] for i in indexes] for k in self._store} def put(self, contents: Dict[str, List], overwrite_indexes: list = None) -> List[int]: """Put new contents in the store. Args: contents (dict): Dictionary of items to add to the store. If the store is not empty, this must have the same keys as the store itself. Otherwise an ``StoreMisalignment`` will be raised. overwrite_indexes (list, optional): Indexes where the contents are to be overwritten. This is only used when the store has a fixed capacity and putting ``contents`` in the store would exceed this capacity. If this is None and overwriting is necessary, rolling or random overwriting will be done according to the ``overwrite`` property. Defaults to None. Returns: The indexes where the newly added entries reside in the store. """ if len(self._store) > 0 and list(contents.keys()) != self._keys: raise StoreMisalignment(f"expected keys {self._keys}, got {list(contents.keys())}") self.validate(contents) added = contents[next(iter(contents))] added_size = len(added) if isinstance(added, list) else 1 if self._capacity < 0: for key, val in contents.items(): self._store[key].extend(val) self._size += added_size return list(range(self._size - added_size, self._size)) else: write_indexes = self._get_update_indexes(added_size, overwrite_indexes=overwrite_indexes) self.update(write_indexes, contents) self._size = min(self._capacity, self._size + added_size) return write_indexes def update(self, indexes: list, contents: Dict[str, List]): """ Update contents at given positions. Args: indexes (list): Positions where updates are to be made. contents (dict): Contents to write to the internal store at given positions. It is subject to uniformity checks to ensure that all values have the same length. Returns: The indexes where store contents are updated. """ self.validate(contents) for key, val in contents.items(): for index, value in zip(indexes, val): self._store[key][index] = value return indexes def apply_multi_filters(self, filters: List[Callable]): """Multi-filter method. The input to one filter is the output from its predecessor in the sequence. Args: filters (List[Callable]): Filter list, each item is a lambda function, e.g., [lambda d: d['a'] == 1 and d['b'] == 1]. Returns: Filtered indexes and corresponding objects. """ indexes = range(self._size) for f in filters: indexes = [i for i in indexes if f(self[i])] return indexes, self.get(indexes) def apply_multi_samplers(self, samplers: list, replace: bool = True) -> Tuple: """Multi-samplers method. This implements chained sampling where the input to one sampler is the output from its predecessor in the sequence. Args: samplers (list): A sequence of weight functions for computing the sampling weights of the items in the store, e.g., [lambda d: d['a'], lambda d: d['b']]. replace (bool): If True, sampling will be performed with replacement. Returns: Sampled indexes and corresponding objects. """ indexes = range(self._size) for weight_fn, sample_size in samplers: weights = np.asarray([weight_fn(self[i]) for i in indexes]) indexes = np.random.choice(indexes, size=sample_size, replace=replace, p=weights / np.sum(weights)) return indexes, self.get(indexes) def sample(self, size, weights: Union[list, np.ndarray] = None, replace: bool = True): """ Obtain a random sample from the experience pool. Args: size (int): Sample sizes for each round of sampling in the chain. If this is a single integer, it is used as the sample size for all samplers in the chain. weights (Union[list, np.ndarray]): Sampling weights. replace (bool): If True, sampling is performed with replacement. Defaults to True. Returns: Sampled indexes and the corresponding objects, e.g., [1, 2, 3], ['a', 'b', 'c']. """ if weights is not None: weights = np.asarray(weights) weights = weights / np.sum(weights) indexes = np.random.choice(self._size, size=size, replace=replace, p=weights) return indexes, self.get(indexes) def sample_by_key(self, key, size: int, replace: bool = True): """ Obtain a random sample from the store using one of the columns as sampling weights. Args: key: The column whose values are to be used as sampling weights. size (int): Sample size. replace (bool): If True, sampling is performed with replacement. Returns: Sampled indexes and the corresponding objects. """ weights = np.asarray(self._store[key][:self._size] if self._size < self._capacity else self._store[key]) indexes = np.random.choice(self._size, size=size, replace=replace, p=weights / np.sum(weights)) return indexes, self.get(indexes) def sample_by_keys(self, keys: list, sizes: list, replace: bool = True): """ Obtain a random sample from the store by chained sampling using multiple columns as sampling weights. Args: keys (list): The column whose values are to be used as sampling weights. sizes (list): Sample size. replace (bool): If True, sampling is performed with replacement. Returns: Sampled indexes and the corresponding objects. """ if len(keys) != len(sizes): raise ValueError(f"expected sizes of length {len(keys)}, got {len(sizes)}") indexes = range(self._size) for key, size in zip(keys, sizes): weights = np.asarray([self._store[key][i] for i in indexes]) indexes = np.random.choice(indexes, size=size, replace=replace, p=weights / np.sum(weights)) return indexes, self.get(indexes) def clear(self): """Empty the store.""" self._store = {key: [] if self._capacity < 0 else [None] * self._capacity for key in self._keys} self._size = 0 self._iter_index = 0 def dumps(self): """Return a deep copy of store contents.""" return clone(dict(self._store)) def get_by_key(self, key): """Get the contents of the store corresponding to ``key``.""" return self._store[key] def _get_update_indexes(self, added_size: int, overwrite_indexes=None): if added_size > self._capacity: raise ValueError("size of added items should not exceed the store capacity.") num_overwrites = self._size + added_size - self._capacity if num_overwrites < 0: return list(range(self._size, self._size + added_size)) if overwrite_indexes is not None: write_indexes = list(range(self._size, self._capacity)) + list(overwrite_indexes) else: # follow the overwrite rule set at init if self._overwrite_type == OverwriteType.ROLLING: # using the negative index convention for convenience start_index = self._size - self._capacity write_indexes = list(range(start_index, start_index + added_size)) else: random_indexes = np.random.choice(self._size, size=num_overwrites, replace=False) write_indexes = list(range(self._size, self._capacity)) + list(random_indexes) return write_indexes @staticmethod def validate(contents: Dict[str, List]): # Ensure that all values are lists of the same length. if any(not isinstance(val, list) for val in contents.values()): raise TypeError("All values must be of type 'list'") reference_val = contents[list(contents.keys())[0]] if any(len(val) != len(reference_val) for val in contents.values()): raise StoreMisalignment("values of contents should consist of lists of the same length")
4,436
421
// <Snippet1> using namespace System; using namespace System::Reflection; public ref class MyClass { public: ref class NestClass { public: static int myPublicInt = 0; }; ref struct NestStruct { public: static int myPublicInt = 0; }; }; int main() { try { // Get the Type object corresponding to MyClass. Type^ myType = MyClass::typeid; // Get an array of nested type objects in MyClass. array<Type^>^nestType = myType->GetNestedTypes(); Console::WriteLine( "The number of nested types is {0}.", nestType->Length ); System::Collections::IEnumerator^ myEnum = nestType->GetEnumerator(); while ( myEnum->MoveNext() ) { Type^ t = safe_cast<Type^>(myEnum->Current); Console::WriteLine( "Nested type is {0}.", t ); } } catch ( Exception^ e ) { Console::WriteLine( "Error {0}", e->Message ); } } // </Snippet1>
445
1,338
/* * Copyright 1998-1999 Be, Inc. All Rights Reserved. * Copyright 2003-2019 Haiku, Inc. All rights reserved. * Distributed under the terms of the MIT License. */ #ifndef VIDEO_CONSUMER_H #define VIDEO_CONSUMER_H #include <Bitmap.h> #include <BufferConsumer.h> #include <MediaEventLooper.h> #include <MediaNode.h> #include <TimedEventQueue.h> #include <TranslatorRoster.h> #include <View.h> #include <Window.h> typedef struct { port_id port; bigtime_t rate; uint32 imageFormat; int32 translator; int32 uploadClient; bool passiveFtp; char fileNameText[64]; char serverText[64]; char loginText[64]; char passwordText[64]; char directoryText[64]; } ftp_msg_info; #define FTP_INFO 0x60000001 class BStringView; class VideoConsumer : public BMediaEventLooper, public BBufferConsumer { public: VideoConsumer(const char* name, BView* view, BStringView* statusLine, BMediaAddOn *addon, const uint32 internalId); ~VideoConsumer(); /* BMediaNode */ public: virtual BMediaAddOn* AddOn(int32* cookie) const; protected: virtual void Start(bigtime_t performanceTime); virtual void Stop(bigtime_t performanceTime, bool immediate); virtual void Seek(bigtime_t mediaTime, bigtime_t performanceTime); virtual void TimeWarp(bigtime_t atRealTime, bigtime_t toPerformanceTime); virtual void NodeRegistered(); virtual status_t RequestCompleted( const media_request_info& info); virtual status_t HandleMessage(int32 message, const void* data, size_t size); virtual status_t DeleteHook(BMediaNode* node); /* BMediaEventLooper */ protected: virtual void HandleEvent(const media_timed_event* event, bigtime_t lateness, bool realTimeEvent); /* BBufferConsumer */ public: virtual status_t AcceptFormat(const media_destination& dest, media_format* format); virtual status_t GetNextInput(int32* cookie, media_input* outInput); virtual void DisposeInputCookie(int32 cookie); protected: virtual void BufferReceived(BBuffer* buffer); private: virtual void ProducerDataStatus( const media_destination &forWhom, int32 status, bigtime_t atMediaTime); virtual status_t GetLatencyFor(const media_destination& forWhom, bigtime_t* outLatency, media_node_id* outId); virtual status_t Connected(const media_source& producer, const media_destination& where, const media_format& withFormat, media_input* outInput); virtual void Disconnected(const media_source& producer, const media_destination& where); virtual status_t FormatChanged(const media_source& producer, const media_destination& consumer, int32 fromChangeCount, const media_format& format); /* implementation */ public: status_t CreateBuffers(const media_format& withFormat); void DeleteBuffers(); static status_t FtpRun(void* data); void FtpThread(); void UpdateFtpStatus(const char* status); status_t LocalSave(char* filename, BBitmap* bitmap); status_t FtpSave(char* filename); private: BStringView* fStatusLine; int32 fInternalID; BMediaAddOn* fAddOn; thread_id fFtpThread; bool fConnectionActive; media_input fIn; media_destination fDestination; bigtime_t fMyLatency; BWindow* fWindow; BView* fView; BBitmap* fBitmap[3]; bool fOurBuffers; BBufferGroup* fBuffers; BBuffer* fBufferMap[3]; BBitmap* fFtpBitmap; volatile bool fTimeToFtp; volatile bool fFtpComplete; bigtime_t fRate; uint32 fImageFormat; int32 fTranslator; int32 fUploadClient; bool fPassiveFtp; char fFileNameText[64]; char fServerText[64]; char fLoginText[64]; char fPasswordText[64]; char fDirectoryText[64]; }; #endif // VIDEO_CONSUMER_H
1,693
690
package com.artemis.injection; public class SharedInjectionCache extends ThreadLocal<InjectionCache> { @Override protected InjectionCache initialValue() { return new InjectionCache(); } }
55