code
stringlengths
281
23.7M
class EventoLAdmin(admin.ModelAdmin): def filter_event(events, queryset): return queryset.filter(event__in=events) def queryset(self, request): self.get_queryset(request) def get_queryset(self, request): queryset = super().get_queryset(request) if request.user.is_superuser: ...
class OptionSeriesColumnpyramidDataDragdropGuideboxDefault(Options): def className(self): return self._config_get('highcharts-drag-box-default') def className(self, text: str): self._config(text, js_type=False) def color(self): return self._config_get('rgba(0, 0, 0, 0.1)') def co...
def main(): files = sorted(glob('tokens/0x*.yaml')) entries = list((read_entry(fn) for fn in files)) for entry in entries: json_fn = 'tokens/{}.json'.format(entry['addr']) with open(json_fn, 'w') as outfile: json.dump(entry, outfile, separators=(',', ':')) with open('tokens/b...
class OptionSeriesCylinderOnpointConnectoroptions(Options): def dashstyle(self): return self._config_get(None) def dashstyle(self, text: str): self._config(text, js_type=False) def stroke(self): return self._config_get(None) def stroke(self, text: str): self._config(text,...
def search_lsh_jaccard_topk(index_data, query_data, index_params, k): (index_sets, index_keys, index_minhashes, index_cache) = index_data (query_sets, query_keys, query_minhashes) = query_data (b, r) = (index_params['b'], index_params['r']) num_perm = (b * r) cache_key = json.dumps(index_params) ...
def extractMilkstaintranslationWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')] for (tagname, nam...
def test_addInstanceDescriptor(): ds = DesignSpaceDocument() instance = ds.addInstanceDescriptor(name='TestInstance', location={'Weight': 400}, styleName='Regular', styleMapStyleName='regular') assert (ds.instances[0] is instance) assert isinstance(instance, InstanceDescriptor) assert (instance.name...
class OptionSeriesHistogramStatesSelectHalo(Options): def attributes(self): return self._config_get(None) def attributes(self, value: Any): self._config(value, js_type=False) def opacity(self): return self._config_get(0.25) def opacity(self, num: float): self._config(num,...
class VCub(BikeShareSystem): meta = {'system': 'Keolis', 'company': ['Keolis'], 'ebikes': True} def __init__(self, tag, meta, feed_url): super(VCub, self).__init__(tag, meta) self.feed_url = feed_url def update(self, scraper=None): scraper = (scraper or PyBikesScraper()) data...
class OptionPlotoptionsDependencywheelStatesSelect(Options): def animation(self) -> 'OptionPlotoptionsDependencywheelStatesSelectAnimation': return self._config_sub_data('animation', OptionPlotoptionsDependencywheelStatesSelectAnimation) def borderColor(self): return self._config_get('#000000') ...
class OptionSeriesVariwideSonificationTracksPointgrouping(Options): def algorithm(self): return self._config_get('minmax') def algorithm(self, text: str): self._config(text, js_type=False) def enabled(self): return self._config_get(True) def enabled(self, flag: bool): sel...
class OptionSeriesWaterfallSonificationContexttracksMappingTremoloDepth(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: str): ...
_command def train_ours(dm: DataManager, key: str, name: str='', mask: str='mask', pose: str=None, scale: int=(- 1), contraction: str=None, config: str=None, run_eval: bool=True, time_prefix: bool=True, use_depths: bool=False, eval_step: int=(- 1), extra_args: List[str]=[]): assert (scale in {(- 1), 1, 2, 4}) i...
def extractNieracolTranslations(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol or frag)) or ('preview' in item['title'].lower())): return None if ("The Sly Emperor's Wild Beast-Tamer Empress" in item['tags']): return buildReleaseMessag...
class ErrorCode(Enum): GENERIC_ERROR = 0 REQUEST_NOT_VALID = 1 AGENT_ADDR_ALREADY_REGISTERED = 2 AGENT_NAME_ALREADY_REGISTERED = 3 AGENT_NOT_REGISTERED = 4 TRANSACTION_NOT_VALID = 5 TRANSACTION_NOT_MATCHING = 6 AGENT_NAME_NOT_IN_WHITELIST = 7 COMPETITION_NOT_RUNNING = 8 DIALOGUE_...
class JsIntensity(): alias = 'intensity' params = ('cols',) value = '\n stats = {};\n cols.forEach(function(col){stats[col] = {min: null, max: null}});\n data.forEach(function(rec){\n cols.forEach(function(col){\n if((stats[col].max == null) || (rec[col] > stats[col].max) ) { stats[col]...
class ASMExtrudedStarPC(ASMStarPC): _prefix = 'pc_star_' def get_patches(self, V): mesh = V.mesh() mesh_dm = mesh.topology_dm nlayers = mesh.layers if (not mesh.cell_set._extruded): return super(ASMExtrudedStarPC, self).get_patches(V) depth = PETSc.Options().g...
class ObjectList(GenericList): def getObjectsInHouse(self, house): res = [obj for obj in self if house.hasObject(obj)] return ObjectList(res) def getObjectsAspecting(self, point, aspList): res = [] for obj in self: if (obj.isPlanet() and aspects.isAspecting(obj, point...
def test_disposing_method_handler1(): class Foo(event.Component): ('xx') def handle_xx(self, *events): pass foo = Foo() assert foo.get_event_handlers('xx') foo_ref = weakref.ref(foo) handler_ref = weakref.ref(foo.handle_xx) del foo gc.collect() gc.collect() ...
def faux_v1_env(): return Lexicon(always_use_pty=True, forward_agent=False, gateway=None, host_string='localghost', key_filename=None, no_agent=False, password=None, port=22, ssh_config_path=None, sudo_password='nope', sudo_prompt=None, timeout=None, use_ssh_config=False, user='localuser', warn_only=False)
def main(): parser = argparse.ArgumentParser(description='\nGenerate a personalized "Life Calendar", inspired by the calendar with the same name from the waitbutwhy.com store') parser.add_argument(type=parse_date, dest='date', help="starting date; your birthday,in either yyyy/mm/dd or dd/mm/yyyy format (dashes...
def test_automatic_variable_selection(df_test): (X, y) = df_test X[['var_0', 'var_6', 'var_7', 'var_9']] = X[['var_0', 'var_6', 'var_7', 'var_9']].astype(int) X['cat_1'] = 'cat1' X['cat_2'] = 'cat2' transformer = SmartCorrelatedSelection(variables=None, method='pearson', threshold=0.8, missing_value...
class isIPv6(Validator): message = 'Invalid IPv6 address' def __init__(self, private=None, link_local=None, reserved=None, multicast=None, routable=None, to4=None, teredo=None, subnets=None, message=None): super().__init__(message=message) self.is_private = private self.is_link_local = l...
class CssImgAInfo(CssStyle.Style): _attrs = {'opacity': 1, 'transition': 'all 0.2s ease-in-out', 'display': 'block', 'text-decoration': 'none', 'padding': '7px 14px', 'text-transform': 'uppercase', 'box-shadow': '0 0 1px #000', 'margin': '10px auto', 'text-align': 'center'} _hover = {'transform': 'translateY(0p...
class TransformerDecoder(Generic[ConfigT], DecoderModule[(ConfigT, KeyValueCache)]): embeddings: Module layers: ModuleList output_layer_norm: Module def forward(self, piece_ids: Tensor, attention_mask: AttentionMask, *, cache: Optional[List[KeyValueCache]]=None, positions: Optional[Tensor]=None, store_c...
def replace_query_param(url, key, val): (scheme, netloc, path, query, fragment) = parse.urlsplit(force_str(url)) query_dict = parse.parse_qs(query, keep_blank_values=True) query_dict[force_str(key)] = [force_str(val)] query = parse.urlencode(sorted(query_dict.items()), doseq=True) return parse.urlun...
_routes.route('/<string:event_identifier>.ics') _event_id _optional def export_event(event_id): event = Event.query.get_or_404(event_id) include_sessions = ('include_sessions' in request.args) my_schedule = ('my_schedule' in request.args) user_id = request.args.get('user_id') response = to_ical(even...
class _IndexedSimpleEditor(BaseSourceWithLocation): source_class = SimpleEditor locator_class = Index handlers = [(MouseClick, (lambda wrapper, _: _interaction_helpers.mouse_click_combobox(combobox=wrapper._target.source.control, index=wrapper._target.location.index, delay=wrapper.delay)))]
def test_jac_invalid(): mesh = UnitIntervalMesh(5) V = FunctionSpace(mesh, 'P', 1) u = TrialFunction(V) v = TestFunction(V) f = Function(V).assign(1) a = (inner(u, v) * dx) L = (inner(f, v) * dx) out = Function(V) problem = LinearVariationalProblem(a, L, out, constant_jacobian=True) ...
class BaseCharacter(ObjectParent, DefaultCharacter): is_pc = False _property def cooldowns(self): return CooldownHandler(self) def hurt_level(self): percent = max(0, min(100, (100 * (self.hp / self.hp_max)))) if (95 < percent <= 100): return '|gPerfect|n' elif...
class BasePlot(): def __init__(self, G: nx.Graph=None, node_grouping: Hashable=None, node_order: Hashable=None, node_color: Hashable=None, node_alpha: Hashable=None, node_size: Hashable=None, nodeprops: Dict=None, edge_color: Hashable=None, edge_alpha: Hashable=None, edge_width: Hashable=None, edgeprops: Dict=None)...
def test_autocorr_estimator(seed=9502): np.random.seed(seed) t = np.linspace(0, 10, 500) period = 2.345 amp = 4.5 y = (amp * np.sin((((2 * np.pi) * t) / period))) results = autocorr_estimator(t, y, min_period=0.01, max_period=10, smooth=0.0) assert ((np.abs((period - results['peaks'][0]['per...
_ns.route('/pending/all/') (timeout=PENDING_ALL_CACHE_SECONDS) def pending_all(): rpm_tasks = builds_logic.BuildsLogic.get_pending_build_tasks(data_type='overview') owner_stats = Counter() owner_substats = defaultdict((lambda : {'projects': Counter(), 'chroots': Counter(), 'background': Counter()})) pro...
def test_is_child_trace_address(): assert is_child_trace_address([0], []) assert is_child_trace_address([0, 0], []) assert is_child_trace_address([0, 0], [0]) assert is_child_trace_address([100, 1, 10], [100]) assert is_child_trace_address([100, 1, 10], [100, 1]) assert (not is_child_trace_addre...
def get_det_meta_arch_cfg(cfg, dataset_name, output_dir): cfg.MODEL.DEVICE = 'cpu' cfg.MODEL.META_ARCHITECTURE = 'DetMetaArchForTest' cfg.DATASETS.TRAIN = (dataset_name,) cfg.DATASETS.TEST = (dataset_name,) cfg.INPUT.MIN_SIZE_TRAIN = (10,) cfg.INPUT.MIN_SIZE_TEST = (10,) cfg.SOLVER.MAX_ITER ...
.parametrize('relation_value_good_bad', [('equals', 5, 5, 4), ('is', '42', '42', 42), ('gt', 100, 99, 101), ('lt', 100, 101, 99), ('in', '42', 'i like 42', 'more a 1337 guy'), ('reverse_in', [1, 3], 3, 2), ('intersection', [1, 2, 3], [2, 3], [4, 5])]) def test_apply_relation(relation_value_good_bad): (relation, val...
class OptionPlotoptionsGaugeSonificationDefaultinstrumentoptionsMappingTime(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: st...
def is_vm_operational(fun): def wrap(view, vm, *args, **kwargs): if vm.locked: raise VmIsLocked if (vm.status not in VM_STATUS_OPERATIONAL): raise VmIsNotOperational if vm.tasks_rw: raise VmHasPendingTasks return fun(view, vm, *args, **kwargs) ...
.slow .parametrize('model_revision', _MODELS) def test_auto_tokenizer_fsspec(model_revision): (name, revision) = model_revision AutoTokenizer.from_fsspec(fs=HfFileSystem(), model_path=name, fsspec_args=FsspecArgs(revision=revision)) AutoTokenizer.from_hf_hub(name=name, revision=revision)
def error_counter(metrics_name: str) -> Callable: def wrap(f: Callable): (f) def wrapper_sync(self: MetricsGetter, *args, **kwargs): try: return f(self, *args, **kwargs) except Exception as err: if self.has_metrics(): self.g...
class ColoredFormatter(Default): error_format = '{path}:{row}:{col}: {code} {text}' def after_init(self) -> None: if (self.options.format.lower() not in ('default', 'colored')): self.error_format = self.options.format self._lexer = PythonLexer() self._formatter = TerminalForm...
_frequency(timedelta(days=2)) def fetch_consumption(zone_key: str='MK', session: Session=Session(), target_datetime: (datetime | None)=None, logger: Logger=getLogger(__name__)) -> list: target_datetime = modify_target_datetime(target_datetime) return ENTSOE.fetch_consumption(zone_key=zone_key, session=session, ...
class OptionSeriesWordcloudDataDatalabelsTextpath(Options): def attributes(self): return self._config_get(None) def attributes(self, value: Any): self._config(value, js_type=False) def enabled(self): return self._config_get(False) def enabled(self, flag: bool): self._conf...
def test_lrucache_size_add_replacement_fails(test_tx_small, test_tx_datacarrier) -> None: cache = LRUCache(max_size=SIZEOF_TEST_TX_SMALL) (added, removals) = cache.set(b'1', test_tx_small) assert added assert (len(removals) == 0) assert (cache.current_size == SIZEOF_TEST_TX_SMALL) (added, remova...
def choose_available_backend() -> BackendAPI: for backend in SUPPORTED_BACKENDS: try: return load_backend(backend) except ImportError: logging.getLogger('eth_hash').debug(f'Failed to import {backend}', exc_info=True) raise ImportError(f'''None of these hashing backends ar...
_numpy_and_pandas def test_serializes_pandas_category(): cat = pd.Categorical(['a', 'c', 'b', 'a'], categories=['a', 'b', 'c']) assert (b'{"d":["a","c","b","a"]}' == JSONSerializer().dumps({'d': cat})) cat = pd.Categorical([1, 2, 3], categories=[1, 2, 3]) assert (b'{"d":[1,2,3]}' == JSONSerializer().dum...
class OptionPlotoptionsTilemapSonificationDefaultspeechoptions(Options): def activeWhen(self) -> 'OptionPlotoptionsTilemapSonificationDefaultspeechoptionsActivewhen': return self._config_sub_data('activeWhen', OptionPlotoptionsTilemapSonificationDefaultspeechoptionsActivewhen) def language(self): ...
class AsyncEth(BaseEth): w3: 'AsyncWeb3' is_async = True _default_contract_factory: Type[Union[(AsyncContract, AsyncContractCaller)]] = AsyncContract _accounts: Method[Callable[([], Awaitable[Tuple[ChecksumAddress]])]] = Method(RPC.eth_accounts, is_property=True) async def accounts(self) -> Tuple[Ch...
class UnstructuredGridReader(FileDataSource): __version__ = 0 reader = Instance(tvtk.Object, allow_none=False, record=True) output_info = PipelineInfo(datasets=['unstructured_grid']) _reader_dict = Dict(Str, Instance(tvtk.Object)) view = View(Group(Include('time_step_group'), Item(name='base_file_na...
def on_state_msg(on_state: Callable[([EntityState], None)], image_stream: dict[(int, list[bytes])], msg: message.Message) -> None: msg_type = type(msg) if (cls := SUBSCRIBE_STATES_RESPONSE_TYPES.get(msg_type)): on_state(cls.from_pb(msg)) elif (msg_type is CameraImageResponse): if TYPE_CHECKI...
_os(*metadata.platforms) def main(): bins = ['sethc.exe', 'utilman.exe', 'narrator.exe', 'magnify.exe', 'osk.exe', 'displayswitch.exe', 'atbroker.exe'] calc = Path('\\windows\\system32\\calc.exe').resolve() temp = Path('temp.exe').resolve() for bin_name in bins: bin_path = Path(('\\Windows\\syst...
class OptionSeriesDumbbellSonificationContexttracksMappingHighpass(Options): def frequency(self) -> 'OptionSeriesDumbbellSonificationContexttracksMappingHighpassFrequency': return self._config_sub_data('frequency', OptionSeriesDumbbellSonificationContexttracksMappingHighpassFrequency) def resonance(self...
class OptionSonificationDefaultinstrumentoptionsMappingTremolo(Options): def depth(self) -> 'OptionSonificationDefaultinstrumentoptionsMappingTremoloDepth': return self._config_sub_data('depth', OptionSonificationDefaultinstrumentoptionsMappingTremoloDepth) def speed(self) -> 'OptionSonificationDefaulti...
class StarResponse(ModelComposed): allowed_values = {} validations = {} _property def additional_properties_type(): lazy_import() return (bool, date, datetime, dict, float, int, list, str, none_type) _nullable = False _property def openapi_types(): lazy_import() ...
def test_get_node() -> None: harness = NodeTestHarness(MyNode) with harness.get_node(config=MyConfig(1), state=MyState(counter=(- 1))) as node: assert isinstance(node, MyNode) assert (node.config.asdict() == {'my_field': 1}) assert (dataclasses.asdict(node.state) == {'counter': (- 1)}) ...
class ImageDisplayer(object): def __init__(self): self._window_name = 'cv2_display_window' cv2.namedWindow(self._window_name) def display(self, image, wait_key_ms=1): cv2.imshow(self._window_name, image) cv2.waitKey(wait_key_ms) def __del__(self): cv2.destroyWindow(se...
class OptionSeriesNetworkgraphSonificationDefaultinstrumentoptionsMappingHighpassFrequency(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo...
class _ConfigValue(object): def __init__(self, dict_key, env_key=None, type=str, validators=None, callbacks=None, callbacks_on_default=True, default=None, required=False) -> None: self.type = type self.dict_key = dict_key self.validators = validators self.callbacks = callbacks ...
class BestModelSelection(ModelSelectionBase): def __init__(self, dump_file: Optional[str], model: Optional[TorchModel], dump_interval: Optional[int]=None, verbose: bool=False): self.dump_file = dump_file self.model = model self.dump_interval = dump_interval self.verbose = verbose ...
def test_track_peer_connection_metadata_updates(remote, caplog): tracker = MemoryEth1PeerTracker() tracker.track_peer_connection(remote, *TRACK_ARGS) node = tracker._get_remote(remote.id) assert (node.genesis_hash == ZERO_HASH_HEX) assert (node.protocol == 'eth') assert (node.protocol_version ==...
def test_revoke_refresh_tokens(new_user): user = auth.get_user(new_user.uid) old_valid_after = user.tokens_valid_after_timestamp time.sleep(1) auth.revoke_refresh_tokens(new_user.uid) user = auth.get_user(new_user.uid) new_valid_after = user.tokens_valid_after_timestamp assert (new_valid_aft...
class OptionPlotoptionsBellcurveStatesSelectMarker(Options): def enabled(self): return self._config_get(None) def enabled(self, flag: bool): self._config(flag, js_type=False) def enabledThreshold(self): return self._config_get(2) def enabledThreshold(self, num: float): se...
def main() -> None: parser = argparse.ArgumentParser() parser.add_argument('--input', '-i', help='Path to the input video', type=Path, required=True) parser.add_argument('--output', '-o', help="Path to where you want to save the output video. Note: Not all extensions are supported. Checkout moviepy's docume...
class AttrBadge(Attrs): def __init__(self, component: primitives.HtmlModel, page: primitives.PageModel=None): super(AttrBadge, self).__init__(component, page=page) self.padding = '1px 3px' self.margin = '1px 1px 1px 2px' self.vertical_align = 'bottom' self.font_size = compone...
class StateBase(): def __init__(self, src: str, md: MarkdownIt, env: EnvType): self.src = src self.env = env self.md = md def src(self) -> str: return self._src def src(self, value: str) -> None: self._src = value self._srcCharCode: (tuple[(int, ...)] | None) ...
def test_handles_multi_step_scenarios(): env = build_dummy_structured_env() env = ActionRecordingWrapper.wrap(env, record_maze_actions=False, record_actions=True, output_dir='action_records') env.seed(1234) env.reset() for _ in range(6): action = env.action_space.sample() env.step(ac...
class WorkflowNode(_common.FlyteIdlEntity): def __init__(self, launchplan_ref=None, sub_workflow_ref=None): self._launchplan_ref = launchplan_ref self._sub_workflow_ref = sub_workflow_ref def launchplan_ref(self): return self._launchplan_ref def sub_workflow_ref(self): return...
class ScriptPlugin(plugin.Plugin): has_settings = True _errors def __init__(self): super().__init__() self.config = None def configure(self, bus: Bus, graph: Graph) -> None: super().configure(bus, graph) self.config = graph.get('tomate.config') _errors (Events.SES...
def check_dependencies(): modules = ['scapy', 'requests'] not_installed_modules = [] for module in modules: spec = importlib.util.find_spec(module) if (spec is None): print(f'[-] WARNING : `{module}` library not installed.') not_installed_modules.append(module) if...
class OptionSonificationDefaultinstrumentoptionsMappingTremoloDepth(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: str): ...
(factory) _all(__all__) class Outliers(Score): def __init__(self, bands, process='median', dist=0.7, name='score-outlier', **kwargs): super(Outliers, self).__init__(**kwargs) self.bands = bands self.process = process self.dist = dist self.range_in = (0, 1) self.name =...
class flow_add(flow_mod): version = 1 type = 14 _command = 0 def __init__(self, xid=None, match=None, cookie=None, idle_timeout=None, hard_timeout=None, priority=None, buffer_id=None, out_port=None, flags=None, actions=None): if (xid != None): self.xid = xid else: ...
class OptionSeriesVennSonificationContexttracksPointgrouping(Options): def algorithm(self): return self._config_get('minmax') def algorithm(self, text: str): self._config(text, js_type=False) def enabled(self): return self._config_get(True) def enabled(self, flag: bool): ...
class ProgressComponents(): def __init__(self, ui): self.page = ui.page def gauge(self, value: float=0, width: types.SIZE_TYPE=(90, 'px'), height: types.SIZE_TYPE=(45, 'px'), html_code: str=None, options: dict=None, profile: types.PROFILE_TYPE=None): width = Arguments.size(width, unit='%') ...
def static_namespace(name): from clu.typespace.namespace import SimpleNamespace as Namespace ns = Namespace() ns.name = str(name) ns.root = os.path.join(projectdir, ns.name) ns.data = os.path.join(ns.root, 'data') ns.relative = (lambda p: os.path.relpath(p, start=ns.root)) ns.listfiles = (la...
def extractElysianpitWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')] for (tagname, name, tl_type...
def finish(Sphynx, *args): parts = [] for (class_name, mod_name, fname) in all_examples: parts.append(('<br /><h3>%s in %s</h3>' % (class_name, mod_name))) parts.append(get_html(('examples/' + fname), 300)) parts.insert(0, '<!DOCTYPE html><html><body>This page may take a while to load ... <b...
class OptionSeriesSunburstDataDragdropGuideboxDefault(Options): def className(self): return self._config_get('highcharts-drag-box-default') def className(self, text: str): self._config(text, js_type=False) def color(self): return self._config_get('rgba(0, 0, 0, 0.1)') def color(s...
class _Sub(_BinaryType): __pnmltype__ = 'difference' def __init__(self, left, right): self._left = left self._right = right _iterable(self, left) def __repr__(self): return ('(%s - %s)' % (repr(self._left), repr(self._right))) def __contains__(self, value): return...
def question_answer_arguments(provider_name: str): return {'texts': question_answer_sample['texts'], 'question': question_answer_sample['question'], 'temperature': question_answer_sample['temperature'], 'examples_context': question_answer_sample['examples_context'], 'examples': question_answer_sample['examples'], '...
def setup_ssl(parser: ArgumentParser, options: Namespace): ssl_context = None if (bool(options.certfile) ^ bool(options.keyfile)): parser.error('To use SSL both --certfile and --keyfile must be passed') elif (options.certfile and options.keyfile): ssl_context = utils.create_ssl_context(optio...
class RawConnectionPool(BaseConnectionPool): def create(self): now = time.time() return (now, now, self.connect(self._db_module, self.connect_timeout, *self._args, **self._kwargs)) def connect(cls, db_module, connect_timeout, *args, **kw): t = timeout.Timeout(connect_timeout, ConnectTime...
.lkc def test_cves_metadata_title(hound, repo): broken = [] meta = hound.metadata for cve in meta: data = meta[cve] if ('cmt_msg' not in data): continue data_msg = data['cmt_msg'] fix = data['fixes'] if (not fix): continue if (not re.ma...
class mgmt(bsn_tlv): type = 211 def __init__(self, value=None): if (value != None): self.value = value else: self.value = 0 return def pack(self): packed = [] packed.append(struct.pack('!H', self.type)) packed.append(struct.pack('!H', 0...
def test_should_change_to_returned_state_on_multiple_target_with_combined_transitions(): class ApprovalMachine(StateMachine): requested = State(initial=True) accepted = State() rejected = State() completed = State(final=True) validate = ((requested.to(accepted, cond='is_ok') ...
def get_proof_size(proof): (depths, extension_present, commitments_sorted_by_path_serialized, other_stems, D_serialized, ipa_proof) = proof size = len(depths) size += (32 * len(commitments_sorted_by_path_serialized)) size += (32 * len(other_stems)) size += ((32 + (((len(ipa_proof) - 1) * 2) * 32)) +...
_os(*metadata.platforms) def main(): common.log('Executing creation on temp StartupParameters.plist file.') plist = '/Library/StartupItems/test/StartupParameters.plist' output_file = Path(plist) output_file.parent.mkdir(exist_ok=True, parents=True) common.temporary_file_helper('testing', file_name=s...
def test_works_with_gym_maze_envs(): env = GymMazeEnv('CartPole-v0') policy = RandomPolicy(action_spaces_dict=env.action_spaces_dict) agent_deployment = AgentDeployment(policy=policy, env=env) external_env = gym.make('CartPole-v0') maze_state = external_env.reset() (reward, done, info) = (0, Fal...
class SpacesConfig(): def __init__(self, action_spaces_dict: Dict[(StepKeyType, gym.spaces.Dict)], observation_spaces_dict: Dict[(StepKeyType, gym.spaces.Dict)], agent_counts_dict: Dict[(StepKeyType, int)]): self.action_spaces_dict = action_spaces_dict self.observation_spaces_dict = observation_spac...
class SimpleType(object): NONE = _types_pb2.NONE INTEGER = _types_pb2.INTEGER FLOAT = _types_pb2.FLOAT STRING = _types_pb2.STRING BOOLEAN = _types_pb2.BOOLEAN DATETIME = _types_pb2.DATETIME DURATION = _types_pb2.DURATION BINARY = _types_pb2.BINARY ERROR = _types_pb2.ERROR STRUCT ...
def extractJoshuasagehiddenkitchenWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')] for (tagname, ...
def test_fft_with_axis_given_returns_correct_arrays(): data = np.sin(((((2 * np.pi) * 1) * np.arange(10)) / (1000 // 100))) data_2 = np.vstack((data, data)) (frequencies, magnitude, phase) = scared.signal_processing.fft(data_2, .0) (frequencies_axis, magnitude_axis, phase_axis) = scared.signal_processin...
def test_cli_stack_decorators(): cli = Radicli() ran = 0 ('one', a=Arg('--a'), b=Arg('--b')) ('two', a=Arg('--a'), b=Arg('--b')) ('three', a=Arg('--a'), b=Arg('--b')) def test(a: str, b: int): assert (a == 'hello') assert (b == 1) nonlocal ran ran += 1 args = ...
def get_default(form: FlowResult, key: str) -> Any: for schema_key in form['data_schema'].schema: if (schema_key == key): if (schema_key.default != vol.UNDEFINED): return schema_key.default() return None raise KeyError(f"Key '{key}' not found")
def parse_args(argv=None): parser = argparse.ArgumentParser() parser.add_argument('--host', required=False, help='Host to bind server to.') parser.add_argument('--port', type=int, default=8080, help='The port to listen to.') parsed_args = parser.parse_args(argv) return parsed_args
def extractHuwlangridgeBlogspotCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')] for (tagname, name, tl_typ...
class OptionSeriesErrorbarSonificationDefaultspeechoptionsMappingTime(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: str): ...
class YoutubeTemplates(): def not_connected(self): return '<service xmlns="urn:dial-multiscreen-org:schemas:dial">\n <name>YouTube</name>\n <options allowStop="true"/>\n <state>stopped</state>\n </service>' def connected(self): ...
_required def edit_entry(request, entry_id): entry = Entry.objects.get(id=entry_id) topic = entry.topic if (topic.owner != request.user): raise Http404 if (request.method != 'POST'): form = EntryForm(instance=entry) else: form = EntryForm(instance=entry, data=request.POST) ...
def test_generate_control_doc(): job_control = proto_control.JobControl(remote=True, scavenging_benchmark=True) nighthawk_source = job_control.source.add() nighthawk_source.identity = proto_source.SourceRepository.SourceIdentity.SRCID_NIGHTHAWK nighthawk_source.source_url = ' nighthawk_source.branch...