content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import pwd
def parse_uid(uid):
"""Parse user id.
uid can be an interger (uid) or a string (username), if a username
the uid is taken from the password file.
"""
try:
return int(uid)
except ValueError:
if pwd:
return pwd.getpwnam(uid).pw_uid
raise | 602d133647ab58dfc3363bea30df46bcd398fceb | 644,499 |
def ngrams(iterable, n=1):
"""Generate ngrams from an iterable
l = range(5)
list(l) -> [0, 1, 2, 3, 4, 5]
list(ngrams(l, n=1)) -> [(0,), (1,), (2,), (3,), (4,)]
list(ngrams(l, n=2)) -> [(0, 1), (1, 2), (2, 3), (3, 4)]
list(ngrams(l, n=3)) -> [(0, 1, 2), (1, 2, 3), (2, 3, 4)]
"""
... | d3a4cbbc87ae6135de663d7e71f4385292732898 | 644,504 |
def counter(string):
"""
Calculate count of elements in string.
"""
result = [f'Count of {elem} = {string.count(elem)}\n'for elem in set(string)]
return "".join(result) | 5a14b0894e5c0690eed267cd3dcaf267349d47d1 | 644,505 |
def try_key(dictionary, key, default):
"""
Try to get the value at dict[key]
:param dictionary: A Python dict
:param key: A key
:param default: The value to return if the key doesn't exist
:return: Either dictionary[key] or default if it doesn't exist.
"""
try:
return dictionary[... | e83b181d8b70a62ca819f8d0356198fbd07b2548 | 644,507 |
def generate_coordinate_rect(x_start, x_finish, y_start, y_finish):
"""
Generate tuples for coordinates in rectangle (x_start, x_finish) -> (y_start, y_finish)
"""
coords = []
for i in range(x_start, x_finish):
for j in range(y_start, y_finish):
coords.append((i, j))
return c... | e7e950b455dc74e483bcf401e1a5998c3f4cf088 | 644,508 |
def detect_cycle(head):
"""
Question 8.4: Detect a cycle in a singly-linked list.
Return None if there is no cycle.
If there is, return the first node in the cycle.
"""
slow = head
fast = head
cycle_length = 0
while fast and fast.next and fast.next.next:
slow = slow.next
... | 636884bd0e595cd37c814bb8e215b43d6b48a131 | 644,509 |
def stdDevOfLengths(L):
"""
L: a list of strings
returns: float, the standard deviation of the lengths of the strings,
or NaN if L is empty.
"""
if (len(L) == 0):
return float('NaN')
# compute mean first
sumVals = 0
for s in L:
sumVals += len(s)
meanV... | 51883d29bf078c5a974a92fb9289fa5e07fea2c9 | 644,512 |
def get_add_llil(src):
"""
Returns llil to add
:param src: source of operation
:return: generator for llil expression for add
"""
def add_llil(il, instr):
return il.set_reg(4, 'a', il.add(4, il.reg(4, 'a'), src(il, instr)))
return add_llil | 62d35ccbfdf976bb6d301a0010c3a30f91af1bf5 | 644,513 |
import json
def ReportJson(build_statuses):
"""Generate the json description of a given build.
Args:
build_statuses: List of build_status dict's from FetchBuildStatus.
Returns:
str to display as the final report.
"""
report = {}
for build_status in build_statuses:
report[build_status['build... | 3ea482787541ee962e1d48e23614143c235974d3 | 644,515 |
def get_static_data(modelSpec):
"""
Return a dictionary of static values that all objects of this model
have.
This applies only to kubernetes resources where ``kind`` and
``apiVersion`` are statically determined by the resource. See the
`Kubernetes OpenAPI Spec Readme`__.
For example for a... | 6b06d3fc05bc53ed0a6436f57ff7a1f89ef46b65 | 644,516 |
def usernameslist(data):
"""
Returns list of usernames of all users.
"""
return [u['name'] for u in data['users']] | 6efd89d2c63af074ebf2a7133a8680be40c08679 | 644,517 |
import math
def distATT(x1,y1,x2,y2):
"""Compute the ATT distance between two points (see TSPLIB documentation)"""
xd = x2 - x1
yd = y2 - y1
rij = math.sqrt((xd*xd + yd*yd) /10.)
tij = int(rij + .5)
if tij < rij:
return tij + 1
else:
return tij | ce704b491d401998afc3dc394452f10825c4afbd | 644,521 |
import time
def gen_filename(sample, dist, temp):
"""
Function to generate the string to use as the filename of the
output file. The information contained in the filename are hardcoded
to match our requirements, but can be easily changed.
Parameters
----------
sample: str
Str... | 062f8bf59f25bf8f6948666bee1ee458b8ccffb6 | 644,524 |
import random
def roll(sides):
""" Roll a (sides) sided die and return the value. 1 <= N <= sides """
return random.randint(1,sides) | aea500961fad3612cf4e42507776a6f754480081 | 644,525 |
import re
def splitCIGAR(SAM_CIGAR):
"""
Split CIGAR string into list of tuples with format (len,operator)
"""
CIGARlist = list()
for x in re.findall('[0-9]*[A-Z|=]',SAM_CIGAR):
CIGARlist.append((int(re.findall('[0-9]*', x)[0]),re.findall('[A-Z]|=', x)[0]))
#174M76S --> [(174,M),(76,S)... | d2fbe4e4280c52ad4673f4928fcce39b06f54818 | 644,526 |
def actionToGcdType(actionType) :
"""Returns the gcdType matching a given actionType
"""
if actionType == 'gcdSkill':
return 'global'
elif actionType == 'instantSkill':
return 'instant' | 67090086864cae075561c04e26f05f30631ff4fd | 644,536 |
import math
def radians_to_degrees(radians):
"""Convert radians to degrees."""
return 180.0 * radians / math.pi | 63d166846ba9bd21a665e74ffbfea8bf2c1cc5be | 644,542 |
def ask(prompt, type_=None, min_=None, max_=None, range_=None):
"""Get user input of a certain type, with range and min/max options."""
if min_ is not None and max_ is not None and max_ < min_:
raise ValueError("min_ must be less than or equal to max_.")
while True:
ui = input(prompt)
... | 76d7e9b9b4623867b4a1d12328fdb7022618cac3 | 644,548 |
def form_metaquast_cmd_list(metaquast_fp, outdir, input_fasta):
"""format argument received to generate list to be used for metquast subprocess call
Args:
metaquast_fp(str): the string representing the path to metaquast executable
outdir(str): the string representing the path to the output dire... | 9a6d2e1419db4c8e630e7bf6577ac02f5c7bf7a8 | 644,552 |
def robots(environ):
"""Returns robots.txt"""
status = "200 OK"
responseHeaders = [("Content-type", "text/plain")]
with open("robots.txt", "r") as f:
output = f.read()
return status, responseHeaders, output | af505f736841057db8b16070b58a8131267445d8 | 644,555 |
def train(data, length=50):
"""Return average of last n data samples.
Args:
data (np.ndarray): Time series data
length (int, optional): Length of used window (last n values). Defaults to 50.
"""
return data.ravel()[-length:].mean() | eb68064433489b7fe933ce8cc6d7c6839b2b9179 | 644,558 |
def find_location(index, SIZE):
"""
Finds the x and y coordinates in a square grid of SIZE**2 given an index.
It is assumed that we are counting from left to right on a set of rows top-down, and that area is square.
Rows and columns start from 0 given Python indexing conventions.
e.g.
0... | 5120079db5e720df7373e186d8235da189b108c0 | 644,560 |
def extract_golden_standard(path_to_standard):
"""
Extracts the golden standard associations into a dict
:param path_to_standard: str, path to the golden standard associations
:return: list<(word<str>, meaning<str>)> tuples
"""
lexicon = set()
with open(path_to_standard) as f:
for l... | 9b49188f19e147a30d19583afe1f5051bc8a3de0 | 644,561 |
import json
def read_json(filename):
"""
Opens the file, reads the data, closes it and turns it into a dictionary.
Parameters
----------
filename : string
The filename of a JSON file to be opened and read.
Returns
-------
Dictionary
The JSON data in the file as a Pyt... | 9ad68d5605162b22e67a4706f212e25d4d826cc0 | 644,563 |
def empty_units(number: int, from_unit: int) -> int:
"""
Puts zeros on all digits from the from_unit
num being 152 and from_unit being 1 gives 100
"""
mask: int = int(10 ** (from_unit + 1))
return number - (number % mask) | d85797380ea17297aa0a7df79d7c80e875b33803 | 644,568 |
def subtract(a, b):
"""
Returns the result of subtracting b from a
>>> subtract(2, 1)
1
>>> subtract(10, 10)
0
>>> subtract(7, 10)
-3
"""
return a - b | a64b604490905fc967230fb8cc9e8359f0b489f7 | 644,569 |
def to_celsius(temp):
"""Converts temperature in Kelvin to Celsius"""
temp_in_c = round(temp-273.15)
return temp_in_c | e59c9c94ba42c369c7eb9721c8017baa340512aa | 644,570 |
import torch
def logistic_rsample(mu_ls):
"""
Returns a sample from Logistic with specified mean and log scale.
:param mu_ls: a tensor containing mean and log scale along dim=1,
or a tuple (mean, log scale)
:return: a reparameterized sample with the same size as the input
mean ... | 9d66a21865b051fc919b0c179b928d1aab60a53f | 644,572 |
def make_record(type_name, attributes, defaults=None):
"""Factory for mutable record classes.
A record acts just like a collections.namedtuple except slots are writable.
One exception is that record classes are not equivalent to tuples or other
record classes of the same length.
Note, each call to `make_rec... | 3ee5f454890779e8a32658a25a437767ceecb1f9 | 644,573 |
def n_max_matchings(A, B):
"""
Compute the number of maximum matchings in a complete bipartite graph on A + B vertices.
A and B are required to be nonnegative.
Corner Case: If at least one of the sides has zero vertices, there is one maximal matching: the empty set.
"""
a = min(A, B)
b = max... | 32ee6e331e48a8ee2b7d5234a6ca033b895f6d75 | 644,575 |
def generate_product_instance_id(vm_fqn, product_name, product_version):
"""
Method to generate instance id for installed products (product instances)
:param vm_fqn: FQN (where product has been installed)
:param product_name: Product name (instance)
:param product_version: Product release (instance)... | d9c5d3aecff66f7263955e400ba98d5625f783fc | 644,577 |
from datetime import datetime
def get_gldas_start_date(product):
"""
Get NOAH GLDAS start date.
Parameters
----------
product : str
Product name.
Returns
-------
start_date : datetime
Start date of NOAH GLDAS product.
"""
dt_dict = {
"GLDAS_Noah_v20_02... | 2bbab8ad593bf5030468a11bf673e412e9b5ab32 | 644,579 |
from typing import List
def adjacent_digits(n: int, digits: str) -> List[str]:
"""List of all adjacent digits of `n` length in `digits`."""
adjacents = []
while len(digits) >= n:
adjacents.append(digits[:n])
digits = digits[1:]
return adjacents | 2a2f1dabf2b6a48937d70892ceb2054d7f74274b | 644,583 |
def descriptor_target_split(file):
"""
Split the input data into descriptors and target DataFrames
Parameters:
file: pandas.DataFrame
Input DataFrame containing descriptors and target data.
Returns:
descriptors: pandas.DataFrame
Descriptors... | 95d518ee9cce190ed08015986fc5b2d86c33318a | 644,584 |
import codecs
import json
def dump(data, handle, **kwargs):
"""Serialize ``data`` as a JSON formatted stream to ``handle``.
We use ``ensure_ascii=False`` to write unicode characters specifically as this improves the readability of the json
and reduces the file size.
"""
try:
if 'b' in han... | 2d8ad1f1693ea3e41ec855934302ac0d396ee996 | 644,585 |
def format_file_size(size):
"""according file size return human format
Arguments:
size {int} -- file size
Returns:
str -- human format file size
"""
if size < 1024:
return '%i' % size + 'B'
if 1024 <= size < 1024 ** 2:
return '%.1f' % float(size / 1024) + 'K'
... | 15342db32a0b8ca08f5857a1907aecef68e1eb5f | 644,589 |
def get_all_duplicate(df, column_list):
"""
Get all duplicated rows.
Extract all rows that the return value of 'DataFrame.duplicated' is true.
Raises
------
ValueError
If the input DataFrame is empty.
Parameters
----------
df : DataFrame
Base dataframe (required)
... | 89daffd32f40a80643736f0d754718345c494e3a | 644,591 |
def isMixedCase (tok):
"""Returns true if the token contains at least one upper-case letter and another character type,
which may be either a lower-case letter or a non-letter. Examples: ProSys, eBay """
# Clojure original:
# (fn [token] ;; ProSys, eBay
# (if-not (empty? token)
... | e163d0adc5ce7af2f4bf25afbaf690f30fdb62d1 | 644,595 |
import statistics
def minMaxAvgPerBin(binnedResults, statFunction):
"""
For each bin in the binned results, find the minimum, maximum, and average of the value of the results determined
by statFunction. The constants MMAMin, MMAMax, and MMAAvg are meant for accessing the results tuple data.
:param bin... | 3cb11ac83d816404e8ae4a32acae5183afb365a1 | 644,597 |
def is_heavy_atom(atom):
"""Check if an atom is neither a hydrogen or a virtual site."""
return not (atom.resname.startswith("H") or atom.resname.startswith("M")) | f78a2b2d849a054b28b33c7590c26319e365f41f | 644,598 |
def split_content(content):
"""
Split the rule into a list of bags.
"""
bags = []
# Return an empty list if there is no content.
if "no other" in content: return bags
# Separate each type of bag.
for bag in content.replace("bags", "").replace("bag", "").split(","):
# Separat... | e976f35688e3c391afdff309970d7d956e987d60 | 644,600 |
import re
def sanitize_output(output):
"""Redact access tokens from CLI output to prevent error messages revealing them"""
return re.sub(r"\"accessToken\": \"(.*?)(\"|$)", "****", output) | 07472b6a7289db9400e56d94d5691fb2f09ba416 | 644,602 |
def to_upper(text):
"""Convert word to uppercase."""
return text.upper().strip() | 7721b9881babef2de879471f44ad848c4f51876a | 644,610 |
def shiftLeft(input, p):
"""Take a bitstring 'input' of arbitrary length. Shift it left by 'p'
places. Left means that the 'p' most significant bits are shifted out
and dropped, while 'p' 0s are inserted in the the least significant
bits. Note that, because the bitstring representation is little-endian,... | 514a1c6f3bd60adc3a095a9dfea9c2468e8a4b38 | 644,614 |
def get_y_values(x: int, slopes: list, coordinates, edge_count: int) -> list:
"""
Calculate the y value of the current x from each edge
:param x: x-coordinate of the current node
:param slopes:a list of slopes of all edges of the polygon
:param coordinates: a list of vertices of the polygon
:par... | 846fd515706eb17b5a564daab8a293037cae6641 | 644,615 |
def create_norm_peptide_column_if_needed(row_meta_df, gcp_normalization_peptide_field, gcp_normalization_peptide_id):
"""If it doesn't already exist, create a new column indicating the norm
peptide for each probe.
Modifies row_meta_df in-place.
Args:
row_meta_df (pandas df):
gcp_normal... | 2b499bb23a186a6c7bff46998a2377fa38b8f114 | 644,617 |
def get_peak_indices(uvvis_obj):
"""Finds indices of unique value/extinction objects at 'peak' scope
:param chemdataextractor.model.UvvisSpectrum uvvis_obj : UvvisSpectrum containng peak data
:returns
list value_peak_indices : UvvisPeak indices pointing to objects solely containing uvvis values
... | f5e14840813c72d83b2ed0ed6f4369822a1da28a | 644,619 |
import six
def _process_model_like_filter(model, query, filters):
"""Applies regex expression filtering to a query.
:param model: model to apply filters to
:param query: query to apply filters to
:param filters: dictionary of filters with regex values
:returns: the updated query.
"""
if q... | 25e1588a2ef50cea04556c6b2046c855bb83d620 | 644,620 |
def to_bool(cfg_value):
"""Convert config file booleans to Python booleans."""
if cfg_value in {"0", "false", "False", "no"}:
return False
if cfg_value in {"1", "true", "True", "yes"}:
return True
raise ValueError("Value {} in config file must be boolean in"
" a form... | 5908a6cc9386678ce7f76b3746b7a42dcaa15964 | 644,623 |
def solve_game(best_actions, game, state):
"""Returns the value of the state (to both players) and the optimal move to
play in this state. Fills in the dictionary 'best_actions' with the best
actions to take in all the states that are descendants of state (including
state).
"""
if game.is_termin... | 78fad694b533f3ef9ddcc70546b38a271181add1 | 644,627 |
def truth(a):
"""Return True if a is true, False otherwise."""
return True if a else False | b98d494fc05fd1bdf3e63b6e6d64cece0c5c2f2d | 644,629 |
def invert_permutation(perm):
"""Implement `invert_permutation`."""
return tuple(perm.index(i) for i in range(len(perm))) | 5bf59a37e490ab93d5fb2d4d1b40c5c5a5a22348 | 644,630 |
def manhattan_distance(point_1, point_2):
"""Return Manhattan distance between two points."""
return sum(abs(a - b) for a, b in zip(point_1, point_2)) | 48808356b202751ce15481c186c3f981481fee91 | 644,635 |
import json
def save_json(input_dict, output_file):
"""save dictionary to file as json. Returns the output file written.
Parameters
==========
content: the dictionary to save
output_file: the output_file to save to
"""
with open(output_file, "w") as filey:
filey.writel... | 05d5c8440f5d7e7a021d91136e2277031de53f18 | 644,636 |
def dwid_exists(dwid, cursor):
"""See if a dwid exists in the database or not. If yes, return 1,
if not return 0."""
array = (dwid,)
cursor.execute('SELECT * from dwids where dwid=?', array)
if cursor.fetchone():
return 1
else:
return 0 | 08586088a14cdc11f8308da3d3038667c672fc13 | 644,637 |
def standardize_name(name: str) -> str:
"""Remove spaces, hyphens, and make lowercase"""
if isinstance(name, str):
return name.replace('-', '').replace(' ', '').lower()
else:
return name | b856eddd4616161a1550d7b8a3f710b966972565 | 644,647 |
def partition(array):
""" partition split array in half """
return [array[len(array)//2:], array[:len(array)//2]] | 713caa069bad18dc5a5a7f69813de34075f8f3eb | 644,656 |
def create_body_dict(name, schema):
""" Create a body description from the name and the schema."""
body_dict = {}
if schema:
body_dict['in'] = 'body'
body_dict['name'] = name
body_dict['schema'] = schema
if 'description' in schema:
body_dict['description'] = schem... | dcdb57ea96c0d871ca1481bd523720aaa51d573b | 644,657 |
import torch
def add_noise(x_data, noise_std_percent):
"""
Adds normal noise to a dataset
@param noise_std_percent tensor with standard deviation of the noise,
as percent of the mean of the magnitude for that dimension
@return x_data_, same as x_data but with noise added to it
"""
assert (... | 4f9f98f36b829745ac9cec1bae43a0fcd2740954 | 644,661 |
def getDocComment(node):
"""
Returns the first doc comment of the given node.
"""
comments = getattr(node, "comments", None)
if comments:
for comment in comments:
if comment.variant == "doc":
return comment
return None | 4cc32f84d4e127880f9a137447e2d9401a6fbd6c | 644,668 |
def distance(a, b):
"""Return the distance between two points (rounded as per TSP datafile)"""
return int(abs(a - b) + 0.5) | c1664a48267854bf6c474323520d04188ce0656c | 644,669 |
def find_class_in_dict(cls, d, include=None, exclude=None):
"""Get a list of keys that are an instance of a class in a dict"""
names = []
for key, value in d.copy().items():
if not isinstance(value, type):
continue
if issubclass(value, cls):
if include and include not... | e9d4ad70a51e12d862a073256378e8a8c54c0680 | 644,671 |
import codecs
import re
def get_replies(message_file, charset=None):
""" Finds replies within a message and returns a list containing each reply.
Args:
message_file (str): The email's filename.
charset (str): The optional codec to use for opening the file.
Returns:
list: ... | 56e6f122b0995deff70e302ef9503fb73ca82a5a | 644,675 |
def has_repeating_letter(text):
"""Check if a string has a repeating letter with one letter in between"""
# Check every combination of three letters
# and see if the first and third are the same.
# If there is any such combination, return True, False otherwise.
for i in range(len(text) - 2):
... | 29b621526ad56c0a04d94f7a53b20e1486c362ad | 644,677 |
import socket
def canonv4(text):
"""canonicalize an IPv4 address"""
if text is None:
return None
try:
addr = socket.inet_pton(socket.AF_INET, text)
return socket.inet_ntop(socket.AF_INET, addr)
except socket.error:
#print 'canonv4 failed on', text
return None | aa502532100d0e434eb7a2a5c8b635f73634e56a | 644,678 |
def is_lock(lock):
"""
Tests if the given lock is an instance of a lock class
"""
if lock is None:
# Don't do useless tests
return False
for attr in ('acquire', 'release', '__enter__', '__exit__'):
if not hasattr(lock, attr):
# Missing something
retur... | d065d54b6c559f9855ef6e37258f0f77b4ebb2b3 | 644,681 |
def printable_str(string):
""" Helper function to convert non-printable chars to its ASCII format """
new_str = ''
for char in string:
if ord(char) >= 32 and ord(char) <= 126:
new_str = new_str + char
else:
new_str = new_str + (r'\x%02x' % ord(char))
return new_... | 82bd560a0c2f2f0f477b9640a5d13cb1e5554c2c | 644,686 |
from typing import Optional
import torch
def ConvNd(
dim: int,
in_channels: int,
out_channels: int,
kernel: int,
stride: int = 1,
dilation: int = 1,
groups: int = 1,
bias: bool = True,
transposed: bool = False,
output_padding: Optional[int] = None,
dtype=None,
):
"""Con... | 814152af6be6ad0175fc199fb7f8007063caf438 | 644,688 |
def _get_last_layer_units_and_activation(num_classes):
"""Gets the # units and activation function for the last network layer.
# Arguments
num_classes: int, number of classes.
# Returns
units, activation values.
"""
if num_classes == 2:
activation = 'sigmoid'
units ... | 17b7384218354c616652b9710e874c42deaf8b6a | 644,689 |
import torch
def qexp_t(q):
"""
Applies exponential map to log quaternion
:param q: N x 3
:return: N x 4
"""
n = torch.norm(q, p=2, dim=1, keepdim=True)
n = torch.clamp(n, min=1e-8)
q = q * torch.sin(n)
q = q / n
q = torch.cat((torch.cos(n), q), dim=1)
return q | 6db3edab4c2bbaf4176625f35381d456ee1aeaa5 | 644,690 |
def solve1(a, b, EPS=1e-6):
"""
Returns root of equation a*x + b = 0.
"""
# a*x + b = 0
if abs(a) < EPS:
return ()
else:
return (complex(-b/a),) | a5854fc6118e49ebf8b380903e838b310acc6a4a | 644,692 |
def get_val(op):
"""Get value of op."""
return op.gate.get_val() | 07b1b0ad7e766cb4758c8f2a913c6620178061ef | 644,693 |
import pickle
def load_data(pickle_file):
""" Load the data from given path.
Args:
pickle_file: pickle file of the requested data
Returns:
A tuple of (features, labels) for the given `pickle_file`
"""
with open(pickle_file, mode='rb') as f:
data = pickle.load(f)
retu... | 4c1f1a56114449feda8cd5450fb6535bb2bd4f65 | 644,694 |
def check_FS_true(output_hdul):
"""
This function checks if the fits file is a Fixed Slit.
Args:
output_hdul: the HDU list of the output header keywords
Returns:
result: boolean, if true, the file is assumed to be Fixed Slit
"""
result = False
if "EXP_TYPE" in output_hdul:
... | a58a629e6c4706333a15ad7f8481f24065b8866e | 644,695 |
def get_key_value(line, sep=":", strip_whitespace=True):
"""
Split a string into key and value parts.
The string must have a separator defined as an argument.
By default, the separator is ":".
An example of a valid string is "name: John Doe ".
The result will be: ("name": "John Doe")
[param... | da055a6a31acfe229190fad0dfca8abe3104d3eb | 644,699 |
def pool_list(transport, request, **kwargs):
"""Gets a list of pools
:param transport: Transport instance to use
:type transport: `transport.base.Transport`
:param request: Request instance ready to be sent.
:type request: `transport.request.Request`
:param kwargs: Optional arguments for this o... | c55a7eb4e5374cb87a168defbaf6d78414e2229b | 644,700 |
def ranks(x, reverse=False):
"""
Returns a tuple containing the rank of each element of the iterable `x`.
The ranks start at `0`. If `reverse` is `False`, the elements of `x` are
ranked in ascending order, and in descending order otherwise.
Equal elements will all be assigned the same (lowest-poss... | 7d8aa94b42eaf2b699fa113ca105907c40f6dc62 | 644,701 |
def to_camel(string: str) -> str:
"""Convert snake_case to camelCase."""
words = []
for num, word in enumerate(string.split("_")):
if num > 0:
word = word.capitalize()
words.append(word)
return "".join(words) | af9967e065573d61b01381aad8c866a402d9e5a0 | 644,702 |
def inrange(value: int, down_limit: int, top_limit: int) -> bool:
"""
Check if number is in specified range and return bool.
"""
if value in range(down_limit, top_limit + 1):
return True
else:
return False | 305c1b62c8857a4e2a74707e258c056f6b0565f7 | 644,704 |
def vowel_count(phrase):
"""Return frequency map of vowels, case-insensitive.
>>> vowel_count('rithm school')
{'i': 1, 'o': 2}
>>> vowel_count('HOW ARE YOU? i am great!')
{'o': 2, 'a': 3, 'e': 2, 'u': 1, 'i': 1}
"""
d = {}
v = set('aeiou')
for c in phrase.l... | 762fc26228fb77040c25249f0a57f3deefad8362 | 644,705 |
def HImass2flux(m_hi, D):
"""
Converts HI masses into observed fluxes, depending on the distance
Input
-----
M : float or ndarray
HI mass in solar masses
D : float
Distance in Mpc
Returns
-------
S : Flux in Jy km/s
"""
S = m_hi / 2.36e5 / D**2
return S | 028ed2f49b66fe560df4455f59cc39a840114499 | 644,707 |
import yaml
def get_rule_set(args):
"""Read and parse the config file at the location given when the
linter script is run.
Parameters
----------
args : argparse.Namespace
Arguments input when script is called from the console
Returns
-------
dict
Contains structured d... | 335b5e73c721f8ca276690444ede1f88fd33c2e9 | 644,712 |
def str_range(start, end):
"""get range with string type"""
return [str(i) for i in range(start, end)] | 7ed8aab00ed414a58439a6ebc5a196ac1ff24ca8 | 644,716 |
def get_moves(pos, xs, ys, step):
"""
Get the 5 possible moves from a position given a constant speed.
(left, right, forward, back, stay still)
:param pos:
:param xs:
:param ys:
:param step:
:return:
"""
moves = []
for dx, dy in [(-step, 0), (step, 0), (0, -step), (0, step), ... | 31d3f6d54da0243370cfe649075cd12c6e2702bc | 644,720 |
from typing import Sequence
def apply_weights(values: Sequence[float], weights: Sequence[float]):
"""
Returns values[0] * weights[0] + values[1] * weights[1] + ... + values[n] * weights[n]
"""
return sum([v[0] * v[1] for v in zip(values, weights)]) | 22e1e2decc29a2c5cdf0d34d97cb70cd3e144d85 | 644,721 |
import math
def move_time(move, eres):
""" Calculates the time it takes to do a move.
Calculates how long it will take to complete a move of the motor. It
is assumed that the motor will decerate to a stop for the end of the
move as opposed to keep moving at velocity.
Everything is in motor units... | 7e71f4c484a9b5553916cc541b4ceaee658fb814 | 644,723 |
def splitIndentDeepness(text):
"""
Return tuple (d, t) where d is deepness of indentation and t is text
without the indentation.
"""
pl = len(text)
text = text.lstrip()
return (pl-len(text), text) | 8a16f023c5d66a53a0f2afe86e6832c3363d66af | 644,726 |
def mjd2met(mjd):
"""
Converts Modified Julian Day in Mission Elapsed Time (MET, in seconds).
Cf. http://fermi.gsfc.nasa.gov/ssc/data/analysis/documentation/Cicerone/Cicerone_Data/Time_in_ScienceTools.html
to see how the time is handled in the Fermi Science Tools.
Input: time in MJD (fraction of a... | 9721ebe622af3a9fe58176a292dd77469095d617 | 644,727 |
from typing import Union
def is_union(etype) -> bool:
""" Determine whether etype is a Union """
return type(etype) == type(Union) | 6bb449b336eeb3e94501781ef39de3ef66a7110f | 644,730 |
def figsize(relwidth=1, aspect=.618, refwidth=6.5):
"""
Return figure dimensions from a relative width (to a reference width) and
aspect ratio (default: 1/golden ratio).
"""
width = relwidth * refwidth
return width, width*aspect | 496a5377bb8ffa9bebe4d1cd6080013b70742bd1 | 644,734 |
def trim_urls(attrs, new=False):
"""Bleach linkify callback to shorten overly-long URLs in the text.
Pretty much straight out of the bleach docs.
https://bleach.readthedocs.io/en/latest/linkify.html#altering-attributes
"""
if not new: # Only looking at newly-created links.
return attrs
... | 57558ab63f042708c88cabe8c9aee94c4237c05c | 644,735 |
def format_error_code(errorCode: int, descriptions: list) -> str:
"""Emergency error code -> description.
Args:
errorCode: Error code to check.
descriptions: Description table with (code, mask, description) entries.
Returns:
Text error description.
"""
description = 'Unknow... | cb13d0f4b338302966db883d69acd26cf1481e74 | 644,736 |
import re
def is_string_id(string_id):
"""Checks if a string is a valid user ID string"""
if re.match('<@![0-9]+>', string_id):
return True
return False | 930f106a624f2c815c9551aa4a1a8eaebe6082ee | 644,738 |
def parse_list(list_string):
"""
Parses IPv6/prefix/route list string (output of wpanctl get for properties WPAN_IP6_ALL_ADDRESSES,
IP6_MULTICAST_ADDRESSES, WPAN_THREAD_ON_MESH_PREFIXES, ...)
Returns an array of strings each containing an IPv6/prefix/route entry.
"""
# List string example (get(W... | b9088f0e36c7f4d21f624c6838905bd9f52d5424 | 644,747 |
def lightness_glasser1958(Y, **kwargs):
"""
Returns the *Lightness* :math:`L^*` of given *luminance* :math:`Y` using
*Glasser et al. (1958)* method.
Parameters
----------
Y : numeric
*luminance* :math:`Y`.
\*\*kwargs : \*\*, optional
Unused parameter provided for signature c... | f1af67296158c0b6c7589f887df51f17ac700daf | 644,751 |
def n_params(model):
"""Return the number of parameters in a pytorch model.
Args:
model (nn.Module): The model to analyze.
Returns:
int: The number of parameters in the model.
"""
pp = 0
for p in list(model.parameters()):
nn = 1
for s in list(p.size()):
... | 02bf6c5cf4c3a8cbbfce2bdf1525bcdc73aac686 | 644,754 |
def as_int(raw):
"""Return an int for the given raw value.
Return None for "falsey", non-zero values.
"""
if raw == 0:
return 0
elif not raw:
return None
else:
return int(raw) | c4048c4ec14251b61a9101d398b4f9a5a2920e5b | 644,756 |
import random
def Jitter(values, jitter=0.5):
"""Jitters the values by adding a uniform variate in (-jitter, jitter)."""
return [x + random.uniform(-jitter, jitter) for x in values] | 3ef6e8e85884b2b6ec472b1daa8bbe2d7450c481 | 644,757 |
from typing import OrderedDict
def alphabetically_sorted_dict(d):
"""
Returns a dictionary with all keys recursively sorted alphabetically
"""
ordered = OrderedDict()
for k, v in sorted(d.items()):
if isinstance(v, dict):
ordered[k] = alphabetically_sorted_dict(v)
else:... | 071d761d4d660480b34da954d3d0410bfacc5dfd | 644,758 |
def ensure_collection(value, collection_type):
"""Ensures that `value` is a `collection_type` collection.
:param value: A string or a collection
:param collection_type: A collection type, e.g. `set` or `list`
:return: a `collection_type` object containing the value
"""
return collection_type((v... | 9afa29fd0672d7ab2e65484fdd0c811781fb9f82 | 644,759 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.