content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def nonzero_indices(arr, max_number=1): """get an array of indices that have nonzero value""" result = [] for i in range(len(arr)): if arr[i] != 0.0: result.append((arr[i], i)) result = sorted(result, reverse=True) n = min(max_number, len(result)) return [result[_][1] for _ i...
453c5709c83dfc6555080d1cde3e00eaab22d89a
650,339
def test_geojson(distribution): """ Test if a DCAT:distribution is GeoJSON. """ return ( distribution.get("mediaType") == "application/vnd.geo+json" or distribution.get("format", "").lower() == "geojson" )
c321795d4f38f7188fb4d9f3ab6403ce8b866bad
650,343
from typing import List def clean_source(source: List[str]) -> List[str]: """ Cleans the source content of a Synapse notebook cell. :param source: The source content of the cell. :returns: The cleaned source content of the cell. """ source = list([line.rstrip() for line in source]) source...
773915a1ec7fc88d1a7ae0eb4cf95578ac4d21a0
650,345
import warnings def puppy_vid_inspected_trajectory(grp, step_width, loc_marker, epoch_idx, obs_offset): """ .. deprecated:: 1.0 Use :py:class:`PuppyActionVideo` instead """ warnings.warn('deprecated, use PuppyActionVideo instead') loc_x = grp['puppyGPS_x'][obs_offset+step_width*e...
582083bc76950437b9ebdd1258393c3c6f0311c8
650,348
from struct import pack def makePalMeta(color_table_ptr: int, colors_count: int, title_len: int): """Generates a metadata record for a palette in a pal file. Since we don't have a serializer in KS, we use the manual one.""" res = bytearray() res += b"\0\0\0" res += pack("<I", color_table_ptr) res += pack("<I",...
61844fcb2cff96ba23e45e8e9647e673b0a0f8d9
650,350
def get_module(module_id, module_registry): """Obtains a configured ContourFeatures given an algorithm identificator. Parameters ---------- module_id : str Module identificator (e.g., bitteli, melodia). module_registry : dict Dictionary of module_ids to class instances Returns ...
479d98c93ef0d9cf852a0e330a2e71827c38f2a6
650,356
from typing import List from typing import Any def flatten(ll: List[List[Any]]) -> List[Any]: """ Flatten a list of lists into a single list. """ return [a for l in ll for a in l]
85c948a15777a1b8f6f401f1cf4a0caf3b18cbe9
650,358
def _class_required(type_, class_, params): """Return true if method requires a `cls` instance.""" if not params or class_ is None: return False return type_ == 'classmethod'
8e4f92074e06e3bc22a1bea435534c062e72761b
650,360
def _make_version(major, minor, micro, level, serial): """Generate version string from tuple (almost entirely from coveragepy).""" level_dict = {"alpha": "a", "beta": "b", "candidate": "rc", "final": ""} if level not in level_dict: raise RuntimeError("Invalid release level") version = "{0:d}.{1:...
5bca2be7e0c4cc31b11bea7fe5ddccb5da1caf0d
650,362
def char_to_decimal(text): """ Converts a string to its decimal ASCII representation, with spaces between characters :param text: Text to convert :type text: string :rtype: string For example: >>> import putil.misc >>> putil.misc.char_to_decimal('Hello world!') '...
e104f5b3aa86347dc0ab10310b10ce83bc72400a
650,363
def _structure_parent_category(_parent_id, _payload): """This function structures the portion of the payload for the parent category. .. versionadded:: 2.5.0 :param _parent_id: The ID of the parent category (if applicable) :type _parent_id: str, None :param _payload: The partially constructed payl...
ea21347aeefcc588270d7b287c82f696f18c259d
650,364
def parse_drive_size(line): """Parses a drive line in the partition information file. """ parts = line.split(":") if len(parts) != 2 or parts[0] != "drive": raise ValueError("Drive size line format is 'drive:<size>'") return parts[1]
5c9eee6463e90c31191e36dfd77edec4c0911343
650,366
import torch def get_duplicate_labels(labels, n_items, max_label): """ Converts the number of items that exist in the game (not including the targets) to a count word that is interchangeable with another count word meaning the same thing. For example, the label for the value "0" can either be 0 or...
dc853331ae5b52c25f654265bba15e3b8b080071
650,367
def NOT(event, sample_space): """Returns subset of events from set of samples that are NOT in the subset event.""" return sample_space - event
838d2641b887cf87ceaa819d1ff4de0c27f2b012
650,369
def _patsplit(pattern, default): """Split a string into the optional pattern kind prefix and the actual pattern.""" if ':' in pattern: kind, pat = pattern.split(':', 1) if kind in ('re', 'glob', 'path', 'relglob', 'relpath', 'relre', 'listfile', 'listfile0', 'set'): ...
d25ead13ec9ab7ea4d660fbf46bec20f6a7f6bbc
650,370
def query_to_json(query, name): """This query is useful to fetch a complex join with some aggregations as a single blob, and later, just hydrate it without having to iterate over the resultset .. Example: SELECT u.id::varchar, to_jsonb(array_agg(scopes)) as scopes, ...
07bee3c4c7f541cafccd1b31a3134bd8378f9de4
650,372
def are_features_consistent(train_df, test_df, dependent_variables=None): """Verifies that features in training and test sets are consistent Training set and test set should have the same features/columns, except for the dependent variables train_dr: pd.DataFrame training dataset test_df: pd.Dat...
cc9f0f42519a77bb01ff1ceb31c89b64f0af0832
650,377
import pathlib from typing import List from typing import Any def get_downloaded_partitions(path_to_folder: pathlib.Path) -> List[Any]: """Retrieves the full paths of the partitions file in a folder. Parameters ---------- path_to_folder: pathlib.Path A pathlib.Path indicating the full path to...
34fe6c78125fda392c28eba47e38cbb206c15864
650,378
from typing import Any def mandatory(val: Any) -> Any: """Raises a ValueError if the provided input is None, otherwise returns it""" if (val is None): raise ValueError("Missing mandatory configuration value") return val
8c6f74c3886f3464488b8f6c6b6529c2cd2ba5a3
650,379
def _snapshot_v2_to_v1(snapv2_result): """Transform a v2 snapshot dict to v1.""" snapshots = snapv2_result.get('snapshots') if snapshots is None: snapshots = [snapv2_result['snapshot']] for snapv1 in snapshots: # The updated_at property was added in v2 snapv1.pop('updated_at', N...
9b7bb020d023d0f85293d5b0ef82e31108ed64ce
650,382
def _table_type(typestr): """Return the translation of CRDS fuzzy type name `typestr` into numpy dtype str() prefixes. If CRDS has no definition for `typestr`, return it unchanged. """ int_types = [">i","<i","uint","int"] float_types = [">f","<f","float","float"] complex_types = [">c","<c","com...
c4be4b3ce4ceb1a90ad6308598976175d8e3c7ea
650,385
def complex_transmission_reflection(in_m0,in_m1,in_m2): """ complex_transmission_reflection(in_m0,in_m1,in_m2) Calculate the complex transmission and reflection coefficients between media 0, 1, and 2 given their complex refractive indices. In the Kramers-Kronig implementation (in which this is most likely us...
a1726a8b5e133582ad2cb0e07eb2e5a1ba561829
650,388
def is_number(word: str) -> bool: """Check if string/words is a number. Args: word: Word to check. Returns: True, if given word is a number. """ try: float(word) return True except ValueError: return False
552f8bdb040d1b6e89d088c85b3db02e0ba1af77
650,392
def rectcenter(rect, cast=float): """Returns the center ``[x,y]`` of the given `rect`. Applies the given `cast` function to each coordinate.""" return [cast((rect[0]+rect[2]-1)/2.0), cast((rect[1]+rect[3]-1)/2.0)]
febc9e064cfd668c45ec6ecfa3cbaf6590d1cc5a
650,393
def mod_exp(val, exp, modulus): """Computes an exponent in a modulus. Raises val to power exp in the modulus without overflowing. Args: val (int): Value we wish to raise the power of. exp (int): Exponent. modulus (int): Modulus where computation is performed. Returns: ...
5b2de4ce19807cbd7b1ffc6d0a532012d183f1ac
650,394
import pickle def read_pickle(filepath): """Read pickle file""" infile = open(filepath,'rb') data = pickle.load(infile) infile.close() return data
eb356661b5ca1f530da0f7623397cf6d8b4eb663
650,398
def _hasclass(context, *cls): """ Checks if the context node has all the classes passed as arguments """ node_classes = set(context.context_node.attrib.get('class', '').split()) return node_classes.issuperset(cls)
97c29ddfa209c69a7a78f71619023878e8ce833d
650,400
def get_rank(raw): """Return the rank of the player.""" display_rank = None prefix = raw.get('prefix') rank = raw.get('rank') playerRank = raw.get('playerRank') if prefix: return prefix elif rank: return rank.replace('_', ' ') else: return playerRank.replace('_'...
d7316243858a51998236597bde0fdd5e1a581e7f
650,405
import torch def _get_idx_worst(name, ref, hyp): """ Computes the batch indices for which the input metric value is worse than the current metric value. Parameters ---------- name : str 'mse', 'psnr', 'ssim', 'lpips', or 'fvd'. Metric to consider. For 'mse', 'fvd' and 'lpips', lower is be...
cdfee3950eb312ad05dc67d3b08d495a73602a85
650,408
def ms_to_time(x): """Converts and integer number of miliseconds to a time string.""" secs = x / 1000.0 s = secs % 60 m = int(secs / 60) % 60 h = int(secs / 3600) rtn = [] if h > 0: rtn.append("{0:02}".format(h)) if m > 0: rtn.append("{0:02}".format(m)) rtn.append("...
693204cec43c0681e027e8ba6881cca6435cf9da
650,409
def fixture_vcf_sample_id(sample_id: str) -> str: """Return a sample id that exists in the test VCF""" return sample_id
1e99d3e60f824fd988c39612a5708e78ceb351be
650,415
def new_dummy_vertex(vertex: int, key: int, biggest: int) -> int: """New dummy vertex ID Args: vertex: Vertex ID key: Edge key biggest: Biggest vertex ID Returns: ID of a new negative dummy vertex if key is greater than one. Otherwise return the same vertex ID as th...
d2cdd84d416fb33956792f9d47c043cd341ec190
650,417
import string def MakeValidFieldName(header): """Turn a header name into a valid bigquery field name. https://developers.google.com/bigquery/docs/tables Field names are any combination of uppercase and/or lowercase letters (A-Z, a-z), digits (0-9) and underscores, but no spaces. The first character must b...
0a0944ead63b15b6d3b7589fbd7b0390de7d61cb
650,419
def principal_form(disc): """Construct principal form for given discriminant. Follows Def. 5.4 from `Binary quadratic forms` by Lipa Long, 2019: https://github.com/Chia-Network/vdf-competition/blob/master/classgroups.pdf """ assert disc % 4 == 0 or disc % 4 == 1 k = disc % 2 f = (1, k, (k *...
22a38e48ba16ac2c937a4ba29c779c088dad8674
650,422
import json def create_snippet(file_path): """ Creates a snippet of the original SQuAD data. Args: file_path: path to the original file Returns: string containing file contents """ with open(file_path) as data_file: data = json.load(data_file)['data'] out = { ...
ff8ddf1e9c6ef012871afe8bc418c8b50bb37ba1
650,424
def zoo(total_head, total_legs, animal_legs=[2, 4]): """ Find the number of kangaroo and tiger in a zoo. For example: zoo(6, 16) -> (4, 2) zoo(8, 20, [4, 2, 2]) -> (2, 0, 6) Parameters ---------- total_head: int Total number of animals total_legs: int ...
e24b678ebaea8ef78a93bbfb8abe1e98b560bb06
650,425
def clean_name(string): """Clean entity/device name.""" return string.replace("-", " ").replace("_", " ").title()
780a9bca200696abe1e68ff3613ba17dde187c77
650,429
def _get_units_prod(array_in, array_out): """Helper method calculate units after a product operation Parameters ---------- array_in : np.ndarray Array before product operation array_out : np.ndarray, float Array after product operation Returns ------- ...
fedd517347cc37e4fa821ced4951c8cf2989f4ab
650,433
def UsersInvolvedInIssues(issues): """Return a set of all user IDs referenced in the issues' metadata.""" result = set() for issue in issues: result.update([issue.reporter_id, issue.owner_id, issue.derived_owner_id]) result.update(issue.cc_ids) result.update(issue.derived_cc_ids) result.update(fv....
0edf8dc760ccad66136c5bb8defb590ddc850685
650,434
def user_info(props): """Decorator to specify a list of properties requested about the current user""" def real_decorator(function): function.pi_api_user_info = props return function return real_decorator
423806a8ffd235a839562b1a9431f84d9596fdc1
650,442
def pretty_print(x, numchars): """Given an object `x`, call `str(x)` and format the returned string so that it is numchars long, padding with trailing spaces or truncating with ellipses as necessary """ s = str(x) if len(s) > numchars: return s[:(numchars - 3)] + '...' else: ...
0ad6998c62b44730fe2316dd3233f49d2905af58
650,447
def choice(*args): """ Creates a choice argument type. The user will be able to choose one of given possibilities. Example: choice("quickly", "slowly") :param args: a list of string the user will be able to choose :return: a dict representing this argument type with the appropriate format t...
91270ff6223674fc9a32dae7f66adcedfde98fe6
650,458
def de_median_redshift(wavelength, median_z): """De-redshifts the same way as above Parameters: wavelength (array): wavelength values to convert median_z (int): redshift to change the wavelength by Returns: wavelength_red (array): redshifted wavelength """ wavelength_red = wavelength...
5a350f68ca5cb7e821f638059bebb459cbb1556c
650,461
def cons(a, b): """ Construct a pair. :param a: first element :param b: second element :return: a function that takes a function and activates it on the pair """ def pair(f): return f(a, b) return pair
2bdae67b7f2227241b51bd7457d1e281ce64ddd8
650,464
def make_filename(instance, filename): """Makes the filename of the users profile image nice.""" return "profile_images/" + str(instance.user.id) + "." + filename.split(".")[-1]
39f473894581ee6b56b5a9104942682d88e267d3
650,467
def padBits(bits, padding): """Pad the input bits with 0's so that it is of length padding""" return [0] * (padding-len(bits)) + bits
6a7bc593be11af7de23f84d090b3c9700ab1d87d
650,468
import itertools def endmembers_from_interaction(configuration): """For a given configuration with possible interactions, return all the endmembers""" config = [] for c in configuration: if isinstance(c, (list, tuple)): config.append(c) else: config.append([c]) ...
189d35f295e7a880bfb9c964a31d029f04c3862f
650,474
import smtplib def connect(smtp_server, smtp_port=25): """ Connect to the SMTP server to send emails. :param smtp_server: Hostname or IP Address of the SMTP server :param smtp_port: Port number of the SMTP server, default is 25. :returns: server instance without logging in. :raises: None ...
d813f5e3382aa9f9761caddbec30cfa5fe567bdd
650,479
def _CheckReadMeComplete(input_api, output_api): """Verifies that any new files have been added to the README file. Checks that if any source files were added in this CL, that they were also added to the README file. We do not warn about pre-existing errors, as that would be annoying. Args: input_api:...
d0f84cf1848eeaf2d2c23f42f4bcaf61e4d82e16
650,483
def _parse_error_msg(err): """Parse MPD error message.""" if not err.startswith('mpd error:'): return err return err.split(':', 1)[1].strip()
d2c313b0fa2e6737265b306a3d645ce35ebe5d95
650,487
def transpose_time_to_spat(x): """Swap time and spatial dimensions. Returns ------- x: torch.Tensor tensor in which last and first dimensions are swapped """ return x.permute(0, 3, 2, 1)
6a107af4a63312db57bd3c218e70d1b8efa0b0df
650,488
def clamp(number, lower, upper): """ Limits the range of a number with a specified boundary """ return max(min(number, upper), lower)
c5de54acd0ac10ebdd5919368c6cc3d3fa3e72bf
650,496
def check_force_length_constraints(force, tol=0.01, printout=False): """Checks whether target length constraints applied to the force diagrams are respected, i.e. are below the tolerance criteria. Parameters ---------- force: compas_ags.diagrams.ForceDiagram The force diagram to check deviation...
cd36d8c0b3d7fa6792ff5f5fd5c66d0536784bf8
650,497
import io from PIL import Image def matplotlib_figure_to_image(fig): """ Convert a matplotlib figure to an image in RGB format, for instance to save it on disk """ buf = io.BytesIO() fig.savefig(buf) buf.seek(0) return Image.open(buf).convert("RGB")
e196817a23c772e29985f37b2af297022914dfc9
650,501
def get_expected_ploidy(gender, chrom): """ Determine expected ploidy of call based on sample's gender and chromosome. Unknown genders are processed as diploid. Args: gender (string): M,F or U chrom (string): chromosome, PAR values should be represented as XY Returns ...
ad25772c66c5fb8bc19e82dca009e2ecd6104266
650,507
import random def cxSimulatedBinary(ind1, ind2, eta): """Executes a simulated binary crossover that modify in-place the input individuals. The simulated binary crossover expects :term:`sequence` individuals of floating point numbers. :param ind1: The first individual participating in the crossover. ...
a056a041168b96d5469952d184c487c92e2d98c7
650,508
def get_lookup_dicts(pred_name): """ Create part-of-speech-specific dicts mapping lemmas to sets of indices :param pred_name: list of pred names, in order :return: {'v':verb_dict, 'n':noun_dict} """ # Initialise lookup dicts v_lookup = {} n_lookup = {} lookup = {'v':v_lookup, 'n':n_l...
9fcdba1ded172e1820288908ea7de063bdf12243
650,509
def process_entry(line: str) -> list: """Take a line from day2_input.txt and return important values""" split_index = line.index(":") split_range_index = line.index("-") password = line[split_index + 2:len(line)] return [split_index, split_range_index, password]
3eb9873533e7b52626d85d56ddb4437f924dded4
650,510
def manhattan(t1b: tuple, t2b: tuple) -> int: """For parm pair of coordinate tuples, each (x, y). Return the Manhattan distance between them.""" t1x, t1y = t1b t2x, t2y = t2b return abs(t1x - t2x) + abs(t1y - t2y)
71ad347a8a05087e861176cfcb8533646060f880
650,511
def strip_terminating_semicolon(sql: str) -> str: """Removes terminating semicolon on a SQL statement if it exists""" return sql.strip().rstrip(";").strip()
5d3b8979d63c37ea4487f7f7ade608ece3ee69c1
650,512
def tracks_max_popularity_of_epoch(df, tracks=str, col_year=str, popularity=str, year_1=int, year_2=int): """ Busca las canciones con máxima popularidad para un rango de años :param df: nombre del datafreme :param tracks: columna con el nombre de las canciones :param col_year: columna con los añ...
9790d416607d7f528f60a2d786c35daeb2e4fdeb
650,513
def add_all_numbers(n): """adds all numbers between zero and n, including n""" return sum([number for number in range(n + 1)])
dbbd561951fc54b8a95882534065f9f7a6891f85
650,514
def create_finances_table_name(csv_name: str): """ Getting a readable table name from the finances csv Example: EUHWC_-_Expense_Claims_(Responses) expenses :param csv_name: :return: """ # table replacements table_name = csv_name.split("_-_")[1] table_name = table_name.sp...
5af0c00b62759d4e38ef5de5bda6aea046a8bc86
650,523
import re def get_edu_text(text_subtree): """return the text of the given EDU subtree, with '_!'-delimiters removed.""" assert text_subtree.label() == 'text', "text_subtree: {}".format(text_subtree) edu_str = ' '.join(word for word in text_subtree.leaves()) return re.sub('_!(.*?)_!', '\g<1>', edu_str)
4add5d6697f5bede2636fb7d2704c5b72827ed97
650,526
def _get_help_lines(content): """ Return the help text split into lines, but replacing the progname part of the usage line. """ lines = content.splitlines() lines[0] = 'Usage: <progname> ' + ' '.join(lines[0].split()[2:]) return lines
71dec5dec57f257a3fd9ec844b7d9fa727bdafa6
650,527
def bestName(inRow): """ helper function for annotate_best_CDS given a row with 'Label' and 'Locus tag', choose the best annotation choose 'Label' if it's present otherwise choose 'Locus tag' return a string with the best name """ if inRow['Label'] == '': result = inRow['Locus T...
70a4f1cd13d9fc4c0f614a07bb6605e0706b0b50
650,528
from unittest.mock import patch def patch_site_configs(values): """ Helper to mock site configuration values. :param values dict. Use either as `@patch_site_configs(...)` or `with patch_site_configs(...):`. """ return patch.dict('openedx.core.djangoapps.site_configuration.helpers.MOCK_SITE_C...
bd9f6938f57e93d053725a78ebaf5c494082fca3
650,535
import itertools def is_clique(old_graph, vertices): """ Tests if vertices induce a clique in the graph Multigraphs are reduced to normal graphs Parameters ---------- graph : networkx.Graph or networkx.MultiGraph graph vertices : list vertices which are tested Retu...
97184b05c1eb89b70f83552e74e04de966790036
650,538
def str_to_int(s): """ Takes a string provided through user input, which may be hexadecimal or an integer, and converts it to the actual corresponding integer. """ s = s.strip().lower() if s.startswith("$"): return int(s[1:], 16) elif s.startswith("0x"): return int(s[2:], 16) ...
1df7e74fd2a67ccd0f2a886a8629031d0feb85f6
650,539
def sensor_param(request): """ parametrize a test with sensor parameters """ parameters = request.param print('test parameters') print('Device list : ' + str(parameters.devices)) print('socket list : ' + str(parameters.sockets)) print('one socket result : ' + str(parameters.one_socket_re...
5c24b583f157b322f9cf102791edc454efb1aaba
650,542
def is_version_compatible(version: dict, expected_version: tuple) -> bool: """ Args: version: Dictionary containing version info. Should have following fields -> 'major', 'minor', 'patch' expected_version: Tuple of 3 elements for ('major', 'minor', 'patch') Returns: ...
1f042593c3306adc3ad315f447d6b3e3e1625d41
650,548
import logging def _test_acc_token(client): """ Tests access token by trying to fetch a records basic demographics """ try: demo = client.get_demographics() status = demo.response.get('status') if '200' == status: return True else: logging.warning('get_d...
7618b6d894f08a37400617440dda35bef99b2b97
650,551
def nf(stage, fmap_base=8192, fmap_decay=1.7, fmap_max=32, fmap_min: int = 32): """Computes the number of feature map given the current stage. This function is inspired from the following Github repo: https://github.com/tkarras/progressive_growing_of_gans/blob/master/networks.py Arguments: sta...
4b952198276781980757d932b14c98740f109e98
650,561
def match(line,keyword): """If the first part of line (modulo blanks) matches keyword, returns the end of that line. Otherwise returns None""" line=line.lstrip() length=len(keyword) if line[:length] == keyword: return line[length:] else: return None
50b61c103ed0a2e0df41326036c1e069fd73ec9e
650,569
def ignore_empty_keys(o: dict): """Removes keys with None-type values from the provided dict. Used for JSON encoding to avoid schema errors due to empty or invalid parameters. """ return {k: v for (k, v) in o if v is not None}
a72fafa532779e231a1f5df93b868e3c1c23d4cd
650,572
def remove_comments(sql: str) -> str: """Remove comments from SQL script.""" # NOTE Does not strip multi-line comments. lines = map(str.strip, sql.split("\n")) return "\n".join(line for line in lines if not line.startswith("--"))
8dfc5f082b59d88a45a8d7fa216553df6b117afa
650,577
def getprofile(space): """Return the profiling function set with sys.setprofile. See the profiler chapter in the library manual.""" w_func = space.getexecutioncontext().getprofile() if w_func is not None: return w_func else: return space.w_None
688c8c5b33152bf8b8d0754fd16ec5edf2bc730b
650,578
import math def time_str(val): """ Convert perfcounter difference to time string minutes:seconds.milliseconds """ return f"{math.floor(val / 60):02}:{math.floor(val % 60):02}.{math.floor((val % 1) * 100):02}"
3b713aeb693c5d2e28788b7b85a78e634b036f84
650,580
def is_fullname_suffix(s): """ Returns Trus if S is a full name suffix """ return s.upper().strip() in ['JUNIOR', 'SENIOR', 'JR', 'JR.', 'SR', 'SR.', 'DR', 'DR.', 'PHD', "PHD.", "SIR", "ESQ", "ESQ.", "I", "II", "III", "IV", "V", "VI", "1ST", "2ND", "3RD", "4TH", "5TH", "6TH"]
73fbd91594a2ea923db9960cfeaf0b21a64a8510
650,584
import pickle def load_pkl(file_path): """Load serialized model with pickle library. Parameters ---------- file_path: str Path to the serialized model. Returns ------- Trained model object. """ with open(file_path, 'rb') as model: clf = pickle.load(model) return ...
edb4efb464a3e5ff79c40431c18bc2cc4a78271a
650,585
def filtany(entities, **kw): """Filter a set of entities based on method return. Use keyword arguments. Example: filtany(entities, id='123') filtany(entities, name='bart') Multiple filters are 'OR'. """ ret = set() for k,v in kw.items(): for entity in entities: if getattr(entity, k)() ...
6f29aaa02d86c00599af02971a3efe527a3e5722
650,586
def tag_limit_sibling_ordinal(tag, stop_tag_name): """ Count previous tags of the same name until it reaches a tag name of type stop_tag, then stop counting """ tag_count = 1 for prev_tag in tag.previous_elements: if prev_tag.name == tag.name: tag_count += 1 if prev_t...
3b1f48e939c0ff772fc53a0bb7705d0a7a13ab0b
650,589
import re def original_image_extender(pipeline_index, finder_image_urls, extender_image_urls=[], *args, **kwargs): """ Example: http://media-cache-ec0.pinimg.com/70x/50/9b/bd/509bbd5c6543d473bc2b49befe75f4c6.jpg http:/...
19c4c2f61cf027acbb5ffc75cd72bd2cc802cfab
650,595
def from_question_name(name: str) -> str: """ Generates GIFT text for a question name. Parameters ---------- name : str Name of a question. Returns ------- out: str GIFT-ready question name. """ return f'::{name}::'
03bc0fc3f6b63e265fd0c75f070738ceaf2fe14d
650,599
import math def _compute_sphere_overlap(d, r1, r2): """ Compute volume overlap fraction between two spheres of radii ``r1`` and ``r2``, with centers separated by a distance ``d``. Parameters ---------- d : float Distance between centers. r1 : float Radius of the first spher...
13fc42154e3b45868658a27bd94df539ffa480a1
650,601
import sympy def solve(a, b, c): """ Determine x valid value(s) for any Quadratic Equation `ax² + bx + c = 0` where a, b, c are known values. Returns a tuple of solutions (x1, x2).""" if a == 0: if b == 0: return (None, None) return (sympy.Rational(-c, b),None) d = b*...
c92e22c1e9384fee916a032a20d2f92e7e8f7f90
650,602
def fragment_retrieval(coll, fields, fragment, case_sensitive = False): """Retrieves a list of all documents from the collection where the fragment appears in any one of the given fields Parameters ---------- coll: generator The collection containing the documents fields: iterable ...
5bbab5fca5d747588408ede9039e0ce4774d19c1
650,611
def convert_dict_vals_to_str(dictionary): """Convert dictionary to format in uppercase, suitable as env vars.""" return {k.upper(): str(v) for k, v in dictionary.items()}
c397235c40fd187041e387d4c19d6e06d1a061d5
650,613
def getifname(sock): """Return interface name of `sock`""" return sock.getsockname()[0]
b13fbc359ad5d3678ffd9a714737f16c7211da85
650,615
from typing import Dict from typing import Set def get_allowed_courses(conflict_graph: Dict[str, Set[str]], already_selected: Set[str], prohibited: Set[str]) -> Set[str]: """ Returns the set of courses in course_df that do not conflict with any course names in already_selected, according to the graph conf...
9c24891fc2baa19eef26f3887a2148ce1dd72dc6
650,616
import itertools def aggr_events(events_raw): """Aggregates event vector to the list of compact event vectors. Parameters: events_raw -- vector of raw events Returns: events_aggr -- list of compact event vectors ([onset, offset, event]) """ events_aggr = [] s = 0 for bi...
ffb5962df2e54b5d6508ac5325746a1d3b4e7c0b
650,617
def filter_profile_sounds(profile, sounds): """ Returns relative paths to sounds that are the folder specified by the profile. :param profile: Str :param sounds: List of Str :return: List of Str """ if profile: filter_lambda = lambda sound: sound.startswith(profile + "\\") else: ...
22e0c2f24acf299354383c4967b94650bbdca35b
650,619
def get_installed_tool_shed_repository( trans, id ): """Get a repository on the Galaxy side from the database via id""" return trans.sa_session.query( trans.model.ToolShedRepository ).get( trans.security.decode_id( id ) )
0364430b6b174378791a07b6a1e086e668a60995
650,621
import json def _GetErrorExtraInfo(error_extra_info): """Serializes the extra info into a json string for logging. Args: error_extra_info: {str: json-serializable}, A json serializable dict of extra info that we want to log with the error. This enables us to write queries that can understand the ...
b1edfc2740dcbeba33ddd54581c6760babffb954
650,625
def end_game(_game): """ Will show a end game screen and thank the player. Args: _game: Current game state Returns: Returns false to end game loop """ print("Thank you for playing") return False
cc95a7bded80ac1840463bb2f462ee5f6b8fdf8e
650,626
def parameter_changed(parameter): """Check whether parameter is in a pre-validation changed state. Args: arcpy.Parameter: Parameter to check. Returns: bool: True if changed, False otherwise. """ return all((parameter.altered, not parameter.hasBeenValidated))
837c7e92a71f7ff800140b93451cb9435e1ecf33
650,627
from typing import Set from typing import List from typing import Dict def deduped_actions(actions: Set[str]) -> List[str]: """Return a sorted list of all the unique items in `actions`, ignoring case.""" # First, group all actions by their lowercased values. This lumps "foo" and "FOO" together. unique: D...
4c5a0ee2c1bcb86f5c26b9d5a20d3293befce0fd
650,631
def append_to_dataset(dataset, sample): """ Append a new sample to a provided dataset. The dataset has to be expanded before we can add value to it. :param dataset: :param sample: data to append :return: Index of the newly added sample. """ old_size = dataset.shape[0] # this function always...
334f9d7ede7d3b394e1fbd45be76e1a25ee2b900
650,634
from typing import List def get_data_element_total( data_element_id: str, data_values: List[dict], ) -> int: """ A DHIS2 data element may be broken down by category options, and ``data_values`` can contain multiple entries for the same data element. This function returns the total for a given ...
d466a372bc353aa00135eb6a431b37a1029f80fc
650,637
def to_megabytes(size_bytes): """ Convert size in bytes to megabytes """ return size_bytes * 1024 * 1024
a7acb200c5c3067f902c190fca54e9bd362beccb
650,640