content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def validate_sample_name(query_name: str, sample_list): """ Function will validate the query name with a sample list of defined names and aliases """ verified_sample_name = [key for key, value in sample_list.items() if query_name.lower() in value['aliases']] if verified_sample_name: return verified_sample_name[0] else: return None
e2fe6274a4d543229ce131cf9060ccf1d3833669
208,582
def compareThresh(value,threshold,mode,inclusive, *, default=False): """Returns a boolean only if value satisfies the threshold test. In case of failure of any sort, returns the default value (which defaults to 'False'). Accepted mode values are '<', '>', '<=' and '>='.""" #normalizing input if inclusive: if mode == ">": mode = ">=" elif mode == "<": mode = "<=" if mode == "<": return value < threshold elif mode == ">": return value > threshold elif mode == "<=": return value <= threshold elif mode == ">=": return value >= threshold return default
ea3b4fc683c7940996d42c27962217a1ebec7efe
664,919
import re def _opts_to_list(opts): """ This function takes a string and converts it to list of string params (YACS expected format). E.g.: ['SOLVER.IMS_PER_BATCH 2 SOLVER.BASE_LR 0.9999'] -> ['SOLVER.IMS_PER_BATCH', '2', 'SOLVER.BASE_LR', '0.9999'] """ if opts is not None: list_opts = re.split('\s+', opts) return list_opts return ""
5befb8447bed48a81e339c8811f58765c3c34182
133,174
def differenclists(list1, list2): """ Returns list1 \ list2 (aka all elements in list 1 that are not in list 2) """ return list(set(list1).difference(list2))
c7309f1463eb567851f88016ce2cbeb8aba45fa3
189,882
def determine_upgrade_actions( repo, format_upgrades, optimizations, sourcereqs, destreqs ): """Determine upgrade actions that will be performed. Given a list of improvements as returned by ``find_format_upgrades`` and ``findoptimizations``, determine the list of upgrade actions that will be performed. The role of this function is to filter improvements if needed, apply recommended optimizations from the improvements list that make sense, etc. Returns a list of action names. """ newactions = [] for d in format_upgrades: name = d._requirement # If the action is a requirement that doesn't show up in the # destination requirements, prune the action. if name is not None and name not in destreqs: continue newactions.append(d) newactions.extend(o for o in sorted(optimizations) if o not in newactions) # FUTURE consider adding some optimizations here for certain transitions. # e.g. adding generaldelta could schedule parent redeltas. return newactions
67aa8ff65e4a795e7feb7fa7296811071592e144
497,863
def stata_string_escape(text: str) -> str: """Escape a string for Stata. Use this when a string needs to be escaped for a single line. Args: text: A string for a Stata argument Returns: A quoted string. """ new_text = text new_text = new_text.replace('\n', ' ') new_text = new_text.replace('\t', ' ') new_text = new_text.replace('"', "'") return f'"{new_text}"'
247f974272a3019fe6d6b8991ad2eb508f717ece
259,075
def _gather_results(tree): """Convert the XML tree into a map of pod types to tuples (title, value). """ result = {} for pod in tree.findall('.//pod'): pod_type = pod.attrib['id'] title = pod.attrib['title'] val = None for plaintext in pod.findall('.//plaintext'): if plaintext.text: val = plaintext.text.replace(u"\n", u", ") if val: result[pod_type] = (title, val) return result
f4f58c296043772c91dc5a6fd72a070dba7c7f62
228,431
def find_last_reaction_index(species_reaction_sets, srs_idx): """Returns the index in species_reaction_sets where the reaction set at srs_idx ends. :param species_reaction_sets: list of species-specific CoMetGeNe reaction sets :param srs_idx: index of a reaction set in species_reaction_sets :return: index in terms of reactions in species_reaction_sets where the reaction set at index srs_idx ends """ last_idx = 0 for i in range(srs_idx + 1): reaction_set = species_reaction_sets[i] last_idx += len(reaction_set.reactions) return last_idx - 1
14f7a9a4c44c74a1f39fb6a9597eaa10bcc64783
150,754
import re def _progress_stdout_handler(progress_cb): """ :return: stdout handler which looks for percentage done reports and makes an appropriate call to the progress callback. The handler uses a regex to look for a 'percentage' output and calls the progress handler with the number found and a 'total' of 100. """ percent_re = re.compile(r"^(\d+)%?$") def _handler(line): match = percent_re.match(line) if match: progress_cb(int(match.group(1)), 100) return _handler
d8a4446c793e44b30ecd1f261d190c037ea562b6
587,673
import torch def cropToFrame(bbox, image_shape): """Checks if bounding boxes are inside frame. If not crop to border""" array_width = torch.ones_like(bbox[:, 1]) * image_shape[1] - 1 array_height = torch.ones_like(bbox[:, 2]) * image_shape[0] - 1 bbox[:, 1:3] = torch.max(bbox[:, 1:3], torch.zeros_like(bbox[:, 1:3])) bbox[:, 1] = torch.min(bbox[:, 1], array_width) bbox[:, 2] = torch.min(bbox[:, 2], array_height) bbox[:, 3] = torch.min(bbox[:, 3], array_width - bbox[:, 1]) bbox[:, 4] = torch.min(bbox[:, 4], array_height - bbox[:, 2]) return bbox
7bfaff063005c4ac40488f9eaebdebdda722f0d6
210,692
def calc_ttr(df_ttr): """Calculates travel time reliability. Args: df_ttr, a pandas dataframe. Returns: df_ttr, a pandas dataframe with new ttr column. """ # Working vehicle occupancy assumptions: VOCt = 1 df_ttr['VOLt'] = df_ttr['pct_truck'] * df_ttr['dir_aadt'] * 365 df_ttr['ttr'] = df_ttr['miles'] * df_ttr['VOLt'] * VOCt return df_ttr
cee9b22dd1866458dfd7ec849c9dccc20da5c92b
658,040
import json def get_creds(file): """ Loads simple json file stored elsewhere with credentials. See the sample_creds.json folder for the expected format. :param file: json file containing key/value cres :return: client_id, client_secret, user_agent for Reddit api """ file = "E:/creds" with open(file, 'r') as fin: creds = json.load(fin) return creds['client_id'], creds['client_secret'], creds['user_agent']
9e70fc000f65992045971543cf99511280105ebb
195,460
def clip(s, n=1000): """ Shorten the name of a large value when logging""" v = str(s) if len(v) > n: v[:n]+"..." return v
b6a56d2fcab1a99371acf9d28847e0de9f717338
424,725
def has_tag(tags, target) -> bool: """ Verifies that the `target` tag is present in a query set. @param tags: tags to be checked @param target: the tag searched for @return: True if the target is present, False otherwise """ for tag in tags: if tag.tag == target: return True return False
a6e46b7e09aa61fe4f2d6ebe2dcb3f8aad14964e
501,127
import math import torch def log_prob_standard_normal(x): """ Computes the log-probability of observing the given data under a (multivariate) standard Normal distribution. Although this function is equivalent to the :code:`log_prob` method of the :class:`torch.distributions.MultivariateNormal` class, this implementation is much more efficient due to the restriction to standard Normal. Parameters ---------- x: torch.Tensor [N, D] The samples whose log-probability shall be computed (number of samples N, dimensionality D). Returns ------- torch.Tensor [N] The log-probabilities for all samples. """ dim = x.size(1) const = dim * math.log(2 * math.pi) norm = torch.einsum('ij,ij->i', x, x) return -0.5 * (const + norm)
3560b5f95648fa3009b562021e6fc8612b681c37
168,510
def print_time(time): """Format a datetime object to be human-readable""" return time.astimezone(tz=None).strftime('%m/%d')
d75deefac5f2326637fe73757b8baee95d0ac42b
684,879
from datetime import datetime def date_check(y, m, d): """Ensure that a date is valid.""" try: test = bool(datetime.strptime(f"{y}{m}{d}", "%Y%m%d")) except: test = False return test
5816510baffb4dba7c736a261cff2d7ba259f908
410,171
def moeda(n=0, moeda='R$'): """ -> Formata os valores monetários :param n: (opcional) Valor a ser formatado :param moeda: (opcional) Moeda a ser utilizado na formatação :return: Valor 'n' formatado """ return f'{moeda}{n:.2f}'.replace('.', ',')
8205cb444b9592cb1f2fce2ca0db7a5d4119bc18
403,389
def add_right_title(ax, title, **kwargs ): """Add a centered title on rigth of the selected axis. All :func:`~matplotlib.Axes.annotate` parameters are accessible. :param ax: Target plot axis. :type ax: :class:`~matplotlib.Axes` :param str title: Title text to add. :return: :class:`~matplotlib.text.Annotation` """ if title is None: return kwargs.setdefault("xy", (1, 0.5)) kwargs.setdefault("xytext", (5, 0)) kwargs.setdefault("xycoords", "axes fraction") kwargs.setdefault("textcoords", 'offset points') kwargs.setdefault("ha", 'left') kwargs.setdefault("va", 'center') return ax.annotate(title, **kwargs)
64839e785945c473b9bfb08d276dc209ff45ce90
207,174
import json def read_notebook(file, store_markdown= False): """Reads a notebook file and returns the code""" code = json.load(open(file)) # file = getBaseNameNoExt(file) py_file = "" # open(f"{file}.py", "w+") for cell in code['cells']: if cell['cell_type'] == 'code': for line in cell['source']: py_file += line # py_file.write(line) py_file += "\n" # py_file.write("\n") elif cell['cell_type'] == 'markdown' and store_markdown: py_file += "\n" # py_file.write("\n") for line in cell['source']: if line and line[0] == "#": py_file += line # py_file.write(line) py_file += "\n" # py_file.write("\n") # py_file.close() return py_file
1a5ff7073be822dd5db972389384277d6b552ad8
313,328
import re def get_valid_filename(s): """Sanitize string to make it reasonable to use as a filename. From https://github.com/django/django/blob/master/django/utils/text.py Parameters ---------- s : string Examples -------- >>> print get_valid_filename(r'A,bCd $%#^#*!()"\' .ext ') 'a_bcd__.ext' """ s = re.sub(r'[ ,;\t]', '_', s.strip().lower()) return re.sub(r'(?u)[^-\w.]', '', s)
a8161a16d0bd8ad0c5d9ff20c56b52fbdba2d859
701,397
def alert_data_to_xsoar_format(alert_data): """ Convert the alert data from the raw to XSOAR format. :param alert_data: (dict) The alert raw data. """ properties = alert_data.get('properties', {}) formatted_data = { 'ID': properties.get('systemAlertId'), 'Kind': alert_data.get('kind'), 'Tactic': properties.get('tactics'), 'DisplayName': properties.get('alertDisplayName'), 'Description': properties.get('description'), 'ConfidenceLevel': properties.get('confidenceLevel'), 'Severity': properties.get('severity'), 'VendorName': properties.get('vendorName'), 'ProductName': properties.get('productName'), 'ProductComponentName': properties.get('productComponentName'), } return formatted_data
fdffb0016cc49fe0240cacfcc7735bf7f09404b4
509,431
def read_labeled_image_list(image_list_file): """Reads a .txt file containing pathes and labeles Args: image_list_file: a .txt file with one /path/to/image per line label: optionally, if set label will be pasted after each line Returns: List with all filenames in file image_list_file """ f = open(image_list_file, 'r') filenames = [] labels = [] for line in f: filename, label = line[:-1].split(' ') filenames.append(filename) labels.append(int(label)) return filenames, labels
7541c3db7bfa6bc9697b541fbe925b53c989b959
335,725
from typing import Dict from typing import Any def dict_argmax(d: Dict[Any, Any]) -> Any: """ Compute argmax for a dictionary with numerical values. """ argmax = None best_val = None for arg, val in d.items(): if argmax is None or val > best_val: argmax = arg best_val = val return argmax
163fef049713645711228624fe98a81bdef3bdac
455,298
def subset_by_iqr(df, column, iqr_mult=3): """Remove outliers from a dataframe by column, including optional whiskers, removing rows for which the column value are less than Q1-1.5IQR or greater than Q3+1.5IQR. Args: df (`:obj:pd.DataFrame`): A pandas dataframe to subset column (str): Name of the column to calculate the subset from. iqr_mult (float): Optional, loosen the IQR filter by a factor of `iqr_mult` * IQR. Returns: (`:obj:pd.DataFrame`): Filtered dataframe """ # Calculate Q1, Q2 and IQR q1 = df[column].quantile(0.25) q3 = df[column].quantile(0.75) iqr = q3 - q1 # Apply filter with respect to IQR, including optional whiskers filter = (df[column] >= q1 - iqr_mult*iqr) & (df[column] <= q3 + iqr_mult*iqr) return df.loc[filter]
ee34ca064c605fe1c1ff36131c8351dfe95321ef
637,290
def chars_different(box1, box2): """Count the number of characters that differ between box1 and box2""" diff = sum( 1 if i != j else 0 for i, j in zip(box1, box2) ) return diff
b9cfa5ba9a97bb48e60c46918953b1daba6d2f61
585,099
def _leading_space_count(line): """Return number of leading spaces in line.""" i = 0 while i < len(line) and line[i] == ' ': i += 1 return i
b28daa2845618df5030a79129bb7cec1167b149a
3,089
def by_time(elem): """ Returns associated times field of elem (elem assumed to be an instance of SPATLocation. """ return elem.times
25f1230a3adfa0e43b3940cca32b596801ce2234
545,378
def find_pivot(unsorted, start, end): """ Find the pivot value using the Median of Three method in a Python list Expected Complexity: O(1) (time and space) :param unsorted: an unsorted Python list to find the pivot value in :param start: integer of starting index to find the pivot value in :param end: integer of ending index to find the pivot value in :return: the value of the pivot found using the Median of Three method """ # pull the first, middle, and last values in the list first = unsorted[start] middle = unsorted[(start + end) // 2] last = unsorted[end] # this method is done so that it can be done in constant time if (middle <= first <= last) or (last <= first <= middle): return first elif (first <= middle <= last) or (last <= middle <= first): return middle elif (first <= last <= middle) or (middle <= last <= first): return last
2a27ac28f60e46011d086d329b5ab32461f4d801
145,142
def findpower2(num): """find the nearest number that is the power of 2""" if num & (num-1) == 0: return num bin_num = bin(num) origin_bin_num = str(bin_num)[2:] near_power2 = pow(10, len(origin_bin_num)) near_power2 = "0b" + str(near_power2) near_power2 = int(near_power2, base=2) return near_power2
14f32842d94ffbb5eb4ef4be70fcbf006a7854dd
388,505
def to_gradepoint(grade): # write an appropriate and helpful docstring """ convert letter grades into gradepoint :param str grade: A, A-, B+, B, B-, C+, C, C-, D, F :return: float """ gradepoint = 0 # initial placeholder # use conditional statement to set the correct gradepoint gradepoint = 4 if grade=='A' else 3.7 if grade=="A-" else 3.3 if grade=="B+" else 3 if grade=="B" else 2.7 if grade=="B-" else 2.3 if grade=="C+" else 2 if grade=="C" else 1.7 if grade=='C-' else 1 if grade=="D" else 0 return gradepoint
47dd2f053de0f456f642c8391c92346e36d9b943
320,382
import random def _random_selection(*args): """ Random selection for the genetic algorithm. This function randomly removes a solution from the population and returns it. :param args: list where args[0] is the population :rtype: Solution :returns: a solution from the population """ return args[0].pop(random.randrange(0, len(args[0])))
b428be98a4d0b3beeee277194b5d749fcae7bfcc
339,476
def align_bbox(src, tgt): """ Return a copy of src points in the coordinate system of tgt by applying a scale and shift along each coordinate axis to make the min / max values align Inputs: - src, tgt: Torch Tensor of shape (N, 3) Returns: - out: Torch Tensor of shape (N, 3) """ src_min = src.min(dim=0)[0] src_max = src.max(dim=0)[0] tgt_min = tgt.min(dim=0)[0] tgt_max = tgt.max(dim=0)[0] scale = (tgt_max - tgt_min) / (src_max - src_min) shift = tgt_min - scale * src_min out = scale * src + shift return out
a0805a012914460b625537c6fdb84770fe6a326c
264,230
def is_mark(codepoint): """Returns true for diacritical marks (combining codepoints).""" return codepoint.general_category in ("Mn", "Me", "Mc")
8fb84f7a1b39fa1ce6504a31f6cc902b2d4ab7c8
602,825
def PZapTable (inUV, tabType, tabVer, err): """ Destroy specified table Returns 0 on success inUV = Python UV object tabType = Table type, e.g. "AIPS AN" tabVer = table version, integer err = Python Obit Error/message stack """ ################################################################ if ('myClass' in inUV.__dict__) and (inUV.myClass=='AIPSUVData'): inUV.zap_table(tabType, tabVer) return return inUV.ZapTable (tabType, tabVer, err) # end PZapTable
b927cabfac51353bc44ea693d4dc7b8687fa6d4e
600,071
import socket def is_port_open(port_num): """ Detect if a port is open on localhost""" sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) return sock.connect_ex(('127.0.0.1', port_num)) == 0
8ee5e4674a2c4444448208d0e8194809665c8014
688,584
from functools import reduce def deepgetattr(obj, attr, default=None, raise_if_missing=False): """Recurses through an attribute chain to get the ultimate value.""" if isinstance(attr, str): attr = attr.split('.') try: return reduce(getattr, attr, obj) except AttributeError: if raise_if_missing: raise return default
d7d6080277af6f9b00b7717f41135c838a3b7af9
568,390
def sign(value): """ Returns an integer that indicates the sign of a number. Parameters: value (int): The number to get the sign of Returns: -1 if the number is negative, 0 if the number is 0, or 1 if the number is positive. """ if value < 0: return -1 elif value == 0: return 0 else: return 1
71997a571fcdbadf45fa1dd3b8d2b6c54eafdd61
43,652
def inp_replace_token_value(lines,token,replace): """replace the value of a token in a list""" if type(lines)!=list: return False replaced=False for i in range(0, len(lines)): if lines[i]==token: if i+1<len(lines): lines[i+1]=replace replaced=True break return replaced
22c50ee9dad7b3f85b339260d6d4b75c37f0efc9
282,866
from sympy.ntheory import primefactors def A001221(n: int) -> int: """omage(n). Number of distinct primes dividing n. """ return len(primefactors(n))
a8ffa15d07da753846b37963dc348b5f7ea1d05d
460,152
def escape_leading_slashes(url): """ If redirecting to an absolute path (two leading slashes), a slash must be escaped to prevent browsers from handling the path as schemaless and redirecting to another host. """ if url.startswith('//'): url = '/%2F{}'.format(url[2:]) return url
108ce47cd51550d5d847f54ea0b88c83eeae8e24
381,276
import re def get_lines_with(input_list, substr) -> list: """ Get all lines containing a substring. Args: input_list [str]: List of string to get lines from. substr (str): Substring to look for in lines. Returns: lines [str]: List of lines containing substr. ----------- Function selftests: >>> len(get_lines_with(tty2list('./samples/RAID.Slot.1-1.log'), '11/15/19')) 746 >>> type(get_lines_with(tty2list('./samples/RAID.Slot.1-1.log'), '11/15/19')) <class 'list'> """ # print (input_list) lines = [] for line in input_list: # print ('testing line: ', line) if re.search(substr, line, re.IGNORECASE): lines.append(line) # print ('Line added. size of result: ', len(lines)) return lines
d7562fc3cd8d830279eeedbf421b515d1a7c2ce2
488,077
def compare_h(new, high): """ Compare the latest temperature with the highest temperature. If higher, replace it. If not, remain the same. :param new: Integer, new!=EXIT, The lasted temperature input :param high: Integer, high!=EXIT, the highest temperature of all time :return: high """ if new > high: high = new return high else: high += 0 return high
b665cd2cb724d8ddaa95f0ce61f00a9265331543
430,950
def inclusion_one_param_from_template(arg): """Expected inclusion_one_param_from_template __doc__""" return {"result": "inclusion_one_param_from_template - Expected result: %s" % arg}
9c4e4f842faaf87f7d328515fbe96ef9d1be2208
623,431
def is_valid_bbox(rect): """Left/top must be >= 0, W/H must be > 0""" return rect[0] >= 0 and rect[1] >= 0 and rect[2] > 0 and rect[3] > 0
8e0661482172e6ca4fc71ae5596903ece69ff570
584,081
import random def _shuffle(x): """ Shuffles an iterable, returning a copy (random.shuffle shuffles in place). """ x = list(x) random.shuffle(x) return x
662627b2b4ae79f630c975cdb8d86837524579ab
67,677
def get_command() -> str: """ __author__ = "Trong Nguyen" Prompt the user for a valid command and return the command input as uppercase. >>> get_command() """ command = input( "L)oad image S)ave-as" "\n2)-tone 3)-tone X)treme contrast T)int sepia P)osterize" "\nE)dge detect I)mproved edge detect V)ertical flip H)orizontal flip" "\nQ)uit \n\n: ") command = command.upper() return command
c8573f03bf2383d5ef6856ff71087b33bb5babb9
267,363
import inspect def is_static_method(klass, name: str) -> bool: """ Check if the attribute of the passed `klass` is a `@staticmethod`. Arguments: klass: Class object or instance to check for the attribute on. name: Name of the attribute to check for. Returns: `True` if the method is a staticmethod, else `False`. """ if not inspect.isclass(klass): klass = klass.__class__ meth = getattr(klass, name) if inspect.isfunction(meth): if getattr(meth, "__self__", None): return False for cls in klass.__mro__: descriptor = vars(cls).get(name) if descriptor is not None: return isinstance(descriptor, staticmethod) return False
5ee84883d6ad52b6c0dd69f7123f80fd553313ea
688,732
def bend_stress(mom, y, i): """ bend_stress(mom, y, i) Returns the bending stress given the applied moment, distance to the centroid, and moment of inertia. """ return mom * y / i
76f5d2f8120d355c69995b5e7edc1f4258084d33
453,871
import torch def calc_parameter_sparsity(p): """Calculates the sparsity percentage of a torch parameter. Args: p: torch parameter Returns: sparsity percentage (as float) with range [0.0, 1.0] """ x = torch.sum((torch.flatten(p) == 0).float()) return float(x) / p.numel()
3f4a7c171c5dd68d7e5040430fc74a0d529ab458
223,655
def _args_or_none(arg): """Return None if the arg is 'None' or the arg.""" if arg == 'None': return None return arg
ffcd8995b97269a4367f1b41bbae54c0e98aa5c1
283,222
def special_structures(input_string): """ Replace some special structures by space. """ input_string = input_string.replace("'", " ") input_string = input_string.replace("(", " ") input_string = input_string.replace(")", " ") input_string = input_string.replace("1er ", " ") input_string = input_string.replace(",", " ") input_string = input_string.replace("«", " ") input_string = input_string.replace("»", " ") output_string = input_string.replace("n°", " ") return output_string
b15b289ee36ea21a61db908e42876ed3b3135e34
189,528
import itertools def get_subsets(itemset, length): """ Gets subsets of an itemset with the specified length. :param itemset: Set of items :param length: Length :return: list of sets """ tuple_list = list((itertools.combinations(itemset, length))) set_list = [] for element in tuple_list: s = set() for t in element: s.add(t) set_list.append(s) return set_list
908d22fe9876b505137e642ff8566b497772d9db
395,336
def nonneg(s): """Returns all non-negative values.""" return filter(lambda x: x>=0, s)
3cbdf9ee64be450143ca28418613514f3b11e0ca
508,802
def join_rows(row_list_1, row_list_2): """Returns a list of list, in which element is the concatenation of the elements in the same position of row_list1 and row_list.""" if not row_list_1: return row_list_2 if not row_list_2: return row_list_1 row_list = [] for (row1, row2) in zip(row_list_1, row_list_2): row_list.append(row1+row2) return row_list
0d414e66e9959250b88f5419355616d128759bd5
219,475
def _calculate_PSF_amplitude(mag): """ Returns the amplitude of the PSF for a star of a given magnitude. Parameters ---------- `mag`: float Input magnitude. Returns ------- amp : float Corresponding PSF applitude. """ # mag/flux relation constants amp = 10**(-0.4*(mag - 12))*1.74e5 return amp
dea6bfb12bfbd548dad4512194b7e3d08b761adc
464,627
def girder_job(title=None, type='celery', public=False, handler='celery_handler', otherFields=None): """Decorator that populates a girder_worker celery task with girder's job metadata. :param title: The title of the job in girder. :type title: str :param type: The type of the job in girder. :type type: str :param public: Public read access flag for girder. :type public: bool :param handler: If this job should be handled by a specific handler, 'celery_handler' by default cannot be scheduled in girder. :param otherFields: Any additional fields to set on the job in girder. :type otherFields: dict """ otherFields = otherFields or {} def _girder_job(task_obj): task_obj._girder_job_title = title task_obj._girder_job_type = type task_obj._girder_job_public = public task_obj._girder_job_handler = handler task_obj._girder_job_other_fields = otherFields return task_obj return _girder_job
789c5e97cac2676731eaddeae15a3469d6cd0030
440,515
import time def format_time(timestamp=None, format=r"%Y%m%d-%H%M%S"): """ Return a formatted time string Commonly used format codes: %Y Year with century as a decimal number. %m Month as a decimal number [01,12]. %d Day of the month as a decimal number [01,31]. %H Hour (24-hour clock) as a decimal number [00,23]. %M Minute as a decimal number [00,59]. %S Second as a decimal number [00,61]. %z Time zone offset from UTC. %a Locale's abbreviated weekday name. %A Locale's full weekday name. %b Locale's abbreviated month name. %B Locale's full month name. %c Locale's appropriate date and time representation. %I Hour (12-hour clock) as a decimal number [01,12]. %p Locale's equivalent of either AM or PM. """ time_str = time.strftime(format, time.localtime(timestamp if timestamp else time.time())) return time_str
91486e08e9c21b36cfbdd7303bf99b4c5b1f78ed
528,636
def min_rotation(target_degrees, source_degrees): """ Return the smallest rotation required to move from source angle to target angle:: min_rotation(20, 10) => 10 min_rotation(-340, 10) => 10 min_rotation(20, 370) => 10 """ return (target_degrees - source_degrees + 180) % 360 - 180
8e60a325ff6a169458f7f425e06e080552f5039b
276,344
def coerce_tuple(item): """Return item converted to tuple if not already tuple. :param Union[str, IKey, Iterable] item: item to coerce to tuple. :returns: coerced value of item as tuple. :rtype: Tuple[Any]. .. Usage:: >>> coerce_tuple('test') ('test',) >>> coerce_tuple(('test', 'two')) ('test', 'two') """ if isinstance(item, (list, tuple)): return tuple(item) return (item,) if item is not None else None
b6b0ed565562f37f596cf0aa148bb59d9416d9bb
606,881
def int_to_rgb(rgb_int): """ Given an integer, converts to to RGB value. Any integer outside the range of (0, 16777215) will raise an invalid >>> int_to_rgb(-1) Traceback (most recent call last): ... ValueError: Integer must be in range [0, 16777215], got -1. >>> int_to_rgb(0) (0, 0, 0) >>> int_to_rgb(255) (0, 0, 255) >>> int_to_rgb(65280) (0, 255, 0) >>> int_to_rgb(16711680) (255, 0, 0) >>> int_to_rgb(16777215) (255, 255, 255) >>> int_to_rgb(20000000) Traceback (most recent call last): ... ValueError: Integer must be in range [0, 16777215], got 20000000. """ if rgb_int < 0 or 16777215 < rgb_int: raise ValueError('Integer must be in range [0, 16777215], got {}.'.format(rgb_int)) blue = rgb_int & 255 green = (rgb_int >> 8) & 255 red = (rgb_int >> 16) & 255 return red, green, blue
c23eef48c564dcb18eec81c1890add55d77fd3a5
619,346
import itertools def SplitNone(l): """Split a list using None elements as separator. Args: l: a list which may contain some None elements. Returns: A list of non-empty lists, each of which contains a maximal sequence of non-None elements from the argument list. """ groups = itertools.groupby(l, lambda x: x is not None) return [list(g) for k, g in groups if k]
794eccdb6764b6d607e415ea9eab146e0dc0e947
573,893
import importlib def class_from_str(str_class): """ Imports the module that contains the class requested and returns the class :param str_class: the full path to class, e.g. pyspark.sql.DataFrame :return: the class requested """ split_str = str_class.split('.') class_name = split_str[-1] module_name = '.'.join(split_str[:-1]) module = importlib.import_module(module_name) return getattr(module, class_name)
7571feb9a7d8dca332554c7fcacdb513c3b8e6de
145,395
def _expand_total_pairs(total_pairs): """Expands total_pairs so that it has one key per direction. e.g., 'breitbart-foxnews' and 'foxnews-breitbart' exist as keys. If expansion is skipped, then total_pairs only has one key per pair of (unordered) elements. e.g., 'breitbart-foxnews' exists as a key but 'foxnews-breitbart' does not. The total per element-pair is the same value for both directions. e.g., 'breitbart-foxnews' and 'foxnews-breitbart' are assigned the same total count. """ total_pairs_expanded = {} for k, v in total_pairs.items(): total_pairs_expanded[(k[0], k[1])] = v total_pairs_expanded[(k[1], k[0])] = v total_pairs_expanded = dict(sorted(total_pairs_expanded.items())) return total_pairs_expanded
74aa6b0475061a480b2a3c098e0cf7f981aa6221
409,930
def count_rounds(half): """ Counts how many rounds were won in the half. """ rounds = 0 for img in half.find_all("img"): if not "emptyHistory.svg" in img["src"]: rounds += 1 return rounds
1e80018ae944746783c51e9e58725ef6ce470f86
455,440
def format_tag(template, tag_name, attrs): """ Format a template of a tag with attributes, so that: >>> format_tag('<{} {}>', 'span', {'id': 'foo'}) >>> '<span id="foo">' Note: use `klass` instead of the `class` attribute. """ return template.format(tag_name, ' '.join(['{}="{}"'.format(key.replace('klass', 'class'), val) for (key, val) in attrs.iteritems()]))
195e8fc1d88f1a2ccdae557ba578e22e91ec942f
249,604
def lookup_expr(collection, key): """ Lookup a value in a Weld vector. This will add a cast for the key to an `I64`. Examples -------- >>> lookup_expr("v", "i64(1.0f)").code 'lookup(v, i64(i64(1.0f)))' >>> lookup_expr("[1,2,3]", "1.0f").code 'lookup([1,2,3], i64(1.0f))' >>> lookup_expr("[1,2,3]", 1).code 'lookup([1,2,3], i64(1))' """ return "lookup({collection}, i64({key}))".format( collection=collection, key=key)
4bb0d46dc1bc3f6cc206634ea5d5c03167d564c7
293,927
from typing import List def fill(index: int, item: float, length: int) -> List[float]: """ Make an array that contains `length` 0s, but with the value at `index` replaced with `item`. """ a = [0.0 for _ in range(length)] a[index] = item return a
bee2c15fc844eae32344b44a7767ce2445e24e90
488,325
def starts_with_five_zeros(md5_hash: str) -> bool: """Whether the given md5 hash starts with five zeros.""" return md5_hash.startswith('00000')
e004fde4485dfddb4d9062dc9b786ce59ae3dbdc
561,409
def _ReplaceVariables(data, environment): """Replace all occurrence of the variable in data by the value. Args: data: the original data string environment: an iterable of (variable name, its value) pairs Returns: the data string which replaces the variables by the value. """ result = data for (k, v) in environment: result = result.replace(k, v) return result
480774fe48844d02a9a74cf2211bd262d9bda150
453,831
def read_experiment_lines(readme_lines, start_marker_a="TGA", start_marker_b="###", end_marker="###"): """ This function iterates over a list of strings and searches for information about a desired experiment. The information is found by looking for sub-strings (markers) that encapsulate the desired information. A shortened list is returned containing the experiment information. :param readme_lines: List of string containing text file content :param start_marker_a: Marker to find the desired experiment :param start_marker_b: Additional marker to make sure the correct line is chosen :param end_marker: Marker to indicate when to stop collecting lines. :return: list, containing lines of string related to a desired experiment """ # Initialise collection of experiment description. experiment_lines = list() # Flag to control what lines to collect. collect_entry = False # Iterate over all the lines of the file content. for line in readme_lines: # Skip empty lines. if line == '': continue if end_marker in line: if "####" not in line: # Stop collecting lines after the TGA experiment # description concluded and a new section starts. collect_entry = False if start_marker_a in line and start_marker_b in line: # Allow collection of lines. collect_entry = True if collect_entry is True: # Collect lines. experiment_lines.append(line) return experiment_lines
e80cd6213ba703f970db8f9b6b42704c179c4fdd
39,985
import math def A000108(i: int) -> int: """Catalan numbers: C(n) = binomial(2n,n)/(n+1) = (2n)!/(n!(n+1)!). Also called Segner numbers. """ return ( math.factorial(2 * i) // math.factorial(i) // math.factorial(2 * i - i) // (i + 1) )
bfc0b3b23fd758fb0ff43936c525c7b5c24dfd6f
328,938
def getFileInfo(filename: str): """Get file information from filename. Parameters ---------- filename : str Filename of CSV file Returns ------- date : str Date of the file time : str Time of the file folder : str Measurement folder of the file filenumber : str Number of the measurement Example ------- path = ir_export_20170815_P0000004_005_10-50-08 date = 20170815 time = 10-50-08 folder = P0000004 filenumber = 005 """ date = filename[10:18] time = filename[-12:-4] folder = filename[19:27] filenumber = filename[28:31] return date, time, folder, filenumber
da81360d7425e27c67465cacbaaf096d6fae7d55
609,677
def point_within_bounds(x,y, bounds): """ Function for checking if a point is within a bounds from a raster :param x: x-coordiante :param y: y-coordinate :param bounds: raster bounds :return: boolean """ if (bounds.left < x) & (bounds.right > x): if (bounds.bottom < y) & (bounds.top > y): return True return False
9b9fe6a76ef1eb8dd039de2ca8bc2e8fef2f5a6e
435,652
def name_generator(nn_name, nn_name2id): """ 生成paddle.nn类op的名字。 Args: nn_name (str): 名字。 nn_name2id (dict): key为名字,value为名字出现的次数-1。 """ if nn_name in nn_name2id: nn_name2id[nn_name] += 1 else: nn_name2id[nn_name] = 0 real_nn_name = nn_name + str(nn_name2id[nn_name]) return real_nn_name
a1788af5a9df1618d161ce725ab7839405faef66
595,997
def stringify_list(list_: list, quoted: bool = False ) -> str: """Converts a list to a string representation. Accepts a list of mixed data type objects and returns a string representation. Optionally encloses each item in single-quotes. Args: list_: The list to convert to a string. quoted: Indicates if the items in the list should be in quotes. Returns: A string representation of the list. """ if quoted: string_ = ', '.join(f"'{i}'" for i in list_) else: string_ = ', '.join(f'{i}' for i in list_) return string_
7f390283de9ee6c136cb4eedff561a505522e58d
306,306
def rename_modified_residues(mol): """ Renames residue names based on the current residue name, and the found modifications. The new names are found in `force_field.renamed_residues`, which should be a mapping of ``{(rename, [modification_name, ...]): new_name}``. Parameters ---------- mol : Molecule The molecule whose residue names should be changed. Is modified in-place. """ rename_map_ff = mol.force_field.renamed_residues rename_map = {} # Sort the list of modifications, so that the order does not matter. Don't # make a frozenset, because it might be possible to have the same # modification multiple times? # This should probably be done as the list is parsed. Also, as we parse it, # make sure we actually recognize all the modification names. for (resname, mods), new_name in rename_map_ff.items(): rename_map[resname, tuple(sorted(mods))] = new_name for node_key in mol: node = mol.nodes[node_key] modifications = node.get('modifications', []) resname = node.get('resname', '') if not modifications: continue modifications = tuple(sorted(mod.graph['name'] for mod in modifications)) try: new_name = rename_map[(resname, modifications)] except KeyError: # We don't know how to rename this residue, so continue to the next # node. continue node['resname'] = new_name return None
4b9eee42e071fb42b7cde5d647fb497eb4ca3730
478,339
import socket def resolve_fqdn_ip(fqdn): """Attempt to retrieve the IPv4 or IPv6 address to a given hostname.""" try: return socket.inet_ntop(socket.AF_INET, socket.inet_pton(socket.AF_INET, socket.gethostbyname(fqdn))) except Exception: # Probably using ipv6 pass try: return socket.inet_ntop(socket.AF_INET6, socket.inet_pton(socket.AF_INET6, socket.getaddrinfo(fqdn, None, socket.AF_INET6)[0][4][0])) except Exception: return ''
2e7680fe3a4ea174f3f7b22e4991a3a65e5e4995
29,516
async def check_tags(problem_tags, tags): """ To check if all tags are present in the problem tags. """ count = 0 for tag in tags: if "'" + tag + "'" in problem_tags: count += 1 return count == len(tags)
ad757eadbc7cd74854901a1da55a5f941dbec668
386,035
import json def jsonRead(path): """Abre un archivo JSON y devuelve los datos del archivo. Argumentos: path (str): Ruta relativa hacia el archivo. Returns: data (Any): Datos contenidos en el JSON. """ with open(path) as json_file: try: data = json.load(json_file) # pprint(data) return data except FileNotFoundError: print('\nArchivo JSON no encontrado.')
5be4df247b253c53ab8c555fd61ffd1f3353b555
414,125
import glob def get_bridges(vnic_dir='/sys/devices/virtual/net'): """Return a list of bridges on the system.""" b_regex = "%s/*/bridge" % vnic_dir return [x.replace(vnic_dir, '').split('/')[1] for x in glob.glob(b_regex)]
685ffe3ccae18306c49eb4091c360e966674e606
653,850
from datetime import datetime def isdate(s_date: str, if_nan=False): """Check whether the date string is yyyymmdd format or not.""" if len(s_date) != 8: return False try: datetime.strptime(s_date, "%Y%m%d") return True except ValueError: return False except TypeError: return if_nan
f11e6ea3387a99dbe905c6dee249365074f2bd10
262,771
def _get_lines(filepath): """ Given a filepath, return a list of lines within that file. """ lines = None with open(filepath) as file: lines = file.readlines() return lines
5762459d6455c3133936fe4dda93059d3e9d17eb
248,331
def _calculate_padding(kernel): """ Calculate padding size to keep the output matrix the same size as the input matrix. Parameters ---------- k: ndarray Convolution kernel Returns ------- out: tuple of tuple of int (row_pad_count_top, row_pad_count_bottom), (col_pad_count_left, col_pad_count_right) """ # row padding diff = int(kernel.shape[0] / 2) row_pad_count_top = diff row_pad_count_bottom = diff # col padding diff = int(kernel.shape[1] / 2) col_pad_count_left = diff col_pad_count_right = diff return ((row_pad_count_top, row_pad_count_bottom), (col_pad_count_left, col_pad_count_right))
8636975a6aaaeb18f52d547d213f70d94d6aca0c
333,038
def cents_to_hz(F_cent, F_ref=55.0): """Converts frequency in cents to Hz Notebook: C8/C8S2_FundFreqTracking.ipynb Args: F_cent (float or np.ndarray): Frequency in cents F_ref (float): Reference frequency in Hz (Default value = 55.0) Returns: F (float or np.ndarray): Frequency in Hz """ F = F_ref * 2 ** (F_cent / 1200) return F
c73c67bb931d07743ee3b53a662485924b0c3f56
45,816
def ident(tensor_in): """ The identity function :param tensor_in: Input to operation. :return: tensor_in """ return tensor_in
9ae521af8ab501e3b5694af9325f3dc2a9ed399f
460,951
def evaluate_coefficients(coefficients,x): """Take a list of coefficients and return the corresponding polynomial evaluated at x-value x """ return sum(pair[1]*(x**pair[0]) for pair in enumerate(coefficients))
b46bce35f4275c71f8f1f7ab59d5fee3e6a58b55
542,766
def integrate(x_dot, x, dt): """ Computes the Integral using Euler's method :param x_dot: update on the state :param x: the previous state :param dt: the time delta :return The integral of the state x """ return (dt * x_dot) + x
b2cc59a953f28b4ce8ceecf3dd154b98c34aa274
532,761
def merge(d1, d2): """Merges d2 into d1 without overwriting keys.""" left = d1.copy() right = d2.copy() for key in right.keys(): if key in left: left_is_dict = isinstance(left[key], dict) right_is_dict = isinstance(right[key], dict) if left_is_dict and right_is_dict: left[key] = merge(left[key], right[key]) elif right_is_dict: left[key] = merge({'': left[key]}, right[key]) elif left_is_dict: left[key] = merge(left[key], {'': right[key]}) else: left[key] = right[key] else: left[key] = right[key] return left
568254522547b47687cdfaab54bfc21e0b535f93
665,456
def _format_links(link_x): """ Format links part :param link_x: list, which has several dicts in it :return: formatted string """ try: pairs = "" for _dict in link_x: pairs += _dict['rel'] + '-> ' + _dict['href'] + '\n' return pairs[:-1] except Exception: return link_x
ea47e3c9d509dc127ae9089c0b410702e1f58a57
96,797
def condition_flush_on_every_write(cache): """Boolean function used as flush_cache_condition to anytime the cache is non-empty""" return len(cache) > 0
5fa7d2d7a43e510fae7ebe545e973f7ab3831666
293,056
def ensure_dict(x): """Make sure ``x`` is a ``dict``, creating an empty one if ``x is None``. """ if x is None: return {} return dict(x)
35eb7b7c2e7be7bd5630135d5a803790d8c5589e
189,622
def __get_node_types(args: dict): """ Given the parsed arguments, returns a dictionary of flags representing the node types to be processed :param dict args: dictionary of parsed args :return: dictionary of node types """ out = dict(pose=False, hand=False, face=False) # check if only face or only hand is required if 'body' in args and args['body'] == '0': # only hand if 'hand' in args and 'face' not in args or args['face'] == '0': out['hand'] = True return out # only face elif 'face' in args and 'hand' not in args or args['hand'] == '0': out['face'] = True return out else: raise RuntimeError('--hand and --face cannot be used' 'simultaneously with --body 0') else: out['pose'] = True if 'hand' in args: out['hand'] = True if 'face' in args: out['face'] = True return out
7b4e72d1e9747654201a6b3ad2b17d9cef37a66e
215,407
import re def regex_escape(string: str) -> str: """Escape the given string for use as a regex.""" return re.escape(string)
7ac2d1c7a8dd3eeeb9f907c39757f7a936e735f9
247,793
def sequence(left_validator, right_validator): """Given two validators, attempt to validate the first If successful, attempt to validate with the second """ def callback(value): """Accept a value to validate, return validation results""" okay, result = left_validator(value) if okay: return right_validator(value) return okay, result return callback
e0a89f1a1a4f78ccd545ce3b78e8f02fa46e4ff5
191,345
def get_valid_classes_phrase(input_classes): """Returns a string phrase describing what types are allowed """ all_classes = list(input_classes) all_classes = sorted(all_classes, key=lambda cls: cls.__name__) all_class_names = [cls.__name__ for cls in all_classes] if len(all_class_names) == 1: return 'is {0}'.format(all_class_names[0]) return "is one of [{0}]".format(", ".join(all_class_names))
8361ad8bfc43c882d4cdc7f08707a0c948230ca0
283,825
import random def mutate_guess_i(old_guess, i): """randomly mutate single element in string""" ls_old_guess = list(old_guess) rand_value = str(random.randint(0, 9)) ls_old_guess[i] = rand_value return ''.join(ls_old_guess)
9116f87d9f9a85017fafffe55a5ae640cce13eb7
90,567
def page_query_with_skip(query, skip=0, limit=100, max_count=None, lazy_count=False): """Query data with skip, limit and count by `QuerySet` Args: query(mongoengine.queryset.QuerySet): A valid `QuerySet` object. skip(int): Skip N items. limit(int): Maximum number of items returned. max_count(int): Maximum statistical value of the counter. If `max_count` is None, it will count all on the `QuerySet`. lazy_count(bool): Don't report correct value of total when queried items is empty, use estimates, instead. Returns: A dict with keys: total, skip, limit, items """ if max_count: total = query.skip(skip).limit( max_count).count(with_limit_and_skip=True) if lazy_count or total > 0: total += skip else: total = query.count() else: total = query.count() items = query.skip(skip).limit(limit) return { 'total': total, 'skip': skip, 'limit': limit, 'items': items }
2aef61019b67f2d9262ad8f671a9991e0915ddcf
672,272
def ensure_leading_slash(path: str) -> str: """ Ensures that the given path has a leading slash. This is needed as mock paths are stored in the database with a leading slash, but flask passes the path parameter without one. """ if path[0] != "/": return "/" + path return path
8f059b4d420ba7409993c2c324a302e993d2259a
94,730
def get_dtype_str(dtype, byteorder="little"): """Parses dtype and byte order to return a type string code. Parameters ---------- dtype : `numpy.dtype` or `str` Either a dtype (e.g., ``numpy.uint32``) or a string with the type code (``'>u4'``). If a string type code and the first character indicates the byte order (``'>'`` for big, ``'<'`` for little endian), ``byteorder`` will be ignored. The type code refers to bytes, while the dtype classes refer to bits, i.e., ``'u2'`` is equivalent to byteorder : str Either ``'big'`` for big endian representation or ``'little'`` for little end. ``'>'`` and ``'<'`` are also accepted, respectively. Returns ------- type_code : `str` The type code for the input dtype and byte order. Examples -------- :: >>> get_dtype_str(numpy.uint32, byteorder='big') '>u4' >>> get_dtype_str('u2', byteorder='>') '>u2' >>> get_dtype_str('<u2', byteorder='big') '<u2' """ if byteorder == "big": byteorder = ">" elif byteorder == "little": byteorder = "<" elif byteorder in [">", "<"]: pass else: raise ValueError(f"invalid byteorder {byteorder}") if isinstance(dtype, str): if dtype[0] in [">", "<"]: return dtype elif dtype[0] == "=": raise ValueError("invalid byte order =. Please, use a specific endianess.") else: return byteorder + dtype dtype_str = dtype().dtype.str return byteorder + dtype_str[1:]
01c19b606abdd7a641384b5564c520cdfe5b6a02
456,583