content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from typing import List
def split_chunks_on(str_: str, maxlen: int, split_char='\n') -> List[str]:
"""
Split a long string along `split_char` such that all strings are smaller than but as close as
possible to `maxlen` size.
Lines that exceed `maxlen` size will not be split.
"""
len_split = len(split_char)
lines = str_.split(split_char)
parts = []
this_part = []
running_len = 0
for line in lines:
len_line = len(line) + len_split # can't forget the newline/split_char!
if len_line + running_len <= maxlen:
this_part.append(line)
running_len += len_line
else:
if this_part: # prevents empty part if the first line is a very long line
parts.append(this_part)
this_part = [line]
running_len = len_line
parts.append(this_part) # last one, not committed in loop
return [split_char.join(part) for part in parts] | 72e2702a1771d5bbc145234c736f62aeec42e7b5 | 96,133 |
def subpaths_from_list(page_list):
"""
Build node pairs (edges) from a list of page hits
:param page_list: list of page hits
:return: list of all possible node pairs
"""
return [[page, page_list[i + 1]] for i, page in enumerate(page_list) if i < len(page_list) - 1] | d2ec81527515a4eb8777245d1558b6cb5ef3ab4f | 96,139 |
def extract_glyphs_from_coverage(coverage):
"""Return a list of glyphs from a coverage."""
if isinstance(coverage, str):
return [coverage]
else:
return coverage.glyphs | a5af639d12fc05ad1fcb4a06f6562782b15e02a1 | 96,142 |
def RotCurve(vel, radius, C=0.3, p=1.35):
"""Create an analytic disk galaxy rotation curve.
Arguments:
vel -- The approximate maximum circular velocity.
radius -- The radius (or radii) at which to calculate the
rotation curve.
Keywords:
C -- Controls the radius at which the curve turns over,
in the same units as 'radius'.
p -- Controls the fall-off of the curve after the turn-over;
values expected to be between 1 and 1.5 for disks.
Returns the value of the rotation curve at the given radius.
See Bertola et al. 1991, ApJ, 373, 369 for more information.
"""
C_ = C # kpc
p_ = p
return vel * radius / ((radius**2 + C_**2)**(p_/2.)) | fe0910cb13af9206b0e3cb4e3e48c871a54542a5 | 96,160 |
def pixel_shuffle_1d(x, upscale_factor):
"""
Performs a pixel shuffle on the input signal
:param x: The input tensor to be dimension shuffled
:param upscale_factor: The upsample factor
:return: The shuffled tensor
"""
batch_size, channels, steps = x.size()
channels //= upscale_factor
input_view = x.contiguous().view(batch_size, channels, upscale_factor, steps)
shuffle_out = input_view.permute(0, 1, 3, 2).contiguous()
return shuffle_out.view(batch_size, channels, steps * upscale_factor) | 866f82de3b9de9c02d666417785a687e9c3401eb | 96,165 |
from typing import Any
def convert_state_to_str(input_state: Any):
"""
Convert a state built from a nested dictionaries, lists and tuples to a string
:param input_state:
:return:
"""
if isinstance(input_state, dict):
return {param_name: convert_state_to_str(input_state[param_name]) for param_name in input_state}
if isinstance(input_state, list):
return [convert_state_to_str(param) for param in input_state]
if isinstance(input_state, tuple):
return tuple((convert_state_to_str(param) for param in input_state))
return str(input_state) | 9b88be6637d7fcb1371c57ef46b2cdd793c28311 | 96,173 |
def predict_cluster(x, centroids):
"""
Given a vector of dimension D and a matrix of centroids of dimension VxD,
return the id of the closest cluster
:params np.array x:
the data to assign
:params np.array centroids:
a matrix of cluster centroids
:returns int:
cluster assignment
"""
return ((x - centroids) ** 2).sum(axis=1).argmin(axis=0) | 3cbd582bd3a947e3d0a11ad05db1ca98547372e5 | 96,175 |
import re
def _parse_code_and_reference_from_pluscode(pluscode):
"""Split a short Plus Code into a Plus Code and reference using regex. For example, "QXGV+XH Denver, CO, USA" will
return ("QXGV+XH", "Denver, CO, USA").
Parameters
----------
pluscode : str
A short Plus Code with a queryable reference location appended to it, delimited by whitespace.
Returns
-------
tuple
The short Plus Code and the reference.
"""
pattern = r"\w{1,8}\+\w{,7}"
code = None
for chunk in pluscode.split(" "):
match = re.search(pattern, chunk)
code = match.group(0) if match else code
if not code:
raise ValueError("Plus code could not be decoded.")
reference = pluscode.replace(code, "")
return (code, reference) | c128c2849187dd05ba8771b4066016fe3f2b2a69 | 96,176 |
def sarea(a, b, c):
"""Calculate the signed area of 3 points."""
return 0.5 * ((b[0]-a[0])*(c[1]-a[1]) - (c[0]-a[0])*(b[1]-a[1])) | a13440ede266b83700b91979a5bba2bcd548eb1a | 96,177 |
from typing import Dict
from typing import Any
def _add_schemas(schema_a: Dict[str, Any],
schema_b: Dict[str, Any]) -> Dict[str, Any]:
"""Add two bigquery schemas together."""
full_schema: Dict[str, Any] = {}
full_schema.update(schema_a)
full_schema.update(schema_b)
return full_schema | c8fb8bf7827217841202abdfca276b6529a047c8 | 96,178 |
def has_magnet(self):
"""Return if any of the Holes have magnets
Parameters
----------
self : LamHole
A LamHole object
Returns
-------
has_magnet : bool
True if any of the Holes have magnets
"""
has_mag = [hole.has_magnet() for hole in self.hole]
return any(has_mag) | 16b52b586b4057d33bb5e636fb41f86403d21852 | 96,182 |
def is_leap_year(year):
"""
Checks if a year is a leap year
:param year: Year
:type year int
:return:
:rtype: bool
"""
return True if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0 else False | 7eb6e51f5a0091d27d5c2a74a78b258a130cb5fb | 96,188 |
def boxSeries(ax,ser):
"""
This function draws a vertical box and whisker plot
:Arguments:
:type ax: matplotlib Axis2D
:param ax: Axis on which bar graph will be drawn
:type ser: pandas Series
:param ser: data to be plotted
:Return:
:type ax: Matplotlib Axis
:param ax: axis with bars graphed onto it
"""
bp = ax.boxplot(ser,showfliers=True)
for flier in bp['fliers']:
flier.set(marker='+', color='#FFFFFF')
return ax | f26c14ca48916e3748651ac2bc6017f1a785d246 | 96,194 |
import json
def writesJson(markov):
"""Encode Model markov in JSON format and write to string."""
serial = dict()
serial['absClasses'] = markov.absClasses
serial['cumDist'] = list(markov.cumDist.flatten())
serial['random'] = markov.random.getstate() # can be serialized
serial['state'] = markov.state
serial['tMatrix'] = list(markov.tMatrix.flatten())
serial['ontology'] = markov.ontology
return json.dumps(serial, indent=4) | 78252b4896b9b401b009a8edae13c5594c50291e | 96,195 |
def get_message(count, name, deleted=True):
"""Generates a message on the number of records inserted or deleted
Args:
count (int): The number of records
name (str): The table name
deleted (bool): The exception handler to wrap the function in
(default: True)
Examples:
>>> print(get_message(5, 'table'))
Deleted 5 records from table `table`.
>>> print(get_message(5, 'table', False))
Inserted 5 records into table `table`.
Returns
str: The message
"""
verb, prep = ('Deleted', 'from') if deleted else ('Inserted', 'into')
return '%s %s records %s table `%s`.' % (verb, count, prep, name) | 5f0fdaad023f6a6b0c55b33e3014e854e3aadd84 | 96,196 |
from typing import Optional
from typing import Union
from typing import Any
def ensure_list(arr: Optional[Union[Any, list[Any]]]) -> Optional[list[Any]]:
"""Wraps single value to list or return list as it is."""
if arr is not None and not isinstance(arr, list):
arr = [arr]
return arr | f94f18150649a2142c3ae61f69316bd982ca3c5a | 96,200 |
import math
def cosine_decay(base_lr, max_iteration, cur_step):
"""cosine learning rate decay
cosine learning rate decay with parameters proposed FixMatch
base_lr * cos( (7\pi cur_step) / (16 max_warmup_iter) )
Parameters
-----
base_lr: float
maximum learning rate
max_warmup_iter: int
maximum warmup iteration
cur_step: int
current iteration
"""
return base_lr * (math.cos( (7*math.pi*cur_step) / (16*max_iteration) )) | 1ab9b7bdddcca8d061c3da8d0bcaa7a8bdb75ad1 | 96,211 |
def get_category_name(id_, categories):
"""
Return category name
"""
if id_ is None or id_ == '':
return None
item = categories[int(id_)]
if item['active'] is True:
return item['name']
return None | ea52af6b6f2bd2ba9662f22d85b9434ef3da7fa8 | 96,213 |
def string_none(value):
"""
Convert the string 'none' to None
"""
is_string_none = not value or value.lower() == 'none'
return None if is_string_none else value | 9988a9b7e6b8a30c318a8926863585f3c2f902f9 | 96,217 |
import csv
def read_strong_csv(strong_meta_csv_path):
"""Read strongly labelled ground truth csv file.
Args:
strong_meta_csv_path: str
Returns:
meta_dict: {'a.wav': [{'onset': 3.0, 'offset': 5.0, 'label': 'Bus'},
{'onset': 4.0, 'offset': 7.0, 'label': 'Train'}
...],
...}
"""
with open(strong_meta_csv_path, 'r') as fr:
reader = csv.reader(fr, delimiter='\t')
lines = list(reader)
meta_dict = {}
for line in lines:
"""line: ['-5QrBL6MzLg_60.000_70.000.wav', '0.917', '2.029', 'Train horn']"""
[audio_name, onset, offset, label] = line
meta = {'onset': onset, 'offset': offset, 'label': label}
if audio_name in meta_dict:
meta_dict[audio_name].append(meta)
else:
meta_dict[audio_name] = [meta]
return meta_dict | 1654f2f716cdd57a506727723238b9c51d71d459 | 96,229 |
import re
def to_snake(s):
"""Convert string to snakes case."""
return re.sub(r'(\s|-)+', '_', s).lower() | a83dc5b505abb67d965c7f8c4b03a422718d7060 | 96,234 |
def clean_url(url):
"""Remove extraneous characters from URL.
Params:
- url: (type: string) URL to clean.
Returns:
- url: (type: string) clean URL.
"""
if url is None:
return None
if '??' in url:
url = url.split('??')[0]
if url.endswith('?'):
url = url[:-1]
if '`' in url:
url = url.replace('`', '')
return url | 41a8a6682d6778c757690cb3a8ad917001aa12e3 | 96,235 |
def deduplicate(constraints):
"""
Return a new ``constraints`` list with exact duplicated constraints removed.
"""
seen = set()
unique = []
for c in constraints:
if c not in seen:
unique.append(c)
seen.add(c)
return unique | cdbd51d99280baf61603e78cf9aea66f9bc0f73e | 96,241 |
def find_markers(body, marker):
"""
Find all the markers in body.
Parameters
----------
body : string
Input string to parse.
marker : character
Search parameter
Returns
-------
list
Input position where the marker was found.
"""
return [i for i, ch in enumerate(body) if ch == marker] | a965907060cb762605032b8d5f8de0be63cc6344 | 96,242 |
from typing import Counter
def count_repeated(sequence: list, nth_repeated: int) -> str:
"""
>>> sequence = ['Algorithms','Algorithm','Python','Python','The','Python','The']
>>> nth_repeated = 2
>>> print(count_repeated(sequence, nth_repeated))
The
"""
return "" if nth_repeated < 1 else Counter(sequence).most_common()[nth_repeated - 1][0] | efbf614677a3d3f71e724a89e64168525035b001 | 96,244 |
def median(seq):
"""Returns the median of *seq* - the numeric value separating the higher half
of a sample from the lower half. If there is an even number of elements in
*seq*, it returns the mean of the two middle values.
"""
sseq = sorted(seq)
length = len(seq)
if length % 2 == 1:
return sseq[int((length - 1) / 2)]
else:
return (sseq[int((length - 1) / 2)] + sseq[int(length / 2)]) / 2 | 110625e47c6e06fad48ff286dea7600fa3c30e24 | 96,245 |
def clamp_value(value, max_value=1.0, min_value=0.0):
"""Clamp a value between max and min
Args:
value (float): value to clamp
Kwargs:
max (float): max value
min (float): min value
Returns:
.float
"""
return max(min(value, max_value), min_value) | 8dbc949361a0c7aff5501bf2a9e3f3faa1821c98 | 96,246 |
import base64
def get_real_room_id(room_encoded):
"""Get a real room ID from a base64 encoded room ID"""
# I found this from a discussion with cisco
# roomId car be different is you are comming from a different endpoint (US/EU)
# This is maybe because of something hardcoded in hookbuster (cisco was not sure)
# They said they would take a look
try:
room_decode = base64.decodebytes(bytes(room_encoded, 'utf-8')).decode("utf-8").split('/')[-1]
except Exception:
room_decode = None
return room_decode | 56cae81a9ca061da706db56c5c97d5f37410ddc0 | 96,248 |
import hashlib
def UUID(self):
"""
Return the cluster UUID
(SHA1 digest of the cluster.ascii_grid representation).
"""
return hashlib.sha1(self.ascii_grid).hexdigest() | 8dc659c1bbfc97332f80bd187b35c133dc12de50 | 96,252 |
def same(*values):
"""
Check if all values in a sequence are equal.
Returns True on empty sequences.
Example
-------
>>> same(1, 1, 1, 1)
True
>>> same(1, 2, 1)
False
>>> same()
True
"""
if not values:
return True
first, rest = values[0], values[1:]
return all(value == first for value in rest) | 9fb20aa6095094eb9fb5110dd50e138a355f07a5 | 96,254 |
def reset_dupe_index(df, ind_name):
"""
Reset index and rename duplicate index column
Parameters:
df (pandas DataFrame): DataFrame to reset index
ind_name (str): Name of column to reset
Returns:
df (pandas DataFrame): DataFrame with reset duplicate index
"""
df.rename({ind_name: ind_name+'_back'}, inplace=True, axis=1)
df.reset_index(inplace=True)
return(df) | 213de79ad7108f759d2bcdf1bfb9eb9d8f193c19 | 96,256 |
def set_ignorables(licensish, ignorables, verbose=False):
"""
Update ``licensish`` Rule or License using the mapping of ``ignorables``
attributes.
Display progress messages if ``verbose`` is True.
"""
for key, value in ignorables.items():
if verbose:
existing = getattr(licensish, key, None)
print(f'Updating ignorable: {key} from: {existing!r} to: {value!r}')
setattr(licensish, key, value)
return licensish | ab11d7375f2b3a1b5257f25bba9bfbdeb9a06897 | 96,258 |
def rearrange_digits(input_list):
"""
Rearrange Array Elements so as to form two number such
that their sum is maximum.
Args:
input_list(list): Input List
Returns:
(int),(int): Two maximum sums
"""
input_list.sort(reverse=True)
x = 0
for i in range(0, len(input_list), 2):
x = x * 10 + input_list[i]
y = 0
for i in range(1, len(input_list), 2):
y = y * 10 + input_list[i]
return [x, y] | 29a7cf3eec77566d23685d894f4e973e77169f87 | 96,262 |
import re
def get_max_age(headers):
"""Parse the 'max-age' directive from the 'CACHE-CONTROL' header.
Arguments:
headers -- dictionary of HTTP headers
Return the parsed value as an integer, or None if the 'max-age' directive
or the 'CACHE-CONTROL' header couldn't be found, or if the header is
invalid in any way.
"""
ret = None
cache_control = headers.get('CACHE-CONTROL')
if cache_control:
parts = re.split(r'\s*=\s*', cache_control)
if len(parts) == 2 and parts[0] == 'max-age' and re.match(r'^\d+$',
parts[1]):
ret = int(parts[1])
return ret | 7b20fff8fa343c28d82df1791b62edb45fcef0dc | 96,264 |
def rot_word(word):
"""Takes a 4-byte word and performs cyclic permutation.
Aka one-byte left circular shift.
[b0, b1, b2, b3] -> [b1, b2, b3, b0]
"""
return word[[1, 2, 3, 0]] | f89b3499009d29c7e3e9745e30f643b941c77f00 | 96,265 |
import torch
def f1_score_binary(y_true, y_pred):
"""
Binary f1. Same results as sklearn f1 binary.
Args:
y_true: [bs*x*y], binary
y_pred: [bs*x*y], binary
Returns:
f1
"""
intersect = torch.sum(y_true * y_pred) # works because all multiplied by 0 gets 0
denominator = torch.sum(y_true) + torch.sum(y_pred) # works because all multiplied by 0 gets 0
f1 = (2 * intersect.float()) / (denominator.float() + 1e-6)
return f1 | 5856fc12197ba54bafc51d17a3467ad0760dcfb5 | 96,266 |
def get_session(monitored_sess):
""" Get Session object from MonitoredTrainingSession.
"""
session = monitored_sess
while type(session).__name__ != 'Session':
session = session._sess
return session | a377a2aeeed1cc7f625f49693adc6b1b6ee203cf | 96,268 |
from datetime import datetime
def utc_timestamp(hours_since_first_epoch):
"""Construct a timestamp of the format "%Y-%m-%d %H:%M:%S"
for the given epoch.
Arguments:
hours_since_first_epoch (int):
Epoch for reftime
Returns:
ts (str)
Timestamp of the format "%Y-%m-%d %H:%M:%S"
"""
epoch = hours_since_first_epoch * 60 * 60
ts = datetime.fromtimestamp(epoch).strftime("%Y-%m-%d %H:%M:%S")
return ts | e82f7b7ee6f2b0d694cac6e77842e112f25c9f79 | 96,269 |
def get_object_range(page, page_size):
""" Get the range of expected object ids given a page and page size.
This will take into account the max_id of the sample data. Currently 5.
"""
max_id = 5
start = min((page - 1) * page_size, max_id)
end = min(start + page_size, max_id + 1)
return list(range(start, end)) | 36d65c05361d6818ffabad9690f1d531f371a0d8 | 96,270 |
def get_content_iter_with_chunk_size(content, chunk_size=1024):
"""
Return iterator for the provided content which will return chunks of the specified size.
For performance reasons, larger chunks should be used with very large content to speed up the
tests (since in some cases each iteration may result in an TCP send).
"""
# Ensure we still use multiple chunks and iterations
assert (len(content) / chunk_size) >= 10
content = iter([content[i:i + chunk_size] for i in range(0, len(content), chunk_size)])
return content | c1550aef62e58b459feb66bde6c2a506e5de31be | 96,273 |
def _invalid_particle_errmsg(argument, mass_numb=None, Z=None):
"""
Return an appropriate error message for an
`~plasmapy.utils.InvalidParticleError`.
"""
errmsg = f"The argument {repr(argument)} "
if mass_numb is not None or Z is not None:
errmsg += "with "
if mass_numb is not None:
errmsg += f"mass_numb = {repr(mass_numb)} "
if mass_numb is not None and Z is not None:
errmsg += "and "
if Z is not None:
errmsg += f"integer charge Z = {repr(Z)} "
errmsg += "does not correspond to a valid particle."
return errmsg | 28866a72a25c79b966ef787e290ab83571f82ef8 | 96,275 |
def _verify_encodings(encodings):
"""Checks the encoding to ensure proper format"""
if encodings is not None:
if not isinstance(encodings, (list, tuple)):
return encodings,
return tuple(encodings)
return encodings | 26b7c16c850e90b16a7aee528ee35c74cfedd230 | 96,276 |
import hashlib
def digest_check(file_path):
"""
Generate hash digest for a file
:param file_path:
:return:
"""
h = hashlib.blake2b()
with open(file_path, "rb") as fh:
for chunk in iter(lambda: fh.read(4096), b""):
h.update(chunk)
return h.hexdigest() | d965aeccb4578011831ec00ed93193b2f52355a4 | 96,277 |
def convert_config_description_dict(configs, for_docs=False):
"""
Recursively converts a documented list of dictionary configurations into a dictionary with the
default values loaded.
Expects a list of the form:
.. code-block:: python
[
{
"key": "config_name",
"description": "a description of the config for documentation",
"default": True, # the default config value
},
{
"key": "required_config_name",
"description": "a description of the config for documentation",
"required": True, # indicates that this must be user-specified and has no default
},
{
"key": "nested_config_name",
"description": "a description of the config for documentation",
"default": None,
"subkeys": [ # note that a list is used for nested dict configs
{
"key": "subconfig",
"description": "a nested key",
"default": None,
}
],
},
]
The list above gets converted to a dictionary mapping each ``key`` to each ``default``:
.. code-block:: python
{
"config_name": True,
"nested_config_name": None,
}
If ``for_docs`` is true, then any specified subkeys are set as the mapped value in the dictionary,
and if the config is required, its default is set to ``None``.
.. code-block:: python
{
"config_name": True,
"required_config_name": None,
"nested_config_name": {
"subconfig": None,
},
}
Any configurations with ``default`` unspecified have their default value set to ``None``. Any
configurations marked with ``"required": True`` are not included in the output dict (so that
they raise a ``KeyError`` if unspecified).
Args:
configs (``list[dict[str,object]]``): the configurations with the structure defined above
Returns:
``dict[str,object]``: a dictionary mapping keys to default values
"""
res = {}
for d in configs:
default = d.get("default")
subkeys = d.get("subkeys")
if isinstance(default, list) and len(default) > 0 and \
all(isinstance(e, dict) for e in default):
default = convert_config_description_dict(default)
elif for_docs and isinstance(subkeys, list) and len(subkeys) > 0 and \
all(isinstance(e, dict) for e in subkeys):
default = convert_config_description_dict(subkeys)
if not d.get("required", False) or for_docs:
res[d["key"]] = default
return res | 16ceb60faad3a964d447404acf2eabd24056147b | 96,278 |
import re
def delete_comments(file_content):
"""Removes all comments from the given string.
:param str file_content: file content
:return str: same content without comments
"""
string_temp = re.sub(r'--.*\n', '', file_content) # Removing comments
string_temp = re.sub(r'\n+', ' ', string_temp) # Replace new line with space
string_temp = re.sub(r' +', ' ', string_temp) # Replace >1 spaces with 1 space
return string_temp | b89cfb4dc884fea93c59c23e2da4f2d8c4b79fe7 | 96,280 |
def get_corr_hex(num):
"""
Gets correspondence between a number
and an hexadecimal string
Parameters
-------------
num
Number
Returns
-------------
hex_string
Hexadecimal string
"""
if num < 10:
return str(int(num))
elif num < 11:
return "A"
elif num < 12:
return "B"
elif num < 13:
return "C"
elif num < 14:
return "D"
elif num < 15:
return "E"
elif num < 16:
return "F" | d7842f54dda04903f09aade6c5adaee4be310bc3 | 96,284 |
def entry_compare(x, y):
"""Comparison function for two StandardEntries.
This function establishes a global order by sorting on the
(timestamp, id) tuple.
"""
assert x and y
if x.timestamp == y.timestamp:
return x.id - y.id
else:
return x.timestamp - y.timestamp | 112c91fca55a822cdffce187e5979a9c3abda8bb | 96,286 |
def can_topic(user):
"""Checks if a user can generate a topic"""
return user.permissions['perm_topic'] | 43070a62e806ea314b0ba938283b8b9fc3a55609 | 96,287 |
def pmt_in_module_id(pmt_index):
"""Returns the pmt number within a
module given the 0-indexed pmt number"""
return pmt_index%19 | 41250ca2eed93a2bc51f4654d324379b22b70ba5 | 96,295 |
def count_frequency(word_list):
"""
Counts frequency of each word and returns
a dictionary which maps the word to their frequency
"""
D = {}
for new_word in word_list:
if new_word in D:
D[new_word] = D[new_word] + 1
else:
D[new_word] = 1
return D | 55f237a2b899f2e2358bec071a10ae3418fd97fc | 96,296 |
def _dj(scalararray):
"""Return the difference scalararray(j+1) - scalararray(j)
A priori, for internal use only.
Parameters
----------
scalararray : xarray.DataArray
xarray that should be differentiated.
Returns
-------
dj : xarray.DataArray
xarray of difference, defined at point j+1/2
"""
dj = scalararray.shift(y=-1) - scalararray
return dj | 274ca1aad19ea8a918393148d2b660ddb3d2ba59 | 96,299 |
def nop(format_chained=True, chained=None, chained_status=None):
"""
This function just returns the chained value. It is a nop/no operation.
This can be useful if you want to do a pipe_on_true to filter out
False values -- you can pipe_on_true to process.nop, and stick a
returner on the nop operation to just return the True values.
"""
return chained | 526816e43d02df8639f824960186ca4d3620b23c | 96,304 |
def square(side):
"""Calculate area of square."""
return side * side | b71cae20b7a140d6a265d0575c715f22ebae6af3 | 96,305 |
def get_scale(f_min, f_max, q_min, q_max):
"""Get quantize scaling factor. """
return (q_max - q_min) / (f_max - f_min) | 0f48cc32c21b2efe9355124e162f2dd2abfa3d58 | 96,312 |
def capitalize(text):
"""
Returns a capitalized string. Note that this differs
from python's str.capitalize()/title() methods for
cases like "fooBarBaz"
"""
if text == '':
return ''
return text[0].upper() + text[1:] | 5bedc2be5fa3aa7659d8bc9521c0082db2cccc43 | 96,317 |
from typing import List
from typing import Union
def get_notes_in_scale(all_notes: List[Union[float, int, str]],
scale: int) -> List[Union[float, int, str]]:
"""Return a list of all notes in scale, where the notes are chosen from a
set of all twelve possible semitones.
Args:
all_notes: List of strings, integers, or floats that make up the set of
all twelve semitones. The list contents could represent notes in
ABC notation (A, #A, B, ...), frequencies, midi note numbers, etc.
scale: an integer mask where each '1' bit means the note is present in
the output scale and a '0' bit means it is not present. The least
significant bit always corresponds to the first note in all_notes.
Returns:
A list of notes that is a subset of the input all_notes list.
Raises:
A ValueError if the scale argument has one or fewer notes or more than
twelve notes.
"""
if scale <= 1 or scale > 0xfff:
raise ValueError(
'A valid musical scale must include at least two notes and no '
'more then twelve notes (0x001 to 0xfff)')
scale_notes = []
for i, note in enumerate(all_notes):
if scale & (0x1 << i):
scale_notes.append(note)
if len(scale_notes) == 1:
raise ValueError(
'Only one note appears in this scale; currently monotonic scales '
'are not supported')
return scale_notes | b1e8b1ef57eaea003dfb68381061d1bdac8aa537 | 96,319 |
def sub_when_empty(string: str, empty_str: str = "-") -> str:
"""
Just returns a given string if it is not empty. If it is empty though, a default
string is returned instead.
Parameters
----------
string
The string to check if it is empty or not
empty_str
The string to be returned if the given string is empty
Returns
-------
result_string
Either the given string (when 'string' is not empty) or the empty_str (when
'string' is empty)
"""
if type(string) is not str:
raise TypeError(f"Input must be of type string. Found: type '{type(string)}'")
if len(string) > 0:
result_string = string
else:
result_string = empty_str
return result_string | 7b7309d58214734cea9bc70c76fe54785761ce50 | 96,325 |
import warnings
def to_completions_display_value(x):
"""Convert user input to value of ``$COMPLETIONS_DISPLAY``"""
x = str(x).lower()
if x in {"none", "false"}:
x = "none"
elif x in {"multi", "true"}:
x = "multi"
elif x in {"single", "readline"}:
pass
else:
msg = '"{}" is not a valid value for $COMPLETIONS_DISPLAY. '.format(x)
msg += 'Using "multi".'
warnings.warn(msg, RuntimeWarning)
x = "multi"
return x | cb075b573aa703b356d6a8cb533748f552dd6412 | 96,327 |
def get_cluster_id_by_name(cluster_list, cluster_name):
"""Helper function to retrieve the ID and output bucket of a cluster by
name."""
cluster = [c for c in cluster_list if c['clusterName'] == cluster_name][0]
return cluster['clusterUuid'], cluster['config']['configBucket'] | b255ea9973557d8152952690aa5342c5532d2a1e | 96,329 |
def is_other_or_unknown(df):
"""Return if vehicle is other/unknown, per NHTSA convention."""
yr = df['YEAR']
body = df['BODY_TYP']
tow_veh = df['TOW_VEH']
return ((yr.between(1975, 1981) & (body.between(35, 42) |
body.isin([44, 45, 99]))) |
(yr.between(1982, 1990) & (body.isin([13, 14, 42, 52, 73, 77,
80, 81, 82, 83, 88, 89,
90, 99]))) |
((1991 <= yr) & (body.isin([12, 13, 23, 42, 65, 73, 90,
91, 92, 93, 94, 95, 96, 97,
99, 98]) |
((body == 79) & tow_veh.isin([5, 6]))))) | a14ce7414adf17e46410c0ad4a7681b57f32f7f4 | 96,334 |
def add(x,y):
"""
Returns the sum x+y
This works on any types that support addition (numbers, strings, etc.)
Parameter x: The first value to add
Precondition: x supports addition and x is same type as y
Parameter x: The second value to add
Precondition: x supports addition and x is same type as y
"""
return x+y | 8c34207fec2fdc1b042cc5b7999eaef4e5beb1db | 96,336 |
import typing
def is_generic_list(tp):
"""Returns true if `tp` is a parameterized typing.List value."""
return tp not in (list, typing.List) and getattr(tp, "__origin__", None) in (
list,
typing.List,
) | 19ad96a2e2325ffb7179d7e30687694c627029dc | 96,343 |
def ct_satratburden(Inom,VArat=None,ANSIv=None,ALF=20,):
"""
ct_satratburden Function
A function to determine the Saturation at rated burden.
Parameters
----------
Inom: float
Nominal Current
VArat: float, optional, exclusive
The apparent power (VA) rating of the CT.
ANSIv: float, optional, exclusive
The ANSI voltage requirement to meet.
ALF: float, optional
Accuracy Limit Factor, default=20.
Returns
-------
Vsat: float
The saturated voltage.
"""
# Validate Inputs
if VArat == None and ANSIv == None:
raise ValueError("VArat or ANSIv must be specified.")
elif VArat==None:
# Calculate VArat from ANSIv
Zrat = ANSIv/(20*Inom)
VArat = Inom**2 * Zrat
# Determine Vsaturation
Vsat = ALF * VArat/Inom
return(Vsat) | 248cf7473113f342451f60b9d0c5a676ab1bf5bb | 96,344 |
def pack_context_with_message(ctxt, msg):
"""Pack context into msg."""
if isinstance(ctxt, dict):
context_d = ctxt
else:
context_d = ctxt.to_dict()
return {'message': msg, 'context': context_d} | 8968712c9e10aa6b016bd322d505c3cb5be288a2 | 96,346 |
def get_structure_from_gismo_cluster(gismo, cluster, depth=3):
"""
Builds a tree structure from Gismo clusterising method.
Args:
gismo: A `Gismo` object used for the clustering.
cluster: The root Cluster of the tree, returned by `gismo.get_clustered_features`
Returns:
A `dict` representing the tree structure.
"""
if depth == 0:
members = [gismo.embedding.features[indice] for indice in cluster.members]
return {
"members": members,
"title": [
gismo.embedding.features[i]
for i in gismo.diteration.y_order
if gismo.embedding.features[i] in members
][:10],
"text": "",
"centroid": sum([gismo.embedding.query_projection(member)[0] for member in members]), # word_centroid
"siblings_centroids": list(),
"children": []
}
members = [gismo.embedding.features[indice] for indice in cluster.members]
return {
"members": members,
"title": [
gismo.embedding.features[i]
for i in gismo.diteration.y_order
if gismo.embedding.features[i] in members
][:10],
"text": "",
"centroid": sum([gismo.embedding.query_projection(member)[0] for member in members]), # word_centroid
"siblings_centroids": list(),
"children": [get_structure_from_gismo_cluster(gismo, c, depth - 1) for c in cluster.children]
} | e746f59c19f3d0c2b0ef514c737f6096853f516a | 96,348 |
def array_sign(nums: list[int]) -> int:
"""Computes the sign of the product of a given array of numbers
Args:
nums:
Returns:
1 if the product of nums is positive.
-1 if the product of nums is negative.
0 if the product of nums is equal to 0.
Examples:
>>> array_sign([-1,-2,-3,-4,3,2,1])
1
>>> array_sign([1,5,0,2,-3])
0
>>> array_sign([-1,1,-1,1,-1])
-1
"""
sign = 1
for num in nums:
if num == 0:
return 0 # `product` will be 0 since 0 is a factor
elif num < 0:
sign *= -1
else:
return sign | a65d37b4f0d8977e67ff5b4f906363a5d781cfbb | 96,352 |
import time
def timeStamp_s_convert_time(time_num):
"""
输入秒级时间戳的时间,转出正常格式的时间
如: 1595498910 -> 2020-07-23 18:08:30
param time_num: ms时间戳
return: 正常格式的时间
"""
time_array = time.localtime(int(time_num))
normal_time = time.strftime("%Y-%m-%d %H:%M:%S", time_array)
# print(normal_time)
return normal_time | a9c7fc53607e2eb90a876212a90a9c9663ad070c | 96,354 |
from typing import Optional
import re
def extract_url(text: str) -> Optional[str]:
"""Extracts url from text
Parameters
----------
text : str
String from which url to be extracted.
Returns
-------
Optional[str]
Return url if present in the given string.
"""
regex_extract = re.search("(?P<url>https?://[^\s]+)", text)
return regex_extract.group("url") if regex_extract else None | 43df2bc3b0db5ec91e6e1313978dabe7e00da13f | 96,357 |
import inspect
import re
def getSubjDict(in_content, examPat):
"""
Finds the subjects and subject code from in_content.
Returns a dict with the subject code as key and subject as
value.
"""
err_msg = ("%s expected argument of type 'list','str'; %s,%s given" %
(inspect.stack()[0][3], type(in_content), type(examPat)))
assert (type(in_content) is list and type(examPat) is str), err_msg
# Only handles 2008 pattern files for now.
if examPat != '2008':
return []
subj_re = (r'((?:[0-9]{3}|[0-9]{2}[A-Z]{1}|[0-9]{2})\s*\.\s*'
r'[-A-Z1-3\s\.&\(\)\,\/]+)\s*(?=PP|PR|OR|TW)')
subjects = []
for line in in_content:
ret_obj = re.findall(subj_re, line)
if ret_obj != []:
ret_obj = [s.strip() for s in ret_obj]
[subjects.append(s_i) for s_i in ret_obj if s_i not in subjects]
# Split subject code and the subject name in list of subjects
subj_code_re = (r'^([0-9]{3}|[0-9]{2}[A-Z]{1}|[0-9]{2})\s*\.\s*'
r'([-A-Z1-3\s\.&\(\)\,\/]+)$')
subjects = [re.findall(subj_code_re, s_i) for s_i in subjects]
# Flatten 'subjects' to make a dict out of it.
subjects = dict([s_pair for sublist in subjects for s_pair in sublist])
return subjects | b523c496cd7f634b6dc5c2f14439e5c4b1ea2e56 | 96,359 |
def node_def_add_node(sss):
""" add node{} to a string of an op.
Args:
sss: original string of an op.
Returns:
new string with node{} added.
"""
sss = sss.replace('\n', '\n\t')
sss = "node {\n\t" + sss
sss = sss[0:len(sss)-1] + '}\n'
return sss | 656073db73db94f3942b4ac8d25b4f3fbf3e7356 | 96,360 |
def centroid2d(points):
"""
Calculate the centroid of a finite set of 2D points.
:param points: the set of points as an iterable. Each point is assumed to
be a sequence of (at least) two real numbers ``[x, y]``, respectively
the x (first element) and y coordinate (second element).
:return: the centroid or ``None`` if the input is empty.
:raise IndexError: if any point is an empty list.
:raise TypeError: if the input is ``None`` or a point has a ``None`` coord
or the coord isn't a number.
"""
number_of_points = 0
centroid = [0, 0]
for p in points:
centroid = (centroid[0] + p[0], centroid[1] + p[1])
number_of_points += 1
centroid = [centroid[0]/number_of_points, centroid[1]/number_of_points] \
if number_of_points else None
return centroid | 0c314f6047468241978a6ec3547eb2ceb3837626 | 96,364 |
def to_timestamp(datetime_timestamp):
"""Convert UTC datetime to microsecond timestamp used by Hangouts."""
return int(datetime_timestamp.timestamp() * 1000000) | c69cb6a4147db25861d700c56d9327960353a87a | 96,365 |
def mean(data):
"""Calculates the mean value from |data|."""
return float(sum(data)) / len(data) | c9b208e11abe46fb16900d957bb3c5428a6b9cfd | 96,368 |
def _encode_int(n: int) -> bytes:
"""
Encodes an integer into a bencoded string.
"""
return f"i{n}e".encode("utf-8") | e891cc0fcbf018521d6f4f41fbfcf8930195e8ff | 96,370 |
import pkg_resources
def load_description(package: str, path: str, filename: str):
"""
This function loads a static description file.
Parameters:
package (str): Package name where file is located in
path (str): Path within the package.
filename (str): Name of file to load.
Returns:
str: Content of loaded file
"""
with open(pkg_resources.resource_filename(
package, f"{path}{filename}"), "r+") as file:
return file.read() | 1a4afa40366d054f8ebf491c301c5cbc2a3a694a | 96,371 |
import operator
def sort_posts(posts, *keys):
"""Sort posts by a given predicate. Helper function for templates.
If a key starts with '-', it is sorted in descending order.
Usage examples::
sort_posts(timeline, 'title', 'date')
sort_posts(timeline, 'author', '-section_name')
"""
# We reverse the keys to get the usual ordering method: the first key
# provided is the most important sorting predicate (first by 'title', then
# by 'date' in the first example)
for key in reversed(keys):
if key.startswith('-'):
key = key[1:]
reverse = True
else:
reverse = False
try:
# An attribute (or method) of the Post object
a = getattr(posts[0], key)
if callable(a):
keyfunc = operator.methodcaller(key)
else:
keyfunc = operator.attrgetter(key)
except AttributeError:
# Post metadata
keyfunc = operator.methodcaller('meta', key)
posts = sorted(posts, reverse=reverse, key=keyfunc)
return posts | 2b2e5447694c88324b780e3ab5aa9f7747147851 | 96,382 |
import json
def read_data_json(file_name: str):
"""Read imported snippet data from json file
Parameters
----------
file_name : str
Name of internal `.json` file with snippet info.
Returns
-------
snippets : List[Snippet]
List of snippet objects: dicts with prefix, body, mode, description.
Superset of the info needed by: vscode/latex-utilities/atom snippets
Derived: `multiline = isinstance(body, list)`, `priority = len(prefix)`
Type: `Snippet = Dict[str, str]` or `Dict[str, List[str]]`.
"""
with open(file_name, 'r') as file:
snippets = json.load(file)
return snippets | 494ba50ab67aac120966791797ca9a17842ff1c0 | 96,386 |
def pivotDiagnostic(df, index, columns, values):
"""Attempt to pivot the DataFrame. If there are duplicate
entries in the pivot table then return a df of duplicates
Parameters
----------
df : pd.DataFrame
index : str
columns : str or list
values : str or list
Returns
-------
df :pd.DataFrame
If no exception then returns pivot table,
otherwise returns duplicate rows in df."""
try:
p = df.pivot(index=index, columns=columns, values=values)
print('Pivot success: return pivoted df')
return p
except ValueError:
if type(columns) in [str, str]:
columns = [columns]
if not isinstance(columns, list):
columns = list(columns)
if type(values) in [str, str]:
values = [values]
if not isinstance(values, list):
values = list(values)
dupInd = df[[index] + columns].duplicated(keep=False)
print('Index contains %d duplicate entries, cannot reshape' % dupInd.sum())
print('Returning duplicate rows')
return df[[index] + columns + values].loc[dupInd].sort_values(by=[index] + columns + values) | e6c8d4ec5d26b37259df8263da8f056e5e583c93 | 96,389 |
def latest_price(prices):
""" returns the latest (i.e., last) price in a list of prices.
input: prices is a list of 1 or more numbers.
"""
return prices[-1] | a4e75253c8ddef9bb0629360e55b816adbcbd0f5 | 96,392 |
def knowledge_area_abbreviation(ka):
"""
Given an ACM knowledge area, split it up by its Abbreviation (eg. AL)
and its Title (eg. Algorithms and Complexity). This is done by
isolating the location of the abbreviation in the title string (where
the first left paren occurs) and only including the subsequent
characters.
"""
return {
'abbr': ka.title,
'title': ka.title[ka.title.find('(')+1:-1]
} | ebe4204b63fe9568ddc82b0656d425ff7277de67 | 96,393 |
import re
def prep_seq(seq):
"""
Adding spaces between AAs and replace rare AA [UZOB] to X.
ref: https://huggingface.co/Rostlab/prot_bert.
Args
seq: a string of AA sequence.
Returns:
String representing the input sequence where U,Z,O and B has been replaced by X.
"""
seq_spaced = " ".join(seq)
seq_input = re.sub(r"[UZOB]", "X", seq_spaced)
return seq_input | 8e66177ae399053d312d5b0c3aa6c6bf9ef174a2 | 96,395 |
from datetime import datetime
import pytz
def _format_datetime(utc_float):
"""Method ingests a utc timestamp float and formats it into
a datetime format that is prefered by the DRF framework.
It performs conversions through datetime and pytz.
Args:
utc (float): A unix timestamp.
Returns:
str: The formatted datetime in string format.
"""
date_obj = datetime.fromtimestamp(utc_float, tz=pytz.utc)
date_str = date_obj.strftime("%Y-%m-%dT%H:%M:%S.%f%z")
return date_str | bad92d7a3297224b42bb8afe3898612b84b5aa79 | 96,398 |
def with_suffix(number, base=1000):
"""Convert number to string with SI suffix, e.g.: 14226 -> 14.2k, 5395984 -> 5.39M"""
mapping = {base**3: "G", base**2: "M", base: "k"}
for bucket, suffix in mapping.items():
if number > 0.999 * bucket:
return "{:.3g}{}".format(number / bucket, suffix)
return "{:.3g}".format(number) | 0a0e346778cd7e6ffa3c6222b351b75ec2ce20a6 | 96,403 |
def disable_option(value):
"""Converts a boolean option to a CMake ON/OFF switch"""
return 'OFF' if value else 'ON' | 177be0fc943351a830edf27c1e12b3430af68239 | 96,404 |
def check_auth(username, password):
""" Check if given username/password are valid """
return username == 'admin' and password == 'test' | d9610eb534843e4129aab7c136437455dc55fd14 | 96,406 |
import attr
def filter_unknown_attributes(cls, package_data):
"""
Given a mapping of package_data, return a new mapping of package_data that
contains only known `cls` attr class attributes.
"""
known_fields = attr.fields_dict(cls)
return {
key: value for key, value in package_data.items()
if key in known_fields
} | 1260d4e60dc4bf27ebbe6eda9197f22cdf67e3d9 | 96,408 |
def frequency_to_band(freq):
"""
band code from frequency in GHz
"""
if freq < 1: return None
elif freq >= 1 and freq < 2: return "L"
elif freq >= 2 and freq < 4: return "S"
elif freq >= 4 and freq < 8: return "C"
elif freq >= 8 and freq < 12: return "X"
elif freq >=12 and freq < 18: return "Ka"
elif freq >=18 and freq < 26.5: return "K"
elif freq >=26.5 and freq < 40: return "Ka"
elif freq >=40 and freq < 50: return "Q"
elif freq >=50 and freq < 75: return "V"
elif freq >=75 and freq <115: return "W"
else: return "D" | ab4e17bae39b4f21dc1d6e4b1007eaf43864501d | 96,409 |
def date_to_cisco_date(date):
"""
This function gets a date and returns it according to the standard of Cisco Email security.
Args:
date: YYYY-MM-DD hh:mm:ss.
Returns:
The date according to the standard of Cisco Email security - YYYY-MM-DDThh:mm:ss.000Z.
"""
return date.replace(' ', 'T') + '.000Z' | 3e6a5f38fe1cfaae726213895f2436e4067eb8de | 96,411 |
def open_file_and_get_lines(file):
"""
Returns the file as a list of lines
"""
with open(file, 'r') as f:
try:
lines = f.readlines()
return lines
except UnicodeDecodeError as error:
print("\n\n")
print(error)
print("Weird char in ", file)
print("\n")
return None; | 552e8e6b649759f0128436e23f2831cfb7cd66ba | 96,412 |
def ReadLLVMChecksums(f):
"""Reads checksums from a text file, produced by WriteLLVMChecksums.
Returns:
A dict, mapping from project name to project checksum.
"""
checksums = {}
while True:
line = f.readline()
if line == "":
break
checksum, proj = line.split()
checksums[proj] = checksum
return checksums | 4f7b9fd1375c25655eb9059fb8607a1f42fd1f48 | 96,416 |
def jaccard_score(y_pred, y_true):
"""Compute Jaccard Score (= Intersection / Union) between a prediction and its ground truth
:param y_pred: prediction
:param y_true: ground truth
:return: Jaccard score value
"""
intersection = (y_pred * y_true).sum()
union = y_pred.sum() + y_true.sum() - intersection
if union == 0:
return 1.
else:
return float(intersection) / union | 518db134089da2c8e1dd4a2ec0cefa82e5ffd1c1 | 96,420 |
import re
def remove_hyphenation(string):
"""
Removes hyphenation from the input string
"""
#regex = r"(\w+)(- )(\w+)?"
#return re.sub(regex,r"\1\3",string)
try:
regex = r"(\w+)(- )(\w+)?"
return re.sub(regex,r"\1\3",string)
except Exception as e:
return string | ef947bfce9d3f8ce513baacb6846af3541bebe74 | 96,423 |
def nonEmpty(v):
"""
If v is a container (tuple, list or dictionary), return None if it is empty,
otherwise return v itself.
"""
if isinstance(v,(tuple,list,dict)):
if len(v) == 0: return None
return v | bc5d0ec29d8986d1cfb03e663a3024d40637ac3e | 96,424 |
import re
def add_hit_symbols(text, search, symbol='_'):
"""Use re to find matches and insert hit symbols."""
find = f'({search})'
replace = f'{symbol}\g<1>{symbol}'
return re.sub(find, replace, text) | 18058fd3ed89899eae9d32bcbaee0e6ff474094b | 96,432 |
def classPath2modulePath(stringIn):
"""
if it get: specification.ocni.AvailabilityInterval
it will return: specification.ocni
"""
tem = stringIn.split('.')
res = ''
#l'indice pour la boucle while
i = 0
while i < len(tem) - 1:
res += tem[i]
if i < len(tem) - 2:
res += '.'
i += 1
return res | a80795241123d9e4cb059a7052284ea90f614997 | 96,435 |
import threading
def spawn_later(seconds, function, *args, **kwargs):
"""Spawns a daemonized thread after `seconds.`"""
thread = threading.Timer(seconds, function, args, kwargs)
thread.daemon = True
thread.start()
return thread | d49fe46b86151442c72435045b87df9fdb465ad9 | 96,438 |
def add_single_letter_words(words):
"""Add single letter words to the dictionary.
"""
words['']=None
words['i']=None
words['a']=None
return words | 0c2eacaf97dddbe0d8106bf38d6b6a7e86f31fa5 | 96,443 |
def standardise(X, how='range=2', mean=None, std=None, midrange=None,
ptp=None):
"""Standardise.
ftp://ftp.sas.com/pub/neural/FAQ2.html#A_std_in
Parameters
----------
X : matrix
Each sample is in range [0, 1]
how : str, {'range=2', 'std=1'}
'range=2' sets midrange to 0 and enforces
all values to be in the range [-1,1]
'std=1' sets mean = 0 and std = 1
Returns
-------
new_X : matrix
Same shape as `X`. Sample is in range [lower, upper]
See also
--------
unstandardise
"""
if how == 'std=1':
if mean is None:
mean = X.mean()
if std is None:
std = X.std()
centered = X - mean
if std == 0:
return centered
else:
return centered / std
elif how == 'range=2':
if midrange is None:
midrange = (X.max() + X.min()) / 2
if ptp is None:
ptp = X.ptp()
return (X - midrange) / (ptp / 2)
else:
raise RuntimeError("unrecognised how '" + how + "'") | b7b8dde69e8203b918f23fd80c5f5fcc3bd55941 | 96,450 |
def _parse_settings_args(args: list):
""" Parse settings command args and get settings option and signal. """
if not args:
return 'common', [] # 'common' is the option, when user does not use any option.
else:
try:
option, signal, *_ = args
except ValueError:
return args[0], ''
return option, signal | 1fdd3e124d7a7b9a456533593b9768814c6553c1 | 96,453 |
def cels_from_fahr(fahr):
"""Convert a temperature in Fahrenheit to
Celsius and return the Celsius temperature.
"""
cels = (fahr - 32) * 5 / 9
return cels | 9ad242078e6092e10a81d78e7de4add3224e4d2f | 96,455 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.