content
stringlengths
22
815k
id
int64
0
4.91M
def get_topic(topic_id): """ Endpunkt `/topic/<topic_id>`. Der Response enthält die JSON-Datei des Thema. """ try: file_path = queries.get_topic_file(topic_id) if file_path is None: err = flask.jsonify({"err_msg": "Unknown topic"}) return err, 400 r...
41,300
def get_epaipm_file(filename, read_file_args, data_dir): """Reads in files to create dataframes. No need to use ExcelFile objects with the IPM files because each file is only a single sheet. Args: filename (str): ['single_transmission', 'joint_transmission'] read_file_args (dict): dict...
41,301
def file_(): """Operations on the device state file.""" pass
41,302
def futures_rule(trade_date: str = "20200712") -> pd.DataFrame: """ 国泰君安期货-交易日历数据表 https://www.gtjaqh.com/pc/calendar.html :return: 交易日历数据 :rtype: pandas.DataFrame """ url = "https://www.gtjaqh.com/fn/128" params = {"base_date": f"{trade_date}"} r = requests.post(url, json=params) ...
41,303
def conjgrad_scipy(A, Y, sigma, tol=1e-4): """Solve the least-squares system using Scipy's conjugate gradient.""" import scipy.sparse.linalg Y, m, n, d, matrix_in = _format_system(A, Y) damp = m * sigma**2 calcAA = lambda x: np.dot(A.T, np.dot(A, x)) + damp * x G = scipy.sparse.linalg.LinearOpe...
41,304
def get_total_revenue(data: list) -> float: """ data: any list with product_id at [0] and revenue at [1] returns: total revenue for data """ revenue = get_revenue(data) total = 0 for r in revenue: total += r[1] return float(total)
41,305
def plot_tttdprc(data_frame): """ Plot Change Total Travel Time % vs distance """ figtt, axtt = plot_var( data_frame=data_frame, x_var="distance", y_var="totTT %", label_var="mpr", pivot="flow", x_label="Distance [m]", y_label=r"Change in Tota...
41,306
def test_fetch_secret(test_dbt_pipeline, test_secret): """Tests obtaining credentials from a mock secretsmanager secret and ensuring the fetched SecretString and ARN match the mocked secret """ if os.environ.get("DBT_PASS"): del os.environ["DBT_PASS"] expected_arn = test_secret["expecte...
41,307
def test_alibibaclass_request(): """AlibabaHost._request""" import apyfal.host.alibaba as alibaba from apyfal.host.alibaba import AlibabaCSP import apyfal.exceptions as exc from aliyunsdkcore import client from aliyunsdkcore.acs_exception.exceptions import ServerException # Mocks some varia...
41,308
def write_pdf_file( fpath: pathlib.Path, puzzle: Puzzle, key: Key, level: int, ) -> pathlib.Path: """Write a PDF file of the current puzzle to `path`. Args: fpath (pathlib.Path): Path to write the CSV to. puzzle (Puzzle): Current Word Search puzzle. key (Key): Puzzle Ans...
41,309
def stage_files(repo_dir: str): """ Stage the modified files in the repo. :param repo_dir: The directory of the repo. :return: """ git_add_changes = subprocess.run( ["git", "add", "."], cwd=Path(os.getcwd(), working_dir, repo_dir), capture_output=True, ) if git_...
41,310
def evaluate(model, dur=750): """ TODO """ patient = HIVPatient(clipping=False, logscale=False) x = patient.reset(mode="unhealthy", extras="small-infection:immunity-failure") dur = dur // 5 states = [x] rewards = [] actions = [] t = trange(dur, desc="evaluation", leave=False)...
41,311
def _unschedule(zkclient, instanceid): """Safely delete scheduled node.""" scheduled_node = z.path.scheduled(instanceid) # Check placement node. Only delete scheduled app if it is currently # placed on the server. # # If we are processing stale events, app can be placed elsewhere, and in # ...
41,312
def throttling_unshift(d, e): """Rotates the elements of the list to the right. In the javascript, the operation is as follows: for(e=(e%d.length+d.length)%d.length;e--;)d.unshift(d.pop()) """ e = throttling_mod_func(d, e) new_arr = d[-e:] + d[:-e] del d[:] for el in new_arr: d.a...
41,313
def create_table(client: bigquery.Client, dataset_id: str, table_id: str, schema: list): """ Creates a table according to the given schema in the specified project:dataset Args: client: BQ API client dataset_id: destination dataset table_id: table to be created schema: schem...
41,314
def get_zip_rate_areas(file_path): """ reads zips.csv file and returns the content as a dictionary Args: file_path: the path to zips.csv file Returns: a dictionary mapping each zip code into a set of rate areas """ zip_rate_areas = dict() with open(file_path, "r") as zi...
41,315
def lucas_mod(n, mod): """ Compute n-th element of Fibonacci sequence modulo mod. """ P, Q = 1, -1 x, y = 0, 1 # U_n, U_{n+1}, n=0 for b in bin(n)[2:]: x, y = ((y - P * x) * x + x * y) % mod, (-Q * x * x + y * y) % mod # double if b == "1": x, y = y, (-Q * x + P * y...
41,316
def compute_demand_balancing(demand_sector, energy_service, energy_carrier): """aggregates the demand over balancing area and balancing time """ cols = get_group_cols_for_ec(energy_carrier) return compute_demand_with_coarseness(demand_sector, energy_service, ...
41,317
def test_interleaved_out(): """Two files input, interleaved output""" run_interleaved( '-q 20 -a TTAGACATAT -A CAGTGGAGTA -m 14 -M 90', inpath1='paired.1.fastq', inpath2='paired.2.fastq', expected1='interleaved.fastq' )
41,318
def check_directory_url_type(url): """ Check that ``url`` is a ``twisted.python.url.URL`` instance, raising `TypeError` if it isn't. """ if not isinstance(url, URL): raise TypeError( 'ACME directory URL should be a twisted.python.url.URL, ' 'got {!r} instead'.format(u...
41,319
def get_file_encoding(filename): """ Get the file encoding for the file with the given filename """ with open(filename, 'rb') as fp: # The encoding is usually specified on the second line txt = fp.read().splitlines()[1] txt = txt.decode('utf-8') if 'encoding' in txt: ...
41,320
def alias(name): """Make property given by name be known under a different name""" def get(self): return getattr(self,name) def set(self,value): setattr(self,name,value) return property(get,set)
41,321
def svc_labels_no_finetune(train_img_fnames, test_img_fnames, y, layer, webcam, conf): """ Use support vector machine (classifier) to predict label using features from layer activations Args: train_img_fnames: a list of paths to training images test_img_fnames: a list to paths to testing im...
41,322
def is_feature_class(symbol): """Check whether the symbols imported from a module correspond to classes defining a feature. We assume that the symbol in question defines a feature if it inherits from the FeatureDefinition class. :param symbol: An imported symbol to check :type symbol: object :r...
41,323
def patch_connect_slots(): """ Patches QtCore.QMetaObject.connectSlotsByName to catch SystemErrors. """ global _connect_slots_unpatched if _connect_slots_unpatched is not None: return # TODO there could be a version check here if we can isolate it _connect_slots_unpatched = QtCore...
41,324
def enforce_config(): """ A fixture that ensures that all checks for MODIN_* variables are done using modin.config to prevent leakage """ orig_env = os.environ modin_start = os.path.dirname(modin.__file__) modin_exclude = [os.path.dirname(modin.config.__file__)] class PatchedEnv: ...
41,325
def overall_sentiment(text): """Function to calculate the overall sentiment using NLTK's vader library. param text: The input text blob being entered by user """ sid = SentimentIntensityAnalyzer() ss = sid.polarity_scores(text) for _ in sorted(ss): if ss["compound"] >= 0.15: ...
41,326
def make_copernicus_hand(out_raster: Union[str, Path], vector_file: Union[str, Path]): """Copernicus GLO-30 Height Above Nearest Drainage (HAND) Make a Height Above Nearest Drainage (HAND) GeoTIFF from the Copernicus GLO-30 DEM covering the watershed boundaries (hydrobasins) defined in a vector file. ...
41,327
def test_absent_when_failing_to_describe_rule(global_config): """ Tests exceptions when checking rule existence """ global_config.conn_parameters["key"] = "".join( random.choice(string.ascii_lowercase + string.digits) for _ in range(50) ) patcher = patch("boto3.session.Session") mock...
41,328
def new_category(blog_id, username, password, category_struct): """ wp.newCategory(blog_id, username, password, category) => category_id """ authenticate(username, password, 'zinnia.add_category') category_dict = {'title': category_struct['name'], 'description': category_str...
41,329
def list_episodes(category): """ Create the list of playable items in Kodi interface. Args: category: podcast/category (str) Returns: None """ episodes = get_episodes(category) listing = [] for episode in episodes: # Create a list item with a text label and a th...
41,330
def test_shuffle_true(): """ Tests shuffle_urls parameter, len and set_epoch functions """ os.environ['AWS_REGION'] = 'us-west-2' # create two datasets, one shuffled with self.epoch s3_dataset_path = 's3://pt-s3plugin-test-data-west2/images/test' s3_dataset0 = S3IterableDataset(s3_dataset_...
41,331
def test_unpickle_gpuarray_as_numpy_ndarray_flag1(): """Only test when pygpu isn't available. test_unpickle_gpuarray_as_numpy_ndarray_flag0 in test_type.py test it when pygpu is there. """ if pygpu_activated: raise SkipTest("pygpu disabled") oldflag = config.experimental.unpickle_gpu_on...
41,332
def test_city(renderer_id): """ This test case appeared as problematic at some point """ for i, j in [(0, 0), (-4, -2)]: scene = Scene() c = StrippedCube(scale=(1, 1, 1), translate=(i, j, 0.5)) scene.add(c) scene.look_at((1.1, 0.8, 8.2), (0, 0.2, 0)) scene.perspec...
41,333
def scatt(coords, id, plot_col='w', bckg_col='k', z_dim=0, **kwargs): """ 2D scatter plot Parameters ---------- coords : np.array unit : str id : str plot_col : str, default = 'w' bckg_col : str, default = 'k' z_dim : int, default = 0 axes : AxesSubplot, optional Return...
41,334
def keep_text_characters(text): """ INPUT: text - Python str object - the raw text OUTPUT: text- Python str object - the text after removing all non-text characters """ filtered_tokens = [] tokens = tokenize_text(text) for token in tokens: if re.search('[a-zA-Z]', t...
41,335
def expm1(x): """ See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_expm1.html :param x: Argument. :type x: float64 :rtype: float64 """
41,336
def global_access(key, val): """function test""" local = 1 MY_DICT[key] = val for i in val: if i: del MY_DICT[i] continue else: break else: return local
41,337
def _ensure_esic_ext(pdf_writer: BasePdfFileWriter): """ Helper function to ensure that the output PDF is at least PDF 1.7, and that the relevant ESIC extension for PAdES is enabled if the version lower than 2.0. """ pdf_writer.ensure_output_version(version=(1, 7)) if pdf_writer.output_versi...
41,338
def generate_auxiliar_basis( sett: Settings, auxiliar_basis: str, quality: str) -> Settings: """Generate the `auxiliar_basis` for all the atoms in the `sett`. Use the`quality` of the auxiliar basis provided by the user. """ quality_to_number = {"low": 0, "medium": 1, "g...
41,339
async def test_state_changes_are_published_to_mqtt( hass, mqtt_mock_entry_with_yaml_config ): """Test publishing of MQTT messages when state changes.""" assert await async_setup_component( hass, alarm_control_panel.DOMAIN, { alarm_control_panel.DOMAIN: { "...
41,340
def extract_user_inputs(job: Job): """Extract the various combinations of user inputs for a job.""" # variables to be used while looping through the runs all_inputs = {} job_id = job.id results_folder = pathlib.Path('data', job_id).resolve() # loop through the runs and find all unique user input...
41,341
def __process_args(args): """ Process the command-line arguments and prompt the user for any missing information :param args: the command-line arguments list :raises CLAException: if an error occurs while validating and processing the command-line arguments """ cla_util = CommandLineArgUtil(_pro...
41,342
def container_updates(label): """Increment container update count based on label""" updated_containers_counter.labels(container=label).inc()
41,343
def float_converter(value: Any) -> float: """Validator that ensures value is a float.""" if isinstance(value, bool): raise ValueError() if isinstance(value, float): return value elif isinstance(value, int): return float(value) else: raise ValueError()
41,344
def setProcessingSite(config, site): """ _setProcessingSite_ Set the (CERN) site used for processing. """ config.Global.ProcessingSite = site return
41,345
def get_args(): """ Gets the arguments from the command line. """ parser = argparse.ArgumentParser("python infer.py") required, optional = parser._action_groups required.add_argument("-i", "--input", help="Audio (.wav) file to diarize", required=True) required.add_argument("--xml", help="Op...
41,346
def generate_row(world_x, world_rpy=[0.0, 0.0, 0.0], algae_obj_dir=None, algae_texture_dir=None): """Generate a row of algaes using the given world transform""" components = [] buoy_z = 0 rope_y = 0 rope_z = buoy_z + 2 anchoring_buoy_params = { ...
41,347
def split_chunk_for_display(raw_bytes): """ Given some raw bytes, return a display string Only show the beginning and end of largish (2x CONTENT_CHUNK_SIZE) arrays. :param raw_bytes: :return: display string """ CONTENT_CHUNK_SIZE = 50 # Content repeats after chunks this big - used by echo c...
41,348
def renew(port): """Renew an existing rule's expiration date. If an existing NAT rule will expire before it should, this allows you to set a new expiration date for the rule """ mgr = Manager() while True: if port is None: port = click.prompt('Enter the port number', type=in...
41,349
def _validate_base_url(url: str) -> None: """Validates the Base (DICOMweb service) URL supplied to `URI`.""" parse_result = urlparse.urlparse(url) if parse_result.scheme not in ('http', 'https'): raise ValueError( f'Only HTTP[S] URLs are permitted. Actual URL: {url!r}') if url.endswi...
41,350
def get_cvi(nodes): """ Returns a dictionary whose keys correspond to samples, and whose values are sets of tuples, where the tuples represnts the two characters this sample caused incompatability :param nodes: A list of target nodes, where each node is in the form 'Ch1|Ch2|....|Chn' :return: A dictionary w...
41,351
def determine_ports(): """Assemble a list of API ports for services the charm is managing @returns [ports] - list of ports that the charm manages. """ # TODO(ajkavanagh) - determine what other ports the service listens on # apart from the main CEILOMETER port cmp_codename = CompareOpenStackRele...
41,352
def validate_ip(name, ip): """IP is a list of 4 bytes.""" emsg1 = "{} type(ip): {}. It should be list".format(name, type(ip)) assert type(ip) == bytes, emsg1 emsg2 = "{} len(ip): {}. It should be 4".format(name, type(ip)) assert len(ip) == 4, emsg2 for num in ip: emsg3 = "{} type(num): {...
41,353
def warp(x, flo): """ warp an image/tensor (im2) back to im1, according to the optical flow x: [B, C, H, W] (im2) flo: [B, 2, H, W] flow """ B, C, H, W = x.size() # mesh grid xx = torch.arange(0, W).view(1,-1).repeat(H,1) yy = torch.arange(0, H).view(-1,1).repeat(1,W) xx = xx.vi...
41,354
async def search(username): """ Do Maigret search on a chosen username :return: - list of telegram messages - list of dicts with found results data """ try: results = await maigret_search(username) except Exception as e: logging.error(e) re...
41,355
async def test_discovered_by_dhcp_discovery_finds_non_steamist_device( hass: HomeAssistant, ) -> None: """Test we can setup when discovered from dhcp but its not a steamist device.""" with _patch_discovery(device=DEVICE_30303_NOT_STEAMIST), _patch_status( MOCK_ASYNC_GET_STATUS_INACTIVE ): ...
41,356
def train(frame, columns, mean_centered=True, k=None): """ Creates a PcaModel by training on the given frame Parameters ---------- :param frame: (Frame) A frame of training data. :param columns: (str or list[str]) Names of columns containing the observations for training. :param mean_cente...
41,357
def test_validate_template_url(): """Test validating an valid download template url.""" packagerbuddy.validate_template_url("http://test.com/{version}")
41,358
def validate_spin(value): """ Validate the value of the spin """ if not isinstance(value, int): raise ValidationError('spin must be integer') if value < -1 or value > 1: raise ValidationError('spin must be among -1, 1 or 0 (undefined)') return value
41,359
def _get_basis_functions(basis, deriv): """ Returns a list of interpolation function for the interpolation definition and derivatives specified by the user. Also returns the number of dimensions as defined in the basis parameter. """ # List of basis functions bsfn_list = { 'L1': [L1,...
41,360
def main(): """Create the model and start the training.""" args = get_arguments() cudnn.enabled = True n_discriminators = 5 logger = tb_logger.Logger(logdir= args.tensorboard_dir, flush_secs=2) # create teacher & student student_net = UNet(3, n_classes=args.num_classes) # saved_state_dic...
41,361
def get_all_loggers() -> List: """Return list of all registered loggers.""" logger_dict = logging.root.manager.loggerDict # type: ignore loggers = [logging.getLogger(name) for name in logger_dict] return loggers
41,362
def argmax(input, axis=None, dtype='int64', name=None): """Index of the maximum value along an axis. Parameters ---------- input : tensor_like Input tensor. axis : () tensor_like, default=None Axis along which to extract the maximum index. If None, work on the flattened tens...
41,363
def __clean(contents): """ remove comments from the list 'contents', and remove unnecessary whitespace """ answer = [] for line in contents: cleaned = string.strip(line) if len(cleaned)>0: if cleaned[0] != "#": answer.append(cleaned) return answer
41,364
def mail_admins(subject, message, fail_silently=False, priority=None): """ Add one or more new messages to the mail queue addressed to the site administrators (defined in ``settings.ADMINS``). This is a replacement for Django's ``mail_admins`` core email method. The ``fail_silently`` argument is o...
41,365
def _get_extract_params(): """ Utility function for extracting the parameters from a Prophet model. The following attributes are not considered for parameter extraction for the reasons listed: The changepoints attribute is being removed due to the fact that it is a utility NumPy array defining the d...
41,366
def deep_update(target, source): """Update a nested dictionary with another nested dictionary.""" for key, value in source.items(): if isinstance(value, Mapping): target[key] = deep_update(target.get(key, {}), value) else: target[key] = value return target
41,367
def markdown_parser(txt: str, entities: Dict[MessageEntity, str] = None, offset: int = 0) -> str: """ Parse a string, escaping all invalid markdown entities. Escapes URL's so as to avoid URL mangling. Re-adds any telegram code entities obtained from the entities object. :param txt: text to parse ...
41,368
def test_calc_vapour_concentration_air(): """Values taken from: https://www.engineeringtoolbox.com/relative-humidity-air-d_687.html""" temp_air = 20.0 relative_humidity = 57.8 ref_concentration = 10 assert abs(calc_vapour_concentration_air(temp_air, relative_humidity) - ref_concentration) < 0.1
41,369
def distmat(func: Callable, x: np.ndarray, y: np.ndarray) -> np.ndarray: """distance matrix""" return jax.vmap(lambda x1: jax.vmap(lambda y1: func(x1, y1))(y))(x)
41,370
def feature_length(attribute_name_var): """ Return number of a attribute values """ attribute = attrDictionary[attribute_name_var] attribute_index, attribute_values = attribute return len(attribute_values)
41,371
def iso2_to_country_name(country_2_code): """Convert country code to country name. """ if country_2_code not in COUNTRY_ALPHA2_TO_COUNTRY_NAME: print(country_2_code, 'NOT FOUND in iso2 to country_name') raise KeyError return COUNTRY_ALPHA2_TO_COUNTRY_NAME[country_2_code]
41,372
def get_related_objects(api_key: str, obj: MISPObject, rel: str, disable_output: bool = False) -> List[Dict]: """Gets related objects from VT.""" if obj.name == "file": vt_id = obj.get_attributes_by_relation("sha256")[0].value else: print_err("[REL] Currently only file objects are supported....
41,373
def _take_along_axis(arr, indices, axis): """Implements a simplified version of np.take_along_axis if numpy version < 1.15""" if np_version >= parse_version('1.15'): return np.take_along_axis(arr=arr, indices=indices, axis=axis) else: if axis is None: arr = arr.flatten() ...
41,374
def moveeffect_022(score: int, move: Move, user: Pokemon, target: Pokemon, battle: AbstractBattle) -> int: """ Move Effect Name: Increases user evasion by one stage """ if move.category == MoveCategory.STATUS: if user.boosts.get("evasion", 0) == 6: score -= 90 else: ...
41,375
def _01f_hybrid_pairing_check_(sf, adt, T, D, C, e): """Check the hybrid pairing through trace matrix `T`, complementary matrix `C`. `D` is the matrix for the Dirichlet boundary condition. Parameters ---------- sf adt T D C e Returns ------- """ raise NotImplem...
41,376
def chan_freq(header, fine_channel, tdwidth, ref_frame): """ Args: header: fine_channel: tdwidth: ref_frame: Returns: """ fftlen = header['NAXIS1'] chan_index = fine_channel - (tdwidth-fftlen)/2 chanfreq = header['FCNTR'] + (chan_index - fftlen/2)*header['DELTA...
41,377
def extract_logger_info( model_a: torch.nn.Module, model_b: torch.nn.Module, model_name_to_use_for_layer_names: str, ) -> Any: """ Extracts intermediate activations from model_a and model_b. """ model_name_a, results_a = _extract_logger_info_one_model(model_a) model_name_b, results_b = ...
41,378
def make_masked_msa(protein, config, replace_fraction): """Create data for BERT on raw MSA.""" # Add a random amino acid uniformly random_aa = tf.constant([0.05] * 20 + [0., 0.], dtype=tf.float32) categorical_probs = ( config.uniform_prob * random_aa + config.profile_prob * protein['hhblits_profile...
41,379
def get_httpserver_root(): """ Construct wingufile httpserver address and port. Returns: Constructed httpserver root. """ from winguhub.settings import HTTP_SERVER_ROOT assert HTTP_SERVER_ROOT is not None, "SERVICE_URL is not set in ccnet.conf." return HTTP_SERVER_ROOT
41,380
def get_incident_command(): """ Retrieves a single incident from ProofPoint API """ args = demisto.args() incident_id = args.pop('incident_id') fullurl = BASE_URL + 'api/incidents/{}.json'.format(incident_id) incident_data = requests.get( fullurl, headers={ 'C...
41,381
def passengers_per_city(list_of_airport_dicts): """ This function takes a list of airport data (e.g. the return from <read_csv_file>), and returns a new dictionary of airports in each state. The output dictionary should have the format: {<airport city>: <total number of passengers passing throu...
41,382
def csys_torusv1_to_xyz_jacobian(v: np.ndarray, rho_0: float, rho_1: float, aspect: float = 1) -> np.ndarray: """ Compute Jacobian matrix of the toroidal coordinate system with respect to the Cartesian coordinate system. :param v: Toroidal coordinates (r, psi, phi) :param rho_0: Torus Radius (major) ...
41,383
def teardown_all(win): """undraws all objects in the window""" for obj in win.items[:]: obj.undraw()
41,384
def normalize_answer(s): """ Lower text and remove punctuation, articles and extra whitespace. """ def remove_articles(text): return re_art.sub(' ', text) def white_space_fix(text): return ' '.join(text.split()) def remove_punc(text): return re_punc.sub(' ', text) # c...
41,385
def intensity(pixel: typing.Tuple[int, int, int]) -> int: """Sort by the intensity of a pixel, i.e. the sum of all the RGB values.""" return pixel[0] + pixel[1] + pixel[2]
41,386
def play(generator): """ Play indefinitely the given generator. Args: generator (derived class of ``SampleGenerator``): the generator to be played. """ player = Player(generator) try: player.start() # Event loop to keep playing. while True: ...
41,387
def load_statistics( input_path): """Loads data statistics proto from file. Args: input_path: Data statistics file path. Returns: A DatasetFeatureStatisticsList proto. """ serialized_stats = tf.python_io.tf_record_iterator(input_path).next() result = statistics_pb2.DatasetFeatureStatisticsList...
41,388
def plot_grid(data): """ Plot a grid of heatmaps showing performance for each tile pairing. """ def _draw_heatmap(*args, **kwargs): """ Draw a heatmap showing flops for (ch_vect x feat_vect). """ data = kwargs.pop('data') reshaped = pd.pivot_table( data, index='c...
41,389
def get_national_holiday(day: datetime.date) -> Optional[Holiday]: """ For a given date, return the national holiday object if the particular date is a Czech national holiday; return None otherwise """ for holiday in Holidays(year=day.year): if day == holiday: return holiday ...
41,390
def test_atomic_hex_binary_length_4_nistxml_sv_iv_atomic_hex_binary_length_5_3(mode, save_output, output_format): """ Type atomic/hexBinary is restricted by facet length with value 74. """ assert_bindings( schema="nistData/atomic/hexBinary/Schema+Instance/NISTSchema-SV-IV-atomic-hexBinary-length...
41,391
def robust_topological_sort(graph): """ First identify strongly connected components, then perform a topological sort on these components. graph should be a dictionary mapping node names to lists of successor nodes. """ components = strongly_connected_components(graph) node_component ...
41,392
def similar_consonants_to(phonet_1: UnmarkableConsonant) -> List[Phonet]: """ a list of vowels that are similar to a specified consonant. """ vocal_folds: List[VocalFolds] = similar_in_voice(phonet_1.vocal_folds) place: List[Place] = similar_in_place(phonet_1.place) manner: List[Manner] = similar_in_manner(phonet...
41,393
def error_handler(error): """Render errors as JSON""" if not all(hasattr(error, attr) for attr in ("code", "name", "description")): LOGGER.exception("An error occured: %r", error) error = InternalServerError() resp = { "code": error.code, "name": error.name, "descript...
41,394
def test_tag_exists(load_inpxml, load_outxml): """ Test of the tag_exists function """ from masci_tools.util.schema_dict_util import tag_exists xmltree, schema_dict = load_inpxml(TEST_INPXML_PATH, absolute=False) outxmltree, outschema_dict = load_outxml(TEST_OUTXML_PATH2, absolute=False) o...
41,395
def get_encoded_len_value(typename, package_specs): """ Get the encoded size of a given type on the wire """ if typename in PRIMITIVE_TYPES: return PRIMITIVE_SIZES[typename] encoded_len = 0 for package in package_specs: for msg in package.definitions: if get_v4_typen...
41,396
def bulk_insert_cluster_heatmap(session, cluster_table, cluster_str, errors='warn'): """ insert every row of cluster table """ # a list of all clusters to add all_clusters = [] for ind, row in cluster_table.iterrows(): # if there is no subcluster identification, input None subcl...
41,397
def parsestream(stream, encoding=None): """Parses sql statements from file-like object. :param stream: A file-like object. :param encoding: The encoding of the stream contents (optional). :returns: A generator of :class:`~sqlparse.sql.Statement` instances. """ stack = engine.FilterStack() s...
41,398
def main(): """ Getting image udp frame & concate before decode and output image """ # Set up socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(('192.168.1.183', 12345)) # YOUR ADDRESS dat = b'' dump_buffer(s) while True: seg, addr = s.recvfrom(MAX_DGRAM) ...
41,399