content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def _frac_scorer(matched_hs_ions_df, all_hyp_ions_df, N_spectra): """Fraction ion observed scorer. Provides a score based off of the fraction of hypothetical ions that were observed for a given hypothetical structure. Parameters ---------- matched_hs_ions_df : pd.DataFrame Dataframe of observed ions that matched a specific hypothetical structure all_hyp_ions_df : pd.DataFrame Dataframe of all possible ions for a given hypothetical structure. N_spectra : int Number of spectra provided. Returns ------- float Score for a given hypothetical structure. """ # Calculate the number of matched ions observed and total possible N_matched_hs_ions = matched_hs_ions_df.shape[0] N_tot_hyp_ions = all_hyp_ions_df.shape[0] score = N_matched_hs_ions / (N_tot_hyp_ions*N_spectra) return score
a341b02b7ba64eb3b29032b4fe681267c5d36a00
4,367
import requests def get_raw_img(url): """ Download input image from url. """ pic = False response = requests.get(url, stream=True) with open('./imgs/img.png', 'wb') as file: for chunk in response.iter_content(): file.write(chunk) pic = True response.close() return pic
67b2cf9f2c89c26fca865ea93be8f6e32cfa2de5
4,369
def is_in_cell(point:list, corners:list) -> bool: """ Checks if a point is within a cell. :param point: Tuple of lat/Y,lon/X-coordinates :param corners: List of corner coordinates :returns: Boolean whether point is within cell :Example: """ y1, y2, x1, x2 = corners[2][0], corners[0][0], corners[0][1], corners[2][1] if (y1 <= point[0] <= y2) and (x1 <= point[1] <= x2): return True return False
5f8f13a65ea4da1909a6b701a04e391ebed413dc
4,370
def format_user_id(user_id): """ Format user id so Slack tags it Args: user_id (str): A slack user id Returns: str: A user id in a Slack tag """ return f"<@{user_id}>"
2b3a66739c3c9c52c5beb7161e4380a78c5e2664
4,371
def calculate_percent(partial, total): """Calculate percent value.""" if total: percent = round(partial / total * 100, 2) else: percent = 0 return f'{percent}%'
4d3da544dd1252acec3351e7f67568be80afe020
4,372
import re def extract_sentences(modifier, split_text): """ Extracts the sentences that contain the modifier references. """ extracted_text = [] for sentence in split_text: if re.search(r"\b(?=\w)%s\b(?!\w)" % re.escape(modifier), sentence, re.IGNORECASE): extracted_text.append(sentence) return extracted_text
4e31a250520b765d998aa8bc88f2414fe206901c
4,374
import random def randomlyInfectRegions(network, regions, age_groups, infected): """Randomly infect regions to initialize the random simulation :param network: object representing the network of populations :type network: A NetworkOfPopulation object :param regions: The number of regions to expose. :type regions: int :param age_groups: Age groups to infect :type age_groups: list :param infected: People to infect :type infected: int :return: Structure of initially infected regions with number :rtype: dict """ infections = {} for regionID in random.choices(list(network.graph.nodes()), k=regions): infections[regionID] = {} for age in age_groups: infections[regionID][age] = infected return infections
213450bfbdba56a8671943905d6ac888a548c8aa
4,377
def timestamp_to_uint64(timestamp): """Convert timestamp to milliseconds since epoch.""" return int(timestamp.timestamp() * 1e3)
165df202cb5f8cee5792bfa5778114ea3e98fa65
4,378
from bs4 import BeautifulSoup def parse_pypi_index(text): """Parses the text and returns all the packages Parameters ---------- text : str the html of the website (https://pypi.org/simple/) Returns ------- List[str] the list of packages """ soup = BeautifulSoup(text, "lxml") return [i.get_text() for i in soup.find_all("a")]
68d831aab69f3ffdd879ea1fa7ca5f28fc1b1e75
4,380
def clean(expr): """ cleans up an expression string Arguments: expr: string, expression """ expr = expr.replace("^", "**") return expr
f7c990146094c43d256fe15f9543a0ba90877ee3
4,382
def xor(text, key): """Returns the given string XORed with given key.""" while len(key) < len(text): key += key key = key[:len(text)] return "".join(chr(ord(a) ^ ord(b)) for (a, b) in zip(text, key))
3cae903ef4751b2f39e0e5e28d448b8d079ce249
4,383
from typing import List from typing import Union def is_prefix(a: List[Union[int, str]], b: List[Union[int, str]]): """Check if `a` is a prefix of `b`.""" if len(a) >= len(b): return False for i in range(len(a)): if a[i] != b[i]: return False return True
4b0605af536aa5fa188cfca0cee62588fe41bf5d
4,384
def text_cleaning(any_text, nlp): """ The function filters out stop words from any text and returns tokenized and lemmatized words """ doc = nlp(any_text.lower()) result = [] for token in doc: if token.text in nlp.Defaults.stop_words: continue # if token.is_punct: # continue result.append(token.lemma_) clean_text = " ".join(result) return clean_text
7383f075a501c7c11565eac2c825c55f37e2a637
4,391
def get_mwa_eor_spec(nu_obs=150.0, nu_emit=1420.40575, bw=8.0, tint=1000.0, area_eff=21.5, n_stations=50, bmax=100.0): """ Parameters ---------- nu_obs : float or array-like, optional observed frequency [MHz] nu_emit : float or array-like, optional rest frequency [MHz] bw : float or array-like, optional frequency bandwidth [MHz] tint : float or array-like, optional integration time [hour] area_eff : float or array-like, optional effective area per station [m ** 2] n_stations : int or array-like, optional number of stations bmax : float or array-like, optional maximum baseline [wavelength] Returns ------- nu_obs, nu_emit, bw, tint, area_eff, n_stations, bmax """ return nu_obs, nu_emit, bw, tint, area_eff, n_stations, bmax
5bc97d666df938c4e5f42d2d429505e2b7f74004
4,392
def count_cells(notebook): """ The function takes a notebook and returns the number of cells Args: notebook(Notebook): python object representing the notebook Returns: len(nb_dict["cells"]): integer value representing the number of cells into the notebook A way you might use me is cells_count = count_cells(nb) """ nb_dict = notebook.nb_dict return len(nb_dict["cells"])
19ec2631888ecbba51fa51870694a7217024e5ae
4,393
def str2bool(value): """ Args: value - text to be converted to boolean True values: y, yes, true, t, on, 1 False values: n, no, false, off, 0 """ return value in ['y', 'yes', 'true', 't', '1']
876a58c86b449ba3fac668a4ef2124ea31fda350
4,394
def add2dict(dict, parent_list, key, value): """ Add a key/value pair to a dictionary; the pair is added following the hierarchy of 'parents' as define in the parent_list list. That is if parent list is: ['5', '1'], and key='k', value='v', then the new, returned dictionary will have a value: dict['5']['1'][k] = v """ d = dict for p in parent_list: if p not in d: d[p] = {} d = d[p] d[key] = value return dict
32252d3253283110eee2edb2eb216cfd777a710f
4,395
def remove_keys(d, to_remove): """ This function removes the given keys from the dictionary d. N.B., "not in" is used to match the keys. Args: d (dict): a dictionary to_remove (list): a list of keys to remove from d Returns: dict: a copy of d, excluding keys in to_remove """ ret = { k:v for k,v in d.items() if k not in to_remove } return ret
94146bb19e8d39ea28c0940307c4c998fe5b7063
4,396
def host_is_local(host: str) -> bool: """ Tells whether given host is local. :param host: host name or address :return: True if host is local otherwise False """ local_names = { "localhost", "127.0.0.1", } is_local = any(local_name in host for local_name in local_names) return is_local
ce823b8c309ec842ed1dd5bb04e41356db500658
4,402
def format_formula(formula): """Converts str of chemical formula into latex format for labelling purposes Parameters ---------- formula: str Chemical formula """ formatted_formula = "" number_format = "" for i, s in enumerate(formula): if s.isdigit(): if not number_format: number_format = "_{" number_format += s if i == len(formula) - 1: number_format += "}" formatted_formula += number_format else: if number_format: number_format += "}" formatted_formula += number_format number_format = "" formatted_formula += s return r"$%s$" % (formatted_formula)
c3c87ffcdc5695b584892c643f02a7959b649935
4,404
import random def permuteregulations(graph): """Randomly change which regulations are repressions, maintaining activation and repression counts and directions.""" edges = list(graph.edges) copy = graph.copy() repressions = 0 for edge in edges: edge_data = copy.edges[edge] if edge_data['repress']: repressions += 1 edge_data['repress'] = False for new_repression in random.sample(edges, repressions): copy.edges[new_repression]['repress'] = True return copy
76a12e573a6d053442c86bc81bebf10683d55dfb
4,416
def create_incident_field_context(incident): """Parses the 'incident_fields' entry of the incident and returns it Args: incident (dict): The incident to parse Returns: list. The parsed incident fields list """ incident_field_values = dict() for incident_field in incident.get('incident_field_values', []): incident_field_values[incident_field['name'].replace(" ", "_")] = incident_field['value'] return incident_field_values
1a56c5b76c4c82827f8b7febde30e2881e6f0561
4,418
def num_of_visited_nodes(driver_matrix): """ Calculate the total number of visited nodes for multiple paths. Args: driver_matrix (list of lists): A list whose members are lists that contain paths that are represented by consecutively visited nodes. Returns: int: Number of visited nodes """ return sum(len(x) for x in driver_matrix)
2a1244cd033029cec4e4f7322b9a27d01ba4abd5
4,421
def gen_custom_item_windows_file(description, info, value_type, value_data, regex, expect): """Generates a custom item stanza for windows file contents audit Args: description: string, a description of the audit info: string, info about the audit value_type: string, "POLICY_TEXT" -- included for parity with other gen_* modules. value_data: string, location of remote file to check regex: string, regular expression to check file for expect: string, regular expression to match for a pass Returns: A list of strings to put in the main body of a Windows file audit file. """ out = [] out.append('') out.append('<custom_item>') out.append(' type: FILE_CONTENT_CHECK') out.append(' description: "%s"' % description.replace("\n", " ")) out.append(' info: "%s"' % info.replace("\n", " ")) out.append(' value_type: %s' % value_type) out.append(' value_data: "%s"' % value_data) out.append(' regex: "%s"' % regex) out.append(' expect: "%s"' % expect) out.append('</custom_item>') out.append(' ') return out
3d0335d91eb700d30d5ae314fce13fc4a687d766
4,422
import inspect def create_signature(args=None, kwargs=None): """Create a inspect.Signature object based on args and kwargs. Args: args (list or None): The names of positional or keyword arguments. kwargs (list or None): The keyword only arguments. Returns: inspect.Signature """ args = [] if args is None else args kwargs = {} if kwargs is None else kwargs parameter_objects = [] for arg in args: param = inspect.Parameter( name=arg, kind=inspect.Parameter.POSITIONAL_OR_KEYWORD, ) parameter_objects.append(param) for arg in kwargs: param = inspect.Parameter( name=arg, kind=inspect.Parameter.KEYWORD_ONLY, ) parameter_objects.append(param) sig = inspect.Signature(parameters=parameter_objects) return sig
011acccada7896e11e2d9bb73dcf03d7dc6e751e
4,423
def perform_step(polymer: str, rules: dict) -> str: """ Performs a single step of polymerization by performing all applicable insertions; returns new polymer template string """ new = [polymer[i] + rules[polymer[i:i+2]] for i in range(len(polymer)-1)] new.append(polymer[-1]) return "".join(new)
c60f760ef6638ff3a221aff4a56dccbeae394709
4,425
def user_city_country(obj): """Get the location (city, country) of the user Args: obj (object): The user profile Returns: str: The city and country of user (if exist) """ location = list() if obj.city: location.append(obj.city) if obj.country: location.append(obj.country) if len(location): return ", ".join(str(i) for i in location) return 'Not available'
be4238246042371215debb608934b89b63a07dab
4,426
def pprint(matrix: list) -> str: """ Preety print matrix string Parameters ---------- matrix : list Square matrix. Returns ------- str Preety string form of matrix. """ matrix_string = str(matrix) matrix_string = matrix_string.replace('],', '],\n') return matrix_string
5c0ffa2b0a9c237b65b5ad7c4e17c2456195c088
4,430
def dashed_word(answer): """ :param answer: str, from random_word :return: str, the number of '-' as per the length of answer """ ans = "" for i in answer: ans += '-' return ans
358be047bfad956afef27c0665b02a2a233fefbf
4,431
def merge_overpass_jsons(jsons): """Merge a list of overpass JSONs into a single JSON. Parameters ---------- jsons : :obj:`list` List of dictionaries representing Overpass JSONs. Returns ------- :obj:`dict` Dictionary containing all elements from input JSONS. """ elements = [] for osm_json in jsons: elements.extend(osm_json['elements']) return {'elements': elements}
c68fde0ddbdf22a34377e1e865be36aaabaa47be
4,432
import torch def unpack_bidirectional_lstm_state(state, num_directions=2): """ Unpack the packed hidden state of a BiLSTM s.t. the first dimension equals to the number of layers multiplied by the number of directions. """ batch_size = state.size(1) new_hidden_dim = int(state.size(2) / num_directions) return torch.stack(torch.split(state, new_hidden_dim, dim=2), dim=1).view(-1, batch_size, new_hidden_dim)
fa58ed9bcf2e9e95aa62b3d18110abe6abce6b1b
4,440
import re def read(line_str, line_pos, pattern='[0-9a-zA-Z_:?!><=&]'): """ Read all tokens from a code line matching specific characters, starting at a specified position. Args: line_str (str): The code line. line_pos (int): The code line position to start reading. pattern (str): Regular expression for a single character. All matching characters will be read. Returns: literal (str): The literal that was read, including only characters that were defined in the pattern argument. line_pos (int): The updated line position. """ length = len(line_str) literal = '' while line_pos < length and re.match(pattern, line_str[line_pos]): literal += line_str[line_pos] line_pos += 1 return literal, line_pos
95ece37e927ff3f8ea9579a7d78251b10b1ed0e6
4,442
import random def fully_random(entries, count): """Choose completely at random from all entries""" return random.sample(entries, count)
a1f494f6b3cc635bc109378305bf547d48f29019
4,443
import yaml def _yaml_to_dict(yaml_string): """ Converts a yaml string to dictionary Args: yaml_string: String containing YAML Returns: Dictionary containing the same object """ return yaml.safe_load(yaml_string)
c7de0c860028d17302cd4d07e20c3215503b977b
4,444
def has_substr(line, chars): """ checks to see if the line has one of the substrings given """ for char in chars: if char in line: return True return False
cf438600894ca43c177af1661a95447daa8b6b0d
4,448
def aq_name(path_to_shp_file): """ Computes the name of a given aquifer given it's shape file :param path_to_shp_file: path to the .shp file for the given aquifer :return: a string (name of the aquifer) """ str_ags = path_to_shp_file.split('/') str_aq = "" if len(str_ags) >= 2: str_aq = str(str_ags[1]) print(str_aq) return str_aq
1cb6f9881383b4627ea4f78bf2f6fd9cdf97dbc4
4,449
def T0_T0star(M, gamma): """Total temperature ratio for flow with heat addition (eq. 3.89) :param <float> M: Initial Mach # :param <float> gamma: Specific heat ratio :return <float> Total temperature ratio T0/T0star """ t1 = (gamma + 1) * M ** 2 t2 = (1.0 + gamma * M ** 2) ** 2 t3 = 2.0 + (gamma - 1.0) * M ** 2 return t1 / t2 * t3
2e5c8ec2ab24dd0d4dfa2feddd0053f277665b33
4,451
def flip_channels(img): """Flips the order of channels in an image; eg, BGR <-> RGB. This function assumes the image is a numpy.array (what's returned by cv2 function calls) and uses the numpy re-ordering methods. The number of channels does not matter. If the image array is strictly 2D, no re-ordering is possible and the original data is returned untouched. """ if len(img.shape) == 2: return img; return img[:,:,::-1]
7aab0222f6fd66c06f8464cd042f30c6eac01c72
4,452
def is_comment(txt_row): """ Tries to determine if the current line of text is a comment line. Args: txt_row (string): text line to check. Returns: True when the text line is considered a comment line, False if not. """ if (len(txt_row) < 1): return True if ((txt_row[0] == '(') and (txt_row[len(txt_row) - 1] == ')')): return True else: return False
db54b90053244b17ec209ed1edb1905b62151165
4,458
def get_missing_ids(raw, results): """ Compare cached results with overall expected IDs, return missing ones. Returns a set. """ all_ids = set(raw.keys()) cached_ids = set(results.keys()) print("There are {0} IDs in the dataset, we already have {1}. {2} are missing.".format(len(all_ids), len(cached_ids), len(all_ids) - len(cached_ids))) return all_ids - cached_ids
cb380c12f26de8b4d3908964f4314bc7efe43056
4,468
def resultcallback(group): """Compatibility layer for Click 7 and 8.""" if hasattr(group, "result_callback") and group.result_callback is not None: decorator = group.result_callback() else: # Click < 8.0 decorator = group.resultcallback() return decorator
1eb938400c90667eb532366f5ca83d02dd6429e1
4,469
def str_input(prompt: str) -> str: """Prompt user for string value. Args: prompt (str): Prompt to display. Returns: str: User string response. """ return input(f"{prompt} ")
ac6c3c694adf227fcc1418574d4875d7fa637541
4,474
from typing import List def get_nodes_for_homek8s_group(inventory, group_name) -> List[str]: """Return the nodes' names of the given group from the inventory as a list.""" hosts_dict = inventory['all']['children']['homek8s']['children'][group_name]['hosts'] if hosts_dict: return list(hosts_dict.keys()) else: return []
806394259816ec4311e69dcd46e7b111c7ca0652
4,475
def getrinputs(rtyper, graph): """Return the list of reprs of the input arguments to the 'graph'.""" return [rtyper.bindingrepr(v) for v in graph.getargs()]
bb0f8861a29cd41af59432f267f07ff67601460c
4,477
def string_with_fixed_length(s="", l=30): """ Return a string with the contents of s plus white spaces until length l. :param s: input string :param l: total length of the string (will crop original string if longer than l) :return: """ s_out = "" for i in range(0, l): if i < len(s): s_out += s[i] else: s_out += " " return s_out
2230a2893913eadb2c42a03c85728a5fe79e1e0f
4,482
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 printer(arg1): """ Even though 'times' is destroyed when printer() has been called, the 'inner' function created remembers what times is. Same goes for the argument arg1. """ times = 3 def inner(): for i in range(times): print(arg1) return inner
7e3d2033602eaef9ef570c97a058208066073427
4,486
def get_listing_panel(tool, ghidra): """ Get the code listing UI element, so we can get up-to-date location/highlight/selection """ cvs = tool.getService(ghidra.app.services.CodeViewerService) return cvs.getListingPanel()
f14477cf13cb7eb4e7ede82b0c2068ca53a30723
4,488
from pathlib import Path from typing import Set def get_files_recurse(path: Path) -> Set: """Get all files recursively from given :param:`path`.""" res = set() for p in path.rglob("*"): if p.is_dir(): continue res.add(p) return res
c129ce43130da09962264f6e7935410685815943
4,489
def offer_in_influencing_offers(offerId, influencing_offers): """ Find if a passed offerId is in the influencing_offers list Parameters ---------- offerId: Offer Id from portfolio dataframe. influencing_offers : List of offers found for a customer Returns ------- 1 if offer is found 0 if not found """ if (offerId in influencing_offers): return 1 else: return 0
81c4a8bcb7432222a1fc5175449192681002539c
4,496
import calendar def generate_days(year): """Generates all tuples (YYYY, MM, DD) of days in a year """ cal = calendar.Calendar() days = [] for m in range(1,13): days.extend(list(cal.itermonthdays3(year, m))) days = [d for d in set(days) if d[0] == year] days.sort() return days
6d87910572957d21c9d5df668dfb5f2d02627817
4,501
import asyncio async def start(actual_coroutine): """ Start the testing coroutine and wait 1 second for it to complete. :raises asyncio.CancelledError when the coroutine fails to finish its work in 1 second. :returns: the return value of the actual_coroutine. :rtype: Any """ try: return await asyncio.wait_for(actual_coroutine, 2) except asyncio.CancelledError: pass
26e3737091ca798dbf8c0f6f2a18a1de4b0ec42b
4,502
from typing import Union from pathlib import Path import yaml def load_cfg(cfg_file: Union[str, Path]) -> dict: """Load the PCC algs config file in YAML format with custom tag !join. Parameters ---------- cfg_file : `Union[str, Path]` The YAML config file. Returns ------- `dict` A dictionary object loaded from the YAML config file. """ # [ref.] https://stackoverflow.com/a/23212524 ## define custom tag handler def join(loader, node): seq = loader.construct_sequence(node) return ''.join([str(i) for i in seq]) ## register the tag handler yaml.add_constructor('!join', join) with open(cfg_file, 'r') as f: cfg = yaml.load(f, Loader=yaml.FullLoader) return cfg
c9137c5052adf8fa62913c352df2bfe9e79fc7ce
4,507
def get_model_defaults(cls): """ This function receives a model class and returns the default values for the class in the form of a dict. If the default value is a function, the function will be executed. This is meant for simple functions such as datetime and uuid. Args: cls: (obj) : A Model class. Returns: defaults: (dict) : A dictionary of the default values. """ tmp = {} for key in cls.__dict__.keys(): col = cls.__dict__[key] if hasattr(col, "expression"): if col.expression.default is not None: arg = col.expression.default.arg if callable(arg): tmp[key] = arg(cls.db) else: tmp[key] = arg return tmp
93c29af27446c558b165159cee4bb41bbb3cad4d
4,508
def read_k_bytes(sock, remaining=0): """ Read exactly `remaining` bytes from the socket. Blocks until the required bytes are available and return the data read as raw bytes. Call to this function blocks until required bytes are available in the socket. Arguments --------- sock : Socket to inspect remaining : Number of bytes to read from socket. """ ret = b"" # Return byte buffer while remaining > 0: d = sock.recv(remaining) ret += d remaining -= len(d) return ret
3d75eaa43b84ac99ac37b4b1a048f1a6615901b1
4,511
def rowcount_fetcher(cursor): """ Return the rowcount returned by the cursor. """ return cursor.rowcount
21b30665391aa16d158083ccb37149bd6ec0f548
4,513
def getParInfo(sourceOp, pattern='*', names=None, includeCustom=True, includeNonCustom=True): """ Returns parInfo dict for sourceOp. Filtered in the following order: pattern is a pattern match string names can be a list of names to include, default None includes all includeCustom to include custom parameters includeNonCustom to include non-custom parameters parInfo is {<parName>:(par.val, par.expr, par.mode string, par.bindExpr, par.default)...} """ parInfo = {} for p in sourceOp.pars(pattern): if (names is None or p.name in names) and \ ((p.isCustom and includeCustom) or \ (not p.isCustom and includeNonCustom)): parInfo[p.name] = [p.val, p.expr if p.expr else '', p.mode.name, p.bindExpr, p.default] return parInfo
01eafb065ef98e1fd4676898aeb8d0c5a7a74b9d
4,516
def _landstat(landscape, updated_model, in_coords): """ Compute the statistic for transforming coordinates onto an existing "landscape" of "mountains" representing source positions. Since the landscape is an array and therefore pixellated, the precision is limited. Parameters ---------- landscape: nD array synthetic image representing locations of sources in reference plane updated_model: Model transformation (input -> reference) being investigated in_coords: nD array input coordinates Returns ------- float: statistic representing quality of fit to be minimized """ def _element_if_in_bounds(arr, index): try: return arr[index] except IndexError: return 0 out_coords = updated_model(*in_coords) if len(in_coords) == 1: out_coords = (out_coords,) out_coords2 = tuple((coords - 0.5).astype(int) for coords in out_coords) result = sum(_element_if_in_bounds(landscape, coord[::-1]) for coord in zip(*out_coords2)) ################################################################################ # This stuff replaces the above 3 lines if speed doesn't hold up # sum = np.sum(landscape[i] for i in out_coords if i>=0 and i<len(landscape)) # elif len(in_coords) == 2: # xt, yt = out_coords # sum = np.sum(landscape[iy,ix] for ix,iy in zip((xt-0.5).astype(int), # (yt-0.5).astype(int)) # if ix>=0 and iy>=0 and ix<landscape.shape[1] # and iy<landscape.shape[0]) ################################################################################ return -result
0205654ef8580a0d6731155d7d0c2b2c1a360e9c
4,517
def remove_duplicates(l): """ Remove any duplicates from the original list. Return a list without duplicates. """ new_l = l[:] tmp_l = new_l[:] for e in l: tmp_l.remove(e) if e in tmp_l: new_l.remove(e) return new_l
81132e3b23592589c19ddb11f661e80be6984782
4,520
def get_band_params(meta, fmt='presto'): """ Returns (fmin, fmax, nchans) given a metadata dictionary loaded from a specific file format. """ if fmt == 'presto': fbot = meta['fbot'] nchans = meta['nchan'] ftop = fbot + nchans * meta['cbw'] fmin = min(fbot, ftop) fmax = max(fbot, ftop) elif fmt == 'sigproc': raise ValueError("Cannot parse observing band parameters from data in sigproc format") else: raise ValueError(f"Unknown format: {fmt}") return fmin, fmax, nchans
61e9b0781559de431e5189b89f69a0763b039d8f
4,525
import functools def logging(f): """Decorate a function to log its calls.""" @functools.wraps(f) def decorated(*args, **kwargs): sargs = map(str, args) skwargs = (f'{key}={value}' for key, value in kwargs.items()) print(f'{f.__name__}({", ".join([*sargs, *skwargs])})...') try: value = f(*args, **kwargs) except Exception as cause: print(f'! {cause}') raise print(f'=> {value}') return value return decorated
25822434fe331c59ce64b6f9cd5ec89b70b2542a
4,526
import math def calculate_distance(p1, p2): """ Calculate distance between two points param p1: tuple (x,y) point1 param p2: tuple (x,y) point2 return: distance between two points """ x1, y1 = p1 x2, y2 = p2 d = math.sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2)) return d
756b609a91e17299eb879e27e83cd663800e46dd
4,528
from textwrap import dedent def package_load_instructions(inst_distributions): """Load instructions, displayed in the package notes""" per_package_inst = '' for dist in inst_distributions: if dist.type == 'zip': per_package_inst += dedent( """ # Loading the ZIP Package Zip packages are compressed, so large resources may load faster. import metapack as mp pkg = mp.open_package('{url}') """.format(url=dist.package_url.inner)) elif dist.type == 'csv': per_package_inst += dedent( """ # Loading the CSV Package CSV packages load resources individually, so small resources may load faster. import metapack as mp pkg = mp.open_package('{url}') """.format(url=dist.package_url.inner)) if per_package_inst: return '\n---\n'+per_package_inst else: return ''
321a7486f27a3cb327ae7556e317bc53c24726ac
4,529
from pathlib import Path def maybe_start_with_home_prefix(p: Path) -> Path: """ If the input path starts with the home directory path string, then return a path that starts with the home directory and points to the same location. Otherwise, return the path unchanged. """ try: return Path("~", p.relative_to(Path.home())) except ValueError: return p
6ee4e49e8dfb9bc68a1c10f5ea792715fb5d5336
4,531
import requests from datetime import datetime def get_time_string(place: str = "Europe/Moscow"): """ Get time data from worldtimeapi.org and return simple string Parameters ---------- place : str Location, i.e. 'Europe/Moscow'. Returns ------- string Time in format '%Y-%m-%d %H:%M:%S' Examples -------- >>> get_time_string() 2021-08-16 16:03:34 """ url = "http://worldtimeapi.org/api/timezone/" + place data = requests.get(url).json() date = datetime.fromisoformat(data["datetime"]) string = date.strftime("%Y-%m-%d %H:%M:%S") return string
f15ef5a843317c55d3c60bf2ee8c029258e1cd78
4,533
def add_suffix(input_dict, suffix): """Add suffix to dict keys.""" return dict((k + suffix, v) for k,v in input_dict.items())
7dbedd523d24bfdf194c999b8927a27b110aad3e
4,536
import json from typing import OrderedDict def build_list_of_dicts(val): """ Converts a value that can be presented as a list of dict. In case top level item is not a list, it is wrapped with a list Valid values examples: - Valid dict: {"k": "v", "k2","v2"} - List of dict: [{"k": "v"}, {"k2","v2"}] - JSON decodable string: '{"k": "v"}', or '[{"k": "v"}]' - List of JSON decodable strings: ['{"k": "v"}', '{"k2","v2"}'] Invalid values examples: - ["not", "a", "dict"] - [123, None], - [["another", "list"]] :param val: Input value :type val: Union[list, dict, str] :return: Converted(or original) list of dict :raises: ValueError in case value cannot be converted to a list of dict """ if val is None: return [] if isinstance(val, str): # use OrderedDict to preserve order val = json.loads(val, object_pairs_hook=OrderedDict) if isinstance(val, dict): val = [val] for index, item in enumerate(val): if isinstance(item, str): # use OrderedDict to preserve order val[index] = json.loads(item, object_pairs_hook=OrderedDict) if not isinstance(val[index], dict): raise ValueError("Expected a list of dicts") return val
dfd92f619ff1ec3ca5cab737c74af45c86a263e0
4,537
def hasTable(cur, table): """checks to make sure this sql database has a specific table""" cur.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='table_name'") rows = cur.fetchall() if table in rows: return True else: return False
dfdb3db0901832330083da8b645ae90e28cfb26d
4,540
import socket def getipbyhost(hostname): """ return the IP address for a hostname """ return socket.gethostbyname(hostname)
9556f537e16fd710a566a96a51d4262335967893
4,542
def is_vertex_cover(G, vertex_cover): """Determines whether the given set of vertices is a vertex cover of graph G. A vertex cover is a set of vertices such that each edge of the graph is incident with at least one vertex in the set. Parameters ---------- G : NetworkX graph The graph on which to check the vertex cover. vertex_cover : Iterable of nodes. Returns ------- is_cover : bool True if the given iterable forms a vertex cover. Examples -------- This example checks two covers for a graph, G, of a single Chimera unit cell. The first uses the set of the four horizontal qubits, which do constitute a cover; the second set removes one node. >>> import dwave_networkx as dnx >>> G = dnx.chimera_graph(1, 1, 4) >>> cover = [0, 1, 2, 3] >>> dnx.is_vertex_cover(G,cover) True >>> cover = [0, 1, 2] >>> dnx.is_vertex_cover(G,cover) False """ cover = set(vertex_cover) return all(u in cover or v in cover for u, v in G.edges)
4213db1953ec976b1606c3756fa73ff0cae9f578
4,549
import requests def extract_stream_url(ashx_url): """ Extract real stream url from tunein stream url """ r = requests.get(ashx_url) for l in r.text.splitlines(): if len(l) != 0: return l
679ca261510413f652d0953551b65db8e5c2a62e
4,555
def none_to_null(value): """ Returns None if the specified value is null, else returns the value """ return "null" if value == None else value
394b1f9620cf69c862905171f4aec96838ffc631
4,556
def is_text_serializer(serializer): """Checks whether a serializer generates text or binary.""" return isinstance(serializer.dumps({}), str)
f08f40662da7fd34f5984028e601d664cac943df
4,562
def chunks(l, k): """ Take a list, l, and create k sublists. """ n = len(l) return [l[i * (n // k) + min(i, n % k):(i+1) * (n // k) + min(i+1, n % k)] for i in range(k)]
7cf0c39941ed8f358c576046154af6b3ee54b70a
4,566
import math def floor(base): """Get the floor of a number""" return math.floor(float(base))
8b00ffccf30765f55ff024b35de364c617b4b20c
4,568
def remove_from_end(string, text_to_remove): """ Remove a String from the end of a string if it exists Args: string (str): string to edit text_to_remove (str): the text to remove Returns: the string with the text removed """ if string is not None and string.endswith(text_to_remove): return string[:-len(text_to_remove)] return string
19cebd002fcf5aea5290a6998129427363342319
4,570
def _variable_map_by_name(variables): """ Returns Dict,representing referenced variable fields mapped by name. Keyword Parameters: variables -- list of 'variable_python_type' Warehouse support DTOs >>> from pprint import pprint >>> var1 = { 'column':'frob_hz', 'title':'Frobniz Resonance (Hz)' ... ,'python_type': 'float' ... ,'table': 'foo_fact'} >>> list1 = [var1] >>> pprint(_variable_map_by_name(list1)) {'frob_hz': {'column': 'frob_hz', 'python_type': 'float', 'table': 'foo_fact', 'title': 'Frobniz Resonance (Hz)'}} """ variable_by_field = {} for var in variables: field_name = var['column'] variable_by_field[field_name] = var return variable_by_field
91c27ceb84614313d036ec216ef4c4d567a68255
4,572
from typing import List def readOneLineFileWithCommas(filepath: str) -> List[str]: """ Reads a file that is one line long, separated by commas """ try: with open(filepath) as fp: s: str = fp.readline() return s.split(",") except: raise Exception(f"Failed to open {filepath}")
4c181523192fab0ea01ae5da0883c543565119c6
4,575
def build_dict_conforming_to_schema(schema, **kwargs): """ Given a schema object (for example, TIMESTAMP_SCHEMA from this module) and a set of keyword arguments, create a dictionary that conforms to the given schema, using the keyword arguments to define the elements of the new dict. Checks the result to make sure that it conforms to the given schema, raising an error if not. Returns the new dict conforming to the schema if there are no problems. """ # Check that schema supports a check_match call. # Duck typing version of this check: if not hasattr(schema, 'check_match'): raise ValueError( 'The given "schema" does not seem to be a schema. It has no ' '"check_match" method. Given schema: ' + repr(schema)) # # Strict typing version of this check: # # Check that schema_name is a SCHEMA.Object. # if not isinstance(schema, schema.Schema): # raise ValueError( # 'The first argument must be a schema.Schema object, but is not. ' # 'Given schema: ' + repr(schema)) # The return value. d = {} for key, value in kwargs.items(): d[key] = value schema.check_match(d) return d
8971b7c6e1df8fd16a1b0e0946c9f21a3c601512
4,580
def empty_call_false(*args, **kwargs) -> bool: """ Do nothing and return False """ return False
3b3964c859a47698f0000e1b26963953980fad51
4,583
def text_to_string(filename): """Read a text file and return a string.""" with open(filename) as infile: return infile.read()
dbd79e78c84c3374c0252544086885b909ae9bd9
4,590
def lgsvlToScenicElevation(pos): """Convert LGSVL positions to Scenic elevations.""" return pos.y
d90f7509285b08c791eac56c1a119f91120cf556
4,591
def false_discovery(alpha,beta,rho): """The false discovery rate. The false discovery rate is the probability that an observed edge is incorrectly identified, namely that is doesn't exist in the 'true' network. This is one measure of how reliable the results are. Parameters ---------- alpha : float The estimate of the true-positive rate. beta : float The estimate of the false-positive rate. rho : float The estimate of network density. Returns ------- float The false discovery rate (probability). References ---------- .. [1] Newman, M.E.J. 2018. “Network structure from rich but noisy data.” Nature Physics 14 6 (June 1): 542–545. doi:10.1038/s41567-018-0076-1. """ return (1-rho)*beta/(rho*alpha + (1-rho)*beta)
849c236157070c5d1becfec3e4e5f46a63d232d2
4,593
import math def ceil(base): """Get the ceil of a number""" return math.ceil(float(base))
ebe78a5eb8fa47e6cfba48327ebb1bdc469b970d
4,599
import torch def _find_quantized_op_num(model, white_list, op_count=0): """This is a helper function for `_fallback_quantizable_ops_recursively` Args: model (object): input model white_list (list): list of quantizable op types in pytorch op_count (int, optional): count the quantizable op quantity in this module Returns: the quantizable op quantity in this module """ quantize_op_num = op_count for name_tmp, child_tmp in model.named_children(): if type(child_tmp) in white_list \ and not (isinstance(child_tmp, torch.quantization.QuantStub) or isinstance(child_tmp, torch.quantization.DeQuantStub)): quantize_op_num += 1 else: quantize_op_num = _find_quantized_op_num( child_tmp, white_list, quantize_op_num) return quantize_op_num
c51b06e476ff4804d5bdfca5a187717536a0418f
4,602
def list_to_string(the_list): """Converts list into one string.""" strings_of_list_items = [str(i) + ", " for i in the_list] the_string = "".join(strings_of_list_items) return the_string
f580dd8646526e64bb50297608e8ad8e338d9197
4,604
import re def run_job(answer: str, job: dict, grade: float, feedback: str): """ Match answer to regex inside job dictionary. Add weight to grade if successful, else add comment to feedback. :param answer: Answer. :param job: Dictionary with regex, weight, and comment. :param grade: Current grade for the answer. :param feedback: Current feedback for the answer. :return: Modified answer, grade, and feedback. """ match = re.search(job["regex"], answer) if match: grade += job["weight"] answer = answer.replace(match[0], "", 1) else: feedback += job["comment"] + "\n" return answer, grade, feedback
487916da129b8958f8427b11f0118135268f9245
4,612
def timefstring(dtobj, tz_name=True): """Standardize the format used for timestamp string format. Include 3 letter string for timezone if set to True. """ if tz_name: return f'{dtobj.strftime("%Y-%m-%d_%H:%M:%S%Z")}' else: return f'{dtobj.strftime("%Y-%m-%d_%H:%M:%S")}NTZ'
5bbf0454a76ed1418cbc9c44de909940065fb51f
4,613
def center_vertices(vertices, faces, flip_y=True): """ Centroid-align vertices. Args: vertices (V x 3): Vertices. faces (F x 3): Faces. flip_y (bool): If True, flips y verts to keep with image coordinates convention. Returns: vertices, faces """ vertices = vertices - vertices.mean(dim=0, keepdim=True) if flip_y: vertices[:, 1] *= -1 faces = faces[:, [2, 1, 0]] return vertices, faces
85743c3b3e3838533e78c66b137cc9c8c7702519
4,617
def get_bridge_interfaces(yaml): """Returns a list of all interfaces that are bridgedomain members""" ret = [] if not "bridgedomains" in yaml: return ret for _ifname, iface in yaml["bridgedomains"].items(): if "interfaces" in iface: ret.extend(iface["interfaces"]) return ret
dad9e634a1c5306289e73d465b08b7ea857518e4
4,618
def get_solubility(molecular_weight, density): """ Estimate the solubility of each oil pseudo-component Estimate the solubility (mol/L) of each oil pseudo-component using the method from Huibers and Lehr given in the huibers_lehr.py module of py_gnome in the directory gnome/utilities/weathering/. This method is from Huibers & Katrisky in a 2012 EPA report and was further modified by Lehr to better match measured values. The equation used here is adapted to return results in mol/L. Parameters ---------- molecular_weight : np.array Molecular weights of each pseudo-component as recorded in the NOAA Oil Library (g/mol) density : np.array Density of each pseudo-component as recorded in the NOAA Oil Library (kg/m^3) Returns ------- solubility : np.array Array of solubilities (mol/L) for each pseudo-component of the oil. """ return 46.4 * 10. ** (-36.7 * molecular_weight / density)
64a951e8a6d9579cf934893fe5c9bc0a9181d4cc
4,625
def _process_input(data, context): """ pre-process request input before it is sent to TensorFlow Serving REST API Args: data (obj): the request data, in format of dict or string context (Context): object containing request and configuration details Returns: (dict): a JSON-serializable dict that contains request body and headers """ if context.request_content_type == 'application/json': data = data.read().decode("utf-8") return data if len(data) else '' raise ValueError('{{"error": "unsupported content type {}"}}'.format( context.request_content_type or "unknown" ))
05d48d327613df156a5a3b6ec76e6e5023fa54ca
4,631
def remove_duplicates(iterable): """Removes duplicates of an iterable without meddling with the order""" seen = set() seen_add = seen.add # for efficiency, local variable avoids check of binds return [x for x in iterable if not (x in seen or seen_add(x))]
d98fdf8a4be281008fa51344610e5d052aa77cae
4,632
from typing import Any from typing import List def is_generic_list(annotation: Any): """Checks if ANNOTATION is List[...].""" # python<3.7 reports List in __origin__, while python>=3.7 reports list return getattr(annotation, '__origin__', None) in (List, list)
0ed718eed16e07c27fd5643c18a6e63dc9e38f69
4,636
from pathlib import Path def create_folder(base_path: Path, directory: str, rtn_path=False): """ Recursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory Parameters ----------- base_path : pathlib.PosixPath Global Path to be root of the created directory(s) directory : str Location in the Songbird-LFP-Paper the new directory is meant to be made rtn_path : bool, optional If True it returns a Path() object of the path to the Directory requested to be created Returns -------- location_to_save : class, (Path() from pathlib) Path() object for the Directory requested to be created Example -------- # Will typically input a path using the Global Paths from paths.py >>> create_folder('/data/') """ location_to_save = base_path / directory # Recursive directory creation function location_to_save.mkdir(parents=True, exist_ok=True) if rtn_path: return location_to_save.resolve()
7c3724b009ef03fc6aa4fbc2bf9da2cbfa4c784d
4,637
def _is_correct_task(task: str, db: dict) -> bool: """ Check if the current data set is compatible with the specified task. Parameters ---------- task Regression or classification db OpenML data set dictionary Returns ------- bool True if the task and the data set are compatible """ if task == "classification": return db['NumberOfSymbolicFeatures'] == 1 and db['NumberOfClasses'] > 0 elif task == "regression": return True else: return False
49790d8e2b7a16ee9b3ca9c8bc6054fde28b3b6f
4,641
def get_only_filename(file_list): """ Get filename from file's path and return list that has only filename. Input: file_list: List. file's paths list. Attribute: file_name: String. "01.jpg" file_name_without_ext: String. "01" Return: filename_list: Only filename list. """ filename_list = list() for file_path in file_list: file_name = file_path.split("/")[-1] file_name_without_ext = file_name.split(".")[0] filename_list.append(file_name_without_ext) return filename_list
3b9b202a4320825eba9d32170f527c0de6e1bdc6
4,652
def seconds_to_time(sec): """ Convert seconds into time H:M:S """ return "%02d:%02d" % divmod(sec, 60)
5fe639a9a6ade59258dfb2b3df8426c7e79d19fa
4,656
import json def serializer(message): """serializes the message as JSON""" return json.dumps(message).encode('utf-8')
7e8d9ae8e31653aad594a81e9f45170a915e291d
4,660
def correct_name(name): """ Ensures that the name of object used to create paths in file system do not contain characters that would be handled erroneously (e.g. \ or / that normally separate file directories). Parameters ---------- name : str Name of object (course, file, folder, etc.) to correct Returns ------- corrected_name Corrected name """ corrected_name = name.replace(" ", "_") corrected_name = corrected_name.replace("\\", "_") corrected_name = corrected_name.replace("/", "_") corrected_name = corrected_name.replace(":", "_") return corrected_name
b1df7a503324009a15f4f08e7641722d15a826b7
4,661