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... | 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()
... | 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], corn... | 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):
e... | 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.
... | 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(te... | 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:
... | 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... | 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 ... | 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:
... | 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... | 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... | 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 ... | 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_d... | 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('i... | 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 no... | 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 p... | 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
... | 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(... | 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.appe... | 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')
retu... | 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.
"""
el... | 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_dire... | 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 (st... | 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:
... | 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... | 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-orde... | 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... | 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... | 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())
el... | 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... | 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 of... | 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:
... | 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
-------
`d... | 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 Mo... | 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 : So... | 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 parame... | 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
----------
lan... | 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)
... | 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])})...')
... | 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(
"""
# Loadi... | 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 Pa... | 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 '%... | 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"... | 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... | 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_rem... | 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)'... | 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 mak... | 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
----------
... | 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... | 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 gr... | 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 = verti... | 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"])
retu... | 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... | 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-ser... | 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
Glob... | 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 da... | 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 lis... | 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, e... | b1df7a503324009a15f4f08e7641722d15a826b7 | 4,661 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.