content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def merge_dols(dol1, dol2): """ Merge two dictionaries of lists. """ result = dict(dol1, **dol2) result.update((k, dol1[k] + dol2[k]) for k in set(dol1).intersection(dol2)) return result
9c508043499cf1c9bda6a1f14306964dea112aeb
615,580
def removeCharacterRelations(cname: str) -> str: """Return a query to remove all of a character's relations.""" return (f"DELETE FROM appears_in " f"WHERE cname='{cname}';" )
ce52c89ecca70147d9f3d93533ee6eb73170b11a
615,583
def datazoom(is_datazoom_show=False, datazoom_type='slider', datazoom_range=None, datazoom_orient='horizontal', **kwargs): """ :param is_datazoom_show: It specifies whether to use the datazoom component. :param datazoom_type: datazoom type...
2398414e0c24cc4faf88a97f192e4aed59ed4d65
615,584
def utf8_decoder(s): """ Decode the unicode as UTF-8 """ if s is None: return None return s.decode('utf-8')
2992eb024d122884367db055c651b588f9964c66
615,585
def nonnegative_int(argument): """ Check for a nonnegative integer argument; raise ``ValueError`` if not. (Directive option conversion function.) """ value = int(argument) if value < 0: raise ValueError('negative value; must be positive or zero') return value
5df66fe8104b3d3e93240bc3609dc68e1b4c17a2
615,593
def mk_endpoint_config(prj, endpoint_name, model_name): """ Return endpoint config creation parameters. """ return { "EndpointConfigName": prj.full_job_name(endpoint_name) + "-config", "ProductionVariants": [ { "VariantName": prj.full_job_name(model_name) + "-variant-...
e556a144abd825dcaa842d00dbc985798c487d00
615,594
def chebyshev(dx, dy): """ Chebyshev distance. """ return max(dx, dy)
8cb655da72ba37351280a04313e928baf4add536
615,597
import importlib def get_networkx_func (func_name, seed=0, **kwargs): """ Uses 'func_name' graph generator of NetworkX library to create a NetworkX graph which can be used as topology. """ nx_func = getattr(importlib.import_module("networkx"), func_name) generated_graph = nx_func(seed=seed, **kwargs) r...
e759ca7c256794d2b8c4c497937e500c99ae7a52
615,599
def loadTab5File(sc, pathToSampleFile): """ Loads a Tab5-formatted file into an RDD. The file is loaded using the Hadoop File API so we can create an RDD based on the tab5 format: [name]\t[seq1]\t[qual1]\t[seq2]\t[qual2]\n Args: sc: A Spark context pathToSampleFile: A valid Hadoop file p...
c7905e59758c3a374354e4752eaf710293505aed
615,603
def o_counter(listy): """ Input: A list of numbers. Ouptut: The number of entries in a list, using the len function. """ return (len(listy))
80cfe29cd8bc132fbd877598923b4d0d823ada36
615,608
from typing import Iterable def toggle_page_menu(menu: Iterable) -> dict: """ Toggle page menu by updating CSS style for menu container. Parameters ---------- menu: list of menu items Return value ------------ style: CSS style for container """ if not menu: return {'d...
996bbbc5f205071a2898fd694a1b367a9469a585
615,617
def get_model_fn(model, train=False): """Create a function to give the output of the score-based model. Args: model: The score model. train: `True` for training and `False` for evaluation. Returns: A model function. """ def model_fn(x, labels): """Compute the output of the score-based model...
743a4209b923c08b712ed39ac289180b7197b812
615,618
def option_to_clblast(x): """Translates an option name to a CLBlast data-type""" return { 'layout': "Layout", 'a_transpose': "Transpose", 'b_transpose': "Transpose", 'ab_transpose': "Transpose", 'side': "Side", 'triangle': "Triangle", 'diagonal': "Diagonal...
dc07fa0c3759b94aab0f86d9527314aae46e94b8
615,619
def reject_info_to_report(starid, reject_info): """ For a given agasc_id, get all of the related "reject" info in an array """ log = [] for entry in reject_info: if entry['id'] != starid: continue log.append(f"Not selected stage {entry['stage']}: {entry['text']}") ret...
f981b408ea37790be8d2f9caef7cc559f9acfce4
615,620
def zoom(crop, factor): """Resizes a cropped bounding box about the centre.""" x, y, w, h = crop cx, cy = x + w / 2, y + h / 2 return (int(cx - factor * w / 2), int(cy - factor * h / 2), int(factor * w), int(factor * h))
f64c6e5670063f06cac6f2b60db3eac9c8076333
615,626
from typing import Dict def parse_guid(guid: str) -> Dict[str, int]: """ Parse a guid back to its four constituents Args: guid: a valid guid str Returns: A dict with keys 'location', 'work_station', 'sample', and 'time' as integer values """ guid = guid.replace('-',...
b76994b2da80b750fb09e33bda6ac4a05dd9d1b1
615,627
def plot_evoked( epochs, picks, events, gfp, spatial_colors, topomap_times, ): """ Plot evoked potentials of different events for individual channels. If multiple events are selected, one figure will be returned for each. Parameters ---------- epochs : mne.epochs.Epochs...
f07ff4e68169b225043230f05bd0e9bda6de74a3
615,629
def calculatechroma(color): """Returns chroma value of color """ chroma = max(color.rgbfraction) - min(color.rgbfraction) return chroma
e7288b3cc4aa9141c185664b1cb55abf714eef86
615,632
def count_mpmcts(filename): """ Given a .pla file with a list of MPMCT gates, tally up the number of gates with each different number of controls Parameters: filename (str): Name of a .pla-formatted file Outputs: num_total_controls (int): the maximum number of control bits ...
253f6388729416b33e8e95fac4f85c5976cef371
615,634
def reverse_string_iterative(s): """ Returns the reverse of the input string Time complexity: O(n) Space complexity: O(n) More efficient, only 3 O(n) operations """ chars = list(s) # O(n) i, j = 0, len(s) - 1 while i < j: # O(n) chars[i], chars[j] = chars[j], chars[i] i += 1 j -= 1 return "".join(ch...
12c8476e949cfcd2ccf2d42ec58d44911dd8aad9
615,636
def remove_stopwords(text, sw): """Remove words that do not add to the meaning; simplifies sentences""" return [w for w in text if w not in sw]
afae1adbeeae7f0b3f7491b5d971696ca8e32158
615,638
def copy_node(graph, node_id): """Copy node. Create a copy of a node in a graph. A new id for the copy is generated by regraph.primitives.unique_node_id. Parameters ---------- graph : regraph.Graph node_id : hashable, node to copy. Returns ------- new_name Id of the co...
e3b30c89e06e971eb0a016aa46e8bc30abaf2723
615,639
import re def is_valid_project_id(project_id): """ Validates project IDs, also known as the project "name". A valid project name should look like: proj-00000001 - It should always start with "proj-" and end with 8 hexadecimal characters in lower case. :type project_id: str :param project_id: ...
f144d4396a2de4511311e0660819df315e50cb6b
615,642
def str_signature(sig): """ String representation of type signature >>> from sympy.multipledispatch.dispatcher import str_signature >>> str_signature((int, float)) 'int, float' """ return ', '.join(cls.__name__ for cls in sig)
e917b1b6c683485540f4b23b775decca8f0a41e7
615,648
def get_start_time(points, time_zero): """Get the first forecast given a time for the first observation. Parameters ---------- points : list of dicts The data points to consider. time_zero : object like datetime.datetime The current time. Returns ------- start : object ...
a3799089c7740ff5ce4ed24b71561ed3d024e2e2
615,655
def _calc_phi(time, params): """Calculates orbital phase assuming zero eccentricity Args: time: observational time (same units at orbital period) params: dict of floats/numpy arrays, including params.per - orbital period (any units) params.T0 - mid-transit time (same uni...
0a563c36595bef9ee3022e7a6a5b7a052ea17739
615,659
import struct import base64 def _encode_real(v): """Encode real numbers as base 64 encoded little endian 8 byte floats.""" bytes_ = struct.pack('<d', v) return base64.b64encode(bytes_)
03647ba91628ed15d6c30f426d079cb506cb78be
615,660
import math def get_long_dmm(long): """Takes an OLEX float and converts it into DMM longitude notation (e.g. 51'6.432 W) :param long: An 'Olex float' representing a longitude coordinate. :type long: float :return: A longitude coordinate (e.g. 51'6.432 W) :rtype: str """ long_d = math.tru...
e98d2cc053d2d9bade9655283f1421001c217693
615,661
def factored_gaussian_params_fn(mean_x, cov_x, mean_y, cov_y): """calculate the parameters of the gaussian q(z | y)q(z | x) Given that the form of the gaussian q(z | x, y) \propto q(z | x)q(z | y) is another gaussian with closed form covariance and mean vectors, we can easily get it from the output of ...
d756a9c1585c177057c78922ab53cbd1af630415
615,663
def total_scored_goals(meta): """ Adds up the total number of scored goals from the match metadata. Note: Own goals are not scored goals, only goals and errors. Args: meta: Match metadata (dict). Returns: Number of scored goals by both teams (int). """ return meta["scored_goa...
ca272b3fb42e603d4c6172519be5495ca26384ff
615,666
def issue_type(insp, fiscaliza): """Checa se a Issue de nº `insp` do Redmine é de um dos tipos válidos: `Inspeção | Ação`""" if (tipo := fiscaliza.issue.get(insp).tracker["id"]) == 1: return "Inspeção" elif tipo == 2: return "Ação" return "Desconhecido"
ad64f8058ac085a76ffcc583c2b0e16a0c7f1e7a
615,667
def column_is_foreign_key(column): """Returns whether a column object is marked as a foreign key.""" foreign_key = column["is foreign key"] if isinstance(foreign_key, str): foreign_key = foreign_key.lower() if foreign_key in {"y", "n", "yes", "no", "-"}: foreign_key = foreign_ke...
b1f1f10116ebc9cc1bc24d141575d997a0caa378
615,674
def binstring_to_bit_list(binstring): """ Converts a string into a list, where each char in the string becomes an item in the list, with matching left to right ordering. Each char in the input string must be able to be casted to an int, as each item in the output list is casted to an int. Args: ...
2cb041de9477736cfdb83c4bf177798974435650
615,680
import click def get_checkpoint(db, id_or_alias): """Returns checkpoint entry in `db` indicated by `id_or_alias`. First tries to match an ID, then an alias. For the case of repeated aliases, will first match local checkpoints and then remotes. In both cases, matching will be newest first. """ ...
84eff1deb3df8c4829cc177aacd89b09501d6b33
615,682
def target_far_field(F, scaled, cheb, tree, indices, chunksize=int(1e6)): """Calculates the :ref:`far-field contributions <eval>` for each target. :param F: the :func:`far_field` contributions for each box. :param scaled: the :func:`scale'd` problem. :param cheb: a :class:`~pybbfmm.chebyshev.Chebyshev...
0ce77ae22cab762341cbd2dfc53b833c324d8f24
615,683
from typing import Tuple def check_version(available: str, needed: Tuple[int, int]) -> bool: """Check that an available version matches the needed version.""" major, minor = available.split(".") if int(major) < needed[0]: return False return int(minor) >= needed[1]
63e1608f92cac9fef2d8429eb505a20a64382b74
615,684
def get_list_from_interval(input_interval): """ Created 20180619 by Magnus Wenzer Updated 20180717 by Magnus Wenzer Takes an interval in a list and returns a list with the gange of the interval: Example: [2, 7] => [2, 3, 4, 5, 6, 7] If start value > stop value the interval in ...
a1439016c7cfca4e08c6bfd4cb3b3b98d46c9403
615,685
def trials2events(events, messages): """Match trial meta information to individual events.""" return events.merge(messages, how="left", on=["trial"])
1bfe8aedb028501b627e07610eb196c2cb80a4a0
615,687
def get_nodes_by_id(ntwrk, nodeid): """ Return a dictionary of nodes (in ntwrk) whose key matches the given 'nodeid'. (Ideally, we shouldn't even need this function; if ntwrk is a simple dict, then simply return {nodeid: ntwrk[nodeid]}.) """ return {k: v for el in ntwrk for k, ...
f0318e1fd72fd38ed7fe884917cc01dfb80a79b4
615,690
import re def find_word_from_root(tokens, root): """Filter token (words) to retain only those containing a root term Args: tokens (iterable of str): the list of tokens. root (str): regular expression for the root term, to look for (e.g 'clay' or 'cl(a|e)y'), which will be padded with '[a-z]*'...
ac4f511adc1eb7bbf643bbbf0e5e8b73bb87bb5d
615,694
import torch def _concat_encoder_hidden_directions(h): """ do the following transformation: (#directions * #layers, #batch, hidden_size) -> (#layers, #batch, #directions * hidden_size) to compensate for two directions in a bidirectional encoder """ return torch.cat([h[0:h.size(0):2], h[1:h...
ca3b46c51d195ee93ceeaa4489419be8fd174814
615,697
def _filter_runs(runs, args): """ Constructs a filter for runs from query args. """ try: run_id, = args["run_id"] except KeyError: pass else: runs = ( r for r in runs if r.run_id == run_id ) try: job_id, = args["job_id"] except KeyError: pass ...
944b18792452d74330e7751a7457358fe5e391c1
615,698
def get_encoding_from_witness(witness_type=None): """ Derive address encoding (base58 or bech32) from transaction witness type. Returns 'base58' for legacy and p2sh-segwit witness type and 'bech32' for segwit :param witness_type: Witness type: legacy, p2sh-segwit or segwit :type witness_type: str ...
dc2bde1407a7965690e41f4b6f0f5a6fdaad285b
615,701
def _get_non_inhereted_function_names(cls): """Gets all methods that cls has that its parents don't have.""" names = set(dir(cls)) for parent in cls.__bases__: names -= set(dir(parent)) return list(names)
4e7a489c457ab1e04e4e54644a32672679c63f0b
615,702
def engagement_rate(followers_who_engaged, total_followers): """Return the engagement rate for a social media account. Args: followers_who_engaged (int): Total unique followers who engaged. total_followers (int): Total number of followers. Returns: Engagement rate (float) as follow...
a519e0a852f5311f3088c12db51f8caee47e0a8d
615,703
def RGB_to_color(r, g, b): """Convert three 8-bit red, green, blue component values to a single 24-bit color value. """ return ((r & 0xFF) << 16) | ((g & 0xFF) << 8) | (b & 0xFF)
265e02c6d828552d1050931d7016be45e269f66d
615,704
def AND(a: bool, b: bool) -> bool: """AND logical gate Args: a (bool): First input signal b (bool): Second input signal Returns: bool: Output signal """ return a and b
04e90abbe660a1a39315b9311b4bba9f13a9dfce
615,707
from typing import List from typing import Dict def bounding_boxes_from_words(word_infos: List[Dict]) -> List[List[int]]: """Returns an array of arrays representing bounding boxes :param List[Dict] word_infos: the words found in the OCR results :returns List[List[int]]: a list of bounding boxes oft...
bed936d78752ab34d9203fed5c2db0e446f9b48f
615,708
import random import string def get_random_name(length): """Returns a random string of given length Args: length (int): Name length Returns: (str): Random name """ return "".join(random.choices(string.ascii_lowercase, k=length))
8eab097d1d919d6c1a78b650efe87dfdf37c6d6d
615,714
def generate_readargs(feature_list): """ Generate bpf_usdt_readargs_p() calls for the given feature list. This function assumes that the following are in scope: - struct pt_regs *ctx - struct SUBST_OU_output *output Parameters ---------- feature_list : List[model.Feature] List ...
9a0c330a3d6fb16a71d248708fd9c0e470a9d2c6
615,715
def abs(var): """ Wrapper function for __abs__ """ return var.__abs__()
c2e834da463e9e3e57933489537545d927f40e85
615,720
def base64_remove_padding(data): """ Remove padding from base64 encoding Args: data: fully padded base64 data Return: base64: Unpadded base64 bytes """ if isinstance(data, str): data = data.encode('utf-8') return data.rstrip(b'=')
130aa5a7f32db28b3b95792a49a09251c5e0993b
615,721
def getBestTextureFormat(ext_list, extensions): """ returns index to a texture from tex_list which has the highest priority in ext_list if none of texture extensions is in ext_list, will return None ext_list is list of extensions in ascending order (the latter, the higher priority), e.g.: ...
7a3d45c2f5fe8f9d5c06fe44474bb379d1ab96e5
615,723
def encode_cell_id(dim: int, row: int, col: int) -> list: """ Get hierarchical encoding binary representation of cell (row, col) with the grid of dim x dim. See Section 3.2 in `https://dl.acm.org/citation.cfm?id=2557559` :param int dim: dimension of the grid :param int row: row index :param int col...
1c29741b87c1dfe1db3e9b01fa8e10870bb6240c
615,726
import torch def augment_light_colour(batch_size, device, ambient_intensity_range=(0.2, 0.8), diffuse_intensity_range=(0.2, 0.8), specular_intensity_range=(0.2, 0.8)): """ Samples batch of random light INTENSITIES (not colours because ...
26d9fa6b5edd021517250400e33c7cd58d7fdb03
615,727
import re import string def split_words(data_str): """ Takes a string, returns a list of pairs (word, 1), one for each word in the input, so [(w1, 1), (w2, 1), ..., (wn, 1)] """ def _scan(str_data): pattern = re.compile('[\W_]+') return pattern.sub(' ', str_data).lower().split...
af72341ccdf2b85a0aa9e0f3bfdd9b0aaf111227
615,732
def functional_equivalence_checking(query, fingerprints_client): """Checks functional equivalence. Args: query: Integer, the fingerprint to query. fingerprints_client: Client to check fingerprints. Returns: Float, the fitness of the equivalence if found, otherwise None. """ return fingerprints_c...
3d105c577becd444c3fccd6098d6d76d19de04db
615,733
def calculate_dmr(delay_list: list, deadline: float) -> float: """Returns the node's deadline miss ratio (DMR).""" miss = 0 for delay in delay_list: if delay > deadline: miss += 1 return miss/len(delay_list)
e6a53327a3844feabd9a1799df44cea723f88096
615,738
import textwrap def AddressArgHelp(include_l7_internal_load_balancing): """Build the help text for the address argument.""" lb_schemes = '(EXTERNAL, INTERNAL, INTERNAL_MANAGED' if include_l7_internal_load_balancing: lb_schemes += ', INTERNAL_MANAGED' lb_schemes += ')' detailed_help = """\ IP addre...
bde91682cc1572a2bb8b0621877bcdf3071fe52d
615,739
def var_dist(v1, v2): """compute absolute distance between two variants """ assert v1.CHROM == v2.CHROM return abs(v1.POS-v2.POS)
41c20a777a663fd85abc514bd90958d7064fb315
615,740
def only_main(compound: str): """Convert a splitted compound into a compound only split into a main compound and its satelite e.g. fietsen_stalling_pas -> fietsenstalling_pas Args: compound (str): an underscore splitted compound """ splitted = compound.split("_") if len(splitted) ==...
3e2f45f5a17bcd222d15edda80c4e0e9ad2d3e7f
615,741
import string def has_digits(word): """ True if word contains digits. """ return bool(set(string.digits).intersection(word))
9d97e23b353f7e028e7718847b7f1d15a2f5ac95
615,745
def binary_labels(labels, in_class, column="inregister"): """ Converts a multiclass dataset to one with binary labels, where 1 represents the "in-class" and 0 represents the "out-classes" (i.e. all classes that are not the in-class or the negative examples.) Parameters ---------- labels : ...
901b297495012f9d528c5201d57b7109dc38c3a5
615,746
def _year_days(year): """_year_days(year) Returns the number of days in a given year. Positional arguments: year (int) - a year Returns: int - number of days in the specified year This is computed according to the Gregorian calendar, under which a leap year occurs every 4 yea...
4ef895b2833c911fc8ba522ab56dfed8ae49d2b5
615,748
import json def load_journal_json(absolute_path): """ This method loads data collected on a single journal by the pybliometrics metadata collection module into a dictionary. Parameters ---------- absolute_path(str, required) - The path to the .json file containing metadata procured by the pybliom...
efb4d3af9b4cecad6749c943a5f08e7425195ced
615,749
def create_filepath(ds, root_path="."): """ Generate a filepath when given an xarray dataset """ varname = [x for x in ds.data_vars][0] start = ds.generalVerticalLayer.data[0] end = ds.generalVerticalLayer.data[-1] filepath = f"{root_path}/{varname}_{start}_{end}.nc" return filepath
17afd9907c6758b792fafdc0d61c1e41a707be1a
615,750
def difference_value_calculator(repository, undeployed_value_tuple, deployed_value_tuple): """ Generate a value based on difference between given undeployed and deployed value. """ return undeployed_value_tuple[2] - deployed_value_tuple[2]
88aa0df4a9c6535f8347b4974a170c8c6a084d52
615,752
def get_coord_by_attr(ds, attr, value): """ Returns a coordinate based on a known attribute of a coordinate. :param ds: Xarray Dataset or DataArray :param attr: (str) Name of attribute to look for. :param value: Expected value of attribute you are looking for. :return: Coordinate of xarray data...
8b7b57ea78f13c6264afce2b5c78119372589f66
615,753
def extract_object(dictionary, key_sequence): """ Extract the object inside the dictionary at a specific path :param dictionary (Dict): dictionary to extract from :param key_sequence (List[str]): list of strings represetning key accesses :return: the value inside dictionary specified by key_sequence...
869445ee642c13119e9e76edcaf771fd0672a6ce
615,756
import glob def get_all_files(basedir): """Get a list of all files in basedir, recursively :param basedir: base of the path where to look for the files :return : a list with all the file paths """ return [name.replace("%s/"%basedir, "", 1) for name in glob.iglob('%s/**/*'%basedir, recursive...
bb889cfe5429785fab0bb62c26f90500cf82ed6e
615,758
from datetime import datetime def append_date_time_to_string(input_string: str) -> str: """Append datetime string to input string. Returns datetime string if input is empty string. """ now = datetime.now() if not input_string: return now.strftime("%Y-%m-%d_%H-%M-%S") else: ret...
421e2564933cdf92e7b731eeaa655587c6d63d13
615,759
import requests def get_html(zipcode): """ Get the html to be parsed. :param zipcode: :return: html from web. """ url = f'https://www.wunderground.com/weather-forecast/{zipcode}' response = requests.get(url) return response.text
28cdb00b7746017b69e955a379eb2f248a675fe2
615,761
import time def wait_for_condition(condition_predictor, timeout_ms=1000, retry_interval_ms=100): """A helper function that waits until a condition is met. Args: condition_predictor: A function that predicts the condition. timeout_ms: Maximum timeo...
4102429e31ee52fa19f78c44d04209cb6530251d
615,762
def norm_cmap(values, cmap, normalize, cm, vmin=None, vmax=None): """ Normalize and set colormap Parameters ---------- values Series or array to be normalized cmap matplotlib Colormap normalize matplotlib.colors.Normalize cm ...
67df85c0ada7984a7dac93cbbe7d6c7e2e10f158
615,763
import re def to_snake_case(text: str) -> str: """ Transform string to snake_case. """ text = re.sub(" +", " ", text) text = text.lower().strip().replace(" ", "_") return text
dc8f3adaae5cd5a272c5ae4b06324c65f241d814
615,764
import struct def get_char(encoded: bytearray, idx: int) -> tuple: """ Returns a char and next to be read index :param encoded: bytearray :param idx: index to start read from :return: tuple of char and next index """ return chr(struct.unpack(">h", encoded[idx:idx + 2])[0]), idx + 2
8f629939880191b0d0fb4e546af53c013adc238e
615,766
def testing_client(testing_app): """ Fixture to setup test client context. :param testing_app: Test app context. :type testing_app: object :return: object """ return testing_app.test_client()
a85393cd4e4222a2826e26c4bce5f98c759e0f9c
615,767
def bytes_to_pascals(dg_bytes): """Takes a list of 3 bytes read from the DG-700 and returns a pressure in Pascals. Larry Palmiter originally wrote this code for TEC in Basic, which has proven immensely useful. """ bx, hi, lo = dg_bytes # unpack the array into individual values pressure =...
130736043b70cc04e91cc43c576606ffcb2a814f
615,769
def expand_qgrams_word_list(wlist, qsize, output, sep='~'): """Expands a list of words into a list of q-grams. It uses `sep` to join words :param wlist: List of words computed by :py:func:`microtc.textmodel.get_word_list`. :type wlist: list :param qsize: q-gram size of words :type qsize: int :p...
f75874d5f0f1cb245306e10de30a2140115110c1
615,773
def is_under_replicated(num_available, expected_count, crit_threshold): """Calculates if something is under replicated :param num_available: How many things are up :param expected_count: How many things you think should be up :param crit_threshold: Int from 0-100 :returns: Tuple of (bool, ratio) ...
7a89e5588cbcc1c920af20eea5a410170fec254e
615,778
def src_from_cell_col(cell_name_col, verbose=False): """ Extract the source name from sample names. Args: cell_name_col: the actual array of sample names verbose: print value_counts if True """ src_names_arr = cell_name_col.map(lambda x: x.split('.')[0].lower()) src_names_arr.name =...
c594666a0194b66bc129ee37acba5af81e7d3d63
615,779
def get_jobid(module, resp): """Get the Job ID from the response header.""" jobid = None if resp.status_code == 202: joburi = resp.headers.get('Location') if joburi is None: module.fail_json(msg="Failed to update firmware.") jobid = joburi.split("/")[-1] else: ...
921ba85e7c1441bb5c150136383543f5c6d2374b
615,783
import textwrap def wrap_paragraphs(text, width=70): """Wrap each paragraph in ``text`` to the specified ``width``. If the ``text`` is indented with any common leading whitespace, then that common leading whitespace is removed from every line in text. Further, any remaining leading and trailing white...
3533b59566374cb8edf140f3326804fc75e1f79e
615,788
def lf_to_hash(lf_dict): """Create a unique string representing an LF Args: lf_dict (dict): A labeling function (LF) Returns: str: unique hash """ def conditions_to_string(cond_list): conds = [] for x in cond_list: conds.append("".join([str(val) ...
2e6ebb118b18c1864c2b10eccb070a65dd1b797b
615,794
def strip_default(arg): """Return the argname from an 'arg = default' string""" i = arg.find('=') if i == -1: return arg t = arg[:i].strip() return t
a4a187a93f6306689642b8e0b40c60d2871ff006
615,797
def is_proper_position(dimension, position): """ Check whether the given position is a proper position for any board with the given dimension. - The given position must be a tuple of length 2 whose elements are both natural numbers. - The first element identifies the column...
6443f1018b0ac993db2b31d51256ae78857cffb5
615,798
def row_series_to_columns(series): """Turn a pandas series of row tuples into a list of column value tuples.""" return list(zip(*series))
8adb3518ed57cb1b51a4cc5132b6762ff827e01d
615,799
def bind(socket, connection, port): """Binds a socket to a port, or a random port if needed. Returns the port.""" if port <= 0: return socket.bind_to_random_port(connection) else: socket.bind(f"{connection}:{port}") return port
e28cee3c8a4353d3869c8c70165c5fa4cee9ba73
615,800
def count(s, *args): """count(s, sub[, start[,end]]) -> int Return the number of occurrences of substring sub in string s[start:end]. Optional arguments start and end are interpreted as in slice notation. """ return s.count(*args)
f07d22b620f76daacec4734487ed0836c7f8ac25
615,801
def get_lowercase_method(method: str) -> str: """Returns the lowercase name of the HTTP method""" return method.lower()
f626f811a96361d72dae1d7ccde495cef91a1794
615,802
def reverse(x, axes): """Reverse a tensor along the specified axes """ if isinstance(axes, int): axes = [axes] slices = [slice(None, None, -1) if i in axes else slice(None, None, None) for i in range(x.ndim)] return x[slices]
651109da0677f568bf9aa599e12fa54ba2b7821b
615,804
def is_json_request_accept(req): """Test if http request 'accept' header configured for JSON response. :param req: HTTP request :return: True if need to return JSON response. """ return not req.accept or req.accept.header_value == 'application/json' \ or req.accept.header_value == '*/*'
773d40cd757f9179f90d2481e0bb666a05d234f4
615,807
from pathlib import Path from typing import Tuple def _is_file_with_supported_extensions(path: Path, extensions: Tuple[str, ...]) -> bool: """ Check if the file is supported for the media type :param path: File path to check :param extensions: Supported extensions for the media type :example: ...
0bab2e1eead6dca863d062bd9d187e6a5f54c788
615,808
def CW_ode(w, t, n): """ Defines the differential equation in terms of the moving frame (CW frame LVLH) Arguments: w : vector of state variables w = [x,y,z,dx,dy,dz] t : time n : mean motion """ x, y, z, dx, dy, dz = w ddx = 3*(n ** 2)*x + 2*n*dy ddy = -...
ef4c093d06d1ffd2002b6d38891ec0cc8ac0fd6b
615,811
def read_mol_list_from_sdf_file(filepath, line_by_line=False): """Simple loader to load a SDF file by only splitting. Args: filepath (str): File path for SDF file. line_by_line (bool): Whether to read SDF file line by line. Returns: list: List of mol blocks as string. """ m...
2cf55c7653f392eca802d295f7dda588d51ec103
615,820
def timeinfo(solar_midnight, utc_to_local): """ Get table of time info for current scheduling period. Parameters ---------- solar_midnight : '~astropy.time.core.Time' UTC solar midnight time. utc_to_local : 'astropy.units' hour difference to convert from UTC to local time. ...
069f081a0ffd2a4a2f559c0c84f3750c81023feb
615,821
def get_adjusted_aspect(ax, aspect_ratio): """Adjust the aspect ratio Parameters ---------- ax : :obj:`~matplotlib.axes.Axes` A :obj:`~matplotlib.axes.Axes` instance aspect_ratio : float The desired aspect ratio for :obj:`~matplotlib.axes.Axes` Returns ------- float ...
8a28e08bf3bcfec03954278cb498f2d56e93d1d1
615,825
from typing import Dict def merge_dictionaries(dictionaries: Dict, key_type: str, reverse: bool = False) -> Dict: """Given any number of dictionaries, shallow copy and merge into a new dict, precedence goes to key value pairs in latter dictionaries. Function from StackOverFlow Post: https://stack...
11e5f50c298005ad8c4e01eefc008bdd2edc58f4
615,827
def Dot_C3V(vec1, vec2): """Simple function for computing the dot product between two three dimensional vectors (index-able objects of length 3).""" return vec1[0] * vec2[0] + vec1[1] * vec2[1] + vec1[2] * vec2[2]
9a07abfc9fd694573d308b477568b509721a273e
615,828
import torch def f_dD(x): """Simple example function defined on interval `[0, 1]` Parameters ---------- x : torch.Tensor coordinates for evaluation Returns ------- torch.Tensor function evaluations """ result = 4 * x[0] * (x[0] - 1) for x_i in x[1:]: r...
157697551bc9760820adca22cf2c506e996ad30e
615,830