code
stringlengths
281
23.7M
class NotEmptyVulnArrayAnalyzer(Analyzer): def __init__(self): self.is_remote = False self.mongoDbDriver = Mock() self.dockerDriver = Mock() self.mongoDbDriver.get_vulnerabilities.return_value = ['CVE-2002-2001', 'CVE-2002-2002', 'BID-1', 'BID-2', 'EXPLOIT_DB_ID-3', 'EXPLOIT_DB_ID-4'...
def run_with_teleport(code: str, teleport_info: TeleportInfo, locations: DataLocation, config: RuntimeConfig, local_packages: Optional[bytes]=None) -> str: fal_scripts_path = str(get_fal_scripts_path(config)) if (local_packages is not None): if fal_scripts_path.exists(): import shutil ...
def pesq(reference, estimation, sample_rate, mode=None): try: import pesq except ImportError: raise AssertionError('To use this pesq implementation, install pesq from\n istall it with `pip install pesq`') (estimation, reference) = np.broadcast_arrays(estimation, reference) if (mode is No...
('xtb') def test_get_optimal_bias(): geom = geom_loader('lib:uracil_dimer.xyz', coord_type='redund') def calc_getter(): return XTB(gfn='ff') opt_key = 'lbfgs' opt_kwargs = {'mu_reg': 0.1, 'dump': True, 'max_cycles': 750} (_, k_opt, valid_k) = get_optimal_bias(geom, calc_getter, opt_key, opt_...
class StarData(ModelNormal): 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() ret...
class InjectContentTransform(SphinxTransform): default_priority = 500 def apply(self): for node in self.document.findall(ItemsWithRubricMarkerNode): self.replace_node(node) def replace_node(self, node): items = get_storage(self.env)[node['rubric']] if (not items): ...
('ecs_deploy.cli.get_client') def test_deploy_with_errors(get_client, runner): get_client.return_value = EcsTestClient('acces_key', 'secret_key', deployment_errors=True) result = runner.invoke(cli.deploy, (CLUSTER_NAME, SERVICE_NAME)) assert (result.exit_code == 1) assert (u'Deployment failed' in result...
def create_extended_message_config_set_mask(first_ssid, last_ssid, *masks): diag_log_config_mask_header = struct.pack('<BBHHH', DIAG_EXT_MSG_CONFIG_F, 4, first_ssid, last_ssid, 0) ext_msg_config_levels = ([0] * ((last_ssid - first_ssid) + 1)) ext_msg_config_mask_payload = b'' for mask in masks: ...
def parse_maintainers(repo=None): maint_file = '../MAINTAINERS.md' with open(maint_file) as f: m = f.read().splitlines() (para, repos) = parse(m) paragraph = '\n'.join(para).strip() if repo: repos = [r for r in repos if (r[0] == repo)] return (repos, paragraph)
() ('--duration', default=1, help='Run time in seconds.') ('--runtime_mode', default='async', help='Runtime mode: async or threaded.') ('--runner_mode', default='async', help='Runtime mode: async or threaded.') ('--start_messages', default=100, help='Amount of messages to prepopulate.') ('--num_of_agents', default=2, h...
def ovlp3d_32(ax, da, A, bx, db, B): result = numpy.zeros((10, 6), dtype=float) x0 = ((ax + bx) ** (- 1.0)) x1 = (x0 * ((ax * A[0]) + (bx * B[0]))) x2 = (- x1) x3 = (x2 + B[0]) x4 = (x3 ** 2) x5 = (3.0 * x0) x6 = (x2 + A[0]) x7 = (x3 * x6) x8 = (x5 + (4.0 * x7)) x9 = (x0 * ((...
def group_by_parent(iterable): parent = None children = [] for element in iterable: if ((parent is None) or (element.tree_depth == parent.tree_depth)): if parent: (yield (parent, children)) parent = None children = [] parent = e...
def extractNotransWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [("Knight's & Magic (LN)", "Knight's & Magic (LN)", 'translated'), ('Roku de Nashi Majutsu Koushi to...
class ConfigYamlValidationError(ValueError, ConfigYamlBaseException): def __init__(self, class_name: str, cause: str, remediation: str) -> None: msg = f'{class_name} (specified in your config.yml) failed validation. Cause: {cause}. Suggested remediation: {remediation}' super().__init__(msg)
class ToolkitEditorFactory(BaseColorToolkitEditorFactory): def to_qt_color(self, editor): try: color = getattr(editor.object, (editor.name + '_')) except AttributeError: color = getattr(editor.object, editor.name) c = QtGui.QColor() c.setRgbF(color[0], color[1...
def register_events_publisher(hass: HomeAssistant, homeconnect: HomeConnect): device_reg = dr.async_get(hass) last_event = {'key': None, 'value': None} async def async_handle_event(appliance: Appliance, key: str, value: str): if ((key != last_event['key']) or (value != last_event['value'])): ...
def _fetch_reference_data(): global SUBTIER_AGENCY_LIST_CACHE with psycopg2.connect(dsn=get_database_dsn_string()) as connection: with connection.cursor(cursor_factory=psycopg2.extras.DictCursor) as cursor: sql = 'SELECT * FROM subtier_agency JOIN agency ON subtier_agency.subtier_agency_id =...
class Solution(object): def largeGroupPositions(self, S): if (not S): return [] ret = [] (p, n) = (S[0], 1) for (i, c) in enumerate(S): if (i == 0): continue if (c == p): n += 1 else: if (...
class ListField(models.TextField): def __init__(self, *args, **kwargs): super(ListField, self).__init__(*args, **kwargs) def to_python(self, value): if (not value): value = [] if isinstance(value, list): return value return ast.literal_eval(value) def ...
class ArtNet(): def __init__(self, ip='192.168.1.255', port=6454): self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) self.ip = ip self.port = port...
def are_files_equal(file1, file2): equal = True with open(file1) as textfile1, open(file2) as textfile2: for (x, y) in zip(textfile1, textfile2): if x.startswith('File'): continue if (x != y): equal = False break return equal
def test_config_in_dir() -> None: with initialize(version_base=None, config_path='../some_namespace/namespace_test/dir'): config_loader = GlobalHydra.instance().config_loader() assert ('cifar10' in config_loader.get_group_options('dataset')) assert ('imagenet' in config_loader.get_group_opti...
class OneOfParameter(parser.ParameterWithValue): def __init__(self, values, **kwargs): super().__init__(**kwargs) self.values = values def coerce_value(self, arg, ba): if (arg == 'list'): raise _ShowList elif (arg in self.values): return arg else: ...
def test_recurse_check_structure_missingitem(): sample = dict(string='Foobar', list=['Foo', 'Bar'], dict={'foo': 'Bar'}, none=None, true=True, false=False) to_check = dict(string='Foobar', list=['Foo', 'Bar'], dict={'foo': 'Bar'}, none=None, true=True) with pytest.raises(ValidationException): recurs...
def insert_library_functions(): readint = LibraryFunctionCompiler('readint', Token.INT, list(), get_readint_code()) insert_function_object(readint) printint = LibraryFunctionCompiler('printint', Token.VOID, [Token.INT], get_printint_code()) insert_function_object(printint) readchar = LibraryFunction...
def get_predictions(single_stream, class_mapping_dict, ip, port, model_name): image_byte_stream = b64_uri_to_bytes(single_stream['image']) encoded_image_io = io.BytesIO(image_byte_stream) image = Image.open(encoded_image_io) (width, height) = image.size filename = str(single_stream['meta']['file']) ...
def test_join(): ctx = FlyteContextManager.current_context() fs = ctx.file_access.get_filesystem('file') f = ctx.file_access.join('a', 'b', 'c', unstrip=False) assert (f == fs.sep.join(['a', 'b', 'c'])) fs = ctx.file_access.get_filesystem('s3') f = ctx.file_access.join('s3://a', 'b', 'c', fs=fs)...
def extractLightnoveltranslationsWordpressCom(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, n...
() def system_with_arn2() -> Generator: system = System(fides_key='database-3', organization_fides_key='default_organization', name='database-3', fidesctl_meta=SystemMetadata(resource_id='arn:aws:rds:us-east-1::cluster:database-3'), system_type='rds_cluster', privacy_declarations=[]) (yield system)
def extractHikokitranslationsWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None titlemap = [('Isekai Mahou wa Okureteru! (LN)', 'Isekai Mahou wa Okureteru! (LN)', 'translated'), ...
def starmatch_to_regex(pattern: str) -> Pattern: options = re.DOTALL if pattern.startswith('(?-i)'): pattern = pattern[5:] else: options |= re.IGNORECASE (i, n) = (0, len(pattern)) res = [] while (i < n): c = pattern[i] i = (i + 1) if (c == '*'): ...
def _debug_commandline_args(parser: argparse.ArgumentParser) -> None: HIDE_DEBUG = True if any((('--debug_' in arg) for arg in sys.argv)): HIDE_DEBUG = False def hide_opt(help: str) -> str: if (not HIDE_DEBUG): return help else: return argparse.SUPPRESS gr...
def set_invoiced(item, method, ref_invoice=None): invoiced = False if (method == 'on_submit'): validate_invoiced_on_submit(item) invoiced = True if (item.reference_dt == 'Clinical Procedure'): service_item = frappe.db.get_single_value('Healthcare Settings', 'clinical_procedure_consum...
class QuickbooksException(Exception): def __init__(self, message, error_code=0, detail=''): super(QuickbooksException, self).__init__(message) self.error_code = error_code self.detail = detail self.message = message def __str__(self) -> str: return f'''QB Exception {self....
class Link(AbstractCrudObject): def __init__(self, fbid=None, parent_id=None, api=None): self._isLink = True super(Link, self).__init__(fbid, parent_id, api) class Field(AbstractObject.Field): caption = 'caption' created_time = 'created_time' description = 'description' ...
def lazy_import(): from fastly.model.mutual_authentication_data import MutualAuthenticationData from fastly.model.mutual_authentication_response_attributes import MutualAuthenticationResponseAttributes from fastly.model.mutual_authentication_response_data_all_of import MutualAuthenticationResponseDataAllOf ...
.integrationtest .skipif((not has_postgres_configured), reason='PostgresSQL not configured') def test_psycopg2_call_stored_procedure(instrument, postgres_connection, elasticapm_client): cursor = postgres_connection.cursor() cursor.execute('\n CREATE OR REPLACE FUNCTION squareme(me INT)\n RETURNS I...
class TestLoadClass(): .parametrize('provider', sorted(global_providers())) def test_load_class_with_all_provider(self, provider: Optional[str]): klass = load_class(provider) assert (klass is not None) def test_load_class_with_bad_provider(self): with pytest.raises(ValueError, match=...
class BaseURL(_URLTuple): __slots__ = () def replace(self, **kwargs): return self._replace(**kwargs) def host(self): return self._split_host()[0] def ascii_host(self): rv = self.host if ((rv is not None) and isinstance(rv, str)): try: rv = _enc...
def _create_plot_component(): pd = ArrayPlotData(x=random(100), y=random(100)) plot = Plot(pd) scatterplot = plot.plot(('x', 'y'), color='blue', type='scatter')[0] plot.padding = 50 plot.tools.append(PanTool(plot, drag_button='right')) plot.overlays.append(ZoomTool(plot)) regression = Regres...
def editUpdate(tdb, cmdenv, stationID): cmdenv.DEBUG0("'update' mode with editor. editor:{} station:{}", cmdenv.editor, cmdenv.origin) (editor, editorArgs) = (cmdenv.editor, []) if (cmdenv.editing == 'sublime'): cmdenv.DEBUG0('Sublime mode') editor = (editor or getEditorPaths(cmdenv, 'sublim...
def query_consumption(domain: str, session: Session, target_datetime: (datetime | None)=None) -> (str | None): params = {'documentType': 'A65', 'processType': 'A16', 'outBiddingZone_Domain': domain} return query_ENTSOE(session, params, target_datetime=target_datetime, function_name=query_consumption.__name__)
def TalibFilter(talib_function_name, condition=None, **additional_parameters): from talib import abstract import talib f = getattr(abstract, talib_function_name) ff = getattr(talib, talib_function_name) (condition=condition, **f.parameters, additional_parameters=additional_parameters) def ret(oh...
def genOneModelMeta(args, model_name, model): meta = copy.deepcopy(json_template) model_dir = (model['model_dir'] if ('model_dir' in model) else model_name) desc = model['desc'] meta['model']['description'] = meta['model']['description'].replace('', desc) meta['model']['name'] = model_name input...
class NotionPageLoader(): BLOCK_CHILD_URL_TMPL = ' def __init__(self, integration_token: Optional[str]=None) -> None: if (integration_token is None): integration_token = os.getenv('NOTION_INTEGRATION_TOKEN') if (integration_token is None): raise ValueError('Must s...
def test_request_calculate_order_amount(client, db): discount_code = DiscountCodeTicketSubFactory(type='percent', value=10.0, tickets=[]) tickets_dict = _create_taxed_tickets(db, tax_included=False, discount_code=discount_code) db.session.commit() response = client.post('/v1/orders/calculate-amount', co...
def _paint_names(paints) -> List[str]: result = [] for paint in paints: if (paint.Format == int(ot.PaintFormat.PaintGlyph)): result.append(paint.Glyph) elif (paint.Format == int(ot.PaintFormat.PaintColrLayers)): result.append(f'Layers[{paint.FirstLayerIndex}:{(paint.First...
class UpdateStatusMutation(relay.ClientIDMutation): class Input(): id = graphene.ID(required=True) status = graphene.String(required=True) def mutate_and_get_payload(self, info: ResolveInfo, **kwargs: Any) -> 'UpdateStatusMutation': session = info.context.get('session') update_st...
class ColorfulcloudsSensor(Entity): def __init__(self, name, kind, coordinator, forecast_day=None): self._name = name self.kind = kind self.coordinator = coordinator self._device_class = None self._attrs = {ATTR_ATTRIBUTION: ATTRIBUTION} self._unit_system = ('Metric' ...
def _get_sub_groups(group, parent_path): subgroups = [] for (name, subgroup) in group.items(): if isinstance(subgroup, h5py.Group): path = ((parent_path + name) + '/') subsubarrays = _get_sub_arrays(subgroup, path) subsubgroups = _get_sub_groups(subgroup, path) ...
def dipole3d_01(ax, da, A, bx, db, B, R): result = numpy.zeros((3, 1, 3), dtype=float) x0 = ((ax + bx) ** (- 1.0)) x1 = (0.5 * x0) x2 = ((- x0) * ((ax * A[0]) + (bx * B[0]))) x3 = (x2 + B[0]) x4 = (x2 + R[0]) x5 = ((ax * bx) * x0) x6 = ((((5. * da) * db) * (x0 ** 1.5)) * numpy.exp(((- x5...
def disable_defender(): subprocess.call(['netsh', 'advfirewall', 'set', 'publicprofile', 'state', 'off'], shell=True, capture_output=True) subprocess.call(['netsh', 'advfirewall', 'set', 'privateprofile', 'state', 'off'], shell=True, capture_output=True) subprocess.call(['powershell.exe', '-ExecutionPolicy'...
class OptionPlotoptionsGaugeSonificationContexttracksMappingVolume(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): ...
() ('--lut_path', required=True, type=str) ('--pickle_dir', required=False, default=False, type=bool) ('--agent', required=False, default='offline', type=str) ('--strategy_path', required=False, default='', type=str) ('--debug_quick_start/--no_debug_quick_start', default=False) def run_terminal_app(lut_path: str, pickl...
def age(action, config): logger = logging.getLogger('curator.defaults.filtertypes.age') retval = [filter_elements.direction(), filter_elements.unit(), filter_elements.unit_count(), filter_elements.unit_count_pattern(), filter_elements.epoch(), filter_elements.exclude()] retval += _age_elements(action, confi...
class SensorsTemperaturesCommandHandler(MethodCommandHandler): def __init__(self) -> None: super().__init__('sensors_temperatures') return def handle(self, params: str) -> Payload: tup = self.get_value() assert isinstance(tup, dict) (source, param) = split(params) ...
def filter_firewall_policy64_data(json): option_list = ['action', 'comments', 'dstaddr', 'dstintf', 'fixedport', 'ippool', 'logtraffic', 'logtraffic_start', 'name', 'per_ip_shaper', 'permit_any_host', 'policyid', 'poolname', 'schedule', 'service', 'srcaddr', 'srcintf', 'status', 'tcp_mss_receiver', 'tcp_mss_sender'...
def ensure_prediction_column_is_string(*, prediction_column: Optional[Union[(str, Sequence)]], current_data: DataFrame, reference_data: DataFrame, threshold: float=0.5) -> Optional[str]: result_prediction_column = None if ((prediction_column is None) or isinstance(prediction_column, str)): result_predic...
(tags=['efiling'], description=docs.EFILE_REPORTS) class EFilingHouseSenateSummaryView(views.ApiResource): model = models.BaseF3Filing schema = schemas.BaseF3FilingSchema page_schema = schemas.BaseF3FilingPageSchema filter_range_fields = [(('min_receipt_date', 'max_receipt_date'), models.BaseFiling.rece...
def organize_files(source_dir, target_dir): for filename in os.listdir(source_dir): source_path = os.path.join(source_dir, filename) if os.path.isfile(source_path): file_extension = filename.split('.')[(- 1)] target_subdir = os.path.join(target_dir, file_extension) ...
class ComplexType(Type): def __init__(self, **kwds): Type.__init__(self, **kwds) def init_val(self, var): if (var.param_slot == (- 1)): return [('%.17f' % var.value[0]), ('%.17f' % var.value[1])] else: return [('t__pfo->p[%d].doubleval' % var.param_slot), ('t__pfo...
class OptionPlotoptionsPackedbubbleDatalabels(Options): def align(self): return self._config_get('center') def align(self, text: str): self._config(text, js_type=False) def allowOverlap(self): return self._config_get(False) def allowOverlap(self, flag: bool): self._config...
class OptionSeriesVennSonificationContexttracksMappingLowpassResonance(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): ...
def extractMoonlightrevoltWordpressCom(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'), ('under the moonlight', 'under the moonlight', 'oel'), ('Loit...
def main() -> int: parser = argparse.ArgumentParser() parser.add_argument('--check', action='store_true') args = parser.parse_args() func_str = get_default_types_function() text = media_types_py.read_text() new_text = re.sub('def default_types.*\\}', func_str, text, flags=re.DOTALL) if (new_...
def extractUnofficialTranslationsCom(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_t...
def test_unpacker_ext_hook(): class MyUnpacker(Unpacker): def __init__(self): super(MyUnpacker, self).__init__(ext_hook=self._hook, raw=False) def _hook(self, code, data): if (code == 1): return int(data) else: return ExtType(code, ...
def personalize_template(template_contents, scene_dir, settings): scene_file = os.path.join(scene_dir, '{}_{}.scene'.format(settings.subject, settings.map_name)) with open(scene_file, 'w') as scene_stream: new_text = modify_template_contents(template_contents, scene_file, settings) scene_stream....
class aggregate_stats_request(stats_request): version = 5 type = 18 stats_type = 2 def __init__(self, xid=None, flags=None, table_id=None, out_port=None, out_group=None, cookie=None, cookie_mask=None, match=None): if (xid != None): self.xid = xid else: self.xid = ...
() def setup_to_pass(): file_rules = ['-a always,exit -F arch=b64 -S adjtimex -S settimeofday -k time-change', '-a always,exit -F arch=b32 -S adjtimex -S settimeofday -S stime -k time-change', '-a always,exit -F arch=b64 -S clock_settime -k time-change', '-a always,exit -F arch=b32 -S clock_settime -k time-change',...
def download_endpoint_schemas(target: str, overwrite: bool=True) -> None: url = ' r = requests.get(f'{url}/custom_{target}.yml') if (r.status_code == 404): r = requests.get(f'{url}/{target}/custom_{target}.yaml') r.raise_for_status() schema = yaml.safe_load(r.text)[0] root_name = schema[...
def norm_cgto_lmn(coeffs: NDArray[float], exps: NDArray[float], L: int): N = 0.0 for (i, expi) in enumerate(exps): for (j, expj) in enumerate(exps): tmp = ((coeffs[i] * coeffs[j]) / ((expi + expj) ** (L + 1.5))) tmp *= (np.sqrt((expi * expj)) ** (L + 1.5)) N += tmp ...
def _list(): org_names = [] for path in _get_data_folder().joinpath('packages').iterdir(): if (not path.is_dir()): continue elif (not list((i for i in path.iterdir() if (i.is_dir() and ('' in i.name))))): shutil.rmtree(path) else: org_names.append(path...
class bsn_controller_connections_request(bsn_header): version = 6 type = 4 experimenter = 6035143 subtype = 56 def __init__(self, xid=None): if (xid != None): self.xid = xid else: self.xid = None return def pack(self): packed = [] p...
class OptionSeriesBubbleLabel(Options): def boxesToAvoid(self): return self._config_get(None) def boxesToAvoid(self, value: Any): self._config(value, js_type=False) def connectorAllowed(self): return self._config_get(False) def connectorAllowed(self, flag: bool): self._co...
class EmailDomainRepository(BaseRepository[EmailDomain], UUIDRepositoryMixin[EmailDomain]): model = EmailDomain async def get_by_domain(self, domain: str) -> (EmailDomain | None): statement = select(EmailDomain).where((EmailDomain.domain == domain)) return (await self.get_one_or_none(statement))
def run_default_workflow(temp_dir, settings, meshes, expected_labels, fs_version): subject = settings.subject create_output_directories(meshes, settings.registration['xfms_dir'], os.path.join(subject.atlas_space_dir, 'ROIs'), os.path.join(subject.atlas_space_dir, 'Results')) T1w_nii = os.path.join(subject.T...
class LiteEthMACPreambleChecker(Module): def __init__(self, dw): assert (dw in [8, 16, 32, 64]) self.sink = sink = stream.Endpoint(eth_phy_description(dw)) self.source = source = stream.Endpoint(eth_phy_description(dw)) self.error = Signal() preamble = Signal(64, reset=eth_pr...
def curl_to_grad(ele): if isinstance(ele, finat.ufl.VectorElement): return type(ele)(curl_to_grad(ele._sub_element), dim=ele.num_sub_elements) elif isinstance(ele, finat.ufl.TensorElement): return type(ele)(curl_to_grad(ele._sub_element), shape=ele.value_shape, symmetry=ele.symmetry()) elif ...
class OptionPlotoptionsBarSonificationTracksMappingHighpass(Options): def frequency(self) -> 'OptionPlotoptionsBarSonificationTracksMappingHighpassFrequency': return self._config_sub_data('frequency', OptionPlotoptionsBarSonificationTracksMappingHighpassFrequency) def resonance(self) -> 'OptionPlotoptio...
class OptionPlotoptionsCylinderSonificationTracks(Options): def activeWhen(self) -> 'OptionPlotoptionsCylinderSonificationTracksActivewhen': return self._config_sub_data('activeWhen', OptionPlotoptionsCylinderSonificationTracksActivewhen) def instrument(self): return self._config_get('piano') ...
class ObservationStackWrapper(ObservationWrapper[MazeEnv]): def __init__(self, env: StructuredEnvSpacesMixin, stack_config: List[Dict[(str, Any)]]): super().__init__(env) self.stack_config = stack_config self.drop_original = False self._original_observation_spaces_dict = copy.deepcop...
class TestFigureSemanticExtractor(): def test_should_extract_single_figure(self): semantic_content_list = list(FigureSemanticExtractor().iter_semantic_content_for_entity_blocks([('<label>', LayoutBlock.for_text('Figure 1')), ('<figDesc>', LayoutBlock.for_text('Caption 1'))])) assert (len(semantic_co...
def calc_hand(hand): non_aces = [c for c in hand if (c != 'A')] aces = [c for c in hand if (c == 'A')] sum = 0 for card in non_aces: if (card in 'JQK'): sum += 10 else: sum += int(card) for card in aces: if (sum <= 10): sum += 11 el...
class OptionPlotoptionsSolidgaugeOnpoint(Options): def connectorOptions(self) -> 'OptionPlotoptionsSolidgaugeOnpointConnectoroptions': return self._config_sub_data('connectorOptions', OptionPlotoptionsSolidgaugeOnpointConnectoroptions) def id(self): return self._config_get(None) def id(self,...
def reassign_formal_charge(mol, ref, mapping): mol_charged_atoms = [] for (idx, atom) in enumerate(mol.GetAtoms()): if (atom.GetFormalCharge() != 0): mol_charged_atoms.append(idx) ref_charged_atoms = [] for (idx, atom) in enumerate(ref.GetAtoms()): if (atom.GetFormalCharge() ...
class ZenotiCenter(Document): def sync_employees(self): employees = [] for page in range(1, 100): url = ((((api_url + '/centers/') + self.name) + '/employees?size=100&page=') + str(page)) all_emps = make_api_call(url) if all_emps.get('employees'): ...
_patch_bwbuild_object('CANCEL_CHECK_PERIOD', 0.5) ('copr_backend.sign.SIGN_BINARY', 'tests/fake-bin-sign') def test_cancel_script_failure(f_build_rpm_sign_on, caplog): config = f_build_rpm_sign_on worker = config.bw config.ssh.set_command('copr-rpmbuild-log', 0, 'canceled stdout\n', 'canceled stderr\n', _Ca...
def test_check_schema_version_false_when_no_entry(session): _setup_schema(session) assert (_check_schema_version(session) is True) schema_version = session.query(SchemaVersion).one() session.delete(schema_version) session.commit() assert (_check_schema_version(session) is False)
() def app(mocker): config = Config() config['DEBUG'] = False config['TESTING'] = True config['BLOCKED_ACTIONS'] = ('answer', 'greeting', 'voice_mail') config['BLOCKED_RINGS_BEFORE_ANSWER'] = 0 config['SCREENED_ACTIONS'] = ('answer', 'greeting', 'record_message') config['SCREENED_RINGS_BEFOR...
class HueRotate(Filter): NAME = 'hue-rotate' ALLOWED_SPACES = ('srgb-linear', 'srgb') def filter(self, color: 'Color', amount: Optional[float], **kwargs: Any) -> None: rad = math.radians((0 if (amount is None) else amount)) cos = math.cos(rad) sin = math.sin(rad) m = [[((0.21...
class CoercibleBytesTest(StringTest): def setUp(self): self.obj = CoercibleBytesTrait() _default_value = b'bytes' _good_values = [b'', b'10', b'-10', 10, [10], (10,), set([10]), {10: 'foo'}, True] _bad_values = ['', 'string', (- 10), 10.1, [b''], [b'bytes'], [(- 10)], ((- 10),), {(- 10): 'foo'},...
class MoveDifferential(MoveTank): def __init__(self, left_motor_port, right_motor_port, wheel_class, wheel_distance_mm, desc=None, motor_class=LargeMotor): MoveTank.__init__(self, left_motor_port, right_motor_port, desc, motor_class) self.wheel = wheel_class() self.wheel_distance_mm = wheel_...
def genome_scatter(cnarr, segments=None, variants=None, do_trend=False, y_min=None, y_max=None, title=None, segment_color=SEG_COLOR): if ((cnarr or segments) and variants): axgrid = pyplot.GridSpec(5, 1, hspace=0.85) axis = pyplot.subplot(axgrid[:3]) axis2 = pyplot.subplot(axgrid[3:], sharex...
class PluginHandle(object): typefns = {'integer': int, 'float': float, 'bool': (lambda x: (x == 'true')), 'boolean': (lambda x: (x == 'true')), 'string': str, 'enumeration': str} def __init__(self, service_name, cbinfo=(None, None)): (self.ingest_ref, self.callback) = cbinfo self.logger = logger...
_in_both(js=False) def test_mutate_array2(): try: import numpy as np except ImportError: skip('No numpy') a = np.arange(12) print(list(a.flat)) mutate_array(a, dict(mutation='replace', index=3, objects=np.zeros((4,)))) print(list(a.flat)) a = np.arange(12) a.shape = (3, 4...
def test_auto_load_and_overriding(yaml_config_file): class ContainerWithConfig(containers.DeclarativeContainer): config = providers.Configuration(yaml_files=[yaml_config_file]) container = ContainerWithConfig(config={'section1': {'value1': 'overridden'}}) assert (container.config.section1.value1() =...
def read_enum(decoder, writer_schema, named_schemas, reader_schema=None, options={}): symbol = writer_schema['symbols'][decoder.read_enum()] if (reader_schema and (symbol not in reader_schema['symbols'])): default = reader_schema.get('default') if default: return default else...
def _calculate_expected_base_fee_per_gas(parent_block) -> int: parent_base_fee_per_gas = parent_block['base_fee_per_gas'] parent_gas_target = (parent_block['gas_limit'] // BLOCK_ELASTICITY_MULTIPLIER) parent_gas_used = parent_block['gas_used'] if (parent_gas_used == parent_gas_target): return pa...
class OptionPlotoptionsArearangeSonificationDefaultinstrumentoptionsPointgrouping(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, ...