content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def checkfname(fname, extension): """ Check if string ends with given extension ========== =============================================================== Input Meaning ---------- --------------------------------------------------------------- fname String with file name extension Extension that fname should have ========== =============================================================== ========== =============================================================== Output Meaning ---------- --------------------------------------------------------------- fname String with the original fname and added extension if needed ========== =============================================================== """ extL = len(extension) if len(fname) <= extL or fname[-extL:] != extension: fname = fname + "." + extension return fname
a33254a7cea4eb8bd6186222b0316696a775caad
124,090
def get_res_atom_name(atom, conf): """ Get the information for each atom :param atom: the input atom :param conf: the molecular conformer :return: the unqiue residue level name, the atom name and the position """ res_info = atom.GetPDBResidueInfo() atom_pos = conf.GetAtomPosition(atom.GetIdx()) position = [atom_pos.x, atom_pos.y, atom_pos.z] identifiers = [ res_info.GetResidueNumber(), res_info.GetChainId(), res_info.GetResidueName(), res_info.GetAltLoc(), ] unique_name = "_".join([str(x) for x in identifiers if x != " "]) atom_name = res_info.GetName().strip() return unique_name, atom_name, position
f0e8807a2e2a13c1ef7a08228ff88229e58060fc
124,091
import inspect def numargs(func): """Gets number of arguments in python 3. """ return len(inspect.signature(func).parameters)
011d39c8e2606a76aae5cea991cd0fc9e0f450ee
124,093
def round_up(rounded, divider): """Round up an integer to a multiple of divider.""" return int(rounded + divider - 1) // divider * divider
ededc0735b6f9e3167e3a826b49f6491df405013
124,097
def get_name(obj): """Return the name of an object.""" return obj.__name__ if hasattr(obj, '__name__') else get_name(type(obj))
76958794b44c9a61b3f56f7e1fa092b3759316b5
124,098
def pressure(block): """Returns the pressure component in block as a real number.""" start = block.find('_')+1 end = block.find(':') return float(block[start:end])
074fde6a7323fe9051ee41dca3fb7027c67b7c70
124,103
import math def scale_to(x, ratio, targ): """Calculate dimension of an image during scaling with aspect ratio""" return max(math.floor(x * ratio), targ)
d41dceae05ea19f7b03c4ed39d96a8b4bc42b508
124,107
def get_duplicates(iterable): """Find and return any duplicates in the iterable.""" duplicates = {} for i in iterable: duplicates.setdefault(i, 0) duplicates[i] += 1 return [d for d in duplicates if duplicates[d] > 1]
cc85a15f8a6cdc5158bcb586abdea4417a2a294e
124,108
def canUnlockAll(boxes): """ You have n number of locked boxes in front of you. Each box is numbered sequentially from 0 to n - 1 and each box may contain keys to the other boxes. Write a method that determines if all the boxes can be opened. Prototype: def canUnlockAll(boxes) boxes is a list of lists A key with the same number as a box opens that box You can assume all keys will be positive integers There can be keys that do not have boxes The first box boxes[0] is unlocked Return True if all boxes can be opened, else return False """ n_boxes = len(boxes) if not boxes or n_boxes <= 0: return False initial_keys = [0] for key in initial_keys: for k_box in boxes[key]: if 0 < k_box < n_boxes and k_box not in initial_keys: initial_keys.append(k_box) if len(initial_keys) == n_boxes: return True return False
7e1d985982d9ab8691c140fed7eda276e193e9c9
124,110
from textwrap import dedent def dedent_strip_nodetext_formatter(nodetext, has_options, caller=None): """ Simple dedent formatter that also strips text """ return dedent(nodetext).strip()
36db3cf7bb286eb3b45dcc5c402fdf1dac4d82dc
124,111
def time_to_str(date): """ Helper function to convert pd.DateTime objects into str. :param date: A pd.DateTime object :returns: A string in the formal 'YYYY-MM-DD' """ return str(date)[:10]
e43bf27f1cdfe8f993d344b4ed653b52823f7329
124,118
def plotter(ax, x, y, e, l, line, scatter, errs, err_kw, **plot_kw): """ Plot data Auxilliary function to plot the specified data Parameters ___________ ax: Axes Axes object on which to plot the data x: array-like x values y: array-like y values e: array-like Error values used to draw error bars l: array-like Labels to be used in the legend line: bool Whether to draw a line connecting the individual data points scatter: bool Whether to draw a marker at each data point errs: bool Whether to include an error bar at each data point err_kw: dict Dict with keywords passed to the plt.errorbars function used to draw errorbars **plot_kw: all remaining keyword arguments are passed to the plt.plot or plt.scatter function used to draw the graphs """ actual_line = None actual_caps = None actual_bars = None if 'marker' not in plot_kw: plot_kw['marker'] = '.' if errs: if 'elinewidth' not in err_kw: err_kw['elinewidth'] = 0.5 if 'capthick' not in err_kw: err_kw['capthick'] = 0.5 if 'capsize' not in err_kw: err_kw['capsize'] = 3 if line and scatter: actual_line, actual_caps, actual_bars = ax.errorbar(x, y, e, label=l, **err_kw, **plot_kw) elif line: plot_kw.pop('marker') actual_line, actual_caps, actual_bars = ax.errorbar(x, y, e, label=l, **err_kw, **plot_kw) else: plot_kw['ls'] = '' actual_line, actual_caps, actual_bars = ax.errorbar(x, y, e, label=l, **err_kw, **plot_kw) else : if line and scatter: actual_line = ax.plot(x, y, label=l, **plot_kw) elif line: plot_kw.pop('marker') actual_line = ax.plot(x, y, label=l, **plot_kw) else: plot_kw['ls'] = '' actual_line = ax.plot(x, y, label=l, **plot_kw) actual_line = actual_line[0] return actual_line, actual_caps, actual_bars
330b7dbebbef57d1a3d5466ce2568a6e26af5029
124,122
def calculate_acc(n300, n100, n50, nMiss): """ calculate the acc based on number of hits :param n300: number of 300s :param n100: number of 100s :param n50: number of 50s :param nMiss: number of misses :return: accuracy """ return (50 * n50 + 100 * n100 + 300 * n300) / (300 * (nMiss + n50 + n100 + n300))
4b111dfba4358f083e864dffb21f998fa855fa9f
124,123
def scaffold_from_gene(gene): """Returns the scaffold from a gene (ggkbase style!)""" return '_'.join(gene.split('_')[:-1])
428b395baafc321ba6c047fedf2cc89db57e1925
124,125
def dotProduct(v1, v2): """Sum product for the components of v1 and v2. v1 and v2 should have same dimensions.""" if (len(v1) != len(v2)): return None return sum(a * b for a,b in zip(v1, v2))
b0557c74b5f33c6d677a73d42d9d2580c2e44e0a
124,127
from typing import Any from typing import Tuple def quick_kwargs(*keys, kwargs: dict, default: Any = None) -> Tuple[Any]: """ Instead of doing... >>> value_1 = kwargs.get("value_1") >>> value_2 = kwargs.get("value_2", "foo") >>> value_3 = kwargs.get("value_3") This compacts that so you can do... >>> value_1, value_2, value_3 = quick_kwargs("value_1", ("value_2", "foo"), "value_3") You could also make certain parameters required by doing so... >>> value_1 = quick_kwargs(("value_1", "__required__")) - If value_1 does not exist, a TypeError with a message of "missing required parameter 'value_1'" will be raised. """ return_values = [] for k in keys: if isinstance(k, tuple): default = k[1] if default == "__required__": if kwargs.get(k[0]) is None: raise TypeError(f"missing required parameter '{k[0]}'") else: return_values.append(kwargs.get(k[0])) else: return_values.append(kwargs.get(k[0], default)) continue return_values.append(kwargs.get(k, default)) if len(return_values) > 1: return tuple(return_values) return return_values[0]
f49e5766717447ddd07e5bc990297e2c9c87ef3c
124,129
def websocket_method(fn): """Decorator to mark a function as valid endpoint method.""" fn.is_endpoint_method = True return fn
f091340e001ffb6ba7fe4d6bf1c8dd538746ab2c
124,130
def is_blank_line(line): """ Returns True if line is blank. """ return not line.set_feature and not line.annotations and not line.comment
00c0466954bcb8b835fe07b8556cfb629f2db963
124,131
import time def time_method(func, *args, ppd=3, return_time=False): """Computes the time of execution for a function. Parameters: func: function to be applied args: any number of arguments to be passed into the function return_time: controls whether to return only the result or the result and time elapsed Returns: depending on return_time, either result or the tuple (result, time_elapsed) """ tic = time.time() res = func(*args) toc = time.time() print(f"{func.__name__} computed in {toc-tic:.3f} seconds.") if return_time: return res, toc - tic else: return res
a6a10c9cb53edfe6ed6929b437461d97f328057d
124,132
def is_probably_inside_string_or_comment(line, index): """Return True if index may be inside a string or comment.""" # Make sure we are not in a string. for quote in ['"', "'"]: if quote in line: if line.find(quote) <= index: return True # Make sure we are not in a comment. if '#' in line: if line.find('#') <= index: return True return False
7a187e7b3cf88b4bdd9e371c727ff9a4d2b9f514
124,139
def get_indices(aperiodic_mode): """Get a dictionary mapping indices of FOOOF params to column labels. Parameters ---------- aperiodic_mode : {'fixed', 'knee'} Which approach taken to fit the aperiodic component. Returns ------- indices : dict Mapping of the column indices for the FOOOF model fit params. """ indices = { 'CF' : 0, 'PW' : 1, 'BW' : 2, 'offset' : 0, 'knee' : 1 if aperiodic_mode == 'knee' else None, 'exponent' : 1 if aperiodic_mode == 'fixed' else 2 } return indices
26b3d16fdbf38bd1eb5472c727028a9cdb82e8a3
124,145
def group_by_event(json_, type_): """ pulls out one specific event type from event_json and returns a list of those specific events. inputs ----- json_: json object type_: type of event ex ('Shot', 'Pass') """ events = [] for event in json_: event_type = event['type']['name'] if event_type == type_: events.append(event) return events
dbe8868e3e965aacf812cc89c5ae46029e161e6c
124,150
def object_exists(model, **kwargs): """ Tests whether a pk exists in a Django model to avoid any exceptions from being raised. """ return model.objects.filter(**kwargs).exists()
37e6d11f9120e5dbfefb4bb5a166b6a778c33f9a
124,151
def compute_2nd_order_finite_difference_coefficients(x): """Compute 2nd-order finite difference coefficients for a centered, three-node stencil. Parameters ---------- x : ndarray 1-D vector of node positions for which to compute the finite difference approximations. Returns ------- am, a0, ap : ndarray Three 1-D vectors containing the coefficients to compute the finite difference approximate 2nd order derivative at the N-2 inner nodes of x. Notes ----- len(am) == len(a0) == len(ap) == len(x) - 2 Example ------- # Get the finite difference approximate second derivative of sin(x) x = np.linspace(0., 1.) am, a0, ap = compute_2nd_order_finite_difference_coefficients(x) y = np.sin(x) result = am * y[:-2] + a0 * y[1:-1] + ap * y[2:] """ h = x[1:] - x[:-1] hm = h[:-1] hp = h[1:] am = 2./(hm*hp + hm*hm) a0 = -2./(hm*hp) ap = 2./(hm*hp + hp*hp) return am, a0, ap
44d7bee3aceaf668276743509ef33afa21d5d305
124,154
def digits(number: int) -> int: """Counts number of digits. Args: number (int): given input number Examples: >>> assert digits(66) == 2 """ return len(str(number))
f79c33f32056e89e979f6e6d4516e2e5c3e859c9
124,157
def euclidean_dist_vec(y1, x1, y2, x2): """ Calculate the euclidean distance between two nodes """ distance = ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5 return distance
cc9de07f43a9730d93042ea2914fbb848b787f96
124,159
def padded_tensor_name(tensor_name, pad): """ A name for the padded tensor :param tensor_name: tensor name :param pad: pad value :return: name """ return "{}_pad{}".format(tensor_name, pad)
057e23d1937f9f5a69282d3f90466653368ab1c4
124,162
def reformat_postcode(df): """Change the POSTCODE feature in uniform format (without spaces). Parameters ---------- df : pandas.Dataframe Dataframe to format. Return ---------- df : pandas.Dataframe Dataframe with reformatted POSTCODE.""" df["POSTCODE"] = df["POSTCODE"].str.replace(r" ", "") return df
c4bc50df26062919378b77b7c1ef80c3a57d2155
124,163
def from_bcd(data: bytes) -> int: """ make a bcd encoded bytestring into an integer Example: b"\x30" should be 30 """ chars = data.hex() return int(chars)
501072405375cce0cc7d24e4652584b70a75e56e
124,166
def Convert_Higher_is_Better(df, columns, conversion_type = 'absolute'): """Converts scores given in a "lower is better" format to a "higher is better" format Parameters ---------- df : a pandas DataFrame object that contains the specified columns columns: a list object that includes the columns to normalize conversion_type : a string specifying the type of conversion to perform - 'absolute' converts based on absolute scale - 'relative' converts based on relative scale Yields ------ temp_df: a copy of the passed dataframe with the conversions performed """ temp_df = df.copy() for column in columns: if conversion_type is 'absolute': new_column = column+' (absolute HIB)' max_entry = temp_df[column].max() temp_df[new_column] = max_entry - temp_df[column] elif conversion_type is 'relative': new_column = column+' (relative HIB)' min_entry = temp_df[column].min() max_entry = temp_df[column].max() temp_df[new_column] = (max_entry - temp_df[column])/(max_entry-min_entry) else: print('You did not enter a valid type, so no changes were made') return temp_df
9179d2780e9e917309fdbc532de29066b550b35f
124,170
def as_tuple(obj): """ Given an object which may be a list/tuple, another object, or None, return that object in list form. IE: If the object is already a list/tuple just return it. If the object is not None, return it in a list with a single element. If the object is None return an empty list. """ if obj is None: return () elif isinstance(obj, list): return tuple(obj) elif isinstance(obj, tuple): return obj return (obj,)
daf6a5c7a5c38a1bcb3cb5c11aeb4f7b5f13e833
124,179
def remove_newlines(s): """ Strips all the newline characters (\\n) from the given input string. >>> remove_newlines('abcd\\nefgh') 'abcdefgh' Args: s: The sreing to remove newlines from. Returns: A new string with all the \\n characters deleted. """ return s.replace('\n', '')
976efeb4d21b71f246e733f88b237b8634b68875
124,181
import torch import math def n_dist(x): """ Cumulative distribution function of the standard normal distribution. """ return 0.5 * (1 + torch.erf(x / math.sqrt(2)))
d09eda893160cf74128f3cb630e80b5b5830e391
124,182
def get_ip_spec(addr, subnet=None): """Get the IP address with the subnet prefix length. Args: addr: network.addr object subnet: network.net object Returns: A string of the IP address with prefix length. Raises: Exception: if ip not in subnet """ if subnet is None: if addr.version == 6: ip_spec = str(addr) + '/128' else: ip_spec = str(addr) + '/32' elif addr in subnet: ip_spec = '%s/%s' % (addr, subnet.prefixlen) else: raise Exception('ip %s is not in subnet %s' % (addr, subnet)) return ip_spec
da4230bdb5e3061689b17f05a744a59f1d10042d
124,184
def _isNumeric(j): """ Check if the input object is a numerical value, i.e. a float :param j: object :return: boolean """ try: x = float(j) except ValueError: return False return True
75b8653f24a9e3f367277eafe00051b3a3533bc3
124,185
import json def load_one_params(params_json_path): """Load params.json as dict""" with open(params_json_path, 'r') as f: data = json.loads(f.read()) if "args_data" in data: del data["args_data"] if "exp_name" not in data: data["exp_name"] = params_json_path.split("/")[-2] return data
2a1546ce9c763ebc322c856f843bd242f209df36
124,191
import hashlib def sha256(code, input): """sha256 <string> -- Create a sha256 hash of the input string""" return code.say(hashlib.sha256(input.group(2)).hexdigest())
58935c8513a158725ed8e2f42be4c7fdda16c390
124,193
def step_function(x: float, step_coordinate: float = 0, value_1: float = 0, value_2: float = 1) -> float: """Simple step function. Parameters ---------- x : float Coordinate. step_coordinate: float Step coordiante. value_1 : float Function returns value_1 if x < step_coordinate. value_2 : float Function returns value_2 if x >= step_coordinate. Returns ------- float """ return value_1 if x < step_coordinate else value_2
0e42385a349e17ee6f4981f33ad3cdbee89f68ad
124,196
def qualified_column(column_name: str, alias: str = "") -> str: """ Returns a column in the form "table.column" if the table is not empty. If the table is empty it returns the column itself. """ return column_name if not alias else f"{alias}.{column_name}"
9920d71e94c0e17bd7a5ce5d0f5c4fabdacfab5e
124,197
def snake_ate_food(sounds, snake, food): """Returns true if the snake has eaten the food.""" if (snake.head_rect.x == food.rect.x and snake.head_rect.y == food.rect.y): sounds.eat_food.play() return True else: return False
137af198b82fcbe9befd864701193f8f0ee1075b
124,204
def is_number(s): """ Function to check if s is a number @ In, s, object, the object to checkt @ Out, response, bool, is it a number? """ response = False try: float(s) response = True except ValueError: pass return response
abf2798ce46eb336c9146cab456ed4a3963dc98d
124,207
import re def get_plain_text(s): """ 获取纯文本内容 清除 html 标签, 空白字符替换为一个空格, 去除首尾空白 :param s: str :return: str """ return re.sub(r'\s+', ' ', re.sub(r'<[^>]+>', '', s)).strip()
e86c000cd01efb639d2a36a316a573fb9adc2e8a
124,211
def mkint( string ) : """Try converting a string to base-10 integer. If that fails, try base-16. If that fails, we'll allow the ValueError to propogate.""" value = None try : value = int(string,10) except ValueError: value = None pass if value is None : # ok, maybe it's hex value = int(string,16) return value
beedec6009df872a35eb032783dbaae09161c5ef
124,212
def get_guest_discard_disk(session): """ Get disk without partitions in guest. :param session: Guest session :return: Guest disk name """ list_disk_cmd = "ls /dev/[shv]d*|sed 's/[0-9]//p'|uniq -u" disk = session.cmd_output(list_disk_cmd).splitlines()[0] return disk
eeeabd0a2542b10d8aa644e386773fd8f0d14f9d
124,214
def __is_now_playing(track): """ Returns True if the track is now playing. """ return '@attr' in track and track['@attr']['nowplaying'] == 'true'
c454a7e3158d2c3af29c665ecb5b618e5a90512e
124,218
def chinese_date(cycle, year, month, leap, day): """Return a Chinese date data structure.""" return [cycle, year, month, leap, day]
7565fc0a88a1a539e55e71cda5e63a17dc7ad85d
124,219
def _get_files_set(path, start_tag, end_tag): """Get set of file paths from the given file. Args: path: Path to file. File at `path` is expected to contain a list of paths where entire list starts with `start_tag` and ends with `end_tag`. List must be comma-separated and each path entry must be surrounded by double quotes. start_tag: String that indicates start of path list. end_tag: String that indicates end of path list. Returns: List of string paths. """ with open(path, 'r') as f: contents = f.read() start = contents.find(start_tag) + len(start_tag) + 1 end = contents.find(end_tag) contents = contents[start:end] file_paths = [ file_path.strip().strip('"') for file_path in contents.split(',')] return set(file_path for file_path in file_paths if file_path)
0e32590e66e22b9ded2688c63363db4b36720110
124,220
import six def get_status(resource, status_attr="status"): """Get the status of a given resource object. The status is returned in upper case. The status is checked for the standard field names with special cases for Heat and Ceilometer. :param resource: The resource object or dict. :param status_attr: Allows to specify non-standard status fields. :return: The status or "NONE" if it is not available. """ for s_attr in ["stack_status", "state", status_attr]: status = getattr(resource, s_attr, None) if isinstance(status, six.string_types): return status.upper() # Dict case if ((isinstance(resource, dict) and status_attr in resource.keys() and isinstance(resource[status_attr], six.string_types))): return resource[status_attr].upper() return "NONE"
8d609986b35ff3cddc3d4e0eac54c3ecc32c7374
124,224
def delete_duplicates(a_list): """This function recives a list, it returns a new list based on the original list but without the duplicate elements of it""" new_list = [] for i in a_list: if not i in new_list: new_list.append(i) return new_list
b5f40baeefb10e96a59a362dfe874aa2aa12786a
124,227
def major_axis_from_iop_cosine(iop_cosine): """Given an IOP direction cosine, i.e. either the row or column, return a tuple with two components from LRPAFH signifying the direction of the cosine. For example, if the cosine is pointing from Left to Right (1\0\0) we return ('L', 'R'). If the direction cosine is NOT aligned with any of the major axes, we return None. Based on a routine from dclunie's pixelmed software and info from http://www.itk.org/pipermail/insight-users/2003-September/004762.html but we've flipped some things around to make more sense. IOP direction cosines are always in the LPH coordinate system (patient-relative): * x is right to left * y is anterior to posterior * z is foot to head """ obliquity_threshold = 0.8 orientation_x = [('L', 'R'), ('R', 'L')][int(iop_cosine[0] > 0)] orientation_y = [('P', 'A'), ('A', 'P')][int(iop_cosine[1] > 0)] orientation_z = [('H', 'F'), ('F', 'H')][int(iop_cosine[2] > 0)] abs_x = abs(iop_cosine[0]) abs_y = abs(iop_cosine[1]) abs_z = abs(iop_cosine[2]) if abs_x > obliquity_threshold and abs_x > abs_y and abs_x > abs_z: return orientation_x elif abs_y > obliquity_threshold and abs_y > abs_x and abs_y > abs_z: return orientation_y elif abs_z > obliquity_threshold and abs_z > abs_x and abs_z > abs_y: return orientation_z else: return None
fc1920e3ee0969164b65ba0c4b5563713fdda7f8
124,229
def news_dictionary_maker(articles_list:list) -> list: """ Description: Function to make a smaller list which doesn't contain the 'seen' key Arguments: articles_list {list} : list contains dictionary's with the 'seen' and 'articles' keys Returns: news_list {list} : list containing just the 'articles' jey from the list in arguments """ news_list = [] # cycles through each news article and appends dictionary if article hasn't been seen before x = 0 for i in articles_list: if articles_list[x]['seen'] == 0: news_list.append(articles_list[x]['articles']) x = x + 1 return news_list
84a70b6c2f711ddb36fbdbadbd45cf609bbd20b8
124,233
def version_tuple(v): """ Converts a version string into a tuple of strings that can be used for natural comparison allowing delimeters of "-" and ".". """ v = v.replace('-', '.') return tuple(map(str, (v.split("."))))
125d791534f6708dd19ea3c5b5832a9acbeb088a
124,234
def parse_filerange(filerange): """ Parse strings like this: 210-214 215 216,217 218-221,223-225 and produce a list of integers corresponding to the range expressed in the string. :param filerange: String representing a range of integers. :type filerange: str :rtype: list of int """ filenumbers = [] ranges = filerange.split(',') for range_limits in ranges: boundaries = range_limits.split('-') if len(boundaries) == 1: filenumbers.append(int(boundaries[0])) elif len(boundaries) == 2: number = int(boundaries[0]) while number <= int(boundaries[1]): filenumbers.append(number) number += 1 else: raise RuntimeError return filenumbers
d46f955fb4f1d55c37d5f54586e7c0e546eb5d99
124,237
def get_valid_bases(return_values="bases_only"): """Returns the valid DNA bases used by the functions in this module. Arguments return_values -- Determines the value (and type) of what the function returns. If return_values == "bases_only", the function returns a list with valid bases; if return_values == "base_complements", the function returns a dict with valid bases as keys and base complements as values. Raises ValueError, if return_values is neither "bases_only" nor "base_complements". Returns (a) A list containing valid bases (if return_values == "bases_only"): ['A', 'G', 'C', 'T'] (b) A dict containing the valid DNA bases and their complements (if return_values == "base_complements"): {'A': 'T', 'G': 'C', 'C': 'G', 'T': 'A'} Doctests >>> get_valid_bases("bases_only") ['A', 'G', 'C', 'T'] >>> get_valid_bases("base_complements") {'A': 'T', 'G': 'C', 'C': 'G', 'T': 'A'} >>> get_valid_bases("Whoops!") Traceback (most recent call last): ... ValueError: return_values must be either "bases_only" or "base_complements" """ valid_bases = ['A', 'G', 'C', 'T'] if return_values == "bases_only": return valid_bases elif return_values == "base_complements": # [::-1] reverses the list of bases return dict(zip(valid_bases, valid_bases[::-1])) else: raise ValueError('return_values must be either "bases_only" or ' + \ '"base_complements"')
7d732ae4ee4c1c24ddacc5c715e3e508674f5cd4
124,245
import jinja2 def jinja(source, environ, destination=None): """ Render a Jinja configuration file, supports file handle or path """ close_source = close_destination = False if type(source) is str: source = open(source, "r") close_source = True if type(destination) is str: destination = open(destination, "w") close_destination = True result = jinja2.Template(source.read()).render(environ) if close_source: source.close() if destination is not None: destination.write(result) if close_destination: destination.close() return result
511bd806167767ce8cb5d9323a8e6702a16e8631
124,252
def are_in_same_column(cell, free_cell): """ Check if the given cell is in the same column than the free_cell. :arg cell, the coordinate of the cell in the table. :arg free_cell, the coordinate of the free cell in the table. """ xcell = list(cell)[0][0] xfreecell = list(free_cell)[0][0] return xcell == xfreecell
5a39cf706f99c22cfb5b3d396a15230ef77b5c6f
124,262
from bs4 import BeautifulSoup import re def get_game_ids(response): """ Get game_ids for date from doc :param response: doc :return: list of game_ids """ soup = BeautifulSoup(response, 'lxml') divs = soup.findAll('div', {'class': "game-header"}) regex = re.compile(r'id="(\d+)') game_ids = [regex.findall(str(div))[0] for div in divs] return game_ids
f2aae5c0c98949a265348b9dd39b926768b0aaee
124,264
def rotmap(start): """ dict[char,char]: Map chars (from start to start+26) to rotated characters. """ ints = range(start,start+26) rots = ( start+i%26 for i in range( 13, 13 +26) ) return dict( zip( map( chr,ints ),map( chr,rots ) ) )
779c7aef38767d1a2a786708af251c5c554cef5a
124,270
def _is_valid_kwarg(provided: dict, available: dict): """ Helper function to check if a user provided dictionary has the correct arguments, compared to a dictionary with the actual available arguments. Updates, if no difference found, the dictionary 'available'. Parameters ---------- provided : `dict` The user defined dictionary of optional additional arguments. available : `dict` The available optional additional arguments possible. :raises KeyError: invalid additional keyword argument supplied """ diff = provided.keys() - available.keys() if diff: # if there are differences msg = "invalid optional keyword argument passed: {}. Available arguments: {}".format(diff, list(available.keys())) raise KeyError(msg) available.update(provided) return available
6890fb1b718e84ad0f055d0fc64649c151ea6d89
124,271
import re def ShouldRunMatchingTest(tests, pattern): """Returns True if regex |pattern| matches an entry in |tests|.""" if not tests: return False for test in tests: if re.match(pattern, test): return True return False
1d37c69a9996d5593cab44eedb7b623f135b9a36
124,279
import math def rotate_point_around_axis( axis_point_1, axis_point_2, point, angle, deg=False): """ Rotate a 3D coordinate about a given arbitrary axis by the specified angle. :param axis_point_1: tuple representing 3D coordinate at one end of the axis :param axis_point_2: tuple representing 3D coordinate at other end of the axis :param point: tuple representing 3D coordinate of starting point to rotate :param angle: rotation angle (defaults to radians) :param deg: Python boolean (default=False), specifies whether the angle is in degrees :returns: Python tuple (len=3) of rotated point """ if (deg): angle *= math.pi/180. xa,ya,za = axis_point_1 xb,yb,zb = axis_point_2 x,y,z = point xl,yl,zl = xb-xa,yb-ya,zb-za xlsq = xl**2 ylsq = yl**2 zlsq = zl**2 dlsq = xlsq + ylsq + zlsq dl = dlsq**0.5 ca = math.cos(angle) dsa = math.sin(angle)/dl oca = (1-ca)/dlsq xlylo = xl*yl*oca xlzlo = xl*zl*oca ylzlo = yl*zl*oca xma,yma,zma = x-xa,y-ya,z-za m1 = xlsq*oca+ca m2 = xlylo-zl*dsa m3 = xlzlo+yl*dsa m4 = xlylo+zl*dsa m5 = ylsq*oca+ca m6 = ylzlo-xl*dsa m7 = xlzlo-yl*dsa m8 = ylzlo+xl*dsa m9 = zlsq*oca+ca x_new = xma*m1 + yma*m2 + zma*m3 + xa y_new = xma*m4 + yma*m5 + zma*m6 + ya z_new = xma*m7 + yma*m8 + zma*m9 + za return (x_new,y_new,z_new)
a0e56d0166aba7e69bba1485b41595a6df55c4be
124,283
def cleanup_ip(ip): """ Given ip address string, it cleans it up """ ip = ip.strip().lower() if (ip.startswith('::ffff:')): return ip.replace('::ffff:', '') return ip
f5b47a03ff2919775b0bcb6a3c74688271ab9f50
124,286
def table_exists(db_cur, table_name): """ Return a table name from a sqlite database to check if it exists. Parameters: db_cur(Cursor): A sqlite cursor connection. table_name(str): Name of a table in the sqite database. """ query = "SELECT name FROM sqlite_master WHERE type='table' AND name='{}'".format( table_name ) return db_cur.execute(query).fetchone() is not None
1d11f196d5175e28617a4c56e80a1a3878e6239f
124,287
from typing import Union def to_bool(inputs: Union[str, bool, int]) -> bool: """ Convert a string "True" or "False" to its boolean value :param inputs: Input string :return: boolean value """ if isinstance(inputs, bool): return inputs if inputs == "False": return False return True
2db677d816d6c54469f0860e1e260c4c72b9f01b
124,290
def subtract(x, y): """Sub two numbers""" return (y-x)
ecd227401580324116bea5413b6002ccff005149
124,296
def validate_confirm_password(value, password): """ Returns 'Valid' if confirmation password provided by user is valid, otherwise an appropriate error message is returned """ if not value: message = 'Please confirm password.' elif value != password: message = 'This password does not match the one entered.' else: message = 'Valid' return message
e8c815f576e57a01fb6d584da5c526f38df1bf75
124,297
def get_child_left_position(position: int) -> int: """ heap helper function get the position of the left child of the current node >>> get_child_left_position(0) 1 """ return (2 * position) + 1
07e35d9b134bcbde8854e704c22251bc15f908ff
124,299
def _ticket_prefix(ticket): """ Add an appropriate prefix to a ticket number. """ if ticket.isdigit(): return f'#{ticket}' return ticket
50132f34fd6119e5739aaafbfe17466bda790428
124,301
def slice_trigram(example): """Does the target word share a trigram between sentences?""" def get_ngrams(tokens, window=1): num_ngrams = len(tokens) - window + 1 for i in range(num_ngrams): yield tokens[i : i + window] trigrams = [] for sent, sent_idx in [ (example.sentence1, example.sentence1_idx), (example.sentence2, example.sentence2_idx), ]: tokens = sent.split() trigrams.append( [ " ".join(ngram).lower() for ngram in get_ngrams(tokens[sent_idx - 2 : sent_idx + 2], window=3) if len(ngram) == 3 ] ) return len(set(trigrams[0]).intersection(set(trigrams[1]))) > 0
638cec8caf4641690a2b358990e62ca7f46f478d
124,303
def token_is_a(token1, token2): """Returns true if token1 is the same type as or a child type of token2""" if token1 == token2: return True parent = token1.parent while(parent != None): if parent == token2: return True parent = parent.parent return False
8e5e2d1ebdaa7ede4a10d314c8285fea73952726
124,307
def bounding_sphere(points): """A fast, approximate method for finding the sphere containing a set of points. See https://www.researchgate.net/publication/242453691_An_Efficient_Bounding_Sphere This method is approximate. While the sphere is guaranteed to contain all the points it is a few percent larger than necessary on average. """ # euclidean metric def dist(a, b): return ((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2) ** 0.5 def cent(a, b): return ((a[0] + b[0]) / 2, (a[1] + b[1]) / 2, (a[2] + b[2]) / 2) p0 = points[0] # any arbitrary point in the point cloud works # choose point y furthest away from x p1 = max(points, key=lambda p: dist(p, p0)) # choose point z furthest away from y p2 = max(points, key=lambda p: dist(p, p1)) # initial bounding sphere center = cent(p1, p2) radius = dist(p1, p2) / 2 # while there are points lying outside the bounding sphere, update the sphere by # growing it to fit for p in points: distance = dist(p, center) if distance > radius: delta = (distance - radius) / 2 radius = (radius + distance) / 2 cx, cy, cz = center x, y, z = p cx += (x - cx) / distance * delta cy += (y - cy) / distance * delta cz += (z - cz) / distance * delta center = (cx, cy, cz) return (center, radius)
30bec8c1d00061962aca1814c64ef52af55870a2
124,312
import copy def build_request_parameters(issue_params, cve_params): """ 构建请求参数 Args: issue_params: Issue请求参数 cve_params: cve请求参数 Returns: issue_params_list, cve_params_list """ parameters_issue = { "community": "openeuler", "state": "all", "milestone": "", "sortKey": "closed_at", "sortValue": "descending", } parameters_cve = { "community": "openeuler", "state": "all", "milestone": "", "sortKey": "closed_at", "sortValue": "descending", } issue_params_list, cve_params_list = [], [] for issue_con in issue_params: parameters_issue["milestone"] = issue_con issue_params_list.append(copy.copy(parameters_issue)) for cve_con in cve_params: parameters_cve["milestone"] = cve_con cve_params_list.append(copy.copy(parameters_cve)) return issue_params_list, cve_params_list
db512d22394d940f2e05a047b9b52327295cb2d1
124,317
def _use_constant_crc_init(sym): """ Return True if the inintial value is constant. """ return sym['crc_init_value'] is not None
22d1f9789e9225856f62afdefae98f8d7d38e9b8
124,319
import random def distinct_permutation(sequence): """ Returns a permutation of the given sequence that is guaranteed to not be the same order as the given input. """ assert len(sequence) > 1, "there is no distinct permutation for this input" original = list(sequence) result = original.copy() while result == original: random.shuffle(result) return result
00fc54ea0a2b3f1f5a775be70a3075d6dc576f99
124,322
import struct def read_node(f): """ Function to read in values of nodes :param f: variable for open file NTv2 being read as binary :return: tuple containing the four ntv2 fields at the grid node. """ # field_1: shift lat / geoid separation (N) byte = f.read(4) field_1 = struct.unpack('f', byte)[0] # field 2: shift lon / deflection in prime meridian value (Xi) byte = f.read(4) field_2 = struct.unpack('f', byte)[0] # field 3: reliability lat / deflection in prime vertical value (Eta) byte = f.read(4) field_3 = struct.unpack('f', byte)[0] # field 4: reliability lon / NA byte = f.read(4) field_4 = struct.unpack('f', byte)[0] return field_1, field_2, field_3, field_4
b79ca9c23946d61a3d7cdb372cbac013f9f1b309
124,325
def KToF(temp): """ Converts temperature from Kelvin to Fahrenheit :param temp: temperature :return: Return the temperature in Fahrenheit """ C = temp - 273 F = (C * 9/5) + 32 F = round(F, 0) return F
4551d1d7a6b170bc3fae5dc4e92f7f6bc3557079
124,326
def cols_to_category_dtype(df, columns=None): """ Converts list of pandas DataFrame columns to category dtype """ if columns is not None: for col in columns: if not hasattr(df[col], 'cat'): df[col] = df[col].astype('category') return df
7c621c10f4eaf23d415ea369f8b96b34fbde1659
124,327
def filter_dict(kwargs): """Return only the keys of a dictionary whose values are truthy""" return (key for key, value in kwargs.items() if value)
ef3881056ed079827bea10b77dda1b5014f6768d
124,331
def GetFreeKey(cspec): """ Get a free key for a new device in the spec """ minkey = -1 deviceChange = cspec.GetDeviceChange() if deviceChange == None: return minkey for devSpec in deviceChange: if minkey >= devSpec.GetDevice().GetKey(): minkey = devSpec.GetDevice().GetKey() - 1 return minkey
3a834524b3f5b1fc5c08d2cfd41fd311a777fb9c
124,333
def open_file(path): """ Open file and read the contents. Args: path (str): Path to file. Returns: str: File contents. """ try: with open(path, 'r') as f: leads = f.read() return leads except OSError: print('Cannot open file')
250990416df37f3a51a8fd8d85f2dcd0e3d7448d
124,335
def divide_by_2(evl, x, y): """Divides the given evaluation by 2. Needed for several samplers.""" return 0.5 * evl
601dda2779f00e5a7c33ba6d72ea036dfe7aca7e
124,337
def blanks(s): """Return the set of positions where s is blank.""" return {i for i, c in enumerate(s) if c == " "}
fd5b59b8dc51a158a6b1262fc4a825a37a49623d
124,340
import math def solar_decline(obliquity_correction, solar_apparent_longitude): """Returns Solar Decline in degrees, with Obliquity Correction, obliquity_correction Solar Apparent Longitude, solar_apparent_longitude""" solar_decline = math.degrees( math.asin( math.sin(math.radians(obliquity_correction)) * math.sin(math.radians(solar_apparent_longitude)) ) ) return solar_decline
073a977b8f60f92387a00adc66590cba806fb547
124,342
def fetch_all_views(eng): """ Finds all views. """ tables = eng.execute("SELECT table_name from information_schema.views;") return [table[0] for table in tables if "exp_view_table" in table[0]]
583abe6efe1c42c27daaf6fbc5b44c4b276e1ded
124,352
from pathlib import Path def read(given_path): """Returns the striped content of a file.""" given_path = Path(given_path) relative_path = Path(__file__).parent / given_path used_path = relative_path if relative_path.is_file() else given_path if not used_path.is_file(): raise FileNotFoundError( f"could not find any of {relative_path} or {given_path}" ) with open(used_path) as stream: return stream.read().strip()
11616021be274e097e44a466e1879993700d16ce
124,357
def pipe_WT(Do, Di): """Calculate pipe wall thickness, given the pipe outer diamater and inner diameter. """ WT = (Do - Di) / 2 return WT
59b6655efe8df9b9482e6930670ac01bcee2fd9d
124,361
def transform_user_info(user): """Converts lastfm api user data into neo4j friendly user data Args: user (dict): lastfm api user data Returns: dict - neo4j friendly user data """ if 'user' in user: user = user['user'] user['image'] = [element['#text'] for element in user['image']] user['registered'] = user['registered']['unixtime'] user['playcount'] = int(user['playcount']) user['playlists'] = int(user['playlists']) user['registered'] = int(user['registered']) return user
6248e868646955477d109aae5656d2621ee66540
124,363
def get_missing_rate(df, features=None): """ Calculate missing rate on selected features from a data frame. If features=None, it returns missing rates for all features. :param df: :param features: :return: """ df = df.copy(deep=True) df = df.loc[:, features].apply(lambda x: x.isna().sum() / len(x)).sort_values( ascending=False).reset_index() df.columns = ['feature', 'missing_rate'] return df
c47120fe991a3943fd1cc206b79d45fbe6a9725f
124,364
def was_label_added(issue, label): """Check if a label was ever added to an issue.""" if not label: return False for action in issue.actions: for added in action.labels.added: if label.lower() == added.lower(): return True return False
0134bee2ced238aa0a8d6f3588ede9277a802b1f
124,367
import re def replace_roff_special_characters(text): """Replace some *roff(7) special characters in the input text""" if "\\" in text: # See https://www.freebsd.org/cgi/man.cgi?query=mandoc_char for a complete list text = re.sub(r"\\&", "", text) text = re.sub(r"\\\.", ".", text) text = re.sub(r"\\-", "-", text) text = re.sub(r"\\\(aq", "'", text) text = re.sub(r"\\\(em", "", text) text = re.sub(r"\\\(tm", "tm", text) text = re.sub(r"\\\([lr]q", '"', text) text = re.sub(r"\\\[rg\]", "(R)", text) # Don't process user defined strings (\*) beside the font style ones: text = re.sub(r"\\f\\\*\[[^\]]*\]", "", text) text = re.sub(r"\\f[^\*]", "", text) # End of line backslash: text = re.sub(r" *\\$", "", text) # "\ " is not processed as it may still be useful return text
c43bde551bb3c446296794ed39e4e9fa7401bbf9
124,370
def member_of(x, val): """ member_of(x, val) Ensures that the value `val` is in the array `x`. """ n = len(x) # cc = intvar(0,n) # constraints = [count(x, val, cc), cc > 0] constraints = [sum([x[i] == val for i in range(n)]) > 0] return constraints
961c72f7c1a1fe57fbd049d6f861a431be065d1d
124,373
def wrap_in_timer(func, timer, name): """ If timer is none, return func, else returns a wrapper function that calls supplied function inside the timer. with timer.time(name): return func(...) """ if timer is None: return func def wrapped(*args, **kwargs): with timer.time(name): return func(*args, **kwargs) return wrapped
922927099fd0213a120772e7e3c3db104ce99817
124,386
def get_clippings_from_book(book_title, parsed_clippings, clipping_type="all"): """ args: book_title: a string of the title of a book parsed_clippings: a list of dictionaries, ie the output of get_clippings() clipping_type: Optional: None or "highlight" or "note" """ clippings = [] for clipping in parsed_clippings: if clipping_type == "all": if clipping["book_title"] == book_title: clippings.append(clipping) else: if clipping["book_title"] == book_title and clipping["clipping_type"] == clipping_type: clippings.append(clipping) return clippings
8048d482f7871c60fbc642f3ed56baab45f67edd
124,390
from typing import Tuple from typing import Any def get_hamming_dist(tuple1: Tuple[Any], tuple2: Tuple[Any]) -> int: """Find the hamming distance between two tuples. The hamming distance is the number of respective elements in the tuples that are not equal. E.g. tuple1 = (1, 23, 'a'), tuple2 = (1, 1, 'a') Hamming distance for the above example is 1, since the 2nd element of the two tuples don't match. Args: tuple1: First tuple tuple2: Second tuple Returns: Number of respective elements that don't match """ dist = 0 assert len(tuple1) == len(tuple2), ('Tuples must have the same length') for val1, val2 in zip(tuple1, tuple2): if val1 != val2: dist += 1 return dist
fb6b22dc48b497d6eabd400609330d122f57af09
124,391
from pathlib import Path from typing import Dict from typing import Any from typing import Iterable def compose_trimming_command( output_path: Path, trimming_parameters: Dict[str, Any], number_of_processes: int, input_paths: Iterable[Path] ): """ Compose a shell command to run skewer on the reads located by read_paths. :param output_path: The Path to a directory where the output from skewer should be stored :param trimming_parameters: The trimming parameters (see virtool_workflow.analysis.trimming_parameters) :param number_of_processes: The number of allowable processes to be used by skewer :param input_paths: The paths to the reads data (see virtool_workflow.analysis.reads_path) """ command = [ "skewer", "-r", str(trimming_parameters["max_error_rate"]), "-d", str(trimming_parameters["max_indel_rate"]), "-m", str(trimming_parameters["mode"]), "-l", str(trimming_parameters["min_length"]), "-q", str(trimming_parameters["end_quality"]), "-Q", str(trimming_parameters["mean_quality"]), "-t", str(number_of_processes), "-o", str(output_path/"reads"), "-n", "-z", "--quiet", ] if trimming_parameters["max_length"]: command += [ "-L", str(trimming_parameters["max_length"]), "-e" ] command += [str(path) for path in input_paths] return command
d4d8e2c4361a2d646e1d7174003737d79d2ead15
124,394
def getPureSuccesors(trans, state): """Function returns the succesors of the state on the basis of the transition dictionary (could be backward transition dictionary, than the ancestor is returned). The state it self is not counted. Args: trans (dict): Transition dictionary. state (string): State whose succesors is returned. Returns: set: The set of a pure succesors of the state. If the state has no succesor/ancestor, then the set containing None is returned. """ succesors = set() if state in trans: for letter in trans[state]: # Self loops does not count. succesors.update(trans[state][letter].difference({state})) # If the set of succesors is emtpy, the set containging None will be reutrned. if not succesors: succesors.add(None) return succesors
2208264d842c1cd4c2c32db039a00cad0e9b0e4b
124,398
from typing import Tuple def tuple_contains(tup1: Tuple, tup2: Tuple) -> Tuple[bool, int]: """Check whether tuple 1 contains tuple 2""" len_tup1, len_tup2 = len(tup1), len(tup2) for i in range(0, len_tup1 + 1 - len_tup2): if tup1[i:i + len_tup2] == tup2: return True, i return False, -1
5967320131a785c0dec22ed7110b9ec6d9f53b9b
124,404
def bytes_in_context(data, index): """Helper method to display a useful extract from a buffer.""" start = max(0, index - 10) end = min(len(data), index + 15) return data[start:end]
b20b35c4a3aaaa8fb81a90ecae775d758f6d6114
124,407
def equivalent_to(binding, cls): """Whether binding.data is equivalent to cls, modulo parameterization.""" return (binding.data.isinstance_Class() and binding.data.full_name == cls.full_name)
cb18b2dfa50e1a08e7300ecff91173506d6a980f
124,410
import torch.nn.functional as F import torch def similarity(x, y): """ calculate similarity between x and y Args: x: feature vector, shape 1xF y: feature vector, shape 1xF Returns: reel number indicating similarity """ return F.cosine_similarity(torch.Tensor(x.reshape(1, -1)), torch.Tensor(y.reshape(1, -1)))
b5c1295101d178879b4362ad4ade03ef21eed9f6
124,413