content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from collections import Counter
def most_common(words, n=10):
"""
Returnes the most common words in a document
Args:
words (list): list of words in a document
n (int, optional): Top n common words. Defaults to 10.
Returns:
list: list of Top n common terms
"""
bow = Counter(words)
ncommon = bow.most_common(n)
return(ncommon) | c4f0adecdec09cb3b2a83e9edbd39eb1789ad592 | 688,948 |
def num_items() -> int:
"""The number of candidate items to rank"""
return 10000 | 437e39083a0abb5f1ce51edd36f7e5bb5e815162 | 688,950 |
import json
def json_dumps(json_obj, indent=2, sort_keys=True):
"""Unified (default indent and sort_keys) invocation of json.dumps
"""
return json.dumps(json_obj, indent=indent, sort_keys=sort_keys) | fdb81417c36c42ae23b72c88041a3be2ea42f0a3 | 688,953 |
def nonSynonCount(t):
""" count the number of nonsynon labels in the transcript annotations.
"""
count = 0
for a in t.annotations:
for l in a.labels:
if l == 'nonsynon':
count += 1
return count | 886c9ae564fabe434b2f30c9f31c78784a311741 | 688,956 |
def _make_socket_path(host: str, display: int, screen: int) -> str:
"""
Attempt to create a path to a bspwm socket.
No attempts are made to ensure its actual existence.
The parameters are intentionally identical to the layout of an XDisplay,
so you can just unpack one.
Parameters:
host -- hostname
display -- display number
screen -- screen number
Example:
>>> _make_socket_path(*_parse_display(':0'))
'/tmp/bspwm_0_0-socket'
"""
return f'/tmp/bspwm{host}_{display}_{screen}-socket' | ea7e36b7058db9291f2ed4b1888bf5fca263ba8d | 688,960 |
def strip_unsupported_schema(base_data, schema):
""" Strip keys/columns if not in SCHEMA """
return [
{key: value for key, value in place.items() if key in schema}
for place in base_data
] | 6faebcbb5b7a7a611ed1befd3daa321d79c925a8 | 688,961 |
def comma_join(items, stringify=False):
"""
Joins an iterable of strings with commas.
"""
if stringify:
return ', '.join(str(item) for item in items)
else:
return ', '.join(items) | 78e823c70fa5896c9cb26140327b485200041369 | 688,962 |
import math
def polar_to_cartesian(r, theta, r_ref=0.0, theta_ref=0.0):
"""
Helper function to convert polar coordinates to Cartesian
coordinates (relative to a defined reference point).
:Parameters:
r: float
Radial distance of point from origin.
theta: float
Angular bearing of point, clockwise from Y axis (in radians)
r_ref: float (optional)
Radial distance of reference point from origin
(if reference point is not the origin).
theta_ref: float (optional)
Angular bearing of reference point, clockwise from Y axis
(in radians)(if reference point is not the origin).
:Returns:
(x, y): tuple of 2 floats
Cartesian coordinates of point
"""
if float(r_ref) > 0.0:
x = r * math.sin(theta) - r_ref * math.sin(theta_ref)
y = r * math.cos(theta) - r_ref * math.cos(theta_ref)
# Old anticlockwise from the X axis code
# x = r * math.cos(theta) - r_ref * math.cos(theta_ref)
# y = r * math.sin(theta) - r_ref * math.sin(theta_ref)
else:
x = r * math.sin(theta)
y = r * math.cos(theta)
# Old anticlockwise from the X axis code
# x = r * math.cos(theta)
# y = r * math.sin(theta)
return (x, y) | a78cc513fc76dcb1a40f12c28310bbe74373c2ff | 688,966 |
from pathlib import Path
def make_paths_absolute(value: str, workdir: Path = Path.cwd()) -> str:
"""
Detect if value is a relative path and make it absolut if so.
:param value: Parameter value from arguments
:param workdir: Path to workdir. Default: CWD
:return:
"""
if "../" in value and (workdir / value).exists():
if (workdir / value).is_symlink():
return str((workdir / value).absolute())
return str((workdir / value).resolve(True))
return value | 00d6809197fc753419ee3abe1cef8d2eb0dd0219 | 688,969 |
from typing import Dict
import math
def position_distance(a: Dict[str, float], b: Dict[str, float]) -> float:
"""Compute the distance between two positions."""
return math.sqrt((a['x'] - b['x'])**2 + (a['y'] - b['y'])**2 + (a['z'] - b['z'])**2) | e945797844132c30bc5c707c2f31f28338c3896c | 688,970 |
def fix_strength(val, default):
""" Assigns given strength to a default value if needed. """
return val and int(val) or default | e9a2414feb1d3e84fb9a02aa83b085d3845d728d | 688,972 |
def get_refs_from_soup(soup):
"""get_refs_from_soup.
Returns a list of `<cite>` tags from the passed BeautifulSoup object.
:param soup: BeautifulSoup object (parsed HTML)
"""
return soup.find_all('cite', recursive=True) | 5bd7ec0e1884aceaf05800775cc304d59e59c458 | 688,974 |
def get_target_value(data_frame, target_type):
"""
Get the value of a specific target from the engineered features pandas data frame.
:param data_frame: The engineered features pandas data frame.
:param target_type: The name of the prediction target.
:return: The prediction target value.
"""
metadata = data_frame._metadata
target_value = metadata[target_type]
return target_value | a31661b6feeadc2b8be3013edf57aa07ebac9f1b | 688,976 |
import string
def filename_from_string(text):
"""Produces a valid (space-free) filename from some text"""
text = text.lower()
valid_chars = "-_." + string.ascii_letters + string.digits
return ''.join(c for c in text if c in valid_chars) | d841923eb4e00f1debb186d7ac3811a5ecfe8f71 | 688,979 |
from pathlib import Path
from typing import List
def read_tabular_data(filename: Path) -> List[List[float]]:
"""Reads a tabular data file, skipping comment lines.
Args:
filename (Path): The full path of the file to be read
Returns:
List[List[float]]: The file contents, with comment lines removed.
"""
lines = []
for line in open(filename, 'r').readlines():
if line.startswith('#'): # Skip comment lines
continue
lines.append([float(x) for x in line.strip().split()])
return lines | ec2d237304d5748e58f6dfcc3282ce32f06ed414 | 688,981 |
def _tile_url(tile_format, x, y, zoom):
"""Build S3 URL prefix
The S3 bucket is organized {tile_format}/{z}/{x}/{y}.tif
Parameters
----------
tile_format : str
One of 'terrarium', 'normal', 'geotiff'
zoom : int
zoom level
x : int
x tilespace coordinate
y : int
x tilespace coordinate
Returns
-------
str
Bucket prefix
Raises
------
TypeError
"""
tile_url = "{tile_format}/{zoom}/{x}/{y}.{ext}"
ext = {"geotiff": "tif", "normal": "png", "terrarium": "png"}
return tile_url.format(tile_format=tile_format, zoom=zoom, x=x, y=y, ext=ext[tile_format]) | 816512f68958c8b04e724e843ce975ededd118d7 | 688,983 |
def parse_opcode(token):
"""Extract the opcode and the mode of all params"""
opcode = token % 100
modes = [0, 0, 0, 0]
if token > 100:
for (i, mode) in enumerate(str(token)[-3::-1]):
modes[i] = int(mode)
return opcode, modes | 90f36fa1b69318739cc8d785639ca9381f8cdb2b | 688,986 |
def _desc_has_possible_number_data(desc):
"""Returns true if there is any possible number data set for a particular PhoneNumberDesc."""
# If this is empty, it means numbers of this type inherit from the "general desc" -> the value
# "-1" means that no numbers exist for this type.
if desc is None:
return False
return len(desc.possible_length) != 1 or desc.possible_length[0] != -1 | 393f16dee7040f044f26909e524b3e11dbf88c94 | 688,987 |
import pickle
def load_pickle(path):
"""
Load object from path
:param path: path to pickle file
:type path: str
:return: object
"""
with open(path, 'rb') as f:
obj = pickle.load(f)
return obj | d75d5bdae7dd84c569b450feb5f1349788a2997c | 688,991 |
def has_dtypes(df, items):
"""
Assert that a DataFrame has ``dtypes``
Parameters
==========
df: DataFrame
items: dict
mapping of columns to dtype.
Returns
=======
df : DataFrame
"""
dtypes = df.dtypes
for k, v in items.items():
if not dtypes[k] == v:
raise AssertionError("{} has the wrong dtype. Should be ({}), is ({})".format(k, v,dtypes[k]))
return df | f542aca7b69116c1c49d09d9ec8a137856d8c4f1 | 688,992 |
def parse_filename(filename):
# time_tag=TIME_INFOLDER_TAG,
# time_fmt=TIME_INFILE_FMT,
# ):
"""Parse Hive and RPi number from filename.
Filename e.g.: raw_hive1_rpi1_190801-000002-utc.jpg
"""
prefix, hive_str, rpi_str, t_str = filename.split("_")
hive = int(hive_str[-1])
rpi = int(rpi_str[-1])
return hive, rpi | d4330e5b1123624288b3cb8d4747971e4cee795b | 688,996 |
def do_steps_help(cls_list):
"""Print out the help for the given steps classes."""
for cls in cls_list:
print(cls.help())
return 0 | 19ce1585f915183fcb38c2ea268a6f30780830bb | 689,001 |
def bbox_to_pptx(left, bottom, width, height):
""" Convert matplotlib bounding box format to pptx format
Parameters
----------
bottom : float
left : float
width : float
height : float
Returns
-------
left, top, width, height
"""
return left, bottom-height, width, height | b32018d50cb022fd65ee87fe258f0cdc9bc04d41 | 689,002 |
def get_ids(cls, inherit=None):
"""Function that returns all the IDs to use as primary key
For a given class, this function will check for the _ids parameter and
call itself recursively on the given class' base classes to append all
other required IDs, thus generating the list of parameters to use as
primary key for the database.
This allows not to repeat the same IDs for each inheritance level and
to compute it automatically.
"""
if not inherit or issubclass(cls, inherit):
ids = list(getattr(cls, '_ids', []))
else:
ids = []
for c in cls.__bases__:
for i in get_ids(c, inherit):
if i not in ids:
ids.append(i)
return ids | 242036494f91e5ee67a6f92a691ec2fde13c241a | 689,006 |
import itertools
def createListWord(n):
"""Creates the list of word with size n on the alphabet {1,2,3,4}."""
temp = [''.join(x) for x in itertools.product('1234', repeat=n)]
L = [int(y) for y in temp]
return L | 7103f269695a77a24c716501b524e1bfddfe2562 | 689,010 |
def build_group_id(ad, desc_list, prettify=(), force_list=(), additional=None):
"""
Builds a Group ID from information found in the descriptors. It takes a number
of descriptor names, invokes and then concatenates their result (converted to string)
to from a group ID. Additional parameters can be passed to modify the result.
Parameters
----------
ad: AstroData
An instance of `AstroData` derivative that the descriptors will be
desc_list: list of str
A list of descriptor names (order matters) which will be used to
build the Group ID
prettify: sequence/set of str
Names of descriptors that need to be invoked with `pretty=True`
force_list: sequence/set of str
The descriptors named in this list will have their results coerced
into a list, if they returned something else.
additional: str
Additional information that will be added verbatim at the end of
the Group ID
Returns
-------
A string with the group id
"""
desc_object_string_list = []
for descriptor in desc_list:
desc_method = getattr(ad, descriptor)
if descriptor in prettify or 'section' in descriptor:
desc_object = desc_method(pretty=True)
else:
desc_object = desc_method()
# Ensure we get a list, even if only looking at one extension
if (descriptor in force_list and
not isinstance(desc_object, list)):
desc_object = [desc_object]
# Convert descriptor to a string and store
desc_object_string_list.append(str(desc_object))
# Add in any none descriptor related information
if additional is not None:
desc_object_string_list.append(additional)
# Create and return the final group_id string
return '_'.join(desc_object_string_list) | 186f56058ecc7dc12bec7e1936416207a09dcdb3 | 689,013 |
import random
def tirage_uniforme(min, max):
"""
Renvoie un nombre décimal (float) choisi de manière (pseudo)aléatoire et uniforme
de l'intervalle \[``min`` ; ``max``\[.
Arguments:
min (float): Un nombre réel.
max (float): Un nombre réel.
"""
return random.uniform(min, max) | 3ea65fd222e7579df207c22111a405f2fee839ab | 689,014 |
def greet(greeting, name):
"""Returns a greeting
Args:
greeting (string): A greet word
name (string): A persons name
Returns:
string -- A greeting with a name
"""
return f'{greeting} {name}' | e58041beabf77a247fb6b0edc0f5385d29934649 | 689,019 |
def _is_parameter_for(name, container, docmap):
"""
@rtype: C{boolean}
@return: True if C{name} is the name of a parameter for the
routine C{container}, given the DocMap C{docmap}.
"""
if docmap is None or not docmap.has_key(container): return 0
container_doc = docmap.get(container)
if container.is_routine():
for param in container_doc.parameter_list():
if param.name() == name: return 1
return 0 | ae65511c006be2d26c6afa78444df7360319a46c | 689,026 |
def is_lvm(name):
"""
Check if device is marked as an lvm
"""
if "lvm" in name:
return True
return False | 8b29fc4b49580cb776529d573c47fdc7b47e7a71 | 689,031 |
def place_figures(figures):
"""Generate LaTeX code for figure placement.
Parameters
----------
figures : list
List holding LaTeX code of individual figures to be placed in document.
Returns
-------
latex : str
LaTeX code for figure alignment.
"""
latex = ''
num_per_row = 2
num_rows = len(figures) // num_per_row + 1
for row in range(num_rows):
for figure in figures[num_per_row * row:num_per_row * (row + 1)]:
latex += (
r'\begin{minipage}{' + str(1 / num_per_row) +
r'\textwidth}' + '\n')
latex += figure
latex += r'\end{minipage}' + '\n'
latex += '\n'
return latex | b6653eed30edd5658bc09282ff8251be4a1338ba | 689,034 |
import random
def scramble_word(word: str) -> str:
"""Return a scrambled version of the word."""
return ''.join(random.sample(word, k=len(word))) | 36e6bb2a5e9c5978b490d8fffe52f3d03fbe4483 | 689,035 |
def _get_node_name_prefix(node_name):
"""
Returns the node name prefix, without phase character or trailing
whitespaces.
"""
wows_name = node_name.strip()
return wows_name[:-1] | aeef1629f098708a1d70317683f6c2b6dda5109b | 689,036 |
def file_requires_unicode(x):
"""
Return whether the given writable file-like object requires Unicode to be
written to it.
"""
try:
x.write(b'')
except TypeError:
return True
else:
return False | c4e287012f5c8fba594a568ac08adcf3f4ccf79a | 689,039 |
def get_type_name(value_type):
"""Returns the name of the given type."""
return value_type.__name__ | 0d510c0de910d90fabbb275a418eab18dca88965 | 689,041 |
def runge_kutta_fourth_xy(rhs, h, x, y):
"""
Solves one step using a fourth-order Runge-Kutta method. RHS expects both x and y variables.
Moin, P. 2010. Fundamentals of Engineering Numerical Analysis. 2nd ed.
Cambridge University Press. New York, New York.
:param rhs: "Right-hand Side" of the equation(s). Everything but the derivative. (e.g dy/dx = f(x, y))
:param h: step size
:param x: step dimension
:param y: output dimension
:return:
"""
k_1 = rhs(x, y)
k_2 = rhs(x + h / 2.0, y + k_1 / 2.0)
k_3 = rhs(x + h / 2.0, y + k_2 / 2.0)
k_4 = rhs(x + h, y + k_3)
return y + (k_1 + 2 * (k_2 + k_3) + k_4) / 6.0 * h | 22b8d042376501b6910ddb1511c61ed7d2282896 | 689,045 |
def ptbunescape(token):
"""Unescape brackets in a single token, including PTB notation."""
if token in ('', '#FRONTIER#', None):
return None
elif token == '-LCB-':
return '{'
elif token == '-RCB-':
return '}'
elif token == '-LSB-':
return '['
elif token == '-RSB-':
return ']'
return token.replace('-LRB-', '(').replace('-RRB-', ')').replace(
'#LRB#', '(').replace('#RRB#', ')') | b47e52812de83275b227d4483be733788a4a1fce | 689,048 |
def mean(list):
"""
Calcula a média de um vetor de números.
Args:
list (list): vetor de números
Returns:
(float) média dos números
"""
return sum(list) / len(list) | a95825083952e529888a8d932a1e2daf2a7aac62 | 689,049 |
def parse_config(configfile):
"""Parse the config file 'configfile' and return the parsed key-value pairs as dict"""
return {k:v for k,v in map(lambda x: x.strip().split('='), filter(lambda x: not x.strip().startswith('#'),
(line for line in open(configfile))))} | 022243368fb63588a4bffaa6dad799e1bc5c2e66 | 689,053 |
def parse_id(string):
"""Returns the UUID part of a string only."""
return string.split('/')[-1] | bc50d9ba09512ac9ead25822be5b0985557acbdf | 689,059 |
def formalize_bbox(_im_summary):
"""
Extract bboxes from all classes and return a list of bbox.
Each element of the list is in the form: [x1, y1, x2, y2, class_id, score].
The returned list is sorted descendingly according to score.
"""
boxes = [] # each element: x, y, w, h, class_id, score
probs = [] # prob distribution for each bounding box
feats = [] # pooled features
for class_id, items in enumerate(_im_summary.pred.boxes):
for bbox in items:
x1, y1, x2, y2, score = bbox
boxes.append([x1, y1, x2, y2, class_id, score])
for class_id, items in enumerate(_im_summary.pred.cls_prob):
for cls_prob in items:
probs.append(cls_prob)
assert len(boxes) == len(probs)
for class_id, items in enumerate(_im_summary.pred.pooled_feat):
for f in items:
feats.append(f)
assert len(boxes) == len(feats)
bundles = list(zip(boxes, probs, feats))
bundles = sorted(bundles, key=lambda x: x[0][-1], reverse = True) # sort by confidence descendingly
boxes, probs, feats = zip(*bundles)
return (list(boxes), list(probs), list(feats)) | d6a35972da005b89de3274a73637474986b2f0f1 | 689,060 |
def row_full(row, puzzle):
"""
Takes a row number, and a sudoku puzzle as parameter
Returns True if there is no empty space on the row
ReturnsFalse if otherwise
"""
for col in range(0, 9):
if puzzle[row][col] == -1:
return False
return True | 96828d1481dccce583b090a247542db87979e2ce | 689,061 |
def collect_families_from_instances(instances, only_active=False):
"""Collect all families for passed publish instances.
Args:
instances(list<pyblish.api.Instance>): List of publish instances from
which are families collected.
only_active(bool): Return families only for active instances.
"""
all_families = set()
for instance in instances:
if only_active:
if instance.data.get("publish") is False:
continue
family = instance.data.get("family")
if family:
all_families.add(family)
families = instance.data.get("families") or tuple()
for family in families:
all_families.add(family)
return list(all_families) | d47d7a0fe70feb291d55bec068b023cedbb6d1c5 | 689,062 |
def isvlan(value):
"""Checks if the argument is a valid VLAN
A valid VLAN is an integer value in the range of 1 to 4094. This
function will test if the argument falls into the specified range and
is considered a valid VLAN
Args:
value: The value to check if is a valid VLAN
Returns:
True if the supplied value is a valid VLAN otherwise False
"""
try:
value = int(value)
return value in range(1, 4095)
except ValueError:
return False | 485f856330fb61fc009d6d84f4b8d71a7ee77198 | 689,065 |
def parse(utxo, offset=0):
""" Parses a given serialized UTXO to extract a base-128 varint.
:param utxo: Serialized UTXO from which the varint will be parsed.
:type utxo: hex str
:param offset: Offset where the beginning of the varint if located in the UTXO.
:type offset: int
:return: The extracted varint, and the offset of the byte located right after it.
:rtype: hex str, int
"""
i = 0
ret = 0
go = True
while go:
next_byte = ord(utxo[i])
go = bool(next_byte & 0x80)
ret = (ret << 7 | next_byte & 0x7f) + go
i += 1
return ret,i | 6330898ae2113370b1f1ec5e2b8ba0ec326eb48d | 689,066 |
def _list_readline(x):
"""Given a list, returns a readline() function that returns the next element
with each call.
"""
x = iter(x)
def readline():
return next(x)
return readline | f1111906b29efa44adef3d4a838eb25ed1dd0801 | 689,071 |
import random
import string
def random_string(nlen):
"""Create random string which length is `nlen`."""
return "".join([random.choice(string.ascii_lowercase) for _ in range(nlen)]) | 49f63e3f8122dd886ce4cc5d3fe0b2c55c0679bb | 689,074 |
def match_word(encoded_word, words_list):
"""
Find first probably correct word
based on list of words and given encoded word.
"""
results = []
for word in words_list:
#skip all items with different first and last char
if word[0] != encoded_word[0] or word[-1] != encoded_word[-1]:
continue
#skip all items with different chars
elif sorted(list(word)) != sorted(list(encoded_word)):
continue
results.append(word)
return results[0] | ffea6f7042f3d8bc47e5f9335c7e944be692e9a3 | 689,076 |
def extract_meta_from_keys(keys, prefix):
"""Extract metadata contained in a key's name.
Parameters
----------
keys : list of strings
prefix : string
Returns
-------
meta : string
"""
return next(k[len(prefix):] for k in keys if k.startswith(prefix)) | 808101a8edf7cab38ac249959ac27f27b9020d08 | 689,078 |
def ChannelFirst(arr):
"""Convert a HWC array to CHW."""
ndim = arr.ndim
return arr.swapaxes(ndim - 1, ndim - 2).swapaxes(ndim - 2, ndim - 3) | 017b7fb8b0597c201cddd546bf47a21228f0bedd | 689,079 |
import torch
def exp(x):
"""
The exponential link function given by
$$ y = e^{x} $$
"""
return torch.exp(x) | 5daf001a96e3deafb8549ec73f9824d3a512fc58 | 689,081 |
def get_linef(fp, line_no):
"""'fp' should be (readable) file object.
Return the line content at line_no or an empty line
if there is less lines than line_no.
"""
fp.seek(0)
for line in fp:
line_no -= 1
if line_no == 0:
return line
return '' | 8c73e672ccf2eaea6b1e23d7ed5b7a66385440b6 | 689,083 |
def make_1024_list() :
"""
Generates a list of 1024 strings of numbers in the format "XXXX", filled with zeros before the number.
It is here to translate integers into the format used in the dataset (+1 because the list starts at "0001").
:return: returns a list of 1024 strings
"""
list = []
for x in range(1,10) :
list.append('000'+str(x))
for x in range(10,100) :
list.append('00'+str(x))
for x in range(100,1000) :
list.append('0'+str(x))
for x in range(1000,1025) :
list.append(str(x))
return list | 6a42dd4e0ff17a5fd84d584627338cf2975399ac | 689,085 |
import collections
def longest_path(current_state):
"""Find longest possible path from the current state to the final state
Args:
current_state: StateForGraphs
The state at the beginning of the search; the root of the tree.
Returns:
The maximum number of steps that can be used to get from
current_state to a final state, using state.possible_next_states to
find states reachable in one step from the current state
See Also: StateForGraphs
to understand the required methods for the states used in the graph.
The states must implement __hash__, __eq__, possible_next_states,
and is_final
"""
queue = collections.deque()
discovered = {current_state: 0}
queue.append(current_state)
lengths = set()
while queue:
state = queue.popleft()
num_steps = discovered[state]
new_states = state.possible_next_states()
for new_state in new_states:
if new_state.is_final():
lengths.add(num_steps + 1)
elif new_state not in discovered:
queue.append(new_state)
discovered[new_state] = num_steps + 1
return max(lengths) | 8acca90179eaff3f8d06972aec0a63a8050fbcf9 | 689,086 |
def get_topic_key(project_name, topic):
"""
Get the topic key for a project name and a topic
:param project_name: project name
:param topic: topic
:return: topic key
"""
return f"{project_name}/{topic}" | fb1e036e75e43429dc3d5f3e44c64fb7fdc62486 | 689,087 |
def nvl(*args):
"""
SQL like coelesce / redshift NVL, returns first non Falsey arg
"""
for arg in args:
try:
if arg:
return arg
except ValueError:
if arg is not None:
return arg
return args[-1] | 3f49d4c855e8e7f8e0359301acf454f731489495 | 689,089 |
def parseFields(fields, output):
""" Take a string of fields encoded as
key1=value1,key2=value2,...
and add the keys and values to the output dict"""
for field in fields.split('|'):
key, value = field.split('=')
try:
value = int(value)
except:
pass
output[key] = value
return output | 7cbe131e0f4c8df85ccc7bca52aa80f0f0d17a59 | 689,092 |
def to_camel_case(snake_str):
"""
Transforms a snake_case string into camelCase.
Parameters
----------
snake_str : str
Returns
-------
str
"""
parts = snake_str.split("_")
# We capitalize the first letter of each component except the first one
# with the 'title' method and join them together.
return parts[0] + "".join(x.title() for x in parts[1:]) | 02e28889da2a92fc5e085ad955b11519b5069dc4 | 689,093 |
def to_bytes(s, encoding="utf-8"):
"""Convert a text string (unicode) to bytestring, i.e. str on Py2 and bytes on Py3."""
if type(s) is not bytes:
s = bytes(s, encoding)
return s | d66b0620e1c71650db11e48fe6f961289f9fed5b | 689,094 |
from typing import List
from typing import Counter
def top_k_frequent_bucket_sort(nums: List[int], k: int) -> List[int]:
"""Given a list of numbers, return the the top k most frequent numbers.
Solved using buckets sort approach.
Example:
nums: [1, 1, 1, 2, 2, 3], k=2
output: [1, 2]
1. Create a list of buckets to store frequencies.
Note: no item can appear more than the length of the array
2. Append each item to the frequency bucket.
Ex. [[], [3], [2], [1], [], [], []]
3. Flatten the list and return last k elements:
[3, 2, 1]
Time: O(n): Where n is len(nums)
Space: O(n): Where n is len(nums) -- worst case, where every number unique.
"""
# All items unique.
if k == len(nums):
return nums
# Declare buckets for each frequency
frequency_buckets = [[] for _ in range(len(nums) + 1)]
# Gets count of item frequency
counts = Counter(nums)
# Add the numbers to the frequency buckets
for num, frequency in counts.items():
frequency_buckets[frequency].append(num)
# Flatten the list
flat_list = [item for sublist in frequency_buckets for item in sublist]
# Return last k items in the list
return flat_list[-k:] | 94970d9c0c21a5288e52207e85f59d631e546600 | 689,098 |
import re
def increment(s):
""" look for the last sequence of number(s) in a string and increment """
lastNum = re.compile(r'(?:[^\d]*(\d+)[^\d]*)+')
m = lastNum.search(s)
if m:
next = str(int(m.group(1))+1)
start, end = m.span(1)
s = s[:max(end-len(next), start)] + next + s[end:]
return s | 918c72990f04fcc36884deeb1e1d5a846b86ea12 | 689,101 |
def _check_delimiter(output_filename, delim=None):
"""Detect delimiter by filename extension if not set"""
if output_filename and (delim is None):
delimiters = {"tsv": "\t", "csv": ","}
delim = delimiters[output_filename.rsplit(".", 1)[-1].lower()]
assert delim, "File output delimiter not known. Cannot proceed."
return delim | db3cbea27c09f1ec67459cfec6e1f4fbbb1ed5c8 | 689,105 |
from typing import Counter
def precision_recall_f1(prediction, ground_truth):
"""
This function calculates and returns the precision, recall and f1-score
Args:
prediction: prediction string or list to be matched
ground_truth: golden string or list reference
Returns:
floats of (p, r, f1)
Raises:
None
"""
if not isinstance(prediction, list):
prediction_tokens = prediction.split()
else:
prediction_tokens = prediction
if not isinstance(ground_truth, list):
ground_truth_tokens = ground_truth.split()
else:
ground_truth_tokens = ground_truth
common = Counter(prediction_tokens) & Counter(ground_truth_tokens)
num_same = sum(common.values())
if num_same == 0:
return 0, 0, 0
p = 1.0 * num_same / len(prediction_tokens)
r = 1.0 * num_same / len(ground_truth_tokens)
f1 = (2 * p * r) / (p + r)
return p, r, f1 | 363be5c9786226d0f95a21791bd4da65623ccd80 | 689,107 |
from bs4 import BeautifulSoup
import requests
def fetch_page(url, method, **kwargs) -> BeautifulSoup:
"""Execute request for page and return as soup"""
ret = requests.request(method, url, **kwargs)
if ret.status_code != 200:
raise Exception(f"Page {url} returned {ret.status_code}")
return BeautifulSoup(ret.text, features='lxml') | 158c10bcdf2db4e60112f7b9a643661732ca2d29 | 689,110 |
def on_off(image, w, h, threshold=128):
"""
Black and white (no greyscale) with a simple threshold.
If the color is dark enough, the laser is on!
"""
result = []
for row in image:
result_row = []
for pixel in row:
# We draw black, so 255 is for dark pixels
result_row.append(255 if pixel < threshold else 0)
result.append(result_row)
return result | c9e577bf851fa972c1bbe7f8a61afc09ffb37de5 | 689,111 |
def get_init(order):
"""Return initial guess for fit parameters."""
lambda_guess = [1.0]
coeff_guess = [0.0] * (2 * order)
return lambda_guess + coeff_guess | 6e1e7a2be2727a0f6c3fedb1ef88c45081643778 | 689,115 |
def get_caller_name(caller):
"""Find the name of a calling (i.e. observed) object.
Args:
caller: The observed object which is calling an observer.
Returns:
The name of the caller. If the caller is a function we return that
function's .__name__. If the caller is a bound method we return the
name of bound object.
"""
if hasattr(caller, "__self__"):
# caller is a Foo instance
name = caller.__self__.name
else:
# caller is a function.
name = caller.__name__
return name | 2b5bf37a34b7b75684c5301159d461535d986f3f | 689,117 |
def wc(q,mc2,B):
"""
Calculate the electron gyrofrequency
q is the charge in multiples of the fundamental
mc2 is the particle rest mass in MeV
B is the magnetic field magnitude in nT
"""
cof = 89.8755311
res = cof*q*B/mc2
return res | 69e015a36384b9e9af07e303993cc74c2c8cae58 | 689,120 |
from typing import Union
from typing import List
from typing import Tuple
def deduplicate(x: Union[List, Tuple]):
"""Remove duplicates in a list or tuple; preserves original order."""
return type(x)(dict.fromkeys(x)) | ad47ec846f08feadb6c89be31205be536a469d8f | 689,126 |
def sizeof(bsObj):
""" Size of BotSense object in bytes. Size is contextual by object type. """
return bsObj.__sizeof__() | 70c55a9002e336d2d827ee21d04260dfc328d7fc | 689,127 |
def extract_variable_index_and_name(string):
"""Takes a string of the form variable_name[index] and
returns the variable_name, and index.
The method will return a `ValueError` if the string does not
contain a valid set of access brackets, or if the string contains
multiple bracket accessors.
Parameters
----------
string: str
The string to inspect
Returns
-------
str
The name of the variable in the string.
str
The index that was inside of the accessor brackets.
"""
if string.count('[') > 1 or string.count(']') > 1:
raise ValueError('Nested array indices (e.g. values[0][0]) are not '
'supported: {}'.format(string))
start_bracket_index = string.find('[')
end_bracket_index = string.find(']')
if start_bracket_index >= 0 > end_bracket_index:
raise ValueError('Property name containts a [ without a matching ]: '
'{}'.format('.'.join(string)))
if end_bracket_index >= 0 > start_bracket_index:
raise ValueError('Property name containts a ] without a matching [: '
'{}'.format(string))
if start_bracket_index > end_bracket_index:
raise ValueError('Property name containts a ] before a [: '
'{}'.format(string))
if end_bracket_index == start_bracket_index + 1:
raise ValueError('There is no index between the array brackets: '
'{}'.format(string))
if end_bracket_index != len(string) - 1:
raise ValueError('The ] array bracket must be at the end of the property name: '
'{}'.format(string))
array_index = string[start_bracket_index + 1: end_bracket_index]
property_name = string[0: start_bracket_index]
return property_name, array_index | 0d31763f5ed96ec99b35e3ef94d030c1ddeb6268 | 689,129 |
async def start_entry() -> dict:
"""Create a mock start_entry object."""
return {
"id": "start_entry_1",
"race_id": "race_1",
"startlist_id": "startlist_1",
"bib": 1,
"name": "name names",
"club": "the club",
"scheduled_start_time": ("2021-08-31T12:00:00"),
"starting_position": 1,
"status": "",
"changelog": [],
} | 3faf34ebd8000e2aafb872a6abf929ed0d9c9543 | 689,134 |
def myfunc(_a, _b):
"""Add two numbers."""
return _a + _b | 7177568b60056ea28b6c880eaba8d05441b14c96 | 689,136 |
def is_one_to_one(table):
"""A staticmethod that takes a codon table as a dictionary and returns
True if it represents a One-To-One genetic code and False otherwise.
A one-to-one code is defined as a code in which every amino acid is
represented with exactly one codon. This defines an unambiguous
mapping of protein sequence to corresponding DNA sequence.
Parameters
----------
dict table: a python dict representing the codon table
Returns
-------
bool one2one: boolean; True if One-To-One, and False otherwise
"""
# declare storage dict to count amino acid number
aa_set = set(aa for aa in table.values())
aa_counts = {aa: 0 for aa in aa_set}
# count number of amino acids
for aa in table.values():
aa_counts[aa] += 1
# iterate through dictionary and check counts
one2one = True
for aa, count in aa_counts.items():
# skip stop and null signals:
if aa in {'*', '0'}:
continue
elif count > 1:
one2one = False
break
return one2one | d90f3cfc69a7ded4b93b8e15e2175234d96ca7a7 | 689,137 |
def mex(L):
"""Return the minimum excluded value of a list"""
L = set(L)
n = 0
while n in L:
n += 1
return n | c35205dd22ca47e28141ae56aba2827065abf164 | 689,141 |
def _get_magnitude(string):
"""
Get the magnitude of the smallest significant value in the string
:param str string: A representation of the value as a string
:returns: The magnitude of the value in the string. e.g. for 102, the magnitude is 0, and for 102.03 it is -2
:rtype: int
"""
split_by_period = string.split(".")
if len(split_by_period) == 2:
return -1 * len(split_by_period[-1])
elif len(split_by_period) == 1:
return len(string) - len(string.rstrip('0'))
else:
raise ValueError(string + " does not contain a value") | 03a3abc46aca847489431ab86aceab1d59f9c626 | 689,146 |
def __get_pivots(diameter, x, y):
"""
Get the x-intercepts and y-intercepts of
the circle and return a list of pivots which
the coin lies on.
"""
pivots = []
radius = diameter / 2
sqval = radius**2 - y**2
if sqval > 0: # no imaginary numbers!
sqrt = sqval**(0.5)
pivots.append((x + sqrt, 0))
pivots.append((x - sqrt, 0))
elif sqval == 0: # tangent
pivots.append((x, 0))
sqval = radius**2 - x**2
if sqval > 0:
sqrt = sqval**(0.5)
pivots.append((0, y + sqrt))
pivots.append((0, y - sqrt))
elif sqval == 0:
pivots.append((0, y))
return pivots | a82c465d82e428797bf98d4ab005335005d44368 | 689,148 |
def create_filename(lecture_num, title):
"""
Create a filename from a title string.
Converts spaces to dashes and makes everything lowercase
Returns:
lecture filename
"""
return "lecture-{:02d}{}.md".format(int(lecture_num), "" if not title else '-' + title.lower().replace(" ", "-")) | 2370a63fb69b8cf0ddd431745d01201f2bafe6c0 | 689,150 |
def get_line(s3_autoimport):
"""Build a list of relevant data to be printed.
Args:
s3_autoimport (S3ProjectImport): instance of
S3 autoimport
Returns:
list(str): list of relevant data to be printed
"""
return "\t".join(
[
str(s3_autoimport.id),
str(s3_autoimport.project_id),
str(s3_autoimport.s3_uri),
]
) | 0624af6e6ce02f23baedda01fb30c4c62c01b7e4 | 689,153 |
def FindPhaseByID(phase_id, phases):
"""Find the specified phase, or return None"""
for phase in phases:
if phase.phase_id == phase_id:
return phase
return None | 5544d47139a00cb6e0e33486031ff49796092907 | 689,154 |
def dataToString(var, data):
"""Given a tuple of data, and a name to save it as
returns var <- c(data)
"""
#convert data to strings
d = [str(d) for d in data]
return "%s <- c(%s)" % (var, ",".join(d)) | dcfb8e443f0a8f8c783047190822c7194104fc44 | 689,155 |
def alt_ternary_handle(tokens):
"""Handle if ... then ... else ternary operator."""
cond, if_true, if_false = tokens
return "{if_true} if {cond} else {if_false}".format(cond=cond, if_true=if_true, if_false=if_false) | d41d4e67f66282648cc13f4e678c8e712c41e01c | 689,156 |
def extract_volume_number(value):
"""Extract the volume number from a string, returns None if not matched."""
return value.replace("v.", "").replace("v .", "").strip() | 50b25b9c33ae62f2e61165ca36648cbe09e39883 | 689,158 |
def get_full_exception_name(exception: Exception) -> str:
"""Get the full exception name
i.e. get sqlalchemy.exc.IntegrityError instead of just IntegrityError
"""
module = exception.__class__.__module__
if module is None or module == str.__class__.__module__:
return exception.__class__.__name__
return module + "." + exception.__class__.__name__ | a188427bbf12d861990c784c65f4d524734ba787 | 689,159 |
def prettyTimeDelta (seconds):
"""
Pretty-print seconds to human readable string 1d 1h 1m 1s
"""
seconds = int(seconds)
days, seconds = divmod(seconds, 86400)
hours, seconds = divmod(seconds, 3600)
minutes, seconds = divmod(seconds, 60)
s = [(days, 'd'), (hours, 'h'), (minutes, 'm'), (seconds, 's')]
s = filter (lambda x: x[0] != 0, s)
return ' '.join (map (lambda x: '{}{}'.format (*x), s)) | 9c52730208782c628ddc26ee7b3570b9f962eb7d | 689,161 |
def _convert_snake_to_pascal(snake_case_string: str) -> str:
"""
Convert a string provided in snake_case to PascalCase
"""
return ''.join(word.capitalize() for word in snake_case_string.split('_')) | 41fd25da7fa5b6f120fae63aafb5bed1438256bd | 689,162 |
def read_file_str(file_path: str) -> str:
"""
Read the target file string.
Parameters
----------
file_path : str
Path of target file.
Returns
-------
file_str : str
The target string read.
"""
with open(file_path, mode='r', encoding='utf-8') as f:
file_str: str = f.read()
return file_str | 01ac8056896b7b40102c032e7a9b132cec0cbb6b | 689,163 |
def getHlAtt(app, n, highlights, isSlot):
"""Get the highlight attribute and style for a node for both pretty and plain modes.
Parameters
----------
app: obj
The high-level API object
n: int
The node to be highlighted
highlights: set|dict
The nodes to be highlighted.
Keys/elements are the nodes to be highlighted.
This function is only interested in whether `n` is in it,
and if so, what the value is (in case of a dict).
If given as set: use the default highlight color.
If given as dict: use the value as color.
isSlot: boolean
Whether the node has the slotType
Returns
-------
hlCls: dict
Highlight attribute, keyed by boolean 'is pretty'
hlStyle: dict
Highlight color as css style, keyed by boolean 'is pretty'
"""
noResult = ({True: "", False: ""}, {True: "", False: ""})
if highlights is None:
return noResult
color = (
highlights.get(n, None)
if type(highlights) is dict
else ""
if n in highlights
else None
)
if color is None:
return noResult
hlCls = {True: "hl", False: "hl" if isSlot else "hlbx"}
hlObject = {True: "background", False: "background" if isSlot else "border"}
hlCls = {b: hlCls[b] for b in (True, False)}
hlStyle = {
b: f' style="{hlObject[b]}-color: {color};" ' if color != "" else ""
for b in (True, False)
}
return (hlCls, hlStyle) | 5e6119cd8fb5622589d84e8831e3e12a02d673c6 | 689,168 |
def dir_tree_find(tree, kind):
"""Find nodes of the given kind from a directory tree structure
Parameters
----------
tree : dict
Directory tree.
kind : int
Kind to find.
Returns
-------
nodes : list
List of matching nodes.
"""
nodes = []
if isinstance(tree, list):
for t in tree:
nodes += dir_tree_find(t, kind)
else:
# Am I desirable myself?
if tree['block'] == kind:
nodes.append(tree)
# Search the subtrees
for child in tree['children']:
nodes += dir_tree_find(child, kind)
return nodes | 935021a2daae3cc53f1e9a44961643171c5a5fc2 | 689,169 |
def solve_tridiag(a, b, c, d, overwrite_bd=False):
"""
Solve a tridiagonal equation system using the Thomas algorithm.
The equivalent using scipy.linalg.solve_banded would be:
ab = np.zeros((3, len(a)))
ab[0, 1:] = c[:-1]
ab[1, :] = b
ab[2, :-1] = a[1:]
x = scipy.linalg.solve_banded((1, 1), ab, d)
Parameters
----------
a : ndarray
Lower diagonal of the tridiagonal matrix as a length n array with
elements (0, a_2, a_3, ..., a_n).
b : ndarray
Main diagonal of the tridiagonal matrix as a length n array with
elements (b_1, ..., b_n).
c : ndarray
Upper diagonal of the tridiagonal matrix as a length n array with
elements (c_1, ..., c_n-1, 0).
d : ndarray
Right hand side of the matrix system as a length n array.
Returns
-------
x : ndarray
Solution vector as a length n array.
"""
n = len(d) # number of equations
if not overwrite_bd:
b = b.copy()
d = d.copy()
for k in range(1, n):
m = a[k] / b[k - 1]
b[k] = b[k] - m * c[k - 1]
d[k] = d[k] - m * d[k - 1]
x = b
x[-1] = d[-1] / b[-1]
for k in range(n - 2, 0 - 1, -1):
x[k] = (d[k] - c[k] * x[k + 1]) / b[k]
return x | af25c811fa1b74b571995ddc531e31bda9efbf59 | 689,171 |
def intToDBaseTuple(x, dim, D):
"""
Transfer a integer to a base-D fixed-length tuple of digits.
Parameters
----------
x : int
A positive integer to be transformed into base-D.
dim : int
The length of digit tuple as the output.
D : int
The base of the digit tuple.
Returns
-------
tuple of ints
[0, D - 1) of the digit tuple, of size (dim, )
"""
res = []
for _ in range(dim):
res.append(x % D)
x = x // D
return tuple(res) | 7f5567aa92602743dfccae026d6c266049092e43 | 689,173 |
def list_product(num_list):
"""Multiplies all of the numbers in a list
"""
product = 1
for x in num_list:
product *= x
return product | 3d6d56f03817f9b4db0e7671f6c95c229a14a042 | 689,175 |
def lin_interp(x, x0, x1, y0, y1):
""" Simple helper function for linear interpolation. Estimates the value of y at x
by linearly interpolating between points (x0, y0) and (x1, y1), where x0 <= x < x1.
Args:
x: Float. x-value for which to esrimate y
x0: Float. x-value of point 0
x1: Float. x-value of point 1
y0: Float. y-value of point 0
y1: Float. y-value of point 1
Returns:
Float. Estimated value of y at x.
"""
y = y0 + (y1-y0)*(x-x0)/(x1-x0)
return y | 07efe42eda983bb9221c26df73bc260204830c53 | 689,179 |
def output_size(W, F, P, S):
"""
https://adventuresinmachinelearning.com/convolutional-neural-networks-tutorial-in-pytorch/
:param W: width in
:param F: filter diameter
:param P: padding
:param S: stride
:return:width out
"""
return (W-F+2*P)/S + 1 | 06bb0e4c6d8b6d46b7ddc4300dd925a8203e9b16 | 689,180 |
import torch
def out_degree(adjacency: torch.Tensor) -> torch.Tensor:
"""Compute out-degrees of nodes in a graph.
Parameters
----------
adjacency
Adjacency matrix.
Shape: :math:`(N_{nodes},N_{nodes})`
Returns
-------
torch.Tensor
Nodewise out-degree tensor.
Shape: :math:`(N_{nodes},)`
"""
return adjacency.sum(dim=1) | 92eec222cf125135b6bcd711dcef6cb7144f2a59 | 689,182 |
def is_fasta_file_extension(file_name):
"""
Check if file has fasta extension
Parameters
----------
file_name : str
file name
Returns
-------
bool
True if file has fasta extension, False otherwise
"""
if file_name[-4:] == ".fna":
return True
elif file_name[-4:] == ".faa":
return True
elif file_name[-6:] == ".fasta":
return True
elif file_name[-6:] == ".fastq":
return True
elif file_name[-3:] == ".fa":
return True
else:
return False | 711267ab304ca188b03f3a7e816a0df70c3f4fa3 | 689,185 |
from typing import Union
def _get_remainder(code: Union[list, int]) -> int:
"""Calculate remainder of validation calculations.
:param Union[list, int] code: input code
:return: remainder of calculations
:rtype: int
:raises TypeError: if code is not a list or an integer
"""
# raise an exception if code is not a list or an integer
if not isinstance(code, (list, int)):
raise TypeError('code should be a list or an integer')
# convert integer code to a list of integers
if isinstance(code, int):
code = list(map(int, str(code)))
# a 10 to 2 list, it will be used for next calculation
reversed_range = range(10, 1, -1)
# calculate the remainder of CodeMelli formula division
return sum([i * j for i, j in zip(code, reversed_range)]) % 11 | c235512d66e1041ab30c376b1e7682a085d27dcc | 689,186 |
def _is_group(token):
"""
sqlparse 0.2.2 changed it from a callable to a bool property
"""
is_group = token.is_group
if isinstance(is_group, bool):
return is_group
else:
return is_group() | 91b8a9a18831c46a878fbbacf72a0ebe9f4f4fdf | 689,187 |
import warnings
def force_connect(client):
"""
Convenience to wait for a newly-constructed client to connect.
Taken from pymongo test.utils.connected.
"""
with warnings.catch_warnings():
# Ignore warning that "ismaster" is always routed to primary even
# if client's read preference isn't PRIMARY.
warnings.simplefilter("ignore", UserWarning)
client.admin.command("ismaster") # Force connection.
return client | a9a49ff79108f38a10215aaab3ee371b860f6270 | 689,190 |
def unescape(st):
"""
Unescape special chars and return the given string *st*.
**Examples**:
>>> unescape('\\\\t and \\\\n and \\\\r and \\\\" and \\\\\\\\')
'\\t and \\n and \\r and " and \\\\'
"""
st = st.replace(r'\"', '"')
st = st.replace(r'\n', '\n')
st = st.replace(r'\r', '\r')
st = st.replace(r'\t', '\t')
st = st.replace(r'\\', '\\')
return st | bce4370ace1162b96a8c4d4e175903b2d8c2e929 | 689,198 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.