content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def clean_spaces(txt): """ Removes multiple spaces from a given string. Args: txt (str): given string. Returns: str: updated string. """ return " ".join(txt.split())
d6b354550ce0aadcf96d3e5131163bd10f27fce7
666,562
def process_z_slice_list(img_obj_list, config): """Make sure all members of z_slices are part of io_obj. If z_slices = 'all', replace with actual list of z_slices Parameters ---------- img_obj_list: list list of mManagerReader instances config: obj ConfigReader instance Ret...
d4142f3c32fffff4cd733bc9f7a912526c36d993
666,564
def blur_augment(is_training=True, **kwargs): """Applies random blur augmentation.""" if is_training: prob = kwargs['prob'] if 'prob' in kwargs else 0.5 return [('blur', {'prob': prob})] return []
bb4254ba956109ea9b2aa52a785d75b810a1b524
666,566
import torch def masked_softmax(x, m=None, dim=-1): """ Softmax with mask. :param x: the Tensor to be softmaxed. :param m: mask. :param dim: :return: """ if m is not None: m = m.float() x = x * m e_x = torch.exp(x - torch.max(x, dim=dim, keepdim=True)[0]) if m i...
c527bfd3102d0c69976fe4ea4e0cddfcd791eb06
666,567
def getCoord(percentX, percentY, image_size): """ Returns the width and height coordinates given the percentage of the image size you want percentX - percentage along x axis percentY - percentage along y axis image_size - tuple (width, height) of the total size of the image @return - tuple f...
7d88b9561d2f758df078e31022ad075120e7d2e5
666,571
import requests from bs4 import BeautifulSoup def scrape_reviews(isbn): """ Scrape reviews from book's Goodreads webpage using BeautifulSoup 4. Return a list of tuples (names,rating,reviews) """ book_page_url = f"https://www.goodreads.com/api/reviews_widget_iframe?did=0&format=html&hide_last_page...
cf387e368c7c97cee1f8bced4551e40d5fa9a3ee
666,574
import re import json def parse_output(s): """Parse a string of standard output text for the "OUTPUT: <JSON>" line and return the parsed JSON object. """ m = re.search(r'^###OUTPUT: (.*)', s, re.MULTILINE) if m is None: return None return json.loads(m.group(1))
2c59a214bca9884b940ea66eb19b372fc2850430
666,575
def get_last_conv_layer(keras_model): """ Get last convolution layer name of keras model input: Keras model output: string of the name of the last convolution layer Make sure last convolution layer has "conv" in the name! """ layer_names=[layer.name for layer in keras_model.layers] layer_names.revers...
b53eb42b9b9f83f790b3b194026ae3f8571db070
666,577
def build_completed_questions_feedback(actor_name, quiz_name, course_name, score, feedback): """ Build the feedback when an user has completed the quiz and has failed the quiz. :param actor_name: Name of the user that has completed the quiz. :type actor_name: str :param quiz_name: Name of the quiz....
b447fb45c742e9f13b0b67b149cd65f5ccb354c2
666,578
def parse_fastq_description(description): """ Parse the description found in a fastq reads header Parameters ---------- description: str A string of the fastq reads description header Returns ------- description_dict: dict A dictionary containing the keys and values fou...
d7d224e587f8053960d7cc235b78317309009ca2
666,579
def convert_alpha_exponent(alpha): """Convert a DFA alpha value to the expected powerlaw exponent. Parameters ---------- alpha : float Alpha value from a detrended fluctuation analysis. Returns ------- exponent : float Predicted aperiodic exponent value, representing a 1/f ...
940ed732f033d1d97d1e7ebfbe8e66df3899963b
666,580
def has_bad_first_or_last_char(val: str) -> bool: """Returns true if a string starts with any of: {," ; or ends with any of: },". Args: val: The string to be tested. Returns: Whether or not the string starts or ends with bad characters. """ return val is not None and (val.startswit...
78cb04442cac2779049ad4e1b4a86969c7b57b43
666,582
def is_own_piece(v, h, turn, grid): """Check if the player is using the correct piece :param v: Vertical position of man :param h: Horizontal position of man :param turn: "X" or "O" :param grid: A 2-dimensional 7x7 list :return: True, if the player is using their own piece, False if otherwise. ...
d3685e226554c9a67f4bef9a388ebbf968c9e5a6
666,584
def linear_interpolation(tbounds, fbounds): """Linear interpolation between the specified bounds""" interp = [] for t in range(tbounds[0], tbounds[1]): interp.append(fbounds[0] + (t - tbounds[0]) * ((fbounds[1] - fbounds[0]) / (tbounds[1] - tbou...
be6bafbefde612859883abd93b562333435f0229
666,586
import time def make_expr_sig(args = None): """create experiment signature string from args and timestamp""" # print ("make_expr_sig", args) # infile = args.infile.replace("/", "_").replace(".wav", "") # expr_sig = "MN%s_MS%d_IF%s_IS%d_NE%d_EL%d_TS%s" % (args.mode, args.modelsize, infile, args.sample...
2da20398ac7fc0e15b713ecabda46e7273958bec
666,591
def filter_nc_files(path_list): """Given a list of paths, return only those that end in '.nc'""" return [p for p in path_list if p.suffix == '.nc']
ed4c3e3eb2f8bb323aaf7ce24b331ec4c9f7bfe9
666,595
def _indent_for_list(text, prefix=' '): """Indent some text to make it work as a list entry. Indent all lines except the first with the prefix. """ lines = text.splitlines() return '\n'.join([lines[0]] + [ prefix + l for l in lines[1:] ]) + '\n'
98da37331f46f50e775bf4676d9d45c8274ffa03
666,596
def transform_results(results, keys_of_interest): """ Take a list of results and convert them to a multi valued dictionary. The real world use case is to take values from a list of collections and pass them to a granule search. [{key1:value1},{key1:value2},...] -> {"key1": [value1,value2]} -> ...
3158ee9f64110f6d2db052419c22c6ac71f51d10
666,598
def calc_iou(bbox_a, bbox_b): """ Calculate intersection over union (IoU) between two bounding boxes with a (x, y, w, h) format. :param bbox_a: Bounding box A. 4-tuple/list. :param bbox_b: Bounding box B. 4-tuple/list. :return: Intersection over union (IoU) between bbox_a and bbox_b, between 0 and 1...
36bc304ffe72a3f4a9d575cdd081e11b6425aa14
666,600
def make_target(objtype, targetid): """Create a target to an object of type objtype and id targetid""" return "coq:{}.{}".format(objtype, targetid)
37a5af1b49ac507127289728d0d386d1f376e8b7
666,601
def get_search_params(url_path): """ From the full url path, this prunes it to just the query section, that starts with 'q=' and ends either at the end of the line of the next found '&'. Parameters ---------- url_path : str The full url of the request to chop up Returns -...
fccc2ecc6606e9d46246b1080bd3a7da6a441906
666,603
def _first_multiple_of(num: int, above: int) -> int: """ Returns first multiple of num >= above """ return above + ((num-(above%num)) % num)
937cfcea1d663998afc730db844ad1c2e9c26ecd
666,604
def linear_cb(valve): """ Linear opening valve function callback. """ @valve.Expression(valve.flowsheet().time) def valve_function(b, t): return b.valve_opening[t]
79693d42fc2a56ea710eee7dba9dddd294f049a8
666,608
def _publications_urls(request, analyses): """Return set of publication URLS for given analyses. Parameters ---------- request HTTPRequest analyses seq of Analysis instances Returns ------- Set of absolute URLs (strings) """ # Collect publication links, if any ...
f60efb37c9603d614f8cf0fa9c53657235d0a156
666,609
import typing def preservation_copy(row: typing.Mapping[str, str]) -> typing.Optional[str]: """A path to the original digital asset in the 'Masters/' netapp mount. If the File Name starts with "Masters/", it will be used as is. Otherwise, it will be prepended with "Masters/dlmasters/", in order to match ...
79a2ee85e695d737c1e4042cf8000887ffe5c5df
666,610
def _test_int_pickling_compare(int_1, int_2): """Add the two given ints.""" return int_1 + int_2
db0c37f6c4a764fc3c46221fca8877e747417af1
666,611
from networkx import get_edge_attributes def uninformative_prediction(G, required_links): """ Function to predict links in an uninformative manner, i.e., the majority parity. So, if there are more positive links that negative links, then a positive link is predicted and vice-versa Args: G...
6f89b6703f8df7c42c3b03c85efea6b2d4318d81
666,617
def flatten(lst, out=None): """ @return: a flat list containing the leaves of the given nested list. @param lst: The nested list that should be flattened. """ if out is None: out = [] for elt in lst: if isinstance(elt, (list, tuple)): flatten(elt, out) else: ...
272f2b51f9f394fcccac3f94ed89c4e8ed6f1dcd
666,620
import re def int_pair(s, default=(0, None)): """Return the digits to either side of a single non-digit character as a 2-tuple of integers >>> int_pair('90210-007') (90210, 7) >>> int_pair('04321.0123') (4321, 123) """ s = re.split(r'[^0-9]+', str(s).strip()) if len(s) and len(s[0]): ...
8238633843e7e3d2dfa2a23b8a3b7e7744b5c70f
666,624
def find_match_brackets(search, opening='<', closing='>'): """Returns the index of the closing bracket that matches the first opening bracket. Returns -1 if no last matching bracket is found, i.e. not a template. Example: 'Foo<T>::iterator<U>'' returns 5 """ index = search.f...
e044cdf5e6c760b995d0e4d26d35e5beebb5cb77
666,625
def get_synapse_from_layer(cur,layer): """ Returns synapses in given layer list of tuples: (mid_object,x-pos,y-pos) Parameters ---------- cur : MySQLdb cursor layer : str Name of layer """ sql = ("select synapsecombined.mid," "object.OBJ_X," "ob...
5daf84eeea34cf059409033d36759c55c041bb74
666,628
def get_fieldnames(records): """ Extract fieldnames for CSV headers from list of results :param records: list :return: list """ fieldnames = [] ordered_fieldname = ( "time_last", "time_first", "source", "count", "bailiwick", "rrname", ...
f8258e03397ee04da91e42cb4d54ba346ad7352d
666,633
import base64 def get_stage1_command(stage1_file): """ The format of a PowerShell encoded command is a base64 encoded UTF-16LE string. This function reads the stage 1 file (UTF-8) into a string, converts it into UTF-16LE encoding, and then base64 encodes that. In Python, Base64 conversion requires Bytes objects, ...
479c4c3f032ff476754982e45a5f99339f5aff92
666,635
def is_int(object): """Check if the given object is an integer""" return isinstance(object, int)
99aeb97e23db5ac6d83776b9e9c1172d7215972c
666,636
def isCardinallyEnvyFree(prefProfile, allocation): """ INPUT: prefProfile: a PrefProfile with cardinal utilities. allocation: a dictionary that maps agents to their bundles. OUTPUT: True iff the given allocation is envy-free according to the agents' cardinal value function >>> prefProfile ...
5d19d2fd4be6f34d84ddfa209d248fed5e6b0260
666,637
import itertools def tiles_info(panoid, zoom=5): """ Generate a list of a panorama's tiles and their position. The format is (x, y, filename, fileurl) """ # image_url = 'http://maps.google.com/cbk?output=tile&panoid={}&zoom={}&x={}&y={}' image_url = "http://cbk0.google.com/cbk?output=tile&pan...
dc5d08deff7e6b6922efb6296b19a5ed23a022e9
666,646
def extend(s, var, val): """ Returns a new dict with var:val added. """ s2 = {a: s[a] for a in s} s2[var] = val return s2
5efbb43fbcc2c46a0479c3fd9323d25e3e04e4d0
666,648
def collect_vowels(s): """ (str) -> str Return the vowels (a, e, i, o, and u) from s. >>> collect_vowels('Happy Anniversary!') 'aAiea' >>> collect_vowels('xyz') '' """ vowels = '' for char in s: if char in 'aeiouAEIOU': vowels = vowels + char return vowel...
0fef4866e7ba78a9dd8209c580330b7874cfe146
666,655
def reward_scaling(r, scale=1): """ Scale immediate rewards by a factor of ``scale``. Can be used as a reward shaping function passed to an algorithm (e.g. ``ActorCriticAlgorithm``). """ return r * scale
3afbfd0114f5e1af7328f8cc1b5da5ed9990a005
666,658
from typing import Dict from typing import List import math def get_mean(data: Dict[int, List[float]]) -> Dict[int, float]: """ Turns a dictionary with float lists into a dict with mean values of all non-NaN list entries. :param data: Input dictionary with float lists :return: Output...
4ebb1faf754f6ceab714aa045ac86bb719096a8b
666,661
def clear_bgp_neighbor_soft(device, command='clear bgp neighbor soft all', alternative_command='clear bgp neighbor soft', fail_regex=None): """ Clear bgp neighbor soft using one of two commands Args: device ('obj'): Device object command ('str'): Command with a...
c3b372bbb74bde33066cd46c722b6eca7847e307
666,662
def is_custom_session(session): """Return if a ClientSession was created by pyatv.""" return hasattr(session, '_pyatv')
741057221f80f0285b8b744e635d419dd9a0a38b
666,663
from typing import Iterable from typing import Callable from typing import List def remove(items: Iterable, predicate: Callable) -> List: """Return a new list without the items that match the predicate.""" return [x for x in items if not predicate(x)]
540a3b0334ff756bc6d81df302f3543997044238
666,667
def cap_length(q, a, r, length): """Cap total length of q, a, r to length.""" assert length > 0, "length to cap too short: %d" % length while len(q) + len(a) + len(r) >= length: max_len = max(len(q), len(a), len(r)) if len(r) == max_len: r = r[:-1] elif len(a) == max_len: a = a[:-1] el...
25292014c5735b5e55a7356cbb0011e89f2d4d8f
666,675
def PySequence_Contains(space, w_obj, w_value): """Determine if o contains value. If an item in o is equal to value, return 1, otherwise return 0. On error, return -1. This is equivalent to the Python expression value in o.""" w_res = space.contains(w_obj, w_value) return space.int_w(w_res)
ad0e4bd70bf283eefb7e3921c17e14fe77e49bce
666,676
def argmax(lst): """Given a list of numbers, return the index of the biggest one.""" return max(range(len(lst)), key=lst.__getitem__)
518ea19a935d83126aa8722af0fb998030076c6f
666,677
def parse_response_browse_node(browse_nodes_response_list): """ The function parses Browse Nodes Response and creates a dict of BrowseNodeID to AmazonBrowseNode object params *browse_nodes_response_list* List of BrowseNodes in GetBrowseNodes response return Dict of BrowseNo...
68a9531afce89af9bcaf5e24d94fa2ab1d068d33
666,680
def depth_calculator(obj): """Determine how far in the hierarchy the file/folder is in. Works for either File or Folder class""" depth = 0 dad = obj.parent_folder next_in = True while next_in: if dad.parent_folder: depth += 1 dad = dad.parent_folder else: ...
6d330c053ad969ae8bf65cef4e99e3a8e3feb075
666,683
def validate_base_sequence(base_sequence, RNAflag=False): """Return True if the string base_sequence contains only upper- or lowercase T (or U, if RNAflag), C, A, G characters, otherwise False""" seq = base_sequence.upper() return len(seq) == (seq.count('A') + seq.count('U' if RNAflag else 'T') + ...
5107a617a512887392a9721d1b62ecfd369f3a73
666,686
import requests def get_csrf(REQ_URL): """Get a csrf token from the request url to authenticate further requests Parameters ---------- REQ_URL string The URL that you want to make a request against after getting the token Returns ------- csrftoken csrf token to use for...
0e1cdc3acf2dd6cb00446e2644b624cf2df7e362
666,687
def int_to_uint32(value_in): """ Convert integer to unsigned 32-bit (little endian) :param value_in: :return: """ return list(value_in.to_bytes(4, byteorder='little', signed=False))
906998350a19e1bf756ad8e87c35f4f3b5b2933c
666,689
def merge_overlapping_intervals(intervals): """ Given a collection of intervals, merge all overlapping intervals. Given the list of intervals A. A = [Interval(1, 3), Interval(2, 6), Interval(8, 10), Interval(15, 18)] The function should return the list of merged intervals. ...
71eae73d5f94f55b052018bb850f7b8a52701442
666,690
import math def get_bearing(vehicle, aLocation1, aLocation2): """ Returns the bearing between the two LocationGlobal objects passed as parameters. This method is an approximation, and may not be accurate over large distances and close to the earth's poles. It comes from the ArduPilot test code: ...
506a14a094b1cfa4ca076bb722a069e105d0ac6d
666,691
def insignificant(path): """Return True if path is considered insignificant.""" # This part is simply an implementation detail for the code base that the # script was developed against. Ideally this would be moved out to a config # file. return path.endswith('Dll.H') or path.endswith('Forward.H') or \ pa...
6610ca32d35d4f0cc8c2a559c08a8157e6fbb473
666,693
def vect3_reverse(v): """ Reverses a 3d vector. v (3-tuple): 3d vector return (3-tuple): 3d vector """ return (v[0]*-1, v[1]*-1, v[2]*-1)
25cc7d3cfed21f9b462d0398cb213c5159dde8f9
666,700
from typing import Dict import re def wikitext_detokenize(example: Dict[str, str]) -> Dict[str, str]: """ Wikitext is whitespace tokenized and we remove these whitespaces. Taken from https://github.com/NVIDIA/Megatron-LM/blob/main/tasks/zeroshot_gpt2/detokenizer.py """ # Contractions text = e...
ad06cc5c394684a265e6e91e29d3744466f18eb6
666,702
from typing import Dict from typing import Any def generate_bulkiness_section(cat_properties: Dict[str, Any]) -> str: """Generate the CAT bulkiness input section.""" def replace_None(x): return "NULL" if x is None else x if "bulkiness" not in cat_properties: return "bulkiness: False" b...
2a20acd97c9ade47ebe000bd2fe0e9c2b55a67a5
666,705
def datetime_to_string(date_object): """ Converts a datetime object to a date string of the format MM/DD/YYYY. Args: date_object: datetime object representing datetime Returns: String representing datetime object of the format MM/DD/YYYY """ return date_object.strftime("%m/%d/%...
87f6a0f9160b3cb5b1636ed052ae7b94672514b8
666,707
def normalize_package_name_for_code(package: str) -> str: """Normalize given string into a valid python package for code usage. Parameters ------------------------ package: str, The name of the package. Raises ------------------------ ValueError, When the name of the packag...
b223fdcae3a4ba382e03b7209e80183ca4c27aad
666,708
def is_list(element): """ Check if element is a Python list """ return isinstance(element, list)
a8acabc39134d1f7c7a495d2c10266267f73e92b
666,712
def process_info(table): """ Helper of get_availabilities_by_url Parser information and returns the room type, price, and number of rooms left. """ rooms = [] for row in table: if len(row) >= 5: rooms.append({ 'type': row[0].split("\n")[0].replace("\n...
acc02d7496a966d53d22beded949ad0c410d4f3f
666,716
def depends_one_or_more(dependencies): """Returns true if any of the dependencies exist, else false""" return any([x.get_exists() for x in dependencies])
b77bf4e7fd049daced040e7dadd3cc4d528860cd
666,718
def find_value_in_list(l_r, value): """ Purpose: To get value in a given list Parameters: list, value Returns: True or False Raises: """ result = False for item in l_r: if item['id'] == value: result = True break return result
aee00fd06c5212dbb7107f6735a240785ebd9b63
666,719
def check_duration(sec, larger=True): """ Creates a function you can use to check songs Args: sec: duration that we compare to in seconds larger: determines if we do a larger than operation Returns: Function that can be used to check songs """ def...
cc646b648580454559ab866a07cad50cec3d2fdc
666,722
import decimal def j_round(float_num): """java like rounding for complying with the OpenLR java: 2.5 -> 3""" num = decimal.Decimal(float_num).to_integral_value(rounding=decimal.ROUND_HALF_UP) return int(num)
5db80df0ad79a41b799970b697dbed8c45f1a09e
666,723
def filter_dict_nulls(mapping: dict) -> dict: """Return a new dict instance whose values are not None.""" return {k: v for k, v in mapping.items() if v is not None}
671e3749703e7d7db21939ff2906cdfd940acef4
666,727
def check_string(string, pos, sep, word): """Checks index 'pos' of 'string' seperated by 'sep' for substring 'word' If present, removes 'word' and returns amended string """ if sep in string: temp_string = string.split(sep) if temp_string[pos] == word: temp_string.pop(pos) ...
96ce5862f8f1b853144b7713e7f6185e3e4efa1a
666,731
from typing import Optional import string def remove_punctuation(input_text: str, punctuations: Optional[str] = None) -> str: """ Removes all punctuations from a string, as defined by string.punctuation or a custom list. For reference, Python's string.punctuation is equivalent to '!"#$%&\'()*+,-./:;<=>?@[...
032b2e50365b8966b402ed0c510f6f9ba2e1cecc
666,732
def coordstr(roi): """String representation of coordinates. Also for URL arguments.""" return str(roi['xll']) + ',' + str(roi['yll']) + ','\ + str(roi['xur']) + ',' + str(roi['yur'])
67edcca8a82b79e0ed78278ee3149ab041090ce7
666,734
def calc_validation_error(di_v, xv, tv, err, val_iter): """ Calculate validation error rate Args: di_v; validation dataset xv: variable for input tv: variable for label err: variable for error estimation val_iter: number of iteration Returns: error rate ...
e705db8b27793e1cdf648ef72c99e56832d39afc
666,736
def dict_get(d, key, default=None): """ exactly the same as standard python. this is to remind that get() never raises an exception https://docs.python.org/3/library/stdtypes.html#mapping-types-dict """ return d.get(key, default)
08176db060c8076467d2e3053618d25875021f5d
666,739
def list_to_dict(keyslist,valueslist): """ convert lists of keys and values to a dict """ if len(keyslist) != len(valueslist): return {} mydict = {} for idx in range(0,len(keyslist)): mydict[keyslist[idx]] = valueslist[idx] return mydict
f0082793a5eeaaecb374650fc3cda87a3345ccf5
666,742
from typing import Optional def linkify(url: str, text: Optional[str] = None): """Make a link clickable using ANSI escape sequences. See https://buildkite.com/docs/pipelines/links-and-images-in-log-output """ if text is None: text = url return f"\033]1339;url={url};content={text}\a"
c13cfbca91d45943f9326325fe1c5bd68b71e6d3
666,748
import random import string def random_string(min_length=5, max_length=10) -> str: """ Get a random string. Args: min_length: Minimal length of string max_length: Maximal length of string Returns: Random string of ascii characters """ length = random.randint(min_lengt...
e92aff7adb290e82946dae907c7dc6ee2e6ebe0c
666,749
import math def dist_d3 (p1, p2): """Returns the euclidian distance in space between p1 and p2. """ return math.sqrt( (p2[0] - p1[0])**2 + (p2[1] - p1[1])**2 + (p2[2] - p1[2])**2)
751aaa69b8c39a808c3b1a625ef78709f721015a
666,750
import torch def batched_gather(data, inds, dim=0, no_batch_dims=0): """https://github.com/aqlaboratory/openfold/blob/5037b3d029efcc9eeb3f5f33eedd4ecdd27ca962/openfold/utils/tensor_utils.py#L67""" ranges = [] for i, s in enumerate(data.shape[:no_batch_dims]): r = torch.arange(s) r = r.view(*(*((1,) * i), -1, *...
fb97551bbe0c84a540e78ca48762c599dc4cadfe
666,752
def find_between(s, start, end): """ Return a string between two other strings """ return (s.split(start))[1].split(end)[0]
de7494240dec8202a61ac47e798cdac6f547966e
666,754
import requests def currency_data_last_n_days(currency = 'ETH', to = 'EUR', days = 14): """Get day by day price of a currency in respect to another one, using the APIs at "min-api.cryptocompare.com". Data are from the last "days" days.""" currencies = 'fsym={0}&tsym={1}'.format(currency, to) days...
05c4f626cce7d99fa1c6d7ce4de5ecbf61eaccb2
666,756
def row2dict(row): """Converts SQLAlchemy row to dict Args: row: A SQLAlchemy query result object Returns dict: Returns the row as dictionary """ d = {} for column in row.__table__.columns: d[column.name] = str(getattr(row, column.name)) return d
080f65b41539ad2ceb7622ea3b9c772bf258542a
666,757
def calc_term_overlap(termsA, termsB): """ Calculate the reciprocal overlap between two lists of HPO terms """ nA = len(termsA) nB = len(termsB) if nA == 0 or nB == 0: ro = 0 else: nOvr = len(set(termsA).intersection(set(termsB))) oA = nOvr / nA oB = nOvr / ...
0140cc9f31ede1cf8023040383dcd45a39738d0a
666,758
from typing import Union def is_palindrome(word: str) -> Union[bool, str]: """Function to check if word is a palindrome >>> from snakypy.helpers.checking import is_palindrome >>> is_palindrome("ana") True >>> from snakypy.helpers.checking import is_palindrome >>> is_palindrome("banana") Fa...
d44480a460a9fc99a136cae7ff601ca3684b9bd7
666,759
from datetime import datetime def day_end(date: datetime) -> datetime: """ Calculates end of date Args: date (datetime): datetime object, for which to calculate the end of the day Returns: date_end (datetime): timestamp for end of the given date """ return datetime(date.year,...
3b21bd2f54bc4ab895ec0aab80def3c895e51ce2
666,762
import torch def quaternion_into_axis_angle(quaternion): """ Takes an quaternion rotation and converts into axis-angle rotation. https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles :param quaternion: 4-element tensor, containig quaternion (q0,q1,q2,q3). :return: (Axis of rotatio...
37569c34dbddacd5820171ebc5935c00b3e2bfb3
666,764
def get_offsprings(g, nodes): """ Find the offspring nodes in a DAG :param g: a directed acyclic graph :param nodes: targeted nodes :return: a set of offspring nodes """ return set.union(*[g.descendants(d) for d in nodes])
9da14e457ac402200aa18ebef90b18fba56379e6
666,766
import collections def rotated_range(start, stop, starting_value): """Produces a range of integers, then rotates so that the starting value is starting_value""" r = list(range(start, stop)) start_idx = r.index(starting_value) d = collections.deque(r) d.rotate(-start_idx) return list(d)
9a941e5dcd95b4dadf73e77cc50f6e4d12fe5885
666,767
def lab2phonemes(labels): """Convert labels to phonemes. Args: labels (str): path to a label file Returns: List[str]: phoneme sequence """ phonemes = [] for c in labels.contexts: if "-" in c: ph = c.split("-")[1].split("+")[0] else: ph = ...
40f8a40a58a047db2870a478677b5369b559a595
666,771
import copy def modify_namespace(namespace, args): """Modify the specified arguments in the passed Namespace. namespace argparse.Namespace object args dict of argument: value pairs For most command-line tests, we define a base argparse.Namespace object, then change a few argumen...
65aee8eb630ee0b75b81b18234ea04b6ca888491
666,773
def xyY2XYZ(xyY): """ convert xyY to XYZ :param xyY: array-like :return: array like """ X = xyY[0] * xyY[2] / xyY[1] Y = xyY[2] Z = ((1 - xyY[0] - xyY[1]) * xyY[2]) / xyY[1] return [X, Y, Z]
c8a56adfa01e3f693b60f088a41807950c2368bc
666,775
def get_leader(units): """Return the leader unit for the array of units.""" for unit in units: out = unit.run('is-leader') if out[0] == 'True': return unit
fe36d216adac6687128459284e5136744d2a0a71
666,776
def vector_to_tuple(vector): """Converts a column vector into a tuple.""" return tuple(row[0] for row in vector)
b7a3a22a6a916801987f5d66347bfcd87742d540
666,777
def get_position_by_substring(tofind, list): """ Get index where `tofind` is a substring of the entry of `list` :param tofind: string to find in each element of `list` :param list: list to search through :return: index in `list` where `tofind` is found as a substring """ for i, e in enumera...
8836fe6cbb1279d21320c6048c45d36746aafc8a
666,778
def _get_creator(hardict): """ Get creator of HAR file. """ creator = hardict["log"]["creator"] return "%s %s%s" % (creator["name"], creator["version"], " (Comment: %s)" % creator["comment"] if creator.get("comment") else "")
59cc6f8fbb754ee61aaa532640882107670f812e
666,780
from datetime import datetime def to_iso(time_millis): """Converts the given time since epoch in millis to an ISO 8601 string""" return datetime.utcfromtimestamp(time_millis / 1000).isoformat()
4ec3d3d3fcbd3d714d627509ddddd8ad1fc1e596
666,783
def _format_range(start, end): """ Build string for format specification. used by many commands, like delete, load, etc... :param start: :param end: :return: the string to be used for range in the command """ if start is None: return '' if end is None: return str(star...
bcca178e1d064ef0a0744906c511fc4b2e289ec8
666,785
def prefix_to_items(items, prefix): """Add a prefix to the elements of a listing. For example, add "Base" to each item in the list. """ return ['{}{}'.format(prefix, x) for x in items]
41c3abc10bfe8b2163ab9d8e5c3394a66f49247c
666,786
def dedupe_in_order(in_list, dont_add=set()): """ Deduplicate the in_list, maintaining order :param dont_add: an additional stoplist """ dedupe = set() | dont_add ordered_deduped = [] for l in in_list: if l not in dedupe: ordered_deduped.append(l) dedupe.add(l) return ordered_deduped
0df861711b28f58410d0234c6b01c4ed8c2b5d0a
666,791
def is_page_editor(user, page): """ This predicate checks whether the given user is one of the editors of the given page. :param user: The user who's permission should be checked :type user: ~django.contrib.auth.models.User :param page: The requested page :type page: ~integreat_cms.cms.models....
51ff98bce8361f6e51654eed6f9021fc5365ae79
666,792
def parse_row(row): """ Take in a tr tag and get the data out of it in the form of a list of strings. """ return [str(x.string) for x in row.find_all('td')]
44b8eadcd11d79ede2ae3d0a0866bfa80ff5e36d
666,796
def eco_fen(board): """ Takes a board position and returns a FEN string formatted for matching with eco.json """ board_fen = board.board_fen() castling_fen = board.castling_xfen() to_move = 'w' if board.turn else 'b' return "{} {} {}".format(board_fen, to_move, castling_fen)
bb8afe9f8cc02ea48e55f9197eed760fe5e25a1f
666,797
def minus(a:int,b:int)->int: """ minus operation :param a: first number :param b: second number :return: a-b """ return a-b
9a20af293d84884fc8d0762c177b301ca197871c
666,800