content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def gen_mask(n: int) -> int: """ Will create a n bit long mask. This works by creating a byte with a 1 at the n+1 place. Subtracting this with one will make all previus bits 1, thus creating a byte with the first n bits set. >>> bin(gen_mask(3)) '0b111' >>> bin(gen_mask(2)) '0b11' ...
482e16f3ac465d841d59bfe4ff312fcbd1ac512c
62,716
def style_str(s, color='black', weight=300): """ Style the supplied string with HTML tags Args: s (str): string to format color( str ): color to show the string in weight( int ): how thick the string will be displayed Returns: html(...
d00e80a153787260c6528bb3f00b697fb2ab8c81
62,717
def get_redact_list(item): """ Get the redaction list, ensuring that the images and metadata dictionaries exist. :param item: a Girder item. :returns: the redactList object. """ redactList = item.get('meta', {}).get('redactList', {}) for cat in {'images', 'metadata'}: redactList...
8452ceb18e43be77d4fe88e73ff7d332372da7f5
62,718
def str_is_int(x: str) -> bool: """Test if a string can be parsed as an int""" try: int(x) return True except ValueError: return False
3740ec6118c84de097b13139581cf5080e910c00
62,720
def replace_escapes(text): """ Replace escape sequences with the characters they represent :param text: string to replace escapes in :return: New string with escapes replaced by the represented characters """ escape = False out = "" for char in text: if escape is True: ...
666133b97cdee52e9cdc94686cdb208cda4dcbba
62,722
def weighted_moving_average(days, weights): """ | Calculates the rolling weighted moving average. The weights list should have the size of the days window. | Name: weighted\_moving\_average\_\ **days** :param days: Size of the window :type days: int :param weights: Weights to use for the calcul...
689e5e88895a28de1850c1563f0f9fcc0f4c34cf
62,726
import json def read_json(filename): """Reads data from a file in JSON format""" with open(filename) as data_file: return json.load(data_file)
b0d8665101851729ed0ed0b9fc2778a5a9d7f3a1
62,728
import json import requests def groupList(apikey): """ Returns all Groups existing in your FileCrypt Account apikey: Your ApiKey from FileCrypt """ data={"api_key":apikey,"fn":"group","sub":"list"} return json.loads(requests.post("https://filecrypt.cc/api.php",data=data).text)
4408d1a585905635e9b8b12d294e91f59f1de3cb
62,729
def check_unique_list(input): """ Given a list, check if it is equal to a sorted list containing 1-9 Return True if the given list is unique, False otherwise """ # convert list string into list of int and sort it int_list = list(map(int, input)) int_list.sort() return int_list == [1, 2, ...
0448d3c054063076b4bcd3eb37def9cc5e1edfed
62,735
def _findstart(line_segment): """Find start of text to autocomplete. >>> _findstart("where x.pers") 8 >>> _findstart("from d.person, d.na") 17 >>> _findstart(" and x.") 10 >>> _findstart("where i") 6 >>> _findstart(" ") 3 """ if '.' in line_segment: retu...
a8e75e2f19c96529021e2eea5cf361be2fefaf74
62,745
def _bin_to_int(b_list): """ Convert b_list, a list of {0,1}, to an integer """ out = 0 for b in b_list: out = (out << 1) | b return out
a82e123348e892e95d5ca476005c34a4d9ead7eb
62,746
def get_byte(byte_str): """ Get a byte from byte string :param byte_str: byte string :return: byte string, byte """ byte = byte_str[0] byte_str = byte_str[1:] return byte_str, byte
2a00e82e10b4ed367ebcb41240d5393477f3b234
62,748
def checkCrossConstraint(env, trajEvader, trajPursuer): """Checks if the evader crosses the boundary. Args: env (gym.Env): the environment. trajEvader (np.ndarray): the trajectory of the evader. trajPursuer (np.ndarray): the trajectory of the pursuer. Returns: bool: True if crossing the ...
630bd9ea5d702a9a8e8b74b064cb91545db364dd
62,751
def split_documents_into_equal_chunks(documents, chunk_size): """This method splits a list or dictionary into equal chunks size :param documents: List or Dictionary to be partitioned into chunks :param chunk_size: Maximum size of a chunk Returns: list_of_chunks: List containing the chunks ""...
3fb2d0bc1b035529915c25372df70e1ec055de4c
62,755
import pprint def mock_render_template(*args, **kwargs): """ Pretty-print the args and kwargs. Allows us to not depend on any actual template rendering mechanism, while still returning a unicode object """ return pprint.pformat((args, kwargs)).encode().decode()
710eabecef2d2f29543788756ae872f73a766011
62,757
def string2bool(allegedstring): """ Tries to return a boolean from a string input if possible, else it just returns the original item, allegedly a string. """ if allegedstring.lower().startswith('t'): return True elif allegedstring.lower().startswith('f'): return False elif a...
a5a8598f0d0c2e79a27f7ae9a4555894b2ccf9ac
62,765
def isWhitespace(char): """ Determine whether a character is whitespace @param char: the character to check @return True if the character is whitespace, False otherwise """ return char == ' ' or char == '\t' or char == '\r' or char == '\n'
72eb79c8bb6a6192dd3c7713bbe5e3944550c994
62,768
import re def _convert_to_code(val): """ Convert ' to code(`) or ''' code blocks(```) and convert ' within code blocks to " e.g.: 'display_name' converts to `display_name` e.g.: '''pip install -U 'resilient-circuits'''' converts to ```shell $ pip install -U "resilient-circu...
143e26a6d6ee322adffa5df9c54d6a5c03b5c4f0
62,774
def parse_ft_line(line, vocab_to_idx=None, lbl_to_idx=None): """Convert line from fastText format to list of labels and tokens. If vocab_to_idx and/or lbl_to_idx provided, tokens are converted to integer indices. """ line = line.strip().split() labels = [w for w in line if w.startswith('__label__')...
08138cf8b1d20f109cc05db5c671a0eb3d69c2f1
62,775
def flatten(l): """ Flattens a list. Written by Bearophile as published on the www.python.org newsgroups. Pulled into Topographica 3/5/2005. """ if type(l) != list: return l else: result = [] stack = [] stack.append((l,0)) while len(stack) != 0: ...
a4a8b9f3bff6e4deea546e58faaec0bd73bb217a
62,783
def validate_dpi(s): """confirm s is string 'figure' or convert s to float or raise""" if s == 'figure': return s try: return float(s) except ValueError: raise ValueError('"%s" is not string "figure" or' ' could not convert "%s" to float' % (s, s))
56778a405a4e15ee5f1acd4ad165e5c33db00d19
62,789
import re import platform def on_ubuntu() -> bool: """ return true on recent ubuntu linux distro. """ match = re.match(r'^.+Ubuntu-\d\d\.\d\d-\w+', platform.platform()) return match is not None
94938ef1dfd9960a3a6c10b8a42e56b695c1fa6f
62,790
def reshape_nda_to_3d(arr) : """Reshape np.array to 3-d """ sh = arr.shape if len(sh)<4 : return arr arr.shape = (arr.size/sh[-1]/sh[-2], sh[-2], sh[-1]) return arr
9adee8d1c9c2bc4afa4a066c116d1d60c143632f
62,796
def similarity_threshold(h, bands): """ Function returning the Jaccard similarity threshold for minhash signature composed of h integers and a signature matrix divided in n bands. Args: h (int): Number of integers in the minhash signature. bands (int): Number of bands dividing the signa...
aa1b35cf8942391077dba01dc87a4489ae94e1cd
62,804
def get_neighbors(r_index, c_index): """Get neighboring cell positions Args: r_index (int): Current row index c_index ([type]): Current column index Returns: [List of list of integers]: List of neighbors with each neighbor containing a list of their row and column index. """ ...
267c7b56ce04085f3095a7d21a0710bb3b980094
62,807
import random import string def string_id(length=8): """ Generate Random ID. Random ID contains ascii letters and digitis. Args: length (int): Character length of id. Returns: Random id string. """ return ''.join(random.choice(string.ascii_letters + ...
dacfef58781c5291ce6bb975ee1de317b5524fda
62,808
import time def created_at(created_at): """Convert a timestamp string to one more suited for sorting""" return time.strftime("%Y-%m-%d %H:%M:%S", time.strptime(created_at, "%a %b %d %H:%M:%S +0000 %Y"))
088fd700be2c308dafb66b243c1eb9f02c2a41cf
62,812
import random def get_random_list(length=100, max_num=10): """ Generate a list containing random numbers. Args: length (int): The length of the list to generate. max_num (int): The largest number to include in the list. """ return [random.randrange(1, max_num, 1) for _ in range...
2ac16cac38c53afebed595110ead8619fa14d583
62,817
def _format_lineno(session, line): """Helper function to format line numbers properly.""" if session == 0: return str(line) return "%s#%s" % (session, line)
f30e29eb016b5246ce94582f95ed0c4c4fe20432
62,819
from typing import Optional import time def make_run_id(model_name: str, task_name: str, run_name: Optional[str] = None) -> str: """Choose a run ID, based on the --run-name parameter and the current time.""" if run_name is not None: return run_name else: return "%s_%s__%s" % (model_name, t...
330b4b18dff3865d98fbc9ed731038e3afb2c989
62,826
def replace(text, searchValue, replaceValue): """ Return a string where all search value are replaced by the replace value. """ return text.replace(searchValue, replaceValue)
60840f9b2896603cf7200186795d088617a38710
62,833
import time def timeit(num: int): """~ Profiling function ~ @Info: Prints average time to execute specific function @Param: - num: int ~ Number of samples to take for average""" def _timeit(fnc): sum = 0 ct = 0 def __timeit(*args, **kwargs): nonlocal sum ...
f479e07ac48b3dbee7b3b93fa7e4c9d73a9a525c
62,834
import re def FileExtension(file_name): """Return the file extension of file 'file' should be a string. It can be either the full path of the file or just its name (or any string as long it contains the file extension.) Example #1: input (file) --> 'abc.tar.gz' return value --> 'tar.gz...
53cff85d1b9c8faa0bb062fa459205ee8dad0b6d
62,835
def make_draw_response(reason: str) -> str: """Makes a response string for a draw. Parameters: - reason: The reason for the draw, in the form of a noun, e.g., 'stalemate' or 'insufficient material'. Returns: The draw response string. """ return f"It's a draw because of ...
638dd1eadc8daae422c8096bd76e81a0c085a5fa
62,839
def MI_Tuple(value, Is): """ Define function for obtaining multiindex tuple from index value value: flattened index position, Is: Number of values for each index dimension Example: MI_Tuple(10, [3,4,2,6]) returns [0,0,1,4] MI_Tuple is the inverse of Tuple_MI. """ IsValuesRev = [] Cu...
97a71e9049fec0e95fccfcebb2aea4032f980fbe
62,844
def add(x, y): """ This function sums up two numbers. Parameters ---------- x : float The first number to be added. y : float The second number to be added. Returns ------- sum : float The sum of x and y. """ sum = x + y return sum
506e2dbf1be7bbc1efde2735b2c634583afcc454
62,846
def store_path(connection, path): """Store the file path in the SQL filepaths table. :param connection: :param path: :return: path id""" insert = '''INSERT OR IGNORE INTO filepaths(filepath) VALUES(?)''' cursor = connection.cursor() cursor.execute(insert, (path,)) return cursor.lastrowid
d8ee7f44539ff642dffd62bd089b818cffe3468b
62,849
def create_cell_metadata(hidden: bool) -> dict: """ Creates the metadata Dict of a Synapse notebook cell. :param hidden: The flag that determines whether a cell is hidden or not. :returns: The metadata Dict of a Synapse notebook cell. """ return {"jupyter": {"source_hidden": hidden, "outputs_h...
8b9b8a8a5a27522cb640205375c18abc264ca400
62,853
def binomial_coefficient(n: int, k: int) -> int: """ Returns the binomial coefficient Defined as: factorial(n) // (factorial(n - k) * factorial(k)) :param n: The number of items :param k: The number of selected items :return: The number of ways to select k items from n options """ if k...
97e75efd159fe3de36f28138ef90b695660f3cf4
62,855
def compress_2d_list(squares_list): """ Convert 2d list to a 1d list """ result = [] for row in squares_list: for col in row: result.append(col) return result
3f4db2227e0dec1bc67ec277637dbcdb001a15ad
62,857
from typing import Dict def get_names(market, name_attr='name', name_key=False) -> Dict[int, str]: """ Get dictionary of {runner ID: runner name} from a market definition - name_attr: optional attribute name to retrieve runner name - name_key: optional flag to return {runner name: runner ID} with name...
64885ee93a8dd0c9ec454bb335cf7fe47d454ef3
62,866
def clean_nested_colname(s): """ Removes map name for MapType columns. e.g. metadata.SeriesInstanceUID -> SeriesInstanceUID """ return s[s.find('.')+1:]
20a8db386c82f66924bda591db8cdeddf6b643a8
62,867
import curses def has_colours(stream): """Determine if an output stream supports colours. Args: stream: the output stream to check Returns: True if more than 2 colours are supported; else False """ if hasattr(stream, 'isatty') and stream.isatty(): try: curses....
46a5cb171213423157f45904f7df9c77aad1c652
62,869
def get_region_for_sample(sample, bpid, target): """ Parse a dictionary and obtain the region for a given sample """ for sample_id in target: if sample.find(sample_id) != -1: if bpid == 1: return target[sample_id]['region1'] else: return ta...
e302f12f72a33a58f296bac24260ce00fed4128b
62,871
def norm_z_value(img, ref_img): """This function will normalize the two images using z-value normalization Parameters ---------- img : ndarray The image to normalize ref_img : ndarray The referene image Returns ------- img : ndarray The image that's been normalize...
e8d02bd31884576f4ef8c65dc7a7a61685e3cece
62,874
def get_api_interfaces_name_by_type(api_interfaces, type_str, key_name='name'): """ Extract interface names from Interfaces API response by type :param api_interfaces: Interfaces API response :param type_str: Type string to match :param key_name: Optional - Key name to use (default 'name') :retu...
b31b554a6698114a060cf756b644abf55c2baf18
62,877
def createRegionStr(chr, start, end=None): """ Creating "samtools"-style region string such as "chrN:zzz,zzz,zzz-yyy,yyy,yyy". If end is not specified, it will create "chrN:xxx,xxx,xxx-xxx,xxx,xxx". :param chr: :param start: :param end: :return: A string of samtool-style region """ ...
99ce4a7c26704ae11c59ee18b8f468d82bf6a182
62,878
def wrapCtr(angDeg): """Returns the angle (in degrees) wrapped into the range (-180, 180]""" # First wrap into [0, 360]; result is 360 if ctrAng < 0 but so near 0 that adding 360 rounds it ctrAng = angDeg % 360.0 if ctrAng > 180.0: ctrAng -= 360.0 return ctrAng
fda5c77288e18517035e33fc0a2dd42030cd0db8
62,879
def find(search_list: list, value: int) -> int: """ Implement a binary search algorithm. :param search_list: a sorted list of values :param value: value to search :return: index of value in the search_list """ # Raise error in case list is empty if not search_list: raise ValueE...
2fe59800f6ddc6869f26ff7bbc7bb82fabb6a1fd
62,893
import logging def get_sample2locusId(all_df, has_gene2, meta_ix, dbg_lvl=0): """ Args: all_df: all.poolcount dataframe has_gene2: list of booleans relating to genes with insertions 0.1 < f < 0.9 meta_ix: integer marking where sets begin and not metadata ...
b61e604079e8061f07275c1ca643f783dc90e3d6
62,898
def mono_comb(n: int, r: int, mod: int = 10**9 + 7) -> int: """Binomial coefficient python 3.8 or later Parameters ---------- n n r r mod, optional mod, by default 10**9+7 Returns ------- nCr Notes ----- Time complexity O(min(r, n ...
aff211b94c71d1c15b4f83416b0a0ebe669f9e7d
62,899
from typing import List def flatten(lst: List) -> list: """Reduce a nested list to a single flat list. >>> flatten(["A", [2, ["C"]], ["DE", (5, 6)]]) == ["A", 2, "C", "DE", 5, 6] True """ result = [] for item in lst: isiterable = False try: iter(item) i...
3837f9578d5917664c8187a1360dab4ba5fd6673
62,901
def getAlleles(ref, alt, gt): """ Given ref alt and gt, return a list of alleles at site :param ref: str Reference allele :param alt: list List of alt alleles at site :param gt: list Genotype at site :return: set Set of alleles at site """ if gt is Non...
2e990444790405343194197f8fd96bf5391179c8
62,906
def make_date_prefix(date): """Make an S3 key prefix from a date. Format a date as: YYYY/MM-Month/DD/ For example: 2016/09-September/15/ """ return date.strftime('%Y/%m-%B/%d/')
41f8fb5600a6d163f580da8d220c758610df4e58
62,907
def moboinfocheck(moboInfo, autoupdate, n_krig): """ Function to check the MOBO information and set MOBO Information to default value if required parameters are not supplied. Args: moboInfo (dict): Structure containing necessary information for multi-objective Bayesian optimization....
c78127c24324089bf80d9dc81378b33579a829d0
62,909
def __wrap_sign_into_row(body_identifiers: dict, hand_identifiers: dict) -> dict: """ Supplementary method for merging body and hand data into a single dictionary. """ return {**body_identifiers, **hand_identifiers}
06e1145d6b48bee6c0f06e0b7311f08b2823ecbd
62,912
import mimetypes def guess_mimetype(filename: str, fallback: bool = False) -> str: """Guess a mimetype based on a filename. Args: filename: The filename to check. fallback: Fall back to application/octet-stream if unknown. """ mimetype, _encoding = mimetypes.guess_type(filename) i...
3cbaafdb2476491c2723ab1ba776eb62abd4b8d2
62,919
def merge_residual_mapping(guide_residuals, guide_mapping, residual_construct_col, mapping_construct_col): """Join guide residual df and mapping to genes Parameters ---------- guide_residuals: DataFrame Guide-level residuals guide_mapping: DataFrame Mapping between guides and genes ...
0eaa4ee53aba4b2d5088526fd06bc96d1115f20e
62,922
def _get_cache_key(account, container): """ Get the keys for both memcache (cache_key) and env (env_key) where info about accounts and containers is cached :param account: The name of the account :param container: The name of the container (or None if account) :returns a tuple of (cache_key, e...
1891eb909cfc37f02f22580e2ed589e258982afd
62,925
import torch def get_perm(N, dtype, device): """ Compute permutation to generate following array 0, 2, 4, ..., 2*(N//2)-2, 2*(N//2)-1, 2*(N//2)-3, ..., 3, 1 """ perm = torch.zeros(N, dtype=dtype, device=device) perm[0:(N-1)//2+1] = torch.arange(0, N, 2, dtype=dtype, device=device) perm[(N-1)//...
72cf6a05d41946a81e4289d9ea33586c1df620f5
62,928
from typing import OrderedDict def simple_reverse(in_dict): """Simple reverse dict key and value.""" out_dict = OrderedDict() for k, v in in_dict.items(): out_dict[v] = k return out_dict
eece4c22bb391a8da3119ed832353e19f7fff1e1
62,929
def get_input(prompt, operation, check=None): """ Prompt the user for input and apply ``operation`` to input. If ``check`` is not None run the check on the converted input If value is invalid it will re-prompt user """ while 1: try: value = input(prompt) value = ...
570df61b6d2b70e6754ce34c81c5346772f1777b
62,934
def padNumber(number, pad): """pads a number with zeros """ return ("%0" + str(pad) + "d") % number
8418c4c9771fd7cdc2c6adc5be34dbb12939b69a
62,937
import functools def reraises(from_exc, to_exc, when=None, make_message=None): """Reraises exception thrown by decorated function. This decorator catches the specified exception 'from_exc' in the decorated function and reraises it as a different exception 'to_exc'. The exceptions to catch can furthe...
42cfa5db9f795e0bb444fc938be7f3f1dbee41a3
62,942
def largest_divisor_five(x=120): """Find which is the largest divisor of x among 2,3,4,5""" largest = 0 if x%5==0: largest = 5 elif x%4==0: largest = 4 elif x%3==0: largest = 3 elif x%2==0: largest = 2 else: ## when all other (if, elif) conditions are not met return "no divisor found for %d" %x ## each...
2747f59faaad7ae9c0ed5ff99f7c2d76ecaafe85
62,950
def next_marker_by_id(collection, limit, marker): """ Returns the next marker based on the limit-1 item in the collection :param collection: an iterable containing the collection to be paginated :param limit: the limit on the collection :marker: the current marker used to obtain this collection ...
447889d9bd333888bfdd41a7b51901c3c556e3fc
62,957
def attending_info_detect(in_data): """Detect if the email address is validate or not See if the email address include the @ sign to determine if it is a valid email address Args: in_data (dict): The dictionary that includes the attending's email address Returns: str or Tr...
2ebeb96049befcd6200bba6fb76cf8709a96bf10
62,961
def cut_indices_of(array, cut): """ Calculates the indices of the elements on the given cut for the given matrix. Where a diagonal runs from top left to bottom right, a cut runs from bottom left to top right. :param array: 2D array :param cut: index of the cut (cut 0 is the single element of the to...
276cac460b64b88fa4c224da10fb55cb93c47509
62,963
def dom_level(dns_name): """ Get domain level """ return dns_name.count(".")
20d54dd98378f377485149bbb9854b6d2001ab55
62,966
def rivers_with_station(stations): """Created a sorted list of Rivers with stations on them""" # Initialise rivers list rivers = [] # Add river to list from station, if river is not present for station in stations: if station.river in rivers: pass else: river...
cd515483aa56d2c9fec767234b22d0993bca3725
62,971
import decimal def _add_percentage_to_progress_bar(progress_bar, count, total): """Add the percentage to the progress bar. Parameters ---------- progress_bar : str The bar component of the progress bar, as built so far. count : int The number of cycles completed. total : int ...
7ab1ae33652e158eae04379944819c103383aec7
62,975
def format_month_interval(val): """ Format a MonthInterval value. """ return f"{int(val)}M"
28ac3d457dab6c4c877d15b137a26930180c389e
62,977
def weighted_count(pdf): """ Return weighted count of items in Pandas DataFrame. """ return pdf['s006'].sum()
083cc2a10f829c2b863224367d360cc2c1a8b0ed
62,983
def build_dsn_string(db_settings): """ This function parses the Django database configuration in settings.py and returns a string DSN (https://en.wikipedia.org/wiki/Data_source_name) for a PostgreSQL database """ return "postgres://{USER}:{PASSWORD}@{HOST}:{PORT}/{NAME}".format(**db_settings)
4d4d14907f76f1a739020f5ca29576d20bb7fdbf
62,986
def chomp( s ): """Return string without terminal newline if present""" return s[:-1] if s.endswith('\n') else s
247415db1784cba1b99a5c20048487c7801130dd
62,988
import logging import re def get_encoder_and_decoder_params(model): """Filter model parameters into two groups: encoder and decoder.""" logger = logging.getLogger(__name__) enc_params = [] dec_params = [] for k, v in model.named_parameters(): if bool(re.match(".*conv1.*|.*bn1.*|.*layer.*",...
4a6fbc25d0cf08f1b9511c981af8abdc55f63ae8
62,993
def swap_places_colon(ingredient): """Split string `ingredient` by colon and swap the first and second tokens.""" components = ingredient.split(':') if len(components) <= 1: return ingredient else: return '{} {}'.format( swap_places_colon(':'.join(components[1:])), components...
f6051ea7611d0bf7edc79c88db2d2369917c2690
62,998
def time_delta(faker): """Time delta.""" return faker.time_delta(1)
eecc214d272d28732dd7d330c36ed06daeec284a
62,999
import pprint def format_for_leo(obj): """ Convert obj to string representiation (for editing in Leo)""" return pprint.pformat(obj)
f552bbbaafa0c229bad6ef6c5a8e2fed89330f08
63,001
def get_group_list(project, client): """Return a sorted list of groups for project.""" groups = client.get(f"/api/projects/{project['pk']}/groups/") groups = sorted(groups, key=lambda x: x["pk"]) return groups
921b95851b6ccc9468d5158f78997f47b022bc3c
63,005
def atf_fc_uri(article_uri): """URI of feature collection""" return article_uri+"/featurecollection"
c725642309955795b5558b638146b782c7f51d0b
63,018
def infer_ap_func(aperiodic_params): """Infers which aperiodic function was used, from parameters. Parameters ---------- aperiodic_params : list of float Parameters that describe the aperiodic component of a power spectrum. Returns ------- aperiodic_mode : {'fixed', 'knee'} ...
259677e4ece98961e8016d505e9047ae99b13289
63,019
from typing import Any def identity(value: Any) -> Any: """Given a value, return the exact same value""" return value
4335555cc3d66b7ec5c3215915c46dda8c4e1a77
63,020
def col(label: str) -> int: """Return the correct index given an Excel column letter.""" if not label.isalpha(): raise ValueError(f"'{label}' is not a valid column label.") return ( sum( (ord(char) - ord("A") + 1) * (26 ** position) for position, char in enumerate(rev...
423cb4d431dcbe5ae8b9ee0e9e53fabecf44d7da
63,024
def lsystemToDrawingCommands(draw, s): """ :param draw: :param s: :return commands: Takes a dictionary, draw, of character->turtle instuctions, and a L-system string, s. Uses draw to map the string to drawing commands, and returns a list, commands, of those commands. """ commands = [] ...
0b7a00d40b69d143746b9dbbc06b77c08e9455dd
63,028
def field_name(field): """ :param field: Tupla que tiene el nombre y valor de un campo del documento original. :return: El nombre del campo. """ return field[0]
c3be05723cbd8a627e0b98c25628d61b04038e4b
63,030
import hashlib def get_hash(file): """ Computes md5 hash for a file to detect duplicates :param file: uploaded file :return: Hex hash """ s = hashlib.md5() with open(file, 'rb') as f: for line in f: s.update(line) return s.hexdigest()
31ba5a4515c850893d0d5428d43cb1b65aafe3ea
63,032
def get_graph(graph): """ Get correct graph due to data parallel :param graph: network graph :type graph: torch.nn.Module :return: correct graph :rtype: torch.nn.Module """ if hasattr(graph, 'module'): # fix DataParallel return graph.module else: return graph
1f9ba8de96359ffd58f422e1063b923fb14c4d1a
63,034
def EntryToHostName(entry): """Extracts the buildbot host name from the slaves list entry. The slave list entry is a dict.""" return entry.get('hostname', None)
84d21e15418f4b632a0fb05978490ecec3e64377
63,036
def yes_or_no(true_or_false): """A convenience function for turning True or False into Yes or No, respectively.""" if true_or_false: return "Yes" else: return "No"
be45e1dbc18451cf8df0f4513dfa49c82f7dc88e
63,038
def handle_content_properties_information(element: object) -> dict: """ Handle API response 'properties' information. Args: element (object): An XML element hierarchy data. Returns: dict: Transformed dictionary of properties information. """ data = {'Name': element.findtext('N...
cd60d70cd7d5e6ca5ad622b1a73c3d879ba29896
63,039
def remove(src, rel, dst): """ Returns an SQL statement that removes edges from the SQL backing store. Either `src` or `dst` may be specified, even both. :param src: The source node. :param rel: The relation. :param dst: The destination node. """ smt = 'DELETE FROM %s' % rel que...
61af56d70d4fb2e6d56225c23de1fdcc3c6ec35a
63,040
def transfer_driver_cookies_to_request(cookies): """ Extract the cookies to a format that the request library understands :param cookies: This should be a driver cookie. Obtained with the command my_driver.get_cookies() :type cookies: dict :return: Cookies dictionary suitable for a requests lib obj...
b81df474c731f939421852bf2f719fee73c9d3c5
63,049
def to_bits(_bytes: bytes) -> list: """Convert bytes to a bit list""" bits = [] offset = 0 for byte in _bytes: for i in range(8): bits.insert(0+offset,(byte >> i) & 1) offset += 8 return bits
157d814dede3bf2e261067f6374ceed1ed7f7697
63,053
def _GetChannelSet(five_g, width): """Returns a tuple of target channels based on spectrum and width given. Args: five_g: (bool) Whether target is 5GHz radio. width: (int) Channel width, eg. 20, 40, 80. """ if five_g: if width == 20: return (36, 40, 44, 48, 52, 56, 60, 64, 100, 104, 108, 112,...
9b5436266a47d52eced41ac8e90471c3cf0dc9f9
63,057
def _flip_bits_256(input: int) -> int: """ Flips 256 bits worth of `input`. """ return input ^ (2**256 - 1)
31e7211330f7d5285b8677f585c460cb903ba113
63,068
import requests import json def get_driving_distance(start_point, end_point): """Gets the driving distance (km) from the start point to the end point (input in [lat, long]).""" # call the OSMR API - needs [long, lat] r = requests.get( f"http://router.project-osrm.org/route/v1/car/{end_point[1]},{...
49551b08a127e33c36117d847155f4c5144be01c
63,070
def fwhm_dict(fwhm): """Convert a list of FWHM into a dictionary""" fwhm = [float(f) for f in fwhm] return {'x': fwhm[0], 'y': fwhm[1], 'z': fwhm[2], 'avg': fwhm[3]}
6192adfff7f2e3c5f5e30671929e59c6e4a6ced4
63,071
import yaml def ordered_dict_representer(dumper, data): """ Represents OrderedDict for yaml dumper. """ values = [] for item_key, item_value in data.items(): node_key = dumper.represent_data(item_key) node_value = dumper.represent_data(item_value) values.append((node_key, ...
b2ef51cc7b45e2860f8522e877641aecf50b77af
63,077
def merge_overlapping_dicts( dicts ): """ Merge a list of dictionaries where some may share keys but where the value must be the same """ result = {} for mapping in dicts: for key, value in mapping.items(): if key in result and result[ key ] != value: raise E...
34bd96af4847e060799c38b68fde0306171a9631
63,078