content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def find_nodes_with_degree(graph, degree): """ Find nodes with degree N in a graph and return a list """ degrees = graph.degree() nodes = list() for node in degrees: if degrees[node] == degree: nodes.append(node) return nodes
846cacd69425c73db312dc2ac09fe4a2192114eb
103,821
from textwrap import dedent import traceback def format_exception_trace(exception: BaseException) -> str: """ Formats the traceback part of an exception as it would appear when printed by Python's exception handler. Args: exception: The exception to format Returns: A string, usually multiline, with the traceback info. There is no newline at the end and no ``'Traceback:'`` header. The text has a base indent of 0, so as to allow you to add your own. """ return dedent(''.join(traceback.format_list(traceback.extract_tb(exception.__traceback__))).rstrip())
c5785ee85d914ebdb241c72e034e9268a2304372
661,294
def auto_intercept(with_intercept, default): """A more concise way to handle the default behavior of with_intercept""" if with_intercept == "auto": return default return with_intercept
1c11eef225cf5a75c78a306ad134ffda3c231100
594,683
def sum_forces(forces): """Returns the summed vector of a dictionary of forces""" return sum(forces.values())
53eb5ee7dc8fed9dc821a6c57214593bb8683694
444,062
def safe_index(l, e): """ Return index of element e in list l. If e is not present, return the last index """ try: return l.index(e) except: return len(l) - 1
29092fcd75a3b2f45899ce8279bb029985d5c69c
211,756
def format_timedelta(time_delta): """ Convert a datetime.timedelta to str format example output: "0h:0m:18s" Parameters ---------- time_delta: datatime.timedelta Returns ------- str: formatted timedelta """ d = {} d["hours"], rem = divmod(time_delta.seconds, 3600) d["minutes"], d["seconds"] = divmod(rem, 60) return "{hours}h:{minutes}m:{seconds}s".format(**d)
3d41644991ec558ea423f24d426e62b417fc9b48
638,431
def title_string(in_str): """ Converts a string to title case Title case means that the first character of every word is capitalized, otherwise lowercase Parameters ---------- in_str: str The string to convert to title case Returns ------- str The input string in title case Examples -------- >>> title_string("this iS a StrING to be ConverTeD") 'This Is A String To Be Converted' >>> title_string("this should be a title some time") 'This Should Be A Title Some Time' """ if not isinstance(in_str, str): raise TypeError('Input must be a string') if in_str == "": return "" lower_case = in_str.lower() new_s = "" for word in lower_case.split(): new_s += word[0].upper() + word[1:] + ' ' return new_s[0:-1]
a9e5e513683b6f46c762302c509b849aa3fe7080
486,805
def find_start_end(grid): """ Finds the source and destination block indexes from the list. Args grid: <list> the world grid blocks represented as a list of blocks (see Tutorial.pdf) Returns start: <int> source block index in the list end: <int> destination block index in the list """ start = grid.index(u'emerald_block') end = grid.index(u'redstone_block') return (start, end)
d69bcb8c45f04148b500ecf2745042e4a0ef2ad2
514,939
def validate_boolean(value, label): """Validates that the given value is a boolean.""" if not isinstance(value, bool): raise ValueError('Invalid type for {0}: {1}.'.format(label, value)) return value
716cf553ae8c957a33424dcbb699ec493c742fe0
606,813
def get_export_type(export_type): """Convert template type to the right filename.""" return { "css": "colors.css", "dmenu": "colors-wal-dmenu.h", "dwm": "colors-wal-dwm.h", "st": "colors-wal-st.h", "tabbed": "colors-wal-tabbed.h", "gtk2": "colors-gtk2.rc", "json": "colors.json", "konsole": "colors-konsole.colorscheme", "kitty": "colors-kitty.conf", "plain": "colors", "putty": "colors-putty.reg", "rofi": "colors-rofi.Xresources", "scss": "colors.scss", "shell": "colors.sh", "speedcrunch": "colors-speedcrunch.json", "sway": "colors-sway", "tty": "colors-tty.sh", "vscode": "colors-vscode.json", "waybar": "colors-waybar.css", "xresources": "colors.Xresources", "xmonad": "colors.hs", "yaml": "colors.yml", }.get(export_type, export_type)
672937324678a30ebbbf3626227328cf444f3934
522,530
def make_get_tensors_fn(output_tensors): """Create a function that outputs a collection of tensors from the dataset.""" def _get_fn(data): """Get tensors by name.""" return {tensor_name: data[tensor_name] for tensor_name in output_tensors} return _get_fn
73572960aba364fe441e52df95a032d1cad5d769
436,529
def check_condition_status(job, condition_type): """ Determines if a generic job has a condition type: Complete(Success) or Failure """ conditions = job.status.conditions if conditions: for condition in conditions: if condition.type == condition_type and condition.status == "True": return True return False
4dc21473ad888534c2260d2aa593a2644c2829f6
450,954
import torch def one_hot(args, indices): """ Returns a one-hot tensor. This is a PyTorch equivalent of Tensorflow's tf.one_hot. """ encoded_indicate = torch.zeros(args.train_n_way*args.train_n_query, args.train_n_way).cuda() index = indices.long().view(-1,1) encoded_indicate = encoded_indicate.scatter_(1,index,1) return encoded_indicate
abc8e50616002a21ec0a45ce00756ba18e9fba28
544,844
def gradient(x, y, w): """MSE gradient.""" y_hat = x @ w error = y - y_hat gradient = -(1.0 / len(x)) * 2 * x.T @ error mse = (error ** 2).mean() return gradient, mse
f2dabaa4a1b90ba91e7cbccc54dec93d2c9d678d
325,971
def _rm_cfg_key(cfg, name): """ Remove key from config and return the updated config. """ if name in cfg: del cfg[name] return cfg
7cc4517f2b284a6854e137aa9478ac5e5d28dd0d
252,290
def _is_valid_age(user_age): """ Determines if the age is valid. Args: user_age: Age to test. Returns: bool: If the age is valid. """ if type(user_age) != int: return False elif user_age < 0: return False return True
4d70b05eb6b18c769f12339537dd567f13c95ba8
134,851
def merge_list(*_list: list): """Combines multiple lists into a new one. Parameters ---------- *_list : list It contains all of the lists inside it. Returns ------- merged_list : list Returns the Merged list. """ merged_list = [] for list in _list: merged_list.extend(iter(list)) return merged_list
78284ea382fb74a1eb21f40fdec4e881d1a9f05f
518,507
def _get_chromosome_dirs(input_directory): """Collect chromosome directories""" dirs = [] for d in input_directory.iterdir(): if not d.is_dir(): continue # Just in case user re-runs and # does not delete output files elif d.name == 'logs': continue elif d.name == 'p_distance_output': continue else: dirs.append(d) return dirs
5047c0c158f11794e312643dbf7d307b381ba59f
705,429
import math def circ_in(t): """Circular in. A quarter of a circle. :math:`f(t) = \sqrt{1 - t^2}`""" return 1 - math.sqrt(1 - t * t)
83b9eb1d3411e58fed96e432572795b9e0c66266
441,836
import json def parse_event(event): """ :param event: event object received by lambda :return: tuple containing message and metadata from an event object """ metadata = {} message = json.loads(event['Records'][0]['Sns']['Message']) if 'NotificationMetadata' in message.keys(): metadata = json.loads(message['NotificationMetadata']) return message, metadata
32f81a305c184a7ca9e05a15eb291f4998735a9c
534,638
def _get_pid_from_file(fn): """Get the PID from the given file""" with open(fn) as pid_file: pid = int(pid_file.read().strip()) return pid
7a6fc4a273e01aced84c09a8888fa4e16b072944
561,953
from typing import OrderedDict import csv def get_fields(csv_file, fields): """Return a dictionary mapping each name in `fields` to the sequence of values seen for that field in the given file. """ result = OrderedDict() for field in fields: result[field] = [] with open(csv_file) as f: reader = csv.DictReader(f) for row in reader: for field in fields: result[field].append(row[field]) return result
463a48d7e144c2f2a459ba64c8cac3f0691f76cb
229,731
def retain_reference(journal_reference, min_size=3, required_fields=["author","title"]): """ Determine whether the input reference should be retained, and thus resolved, or skipped. This allows to skip erroneously extracted references, partial ones, etc. :param journal_reference: the input reference (extracted from journals in LinkedBooks) :type journal_reference: dict :param min_size: the minimum number of fields `journal_reference` must have :type min_size: int :param required_fields: the fields that must be contained in `journal_reference` :type required_fields: list of str :return: bool -- True if the reference should be retained, False otherwise """ fields = [field["tag"] for field in journal_reference["contents"].values()] if(len(fields)>=min_size): if(len(set(fields).intersection(set(required_fields))) >= len(required_fields)): return True else: return False else: return False
777c36b9f3f9f41f89b163ce8b4dc74315b34a7e
267,423
def first_non_consecutive(arr): """ Finds the first element within an array that is not consecutive. :param arr: An array of ints. :return: the first element not consecutive, otherwise None. """ for i, j in enumerate(arr): if j != arr[0] + i: return j return None
020078d18df6f6b8c4ec7ae550f0dc98bb93bbb7
74,249
def get_digits(value: float) -> int: """ Get number of digits after decimal point. """ value_str: str = str(value) if "e-" in value_str: _, buf = value_str.split("e-") return int(buf) elif "." in value_str: _, buf = value_str.split(".") return len(buf) else: return 0
93cff2e3b8b10125b8861f7e5c226eb3473bdb9e
513,484
def translate(atms, vec): """Translate a list of atoms :param atms: The list of atoms, given as a pair of the symbol and the coordinate in numpy array. :param vec: A numpy array giving the translation vector. """ return [ (i[0], i[1] + vec) for i in atms ]
8bb91839268d40010b95233752edc516b51e1de7
240,610
import pickle import glob def get_num_examples(data_dir, mode): """ Get the number of examples in directory. :param data_dir: str - data directory :param mode: str - `training`, `test` or `validate` (must match folder names) :return: int - number of examples """ with open('{}/labels.pickle'.format(data_dir), 'rb') as f: data = pickle.load(f) modes = list(data.keys()) del modes[-1] assert mode in modes, "'{}' not a valid mode (must be one of {})".format(mode, str(modes)) assert glob.glob(data_dir), "Check directory." return len(data[mode])
b505a310e371b1da76fc3893a937f597b5ae673f
613,162
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__')] if lbl_to_idx: labels = [lbl_to_idx[w] for w in labels] tokens = [w for w in line if not w.startswith('__label__')] if vocab_to_idx: tokens = [vocab_to_idx.get(w, len(vocab_to_idx)) for w in tokens] return labels, tokens
08138cf8b1d20f109cc05db5c671a0eb3d69c2f1
62,775
import typing import pathlib def parse_requirements_file (filename: str) -> typing.List: """read and parse a Python `requirements.txt` file, returning as a list of str""" with pathlib.Path(filename).open() as f: # pylint: disable=C0103 return [ l.strip().replace(" ", "") for l in f.readlines() ]
f5a3574b49d492d5671ceb0946df771673070d74
650,215
def get_node(value): """Return new node with value.""" return { 'value': value, 'next': None, 'prev': None, }
d98c9edfe9cb1ee950bc65e809d2616a92b057df
181,954
def check_dataset_groups(dataset, groups): """Check that all groups given are actually contained in the dataset. """ dataset_groups = {d.group for d in dataset} return set(groups) == dataset_groups
aee475c3addec4889fd8c70786196654bab8a668
232,975
def aggregate_shares(df): """Compute share types by year and field.""" return (df.groupby(["Year", "types", "field"]).size() .reset_index() .rename(columns={0: "count"}))
696325e80cc6249906181ee670f428e54b22c204
508,885
def SymbolTypeToHuman(type): """Convert a symbol type as printed by nm into a human-readable name.""" return {'b': 'bss', 'd': 'data', 'r': 'read-only data', 't': 'code', 'w': 'weak symbol', 'v': 'weak symbol'}[type]
0059419bd89a80d4f172e870641ed78fb74aca08
513,744
import math def num_action_type_bits(num_actions): """For a table with `num_actions` different actions that can be performed, return the number of bits to do a straightforward encoding of these as separate unique ids.""" assert(num_actions >= 0) if num_actions == 0: return 0 return int(math.ceil(math.log(num_actions, 2)))
4a375cd3ebea613f1f7eb7450349757656cf33cc
142,808
def _split(f, children): """ Given a function that returns true or false and a list. Return a two lists all items f(child) == True is in list 1 and all items not in the list are in list 2. """ l1 = [] l2 = [] for child in children: if f(child): l1.append(child) else: l2.append(child) return l1, l2
0308cac143097bfa02bf40b118168f7c98defbbb
344,604
def parse_messages(buf): """ Parses for messages in the buffer *buf*. It is assumed that the buffer contains the start character for a message, but that it may contain only part of the rest of the message. NOTE: only understands lengthless messages for now. Returns an array of messages, and the buffer remainder that didn't contain any full messages.""" msgs = [] end_idx = 0 while buf: assert ord(buf[0]) == 0, "Don't understand how to parse this type of message: %r" % buf end_idx = buf.find("\xFF") if end_idx == -1: break msgs.append(buf[1:end_idx].decode('utf-8', 'replace')) buf = buf[end_idx+1:] return msgs, buf
b89b0b4546848cc4e265e16a805468171a7d343a
209,770
def precprint(prec_type, prec_cap, p): """ String describing the precision mode on a p-adic ring or field. EXAMPLES:: sage: from sage.rings.padics.misc import precprint sage: precprint('capped-rel', 12, 2) 'with capped relative precision 12' sage: precprint('capped-abs', 11, 3) 'with capped absolute precision 11' sage: precprint('floating-point', 1234, 5) 'with floating precision 1234' sage: precprint('fixed-mod', 1, 17) 'of fixed modulus 17^1' """ precD = {'capped-rel':'with capped relative precision %s'%prec_cap, 'capped-abs':'with capped absolute precision %s'%prec_cap, 'floating-point':'with floating precision %s'%prec_cap, 'fixed-mod':'of fixed modulus %s^%s'%(p, prec_cap), 'lattice-cap':'with lattice-cap precision', 'lattice-float':'with lattice-float precision', 'relaxed':'handled with relaxed arithmetics'} return precD[prec_type]
b3eab5f0fd133ead8c413aded650d839a2c818b9
698,846
def read_file(filename): """ Read whole file to list of stripped strings :param filename: filepath :return: list of strings """ with open(filename) as f: lines = f.readlines() return map(str.rstrip, lines)
cf164eab607972e9a3c27e437f37723ac75bdcdc
421,268
def fits_column_format(format): """Convert a FITS column format to a human-readable form. Parameters ---------- format : :class:`str` A FITS-style format string. Returns ------- :class:`str` A human-readable version of the format string. Examples -------- >>> fits_column_format('A') 'char[1]' >>> fits_column_format('J') 'int32' >>> fits_column_format('12E') 'float32[12]' """ if format.startswith('1P'): cmap = {'B': '8-bit stream', 'I': '16-bit stream', 'J': '32-bit stream'} return cmap[format[2]] fitstype = format[-1] if fitstype == 'A' and len(format) == 1: return 'char[1]' fmap = {'A': 'char', 'I': 'int16', 'J': 'int32', 'K': 'int64', 'E': 'float32', 'D': 'float64', 'B': 'binary', 'L': 'logical'} if len(format) > 1: return fmap[fitstype] + '[' + format[0:len(format)-1] + ']' else: return fmap[fitstype]
116b7cf55a0d5ec786a149e20217ce3bce6313d8
66,879
from pathlib import Path def strip_build_dir(build_dir, node): """Small util function for making args match the graph paths.""" return str(Path(node).relative_to(build_dir))
487b81a194f0e203ba1b6963105ea02e7c5ee6d3
511,218
def quotify(string): """Return the string with quotes >>> quotify("some string") '"some string"' """ return f'"{string}"'
a4dd853b0b68932f5c9a1e6e962a6e4af850afe4
310,266
def link_cmd(path, link): """Returns link creation command.""" return ['ln', '-sfn', path, link]
a7c0477fd643b6eebc028fdfbd890922ac4ceb09
688,794
def locate_zephyr_base(checkout, version): """Locate the path to the Zephyr RTOS in a ChromiumOS checkout. Args: checkout: The path to the ChromiumOS checkout. version: The requested zephyr version, as a tuple of integers. Returns: The path to the Zephyr source. """ return (checkout / 'src' / 'third_party' / 'zephyr' / 'main' / 'v{}.{}'.format(*version[:2]))
9e2bba1debcd60240701360348b4a894b7c3915a
66,415
def valid_number(phone_number): """Valid a cellphone number. :param phone_number: Cellphone number. :type phone_number: str :returns: true if it's a valid cellphone number. :rtype: bool """ phone_number = phone_number.replace(" ", "") if len(phone_number) != 10: return False for i in range(10): try: int(phone_number[i]) except ValueError: return False return True
60f40b8ca93a9490ff7ae971879c7d219bec7035
450,070
def bool_from(obj, default=False): """ Returns: True if obj is not None and its string representation is not 0 or False (case-insensitive). If obj is None, 'default' is used. """ return str(obj).lower() not in ('0', 'false') if obj is not None else bool(default)
2d09ffac8eaa5f05079ce4f43e56e07a4073e028
434,638
def edges_to_adj_list(edges): """ Transforms a set of edges in an adjacency list (represented as a dictiornary) For UNDIRECTED graphs, i.e. if v2 in adj_list[v1], then v1 in adj_list[v2] INPUT: - edges : a set or list of edges OUTPUT: - adj_list: a dictionary with the vertices as keys, each with a set of adjacent vertices. """ adj_list = {} # store in dictionary for v1, v2 in edges: if v1 in adj_list: # edge already in it adj_list[v1].add(v2) else: adj_list[v1] = set([v2]) if v2 in adj_list: # edge already in it adj_list[v2].add(v1) else: adj_list[v2] = set([v1]) return adj_list
683f10e9a0a9b8a29d63b276b2e550ebe8287a05
706,638
def format_sec_to_dhm(sec): """Format seconds to days, hours, minutes. Args: sec: float or int Number of seconds in a period of time. Returns: str Period of time represented as a string on the form ``0d\:00h\:00m``. """ rem_int, s_int = divmod(int(sec), 60) rem_int, m_int, = divmod(rem_int, 60) d_int, h_int, = divmod(rem_int, 24) return "{}d {:02d}h {:02d}m".format(d_int, h_int, m_int)
0dff0fb83f904465f5177cf7d38368ac1f44e8e4
656,680
def area_tr(base_t,height_t): """Calculates the area of a triangle with given base and height :Input: The base and height of the triangle (float, >=0) :Returns: The area of the triangle (float).""" if base_t < 0: raise ValueError("The base must be >= 0.") if height_t < 0: raise ValueError("The height must be >= 0.") area_out = 0.5*base_t*height_t print("The area of a triangle with base b = {:3.2f}cm and height h = {:3.2f}cm is A = {:4.2f}cm2".format(base_t,height_t,area_out)) return area_out
e210b34a9679a799677007ead89ed3de1cb1c4d6
613,981
import six def ensure_unicode(val): """Ensure that a a given value is a unicode string. If ``val`` is a :py:data:`six.binary_type <binary type>`, assume it's UTF-8 and decode it. :param val: A :py:data:`six.binary_type <binary>` or :py:data:`six.text_type <text>` type. :rtype: :py:class:`unicode` on Python 2, :py:class:`str` on Python 3 """ if isinstance(val, six.binary_type): return val.decode('utf-8') return val
0b1f6a6f48b23860c3c2aa7ef8ac2480779899bd
303,531
def is_super(node): """return True if the node is referencing the "super" builtin function """ if getattr(node, 'name', None) == 'super' and \ node.root().name == '__builtin__': return True return False
bea8392d69271c20c6b0648fdd20e67006c55016
76,227
def correct_capitalization(token, pronoun): """ If the original pronoun was capitalized, capitalize the new pronoun. """ if token.text[0].isupper(): pronoun = pronoun.capitalize() return pronoun
8ee4d271ba5008908928ea8b02209d6bf6837365
264,748
def cache_get_langs(sql): """Get the list of languages from tooltip database.""" return [row[0] for row in sql.execute( "SELECT DISTINCT lang FROM vars").fetchall()]
160e61c15c5141ac9a590a0993361ab6548796b5
646,770
def ellipsis(text, length, cutoff='[...]'): """ shortens text with a [...] at the end """ return text if len(text) <= length else \ text[:length - len(text) - len(cutoff)] + cutoff
65d61e525e26f9d13efbd12e3e7db2f4761521c1
531,415
def get_clean_path_option(a_string): """ Typically install flags are shown as 'flag:PATH=value', so this function splits the two, and removes the :PATH portion. This function returns a tuple consisting of the install flag and the default value that is set for it. """ option, default = a_string.split('=') option = option[:-5] return option, default
56954c706de0d01077a6c6e023e997d66517e5a1
686,893
def trim_leading_lines(lines): """ Trim leading blank lines. """ lines = list(lines) while lines and not lines[0]: lines.pop(0) return lines
6256a144b6a3b533229762dcaa62ee98d91038b8
480,562
def parse_bim_line(line): """ Parse a bim line. Format should be: chromosome SNP_name 0 location allele_1 allele_2. allele_1 != allele_2. Parameters ---------- line: str bim line to parse. Returns: tuple Dictionary entry with SNP name as key. """ elems = line.translate(None, "\n").split("\t") if len(elems) == 1: elems = line.translate(None, "\n").split(" ") try: assert len(elems) == 6 chromosome = int(elems[0]) SNP_name = elems[1] assert int(elems[2]) == 0, "Third index is not 0" location = int(elems[3]) allele_1 = elems[4] assert allele_1 in "TCAG", "Allele not in TCAG" allele_2 = elems[5] assert allele_2 in "TCAG", "Allele not in TCAG" assert allele_1 != allele_2, "Allele 1 and 2 are equal." except AssertionError as e: raise ValueError("Could not parse bim line \"%s\"(%s)" % (line, e)) return (SNP_name, {"location": location, "chromosome": chromosome, "allele_1": allele_1, "allele_2": allele_2})
8b632d64a7d92d07a8ac97b12b83af8dc93e47dd
453,471
import torch def interpolate_irreg_grid(interpfunc, pos): """Interpolate the funtion Args: interpfunc (callable): function to interpolate the data points pos (torch.tensor): positions of the walkers Nbatch x 3*Nelec Returns: torch.tensor: interpolated values of the function evaluated at pos """ nbatch, nelec, ndim = pos.shape[0], pos.shape[1]//3, 3 return torch.as_tensor(interpfunc(pos.reshape(nbatch, nelec, ndim)))
3509f7a102211b43b4964ef908a0ce0a68579e53
688,137
def _log_probability_picklable(theta, instance, name): """ Method for multiprocessing to work with class instance methods (making it pickleable). """ return getattr(instance, name)(theta)
a651e2a76eaca032e837624a604ed4f536de4702
611,632
import requests def get_test_quote(backend, headers, amount, buy_sell="buy", pair="XUS_USD") -> str: """Creates a test quote and returns its id""" quote_payload = {"action": buy_sell, "amount": amount, "currency_pair": pair} quote_res = requests.post( f"{backend}/api/account/quotes", headers=headers, json=quote_payload ) quote_res.raise_for_status() quote_id = quote_res.json().get("quote_id") return quote_id
5676456443dd08b22c89db9c0a228394de791961
335,196
from pathlib import Path from typing import Optional import filecmp def files_are_identical(src_path: Path, dst_path: Path, content: Optional[str]) -> bool: """Tell whether two files are identical. Arguments: src_path: Source file. dst_path: Destination file. content: File contents. Returns: True if the files are identical, False otherwise. """ if content is None: return filecmp.cmp(str(src_path), str(dst_path), shallow=False) return dst_path.read_text() == content
1f55da5777c89c588ad51a73c992a2d0838036c7
358,560
def single_type_count(clothes_list, type): """ Returns an integer value of the number of a given type of clothing in a list. Args: clothes_list (list): List of clothing objects to count from type (str): Clothing type to count Returns: type_count (int): Number of garments of the specified type in the given list of clothing objects """ type_count = 0 for garment in clothes_list: if garment.db.clothing_type: if garment.db.clothing_type == type: type_count += 1 return type_count
52219cae17bd67671904bd7ee9ae01fc4548ef96
77,886
def remember_umbrella(weather_arg: str) -> bool: """Remember umbrella Checks current weather data text from :meth:`get_weather` for keywords indicating rain. Args: weather_arg: String containing current weather text of specified city. Returns: True if any of the rain keywords are found, False otherwise. """ # Check weather_arg for rain tokens = ['rain', 't-storms'] """list: Strings of keywords that indicate rain.""" weather_arg = weather_arg.lower() # To match tokens' case for token in tokens: if token in weather_arg: return True return False
a912b75f1e4a32c7088120e09843609a08fe20f3
672,037
import torch def mse(target, predicted): """Mean Squared Error""" return torch.mean((target - predicted)**2)
27b60d509f4cddac3e06f8cb76ee3221f60e8d0b
677,968
def _build_merge_vcf_command_str(raw_vcf_path_list): """Generate command string to merge vcf files into single multisample vcf.""" command = " ".join([ 'bcftools merge', " ".join(raw_vcf_path_list) ]) return command
8c8992770f51d4393155ccbb6956d0ae6ce23465
413,499
def roi_reorder(sectors, new_order): """ Given a roi with dimensions RxWxH where R are rois, reorder the roi order. Parameters ---------- sectors : 3D array numpy array with dimensions RxHxW where R=roi, H=height, W=width new_order : list list of indices in correct order Returns ------- reordered: 3D array numpy array with dimensions RxHxW with reorders rois """ reordered = sectors[new_order,:,:] return reordered
599adeb9dabd888f86bf8a4dc83589c5d99ddc06
404,947
def regularise_periapse_time(raw, period): """ Change the periapse time so it would be between 0 and the period """ res = raw if res < 0: res += period if res > period: res -= period return res
3a135b7f45b99f7bdf8a7107d87f606b1f290e66
681,758
def get_next_item(iterable): """Gets the next item of an iterable. If the iterable is exhausted, returns None.""" try: x = iterable.next() except StopIteration: x = None except AttributeError: x = None return x
b5f595a3d3cd65c78910abcf2aa6074a18ecb086
133,868
import six import binascii def _uvarint(buf): """Reads a varint from a bytes buffer and returns the value and # bytes""" x = 0 s = 0 for i, b_str in enumerate(buf): if six.PY3: b = b_str else: b = int(binascii.b2a_hex(b_str), 16) if b < 0x80: if i > 9 or (i == 9 and b > 1): raise ValueError("Overflow") return (x | b << s, i + 1) x |= (b & 0x7f) << s s += 7 return 0, 0
825921b72501436ca52dff498c76c43c0f5f48ca
23,720
def _ensure_exists(path): """Return the path after ensuring it exists.""" if not path.exists(): raise RuntimeError(f"The path {path} does not exist!") return path
71fda14222bdb75e8950051d8f7852defed27f42
540,083
def row_divisibles(row): """Find two items in a list of integers that are divisible""" row = list(row) row_max = max(row) for i in sorted(row): for multiplier in range(2, int(row_max/i) + 1): if i * multiplier in row: return (i, i * multiplier)
195362afb559cc85abff338cfa46a65bb82f3f52
56,519
def load_plugin_names(settings): """ Generate a unique name for a plugin based on the class name module name and path >>> settings = {'PLUGINS': ['a', 'b.c', 'a.c']} >>> load_plugin_names(settings) ['a', 'c', 'a.c'] """ seen = set() def generate_name(path, maxsplit=0, splits=None): if splits is None: splits = len(path.split('.')) - 1 name = '.'.join(path.split('.', splits - maxsplit)[-1].rsplit('.', maxsplit)) if name not in seen or maxsplit >= splits: seen.add(name) return name return generate_name(path, maxsplit + 1, splits) if settings['PLUGINS']: return [generate_name(path) for path in settings['PLUGINS']] else: return ['Annotations']
8d0a2a2ee8c33611d96060775e58eb69dbbc2745
254,496
def test_function_with_fancy_docstring(arg): """Function with a fancy docstring. Args: arg: An argument. Returns: arg: the input, and arg: the input, again. @compatibility(numpy) NumPy has nothing as awesome as this function. @end_compatibility @compatibility(theano) Theano has nothing as awesome as this function. Check it out. @end_compatibility """ return arg, arg
24e0dd0953df64b92ec0c2f1dd21726c5d2588b3
408,400
def parse_etraveler_response(rsp, validate): """ Convert the response from an eTraveler clientAPI query to a key,value pair Parameters ---------- rsp : return type from eTraveler.clientAPI.connection.Connection.getHardwareHierarchy which is an array of dicts information about the 'children' of a particular hardware element. validate : dict A validation dictionary, which contains the expected values for some parts of the rsp. This is here for sanity checking, for example requiring that the parent element matches the input element to the request. Returns ---------- slot_name,child_esn: slot_name : str A string given to the particular 'slot' for each child child_esn : str The sensor id of the child, e.g., E2V-CCD250-104 """ for key, val in validate.items(): try: rsp_val = rsp[key] if isinstance(val, list): if rsp_val not in val: errmsg = "eTraveler response does not match expectation for key %s: " % (key) errmsg += "%s not in %s" % (rsp_val, val) raise ValueError(errmsg) else: if rsp_val != val: errmsg = "eTraveler response does not match expectation for key %s: " % (key) errmsg += "%s != %s" % (rsp_val, val) raise ValueError(errmsg) except KeyError: raise KeyError("eTraveler response does not include expected key %s" % (key)) child_esn = rsp['child_experimentSN'] slot_name = rsp['slotName'] return slot_name, child_esn
b8f8d0cb395889dd2266e926abbf323c6ea7ae84
48,201
import re def keyword_score(title, desc, keywords): """Return match score for column title:desc given keyword list. Args: title: str of column title desc: str of column description keywords: list of keywords to match Returns: int of weighted keyword matches """ score = 0 title_words = set(re.split("[^a-z]+", title.lower())) desc_words = set(re.split("[^a-z]+", desc.lower())) score += 2.0 * len(keywords & title_words) score += 1.0 * len(keywords & desc_words) return score
f6532924fa8b12bb62d42b0df4ff131ae3e88a6e
241,124
import sqlite3 def get_columns(cursor, table): """Returns list of column names used in table.""" cursor.execute('PRAGMA table_info({0})'.format(table)) columns = [x[1] for x in cursor] if not columns: raise sqlite3.ProgrammingError('no such table: {0}'.format(table)) return columns
3382d6a7e010d2363df6a97c5ef840f7a5567a06
516,336
import re def _extract_id(id_string): """Extracts the numeric ID from the representation of the subject or object ID that appears as an attribute of the svo element in the Medscan XML document. Parameters ---------- id_string : str The ID representation that appears in the svo element in the XML document (example: ID{123}) Returns ------- id : str The numeric ID, extracted from the svo element's attribute (example: 123) """ p = 'ID\\{([0-9]+)\\}' matches = re.match(p, id_string) assert(matches is not None) return matches.group(1)
6adb033ca87c54ff854438e2640f381ca0fda5e4
310,841
def format_vdu_interfaces(interfaces_list): """ Convert the list of VDU interfaces in a dict using the name of the interfaces as keys Args: interfaces_list (list): The list of VDU net interfaces. Each item is a dict. Returns: dict: The interfaces as dict { "user": { "mac-address": "fa:16:3e:0c:94:7f", "ip-address": "192.168.252.12", "name": "ens6", "ns-vld-id": "user" }, "cache": { "mac-address": "fa:16:3e:4d:b9:64", "ip-address": "192.168.253.9", "name": "ens7", "ns-vld-id": "cache" }, "management": { "mgmt-vnf": "true", "mac-address": "fa:16:3e:99:33:43", "ip-address": "192.168.111.29", "name": "ens3", "ns-vld-id": "management" } } """ interfaces = {} for interface in interfaces_list: net_type = interface.get('ns-vld-id', None) if net_type is None: continue interfaces[net_type] = interface return interfaces
5b586742b46380a40c921124c46dd3ced0ec6649
200,885
import requests import json def cts_brenda_to_kegg(brenda_name, max_requests=3): """ Returns the KEGG id of a compound, from the name on BRENDA. """ cts_response = requests.get('http://cts.fiehnlab.ucdavis.edu/' 'service/convert/Chemical%20Name/' 'KEGG/' + brenda_name) request_counter = 0 while request_counter <= max_requests: try: kegg_ids = json.loads(cts_response.text)[0]['result'] break except (KeyError, IndexError): request_counter = request_counter + 1 else: assert False if kegg_ids: return kegg_ids[0] else: return None
a5190172f445debafe2a2e32ae08865d7f00db3a
584,040
import math def human_filesize(filesize): """Display the filesize in a human-readable unit.""" if filesize > 0: names = [" ", "k", "M", "G", "T", "P", "E"] exponent = math.floor(math.log(filesize, 1000)) digits = filesize / math.pow(1000, exponent) prefix = names[exponent] return "%6.2f %sB" % (digits, prefix) else: return " 0.00 B"
ef2c0184f2fa6b8986a58e8c0226fd48d38b3ec1
515,680
def ele_types(eles): """ Returns a list of unique types in eles """ return list(set([e['type'] for e in eles] ))
e87ea4c6256c2520f9f714dd065a9e8642f77555
4,484
def pcp(pred, target, dist_func, threshold, reduce=True): """ Computes the percentage of correct predictions (PCP) between pred and target. Args: pred(np.ndarray): array of predicted data. target(np.ndarray): array of target data. dist_func(function): function to use to compute distance. threshold(float): threshold to consider the detection correct. reduce(bool): if reduction method should be applied. Returns: (np.ndarray): pcp between pred and target """ dists = dist_func(pred, target) pck = dists < threshold return pck.mean() if reduce else pck
201f84984564918336020538faee56d08f5abdee
457,293
def parcellate_hemisphere(roiname: str): """ Parcellation Region's name into its related hemisphere Parameters ---------- roiname : str [description] Returns ------- [type] [description] """ if roiname.endswith("_L"): return "Left" elif roiname.endswith("_R"): return "Right" else: return "Cerebellum"
5a0839b1da816aec842b43ff1a63cdc1ed766896
489,624
def s3_url(row): """ Create S3 URL for object from S3 bucket and key """ return f's3://{row["Bucket"]}/{row["Key"]}'
16046ce0d7b1e651649d6bd21b8eea336cd200bf
489,421
def time_average(a, C, emin, emax, eref=1): """ Average output of events with energies in the range [emin, emax] for a power-law of the form f = C*e**-a to the flare energy distribution, where f is the cumulative frequency of flares with energies greater than e. If the power law is for flare equivalent durations, this amounts to the ratio of energy output in flares versus quiesence. If the power law is for flare energies, it is the time-averaged energy output of flares (units of power). """ return a * C / (1 - a) * eref * ((emax/eref) ** (1 - a) - (emin/eref) ** (1 - a))
ad7afe715025f27cfc81d6948bf024fa55752d7b
531,200
def executor_type(request) -> str: """Test fixture which yields an executor type.""" return request.param
4b8d9daeeca3f0347653c0111bb785ca9584ccb2
385,338
def mask_list(l, mask): """Returns the values of the specified list that are True in the specified mask.""" return [v for i, v in enumerate(l) if mask[i]]
205ebfe62b48d22c1f439eb9a25332cc32c8a08b
234,653
def word_overlap(left_words, right_words): """Returns the Jaccard similarity between two sets. Note ---- The topics are considered sets of words, and not distributions. Parameters ---------- left_words : set The set of words for first topic right_words : set The set of words for the other topic Returns ------- jaccard_similarity : float """ intersection = len(left_words.intersection(right_words)) union = len(left_words.union(right_words)) jaccard = intersection / union return jaccard
3baa3ec5605bef4658815ac4d546539c480ae4b5
38,133
def convert(lines): """Convert compiled .ui file from PySide2 to Qt.py Arguments: lines (list): Each line of of .ui file Usage: >> with open("myui.py") as f: .. lines = convert(f.readlines()) """ def parse(line): line = line.replace("from PySide2 import", "from Qt import") line = line.replace("QtWidgets.QApplication.translate", "Qt.QtCompat.translate") return line parsed = list() for line in lines: line = parse(line) parsed.append(line) return parsed
70324df5dfec895d6bbd5100d7634cbb8b6a358a
630,544
def load_grid(filename): """ reads the file and saves the content as a 2d list :param filename: str - absolute path if the file is not part of the project :return: list of lists - 2d grid """ return [list(line.rstrip('\n')) for line in open(filename)]
b5e8091289ceb52133ef8c744039fe989cea8c62
428,419
from typing import Tuple def get_word_from_cursor(s: str, pos: int) -> Tuple[str, int, int]: """ Return the word from a string on a given cursor. :param s: String :param pos: Position to check the string :return: Word, position start, position end """ assert 0 <= pos < len(s) pos += 1 s = ' ' + s p = 0 # Check if pos is an empty character, find the following word if s[pos].strip() == '': found = False for k in range(pos, len(s)): # First if s[k].strip() != '' and not found: p = k found = True elif s[k].strip() == '' and found: return s[p:k].strip(), p, k - 1 else: for w in range(pos): # Find prev j = pos - w - 1 if s[j].strip() == '': p = j break elif s[j].strip() == '>': p = j + 1 break for j in range(pos + 1, len(s)): # Find next if s[j].strip() in ('', '<'): return s[p:j].strip(), p, j - 1 return '', -1, -1
b777bb454a4e3a206f57388c3136ddc6de7af544
678,904
def total_return_nb(total_profit, init_cash): """Get total return per column/group.""" return total_profit / init_cash
7ccf811471ea2d12400b6c1f53bde1e28726321e
614,517
from io import BytesIO def bytes_to_bytesio(bytestream): """Convert a bytestring to a BytesIO ready to be decoded.""" fp = BytesIO() fp.write(bytestream) fp.seek(0) return fp
d59e4f5ccc581898da20bf5d3f6e70f8e8712aa6
707,700
def post_list_mentions(db, usernick, limit=50): """Return a list of posts that mention usernick, ordered by date db is a database connection (as returned by COMP249Db()) return at most limit posts (default 50) Returns a list of tuples (id, timestamp, usernick, avatar, content) """ cursor = db.cursor() search_nick = '%@' + usernick + '%' sql = """SELECT id, timestamp, usernick, avatar, content FROM posts JOIN users ON posts.usernick=users.nick WHERE content LIKE (?) ORDER BY timestamp DESC LIMIT (?);""" cursor.execute(sql, (search_nick, limit)) result = [] for row in cursor: result.append(row) return result
4e89014a65d12c677f8dc8489f80017acd51d726
167,683
def maskLandsatclouds(image): """ Function to mask out clouds from Landsat images args: Landsat image returns: Cloud masked image """ orig = image qa = image.select('pixel_qa') #cloudsShadowBitMask = 1 << 3 cloudsBitMask = 1 << 4 mask = qa.bitwiseAnd(cloudsBitMask).eq(0) #\ #.And(qa.bitwiseAnd(cloudsBitMask).eq(0)) return (image.updateMask(mask).copyProperties(orig, orig.propertyNames()))
3360ef2146e519d1d910ba301c95f912a8827509
448,791
import configparser def configurations(path): """Parses and reads the configuration file named found at path. Returns a configparser Object.""" # create config parsing object config = configparser.ConfigParser() # read config config.read(path) return config
de3177feee980f1ffa3be9b1b330ed780304108f
43,301
def ensure_list_or_tuple(obj): """ Takes some object and wraps it in a list - i.e. [obj] - unless the object is already a list or a tuple instance. In that case, simply returns 'obj' Args: obj: Any object Returns: [obj] if obj is not a list or tuple, else obj """ return [obj] if not isinstance(obj, (list, tuple)) else obj
1b8e0365bc303f43f465feb77b88c2091bf943df
677,054
def sizeFormat(sizeInBytes): """ Format a number of bytes (int) into the right unit for human readable display. """ size = float(sizeInBytes) if sizeInBytes < 1024: return "%.0fB" % (size) if sizeInBytes < 1024 ** 2: return "%.3fKb" % (size / 1024) if sizeInBytes < 1024 ** 3: return "%.3fMb" % (size / (1024 ** 2)) else: return "%.3fGb" % (size / (1024 ** 3))
ec206c7e1b68c220e6053da32bfe7ca6c015e9e3
205,383
def get_precipitation_forecast(points): """Get the precipitation forecast from forecast data. Parameters ---------- points : list of dicts The forecast raw data. Returns ------- precipitation_forecast : dict of list of dicts The precipitation forecast grouped by time resolution. """ precipitation = [i for i in points if 'precipitation' in i] # The precipitation forecast have a time resolution based given # by its to and from values. We will first group by this. precipitation_forecast = {} for point in precipitation: timediff = int( (point['time']['to'] - point['time']['from']).total_seconds() ) if timediff not in precipitation_forecast: precipitation_forecast[timediff] = [] precipitation_forecast[timediff].append(point) return precipitation_forecast
cd849697ea42234ea54496a013062cc0dab6ede3
350,292
import pathlib def absolute_path(*paths): """Given a path relative to this project's top-level directory, returns the full path in the OS. Args: paths: A list of folders/files. These will be joined in order with "/" or "\" depending on platform. Returns: The full absolute path in the OS. """ # First parent gets the scripts directory, and the second gets the top-level. result_path = pathlib.Path(__file__).resolve().parent.parent for path in paths: result_path /= path return str(result_path)
eb275e00e092cce70d35b4042cad5d6a5de0a5ba
286,625
import requests def status_crawler(LEETCODE_SESSION: str, question_name: str) -> bool: """Check if question solved Args: LEETCODE_SESSION (str): User's LeetCode session. question_name (str): LeetCode question name. Returns: bool: Solved or not. """ cookies = {"LEETCODE_SESSION": LEETCODE_SESSION} response = requests.get( "https://leetcode.com/api/problems/all/", cookies=cookies ).json() for question in response["stat_status_pairs"]: question_title = question["stat"]["question__title"] if question_title == question_name: if question["status"] == "ac": return True return False
0cad01ba7331680628da089c33cc9dccf37d3815
632,181