content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from typing import Tuple
def _get_start_size(d: dict) -> Tuple[int, int]:
"""Returns a tuple of ints that represent the true start byte and size
based on the provided dict.
This is a convenience function such that if you have these values in a
dictionary with a *StartByte* and *Bytes* keys.
Since the StartByte labels on an ISIS cube are 1-based counts, and not
0-based, in order to convert from the numbers provided in the labels
to a byte count for Python's read() functions, you must subtract one
from the listed StartByte, which this function does.
"""
start = int(d["StartByte"]) - 1
size = int(d["Bytes"])
return start, size | a4c5b87000bccca282e31dba2f30da81cedaf150 | 111,354 |
def power(base: float, exponent: float) -> float:
"""
Returns the value of the first argument raised to the power of the second argument.
:param base: the base
:param exponent: the exponent
:return: the value a :sup:b
"""
return base ** exponent | f80ee99054fb36098e1ac63ae0240eace78a4fc8 | 111,355 |
def _match_instname_wo_host(instance_name1, instance_name2):
"""
Test 2 instance names for equality ignoring the host name. Creates copy
to avoid changing input instance names.
"""
in1 = instance_name1.copy()
in2 = instance_name2.copy()
in1.host = None
in2.host = None
return in1 == in2 | 21d755524ff78d3be023a7aa888d5252a6c9258f | 111,364 |
from pathlib import Path
def _represent_path(self, data: Path):
"""
Serialize a `Path` object to a string.
.. warning::
Path("./aaa") serializes to "aaa"
:param data: [description]
:type data: pathlib.Path
"""
return self.represent_scalar("tag:yaml.org,2002:str", str(data)) | 5b9da2c3b849d756a9a895ee85ea4c1f80ac3630 | 111,367 |
import time
def FORMATTED_TIME(format="[%Y-%m-%d_%H.%M.%S]"):
"""Return the formatted current time.
Args:
format (str): The time format.
Returns:
str: The formatted current time.
"""
return time.strftime(format,time.localtime(time.time())) | 81a7dda3d1e041f647bb61f10e492ad78330aee5 | 111,368 |
def tee(*funcs, name=None, doc=None):
"""Create a function which broadcasts all arguments it receives to a list of "sub-functions".
The return value of the tee function is a generator expression containing the return values
of the individual sub-functions.
T = func.tee(f, g, h)
T(x) # equivalent to... [f(x), g(x), h(x)] (as a generator expression, not a list!)
The name and docstring of the newly created function can be given through the 'name' and
'doc' keyword-only arguments.
"""
def tee_func(*args, **kwargs):
return (func(*args, **kwargs) for func in funcs)
tee_func.__name__ = name or "tee({})".format(", ".join(f.__name__ for f in funcs))
tee_func.__doc__ = doc
return tee_func | b3c3b7e85844fe9c31255ac2b265c3c2048ffa80 | 111,370 |
import json
def pretty_json(obj):
"""Format an object into json nicely"""
return json.dumps(obj, separators=(',', ':'), sort_keys=True, indent=2) | 028b1de8ddd66c4c9cc4937371d87c62db8fb9d2 | 111,374 |
def change_one(pair, index, new_value):
"""Return new tuple with one element modified."""
new_pair = list(pair)
new_pair[index] = new_value
return tuple(new_pair) | 82f3f29639044bdfdf861cc0c7917cf521ac74aa | 111,375 |
import logging
def calculateDelay(fSampling, receptionDelay):
"""
Calculates delay until signal acquisition starts.
:param fSampling: Sampling frequency of DAQ
:param receptionDelay: Delay until reception of signals
:return: Active delay until acquisition
"""
logging.info(' Function "calculateDelay" : %s', __name__)
delayOffsetSamples = 45.8e-6 * fSampling
activeDelay = receptionDelay - delayOffsetSamples
return activeDelay | 94023ea66908a41e5d267e6d355535274be3067c | 111,377 |
def __replace_symbols(transcript):
"""
Replaces Chinese symbols with English symbols.
"""
transcript = transcript.replace("。", ".")
transcript = transcript.replace(",", ",")
transcript = transcript.replace("!", "!")
transcript = transcript.replace("?", "?")
return transcript | e14726736be275321bb4f7112587a5623b7b90ac | 111,378 |
from pathlib import Path
def ensure_exists(p: Path) -> Path:
"""
Helper to ensure a directory exists.
"""
p = Path(p)
p.mkdir(parents=True, exist_ok=True)
return p | b64968cd6f4e29a0d44d78da1b27003415731f86 | 111,379 |
def calc_data_rate(bands_spectral,
bits,
cameras,
frame_rate,
pixels_total):
"""
Calculate the data rate generated by an imager that may comprise multiple
cameras.
Returns
-------
double : bits per second
"""
return bands_spectral * bits * cameras * frame_rate * pixels_total | 92903108091520f63da26b18d982b151ca44b3be | 111,380 |
def parseprevload(prevload):
"""
Parses prevload list into readable HTML option objects
:param prevload: Array of txt filenames
:return: HTML String of <option> objects
"""
resultstring = ''
for f in prevload:
resultstring += '<option value="' + f + '">' + f + '</option>'
return resultstring | 7bc38596742eee69e89b4cf2bdc0a4f80b6f7c91 | 111,381 |
import requests
def is_responsive_404(url):
"""
Hit a non existing url, expect a 404. Used to check the service is up as a fixture.
:param url:
:return:
"""
try:
response = requests.get(url)
if response.status_code == 404:
return True
except ConnectionError:
return False | 46a5f869d4e86accaa07dc186e1fe758a49ab312 | 111,384 |
def __get_type_CMA(code):
"""
Get the intensity category according to "Chinese National Standard for
Grade of Tropical Cyclones", which was put in practice since 15 June 2006.
Reference:
http://tcdata.typhoon.org.cn/zjljsjj_sm.html
0 - weaker than TD or unknown
1 - tropical depression (TD , 10.8-17.1 m/s)
2 - tropical storm (TS , 17.2-24.4 m/s)
3 - severe tropical storm (STS, 24.5-32.6 m/s)
4 - typhoon (TY , 41.4-32.7 m/s)
5 - severe typhoon (STY, 41.5-50.9 m/s)
6 - super typhoon (superTY, >=51.0 m/s)
9 - extratropical cyclone (EC)
Parameters
----------
code : str
A string code represents the type.
Returns
-------
re : str
One of the type in ['TD', 'TS', 'STS', 'TY', 'STY', 'EC', 'OTHERS'].
"""
if code == '0':
return 'OTHERS'
elif code == '1':
return 'TD'
elif code == '2':
return 'TS'
elif code == '3':
return 'STS'
elif code == '4':
return 'TY'
elif code == '5':
return 'STY'
elif code == '6':
return 'STY'
elif code == '9':
return 'EC'
else:
raise Exception('unknown code ' + code) | 4b310e3ddb9fc71d16b6026bb2240ca78141503e | 111,386 |
import pathlib
def get_directory_contents(path: pathlib.Path):
"""Iterates through a directory and returns a set of its contents."""
contents = set()
for filename in path.glob('**/*'):
# Remove the original parent directories to get just the relative path.
contents.add(filename.relative_to(path))
return contents | a6e5e8bb2a4894de4b0ef54a1f2f727ec68c86a5 | 111,393 |
def gby_count(df, col, col_full_name=False):
"""
Perform groupby count aggregation, rename column to count,
and keep flat structure of DataFrame.
Wrapper on pd.DataFrame.groupby
"""
if col_full_name:
col_name = "count_" + col
else:
col_name = "count"
return df.groupby(col).size().reset_index(name=col_name).sort_values(by=col_name, ascending=False) | 413dc3b6b74d631c40d2f7e7ade3c8188893efea | 111,395 |
from pathlib import Path
def get_file_stem(file: str) -> str:
"""
Returns file stem
:param file: Filename with or without path
:return: just the filename without extension
"""
return Path(file).stem | 886525fbfbeb2c93d61a6d25d03b8411f13de9f0 | 111,399 |
def canonicalise_message_line(line):
"""
Given a line known to start with the '%' character (i.e. a line
introducing a message), canonicalise it by ensuring that the result
is of the form '%<single-space>MESSAGE_IDENTIFIER<single-space>text'.
Parameters:
line - input line. Known to start with a '%' and to have leading
and trailing spaces removed.
Return:
Canonicalised line.
"""
# Cope with degenerate case of a single "%"
if len(line) == 1:
return line
# Get the rest of the line
line = line[1:].lstrip()
# Extract the first word (the message ID)
words = line.split()
message_line = "% " + words[0]
# ... and now the rest of the line
if len(line) > len(words[0]):
message_line = message_line + " " + line[len(words[0]):].lstrip()
return message_line | 07afdd59035bb68582e0d51e8695231beeaf8169 | 111,400 |
def _filter_col8(interval, keys=None):
"""
Filter the content of last column in interval.
Parameters
----------
interval : pybedtools.Interval
Interval.
keys : list
List of keys that should be kept in result.
Returns
-------
string
Filtered content of last column.
"""
if keys is None:
keys = ['gene_id', 'gene_name', 'transcript_id', 'transcript_name']
return ' '.join(['{} "{}";'.format(key, value) for key, value in
sorted(interval.attrs.items()) if key in keys]) | 80fc16469c17d1165d9162a19188b210ea76204e | 111,404 |
from pathlib import Path
from typing import List
def search_all_files(directory: Path) -> List[Path]:
"""
Search all compressed files in a directory
Args:
directory (Path): Directory to search.
Returns:
List[Path]: List of files ending in .gz in search directory.
"""
dirpath = Path(directory)
assert(dirpath.is_dir())
file_list = []
for file in dirpath.iterdir():
if file.is_file() and file.suffix == ".gz":
file_list.append(file)
else:
continue
return file_list | a9abb5150da9c5492f3acfd5b61609da889d49f6 | 111,410 |
def is_legal_name(val):
"""
Function to check if a string is a valid column name, attribute name or
condition name.
These are the characters that have been found to be problematic with
these names and the responsible for these anomalies:
- " Provokes a db error when handling the templates due to the encoding
produced by the text editor.
- ' String delimiter, python messes around with it and it is too complex to
handle all possible cases and translations.
In principle, arbitrary combinations of the following symbols should be
handle by OnTask::
!#$%&()*+,-./:;<=>?@[\]^_`{|}~
:param val: String with the column name
:return: String with a message suggesting changes, or None if string correct
"""
if "'" in val:
return "The symbol ' cannot be used in the column name."
if '"' in val:
return 'The symbol " cannot be used in the column name.'
return None | 9f00393fca0fcd7043a364f692bbbd1a86f3f3a5 | 111,411 |
from typing import Counter
def most_common(sequence):
"""Return most common item in sequence."""
return Counter(sequence).most_common(1)[0][0] | f471b3b0197a6d7b85bf7554c2fb733990bcb210 | 111,412 |
def get_subdirs(path):
"""
Returns all the sub-directories under `path`.
"""
return (item for item in path.iterdir() if item.is_dir()) | d7632c27118d53682fab631b3a365a346da793ad | 111,419 |
def remove_toffoli_from_line(local_qasm_line, qubit_1, qubit_2, target_qubit):
"""
Remove a specific Toffoli gate from a line of qasm.
Args:
local_qasm_line: The line of qasm
qubit_1: The first control qubit of the Toffoli gate
qubit_2: The second control qubit
target_qubit: The target qubit
Returns: The same line of qasm without the Toffoli gate call
"""
single_application = "Toffoli q[{}],q[{}],q[{}]".format(qubit_1, qubit_2, target_qubit)
# if there is a parallel bar right
local_qasm_line = local_qasm_line.replace(single_application + " | ", "")
# else: if there is a parallel bar left
local_qasm_line = local_qasm_line.replace(" | " + single_application, "")
# else: if it is the only gate in parallelized brackets
local_qasm_line = local_qasm_line.replace("{" + single_application + "}", "")
# else: if it is not parellelized at all
local_qasm_line = local_qasm_line.replace(single_application, "")
return local_qasm_line | 3bd95d5514af966dddb1f203b43749b51def1646 | 111,423 |
def bytes_from_int(x: int):
"""
Convert integer to bytes
"""
return x.to_bytes((x.bit_length() + 7) // 8, byteorder='big') | 95542506f87cffe21e05032ef5449017dd13732f | 111,424 |
def put_pixel(color: list, pixels: list, w: int, cord: tuple) -> list:
"""[Put pixel at coordinate]
Args:
color (list): [color of the pixel]
pixels (list): [list of pixels]
w (int): [width of the image]
cord (list): [tuple of x,y]
Returns:
list: [list of pixels]
"""
x = cord[0]
y = cord[1]
# x+w*y put pixel at cord
pixels[x + w * y] = color
return pixels | a2d8b0a0b52e289f0bbc1fb22f67c1e0483f10de | 111,431 |
def all_identical(seq):
""" Return true if all items in seq are identical. """
return len(seq) == 0 or seq.count(seq[0]) == len(seq) | a053564ceef48815ac0910dea768a48e2c824d65 | 111,433 |
import click
def _validate_ambiguous_command(kwargs):
"""Validate for conflicting options and suggest a fix."""
msg = (
'Ambiguous command! You have requested both to delete all'
' {resource}s _and_ to delete {resource}s by layer ID. Please choose'
' only one.'
)
if kwargs['delete_all_wip'] and kwargs['delete_wips_by_pattern']:
raise click.UsageError(msg.format(resource='WIP'))
if kwargs['delete_all_input'] and kwargs['delete_inputs_by_pattern']:
raise click.UsageError(msg.format(resource='input'))
return kwargs | 3af30b7d819236fa10b2577a2e431659cfa87cd2 | 111,439 |
def HMS(secs):
"""Return tuple of hours, minutes, and seconds given value in seconds."""
minutes, seconds = divmod(secs, 60.0)
hours, minutes = divmod(minutes, 60.0)
return hours, minutes, seconds | 9f0a099392d554a789c5d13483a266ac414807bf | 111,447 |
def number_of_divisors(n):
"""
Number of divisors of n.
>>> number_of_divisors(28)
6
"""
cnt = 1
if n > 1:
cnt += 1
half = n//2
for i in range(2, half+1):
if n % i == 0:
cnt += 1
return cnt | dc0c758b480d30335ddf89fcba5d09e40b2683e6 | 111,451 |
import requests
def get_reg_D_page() -> str:
"""
pulls the list of recent reg D fillings from the SEC
"""
list_of_results = "https://www.sec.gov/cgi-bin/current?q1=0&q2=4&q3=D"
list_html = requests.get(list_of_results)
assert list_html.status_code == 200, "Problem pulling list of reg D fillings"
return list_html.text | d7db2f99a79a855a1c8c59e67de000e3684081db | 111,456 |
def _fix_links(md):
"""Change links in markdown to make them work in HTML."""
md = md.replace('(doc/', '(')
md = md.replace('.md)', '.html)')
return md | ed6f215a7525f8a62b7323417ab8843a142680aa | 111,459 |
def to_wld(mapnik_map, x_rotation=0.0, y_rotation=0.0):
""" Generate a World File string from a mapnik::Map."""
extent = mapnik_map.envelope()
pixel_x_size = (extent.maxx - extent.minx)/mapnik_map.width
pixel_y_size = (extent.maxy - extent.miny)/mapnik_map.height
upper_left_x_center = extent.minx + 0.5 * pixel_x_size + 0.5 * x_rotation
upper_left_y_center = extent.maxy + 0.5 * (pixel_y_size*-1) + 0.5 * y_rotation
wld_string = '''%.10f\n%.10f\n%.10f\n-%.10f\n%.10f\n%.10f\n''' % (
pixel_x_size,
y_rotation,
x_rotation,
pixel_y_size,
upper_left_x_center,
upper_left_y_center)
return wld_string | b193fedfdb05fd8b6f46e5b8a603e8a13152d60f | 111,460 |
def make_testitem(nodeid, keywords, location):
"""Return JSON-serializable test item."""
item = {
'nodeid': nodeid,
'lineno': location[1],
# The outcome will be overridden in case of failure
'outcome': 'passed',
}
if keywords:
item['keywords'] = keywords
return item | cfcf0a4233f8ef73cce889cf4b674c47936deb09 | 111,461 |
def get_total_num_policies(data):
"""Returns a dictionary of US state id and the total number of state-level policies as key-value pairs.
Parameters:
data (list): a list of dictionaries where each dictionary is formed from the data.
Returns:
state_id_2_policy_counts (dict): a dictionary of US state id and the total number of state-level policies as key-value pairs
"""
state_id_2_policy_counts = {}
for row in data:
if row['policy_level'] == 'state' and row['start_stop'] == 'start':
if row['state_id'] not in state_id_2_policy_counts:
state_id_2_policy_counts[row['state_id']] = 1
else:
state_id_2_policy_counts[row['state_id']] += 1
return state_id_2_policy_counts | b36e45e3799cba37e443ec18bddac21e5459b71b | 111,464 |
def truncate_chars_end_word(value: str, max_length: int):
"""
Truncates a string after a specified character length
but does not cut off mid-word.
"""
if len(value) > max_length:
truncd_val = value[:max_length]
if value[max_length] != " ":
truncd_val = truncd_val[:truncd_val.rfind(" ")]
return truncd_val + "..."
return value | 4348293177e88b5f1bc453431f676c3734217553 | 111,465 |
import re
def words(text, reg=re.compile('[a-z0-9]+')):
"""Return a list of the words in text, ignoring punctuation and
converting everything to lowercase (to canonicalize).
>>> words("``EGAD!'' Edgar cried.")
['egad', 'edgar', 'cried']
"""
return reg.findall(text.lower()) | ff2ba22c24b6edab6d2beb49ba18e182cc7cd440 | 111,467 |
def get_name_for_obj(obj):
"""Return a 'name' field for an object. Most objects have a field called `name`, so we try this first.
If this fails, we try `reference` (for Datafiles) and `synonym` (for Synonyms), otherwise we just return
'Unknown'.
"""
if "name" in obj.__dict__:
return obj.name
elif "reference" in obj.__dict__:
return obj.reference
elif "synonym" in obj.__dict__:
return obj.synonym
else:
return "Unknown" | afa09f74d30809c826b39ce4a0973453154f451c | 111,471 |
def number_in_set(c,s):
"""Function that takes a counter and a set and returns the sum of counts for all
items in that set"""
return sum(v for k,v in c.items() if k in s) | 3f9387e0caf98762a053e6c8ab1dc253203da825 | 111,473 |
from typing import Callable
import functools
from typing import Any
import torch
def torch_no_grad(func: Callable) -> Callable:
"""Decorator that runs the decorated function in a context with disabled PyTorch
gradient calculations.
Disabling gradient calculations is useful for inference time, when you are sure
that you will not call `Tensor.backward()`.
This will reduce memory consumption for computations that would otherwise have
`requires_grad=True`. In this mode, the result of every computation will have
`requires_grad=False`, even when the inputs have `requires_grad=True`.
Arguments:
func: the function to be decorated.
Returns:
The decorated function, which evaluates in a context with disabled gradient
calculations.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs) -> Any:
"""Wrapped function to be returned by the decorator.
Returns:
The original function evaluation.
"""
with torch.no_grad():
return func(*args, **kwargs)
return wrapper | b2819c3289b34c9704c992b1b9733e7009d1ed06 | 111,475 |
def read_excluded(exc_arg):
"""Read the list of excluded genes."""
if exc_arg is None:
return set()
f = open(exc_arg, "r")
ret = set(x.rstrip() for x in f)
f.close()
return ret | feaa1d19bc2c5adf3dae108391302825b11f586e | 111,477 |
import base64
def make_pubsub_event(data: str) -> dict:
"""Make pubsub event dictionary with base64-encoded data."""
b64data = base64.encodebytes(bytes(data, "utf-8"))
return {"data": b64data} | a541c6647671efd528c24194449ec72d38e89592 | 111,478 |
def partisan_gini(election_results):
"""
Computes the partisan Gini score for the given ElectionResults.
The partisan Gini score is defined as the area between the seats-votes
curve and its reflection about (.5, .5).
"""
# For two parties, the Gini score is symmetric--it does not vary by party.
party = election_results.election.parties[0]
# To find seats as a function of votes, we assume uniform partisan swing.
# That is, if the statewide popular vote share for a party swings by some
# delta, the vote share for that party swings by that delta in each
# district.
# We calculate the necessary delta to shift the district with the highest
# vote share for the party to a vote share of 0.5. This delta, subtracted
# from the original popular vote share, gives the minimum popular vote
# share that yields 1 seat to the party.
# We repeat this process for the district with the second-highest vote
# share, which gives the minimum popular vote share yielding 2 seats,
# and so on.
overall_result = election_results.percent(party)
race_results = sorted(election_results.percents(party), reverse=True)
seats_votes = [overall_result - r + 0.5 for r in race_results]
# Apply reflection of seats-votes curve about (.5, .5)
reflected_sv = reversed([1 - s for s in seats_votes])
# Calculate the unscaled, unsigned area between the seats-votes curve
# and its reflection. For each possible number of seats attained, we find
# the area of a rectangle of unit height, with a width determined by the
# horizontal distance between the curves at that number of seats.
unscaled_area = sum(abs(s - r) for s, r in zip(seats_votes, reflected_sv))
# We divide by area by the number of seats to obtain a partisan Gini score
# between 0 and 1.
return unscaled_area / len(race_results) | 31fbca907e30e55dfe87cab4b524e5e1cff984ab | 111,488 |
import math
def l2_distance(data1, data2):
""" l2_distance function
Find the L2 distance between two data points.
Args
----
data1 : np.array
pixel array
data2 : np.array
pixel array
Returns
-------
Number
"""
sum = 0
for i in range(len(data1)):
val1 = data1[i]
val2 = data2[i]
sum += ((val1-val2) ** 2)
return math.sqrt(sum) | e2c88d67783e7812656d1577d04529eb523df368 | 111,491 |
def name(obj):
"""return the object name
Using in template:
'{{ obj|name }}'
"""
return obj.__class__.__name__ | e35f26f13b04ead1c77444883c80ba55147a3937 | 111,494 |
def extract_first_authors_name(author_list):
"""
Extract first name from a string including list of authors in form Author1; Author2; ...; AuthorN
"""
return author_list.split(';')[0].split(' ')[0] | 95828febeb44357e86e291a912c7ed730aa05769 | 111,501 |
def _resolve_yes_no(value):
"""
Fix for default values other than True or False for click_prompt_yes_no().
:param value: Return value of click.prompt(..., ..., type=click.BOOL)
:returns: Returns True/False.
"""
return True if value in [True, 'True', 1, '1', 'yes', 'y'] else False | 4315841791798df5cac7dbda995f27858f948fb4 | 111,503 |
def produce_inter_times(timestamps, max_filter=None):
"""
Produces a list of the ordered timespans in seconds between epoch
timestamps.
Args:
timestamps: list of positive numbers representing epoch time
stamps in seconds.
Returns:
inter_times: list of time invervals (in seconds) between the
values in timestamps.
"""
inter_times = []
last_t=None
for t in timestamps:
if (not last_t is None) and (not t is None):
if t<last_t:
raise ValueError("Timestamps are not increasing!")
if t!=0 and last_t!=0:
if max_filter is None or t-last_t<=max_filter:
inter_times.append((t-last_t))
last_t=t
return inter_times | e7b91435dd4bfe24cd02f81c759872e9bd4ed359 | 111,507 |
def calculate_percentages(counts):
"""
Given a list of (token, count) tuples, create a new list (token,
count, percentage) where percentage is the percentage number of
occurrences of this token compared to the total number of tokens.
Arguments:
counts (list of (str or unicode, int)): tuples of form (token,
count).
Arguments:
list of (str or unicode, int, double): tuples of form (token,
count, percentage).
"""
total = 0
for count in counts:
assert count[1] >= 0
total += count[1]
tuples = [(token, count, (float(count) / total) * 100.0)
for (token, count) in counts]
return tuples | 7f474ac0635da47dda9409e209481c8078e2881f | 111,511 |
def _get_target_service_attr_obj(service_instance, target_attr_name):
"""
get attribute object, includes validation for 2nd gen shell namespace
:param ServiceInstance service_instance:
:param str target_attr_name: the name of target attribute. Do not include the prefixed-namespace
:return ServiceAttribute:
"""
# Attribute names with 2nd gen name space (using ServiceName)
target_namespaced_attr = "{service_name}.{attr}".format(service_name=service_instance.ServiceName,
attr=target_attr_name)
# check against all possibilities
target_service_attr_filter = [attr for attr in service_instance.Attributes if attr.Name == target_attr_name
or attr.Name == target_namespaced_attr]
if target_service_attr_filter:
return target_service_attr_filter[0]
else:
raise AttributeError("'{}' has no attribute '{}'".format(service_instance, target_attr_name)) | eefc3df77992dbb1a8df4b125dbb367517a0f088 | 111,515 |
def _static_vars_(**kwargs):
"""
Adds static variables to a decorated function
Code taken from https://stackoverflow.com/questions/279561/
what-is-the-python-equivalent-of-static-variables-inside-a-function
:param kwargs:
:return:
"""
def decorate(func):
for k in kwargs:
setattr(func, k, kwargs[k])
return func
return decorate | 2d426a50678aeb7c6ebb667bd172b11ccfe6e244 | 111,517 |
def jumpTable(prefix, *args):
"""
Return a string consisting of a series of <a href='#prefix-xxx'>xxx</a>.
Include <font size='1'></font> around all of it.
"""
header = "<font size='1'>"
sep = ""
for table in args:
header = header + sep + "<a href='#" + prefix + "-" + table + "'>" + table + "</a> "
sep = " | "
header = header + "</font>"
return header | 3ed0bed76243b5f0c805ddf331e8d3e67fc162a1 | 111,519 |
def factorielle(n):
"""Fonction récursive qui renvoie la valeur
n! = 1 x 2 x 3 x ... x n
"""
if n == 0:
return 1
return n * factorielle(n - 1) | e12a87f9799bd56ee4c18b2f392c32c51a91dbe4 | 111,521 |
import pickle
def binary_encode(data):
""" default binary encoder
"""
return pickle.dumps(data, 0) | 56489ad67e601387e9671cc88dbcb4957140b2e5 | 111,522 |
import re
def parse_rst_params(doc):
"""
Parse a reStructuredText docstring and return a dictionary
with parameter names and descriptions.
>>> doc = '''
... :param foo: foo parameter
... foo parameter
...
... :param bar: bar parameter
... :param baz: baz parameter
... baz parameter
... baz parameter
... Some text.
... '''
>>> params = parse_rst_params(doc)
>>> params['foo']
'foo parameter foo parameter'
>>> params['bar']
'bar parameter'
>>> params['baz']
'baz parameter baz parameter baz parameter'
"""
param_re = re.compile(r"""^([ \t]*):param\
(?P<param>\w+):\
(?P<body>.*\n(\1[ \t]+\w.*\n)*)""",
re.MULTILINE|re.VERBOSE)
params = {}
for match in param_re.finditer(doc):
parts = match.groupdict()
body_lines = parts['body'].strip().split('\n')
params[parts['param']] = ' '.join(s.strip() for s in body_lines)
return params | be35bdff9ea9aca182b44d3423c4987696e8c2c4 | 111,523 |
def _get_alpha(i, n, start=0.4, end=1.0):
""" Compute alpha value at position i out of n """
return start + (1 + i)*(end - start)/n | 464a5d0388262d77a29593062d55ffc3da220262 | 111,525 |
def against_wall(data, pos):
""" Get a list of the directions of walls that the snake is adjacent to. """
width = data['board']['width']
height = data['board']['height']
adjacent = []
if pos['x'] == 0:
adjacent.append("left")
if pos['x'] == width - 1:
adjacent.append("right")
if pos['y'] == 0:
adjacent.append("up")
if pos['y'] == height - 1:
adjacent.append("down")
return adjacent | 2a51d433e42d2cb9f13bda1d165027fd33429735 | 111,528 |
def dec_to_bin(number):
"""
Returns the string representation of a binary
number.
:param number: int, base 10
:return: str, string representation base 2
>>> assert(dec_to_bin(10) == '1010')
"""
return '{0:b}'.format(number) | 421986f99f8777555098287a02add89335ba5619 | 111,534 |
def remove_punctuation(text, keep_cash=True):
"""
Remove punctuation from text.
Input
-----
text : str
Text to remove punctuation from.
keep_cash : bool (default True)
Whether to remove the dollar sign '$' or not.
"""
# Define which punctuation to remove:
punctuation = '!"#%&\'()*+,-.:;<=>?@[\\]^_`{|}~'
if keep_cash == False:
punctuation = punctuation + '$'
return text.translate(str.maketrans('/', ' ', punctuation)) | d882292635c628d7f7c7a00626c5901a7acdf6a3 | 111,537 |
def fmt(docstr):
"""Format a docstring for use as documentation in sample config."""
# Replace newlines with spaces, as docstring contain literal newlines that
# should not be rendered into the sample configuration file (instead, line
# wrappings should be applied automatically).
docstr = docstr.replace('\n', ' ')
# Because it's common for docstrings to begin and end with a newline, there
# is now whitespace at the beginning and end of the documentation as a side
# effect of replacing newlines with spaces/
docstr = docstr.strip()
return docstr | c6932066135d576b583be497a0075f203ccbdb99 | 111,539 |
def getResidInfo(resid, nodes, resExcludes=[]):
"""
Get the node information for specified protein residue index.
Parameters
----------
resid : int
protein residue number
nodes : pandas dataframe
Dataframe in which to translate protein index to node index (indices).
resExcludes: list
List containing strings for residues to ignore. E.g., ['WAT']
Returns
-------
pandas dataframe
"""
nodes_id = nodes.loc[nodes['resid'] == resid]
nodes_id = nodes_id[~nodes_id.resname.isin(resExcludes)]
return nodes_id | 74d217896923c3e6ee2a73607df1e01e24502df1 | 111,540 |
import math
def pixel_coords_zoom_to_lat_lon(PixelX, PixelY, zoom):
"""Convert pixel coordinates and zoom from Bing maps to lan, lot
Parameters
----------
PixelX : int
horizontal distance from upper left corner in pixels
PixelY : int
vertical distance from upper left corner in pixels
zoom : int
zoom of the map (essentially size of a pixel)
Returns
-------
tuple of floats
latitude, longitude
"""
MapSize = 256 * math.pow(2, zoom)
x = (PixelX / MapSize) - 0.5
y = 0.5 - (PixelY / MapSize)
lon = 360 * x
lat = 90 - 360 * math.atan(math.exp(-y * 2 * math.pi)) / math.pi
return lon, lat | b7e338e756ae606c95078d8c6a684e8fa81614be | 111,541 |
def text_compare(one, two):
"""Compares the contents of two XML text attributes."""
if not one and not two:
return True
return (one or "").strip() == (two or "").strip() | 442db43f4fdeb4d563f38b384a2ffa00cf0233ec | 111,544 |
def uniquifier(seq, key=None):
"""
Make a unique list from a sequence. Optional key argument is a callable
that transforms an item to its key.
Borrowed in part from http://www.peterbe.com/plog/uniqifiers-benchmark
"""
if key is None:
key = lambda x: x
def finder(seq):
seen = {}
for item in seq:
marker = key(item)
if marker not in seen:
seen[marker] = True
yield item
return list(finder(seq)) | ab834043538b4207a4b124977c97ba89fa9adcb7 | 111,547 |
def get_objects_zsize(L):
"""Retrieve objects size (2/3D).
Args:
L (np.array): labelled thresholded image.
Returns:
list: Z size of every object in the labelled image.
"""
return [(L == i).astype("int").sum(0).max() for i in range(1, L.max())] | 73e8ae27c6338a8659fcd4662d3791ca16d38dc4 | 111,551 |
def parse_is_forfeit(d):
""" Used to parse whether or not one of the teams forfeited the match.
"""
return bool("FOR" in d.get("uitslag", "")) | eb5f96e6003df4d656314040c144ccdbd1168f27 | 111,555 |
def frozenset_repr(iterable):
"""
Return a repr() of frozenset compatible with Python 2.6.
Python 2.6 doesn't have set literals, and newer versions
of Python use set literals in the ``frozenset()`` ``__repr__()``.
"""
return "frozenset(({0}))".format(
", ".join(map(repr, iterable))
) | a5074a59f58898cbb42db6fcb827c47034e32acb | 111,556 |
def bytes_from_int(v, pad_to):
"""Creates little-endian bytes from integer."""
assert v >= 0
return int.to_bytes(v, pad_to, byteorder="little") | 04bf58f6e71494e690788bd870fdfc361abe2513 | 111,559 |
from typing import List
def generate_class(class_type: str, name: str, types: List[str]) -> str:
"""Generate thrift struct from types
>>> print(generate_class("struct", "Foo", ["i64", "optional string", "set<i32> (cpp.ref = 'true')"]))
struct Foo {
1: i64 field_1;
2: optional string field_2;
3: set<i32> (cpp.ref = 'true') field_3;
}
"""
lines = [f"{class_type} {name} {{"]
for i, t in enumerate(types):
lines.append(" {0}: {1} field_{0};".format(i + 1, t))
lines.append(f'}} (any_type.name="facebook.com/thrift/test/testset/{name}")')
return "\n".join(lines) | 6c51f7fcccefaba675a30707dcd1d65b46e85319 | 111,563 |
def percent2float(percent):
"""
Converts a string with a percentage to a float.
"""
percent = percent.replace(" ", "")
percent = percent.strip("%")
return float(percent) / 100 | 059bd0accdf6c3ac249604bb342f523c1825a173 | 111,569 |
from typing import Dict
from typing import Any
def constant() -> Dict[str, Any]:
"""
Returns:
Schema for validating the `constant` block
"""
data = {
"type": "list",
"schema": {
"type": "dict",
"schema": {
"name": {"type": "string", "required": True},
"inherits": {"type": "list", "schema": {"type": "string"}},
"data": {
"type": "list",
"schema": {
"type": "dict",
"schema": {
"key": {"type": "string", "required": True},
"value": {"type": "string", "required": True},
},
},
},
},
},
}
return data | c82a50e181786ae8e5cad30e4fe131063469077d | 111,573 |
def match_state(exp_state, states):
"""
Matches state values.
- exp_state:
A dictionary of expected state values, where
the key is the state name, the value the expected state.
- states:
The state content of the state change event.
Returns either True or False based on the match.
"""
for exp_state_name, exp_state_val in exp_state.items():
if exp_state_name not in states:
return False
if states[exp_state_name] != exp_state_val:
return False
return True | 4cfceb2bbc03c433aefda0e6b2da7c182da57d9e | 111,574 |
import six
def str_map(param):
"""Ensure that a dictionary contains only string values."""
if not param:
return {}
for k, v in six.iteritems(param):
if v is not None and (not isinstance(k, six.string_types) or
not isinstance(v, six.string_types)):
raise Exception("Invalid config entry %s:%s (not strings)",
k, v)
return param | 8f57a0fb3c23796c4f2b2bee7022581bb9435e42 | 111,576 |
def compute_empirical_p_value(value, random_values, direction):
"""
Compute empirical p-value.
Arguments:
value (float):
random_values (array):
direction (str): 'less' | 'great'
Returns:
float: p-value
"""
if direction == 'less':
significant_random_values = random_values <= value
elif direction == 'great':
significant_random_values = value <= random_values
else:
raise ValueError('Unknown direction: {}.'.format(direction))
p_value = significant_random_values.sum() / random_values.size
if p_value == 0:
p_value = 1 / random_values.size
return p_value | 530d3c9f8d6674cdf10680c401657a63ce44f3fa | 111,579 |
def checkValence( k,newgraphs,nodesValence ):
"""
Returns True if graph k's valence is different from any other new graph's
valence, False otherwise.
"""
for i in newgraphs:
# check if valences are equal
if nodesValence[k] == nodesValence[i]:
return False
return True | 3877d512e0f305485f4d5606ab048bbb054a33cb | 111,580 |
import math
def implied_vol_quadratic_approx(
underlying, strike, rate, maturity, option_value):
"""implied_vol_quadratic_approx
calculates implied volatility by Corrado-Miller approximation formula.
See Corrado, C. J., & Miller, T. W. (1996).
A note on a simple, accurate formula
to compute implied standard deviations.
Journal of Banking & Finance, 20(1996), 595–603.
https://doi.org/10.1016/0378-4266(95)00014-3
:param float underlying:
:param float strike:
:param float rate:
:param float maturity:
:param float option_value:
:return: approximated implied volatility.
If `maturity` is not positive, this function returns 0.
:rtype: float.
"""
if maturity <= 0.0:
return 0.0
discount_strike = math.exp(-rate * maturity) * strike
moneyness_delta = underlying - discount_strike
diff = option_value - moneyness_delta / 2.0
moneyness_delta2 = moneyness_delta ** 2
# take lower bound
sqrt_inner = max(diff ** 2 - moneyness_delta2 / math.pi, 0.0)
factor1 = diff + math.sqrt(sqrt_inner)
factor2 = (math.sqrt(2.0 * math.pi / maturity)
/ (underlying + discount_strike))
return factor1 * factor2 | 6d5d649399878deb7c3018f81ef4528fd462eb4a | 111,582 |
def choose(n, r):
"""Return number of ways of choosing r items from an array with n items.
Parameters
----------
n : int
number of items to choose from
r : int
number of items to choose
Returns
-------
combinations : int
The number if ways of making the choice
"""
if n < 0 or r < 0:
raise ValueError('Negative values not allowed')
if r > n:
raise ValueError('r must not be greater than n')
combinations = 1
r1 = min(r, n-r)
for k in range(r1):
combinations = combinations * (n - k) // (k + 1)
return combinations | 7eea6484f92c87560ea7f74c43cc688a1f76b9c3 | 111,585 |
def get_public_email(user):
"""
Helper function to return public user email to send emails
"""
if len(user.get_all_user_emails()) > 0:
return next((email for email in user.get_all_user_emails() if "noreply.github.com" not in email), None) | 2681833db958bc985017b4446576703c3a91a6e5 | 111,588 |
def makeRootRelativePath( env, path ):
"""
Takes a path relative to the current working directory and
converts it to a root-relative path (e.g., a path beginning
with a hash symbol).
"""
return "#%s" % env.Dir( path ).path | 2f3d1c2d6f013f685dedef991b1e2df722fabb2c | 111,589 |
def part1(depths):
"""Count no. of times depth increases"""
increase_count = 0
for i in range(1, len(depths)):
if depths[i] > depths[i - 1]:
increase_count += 1
return increase_count | 526a111c1b17da715699d78ebaeb1460223a9129 | 111,590 |
def get_nested_attr(obj, attr_name):
"""Same as getattr(obj, attr_name), but allows attr_name to be nested
e.g. get_nested_attr(obj, "foo.bar") is equivalent to obj.foo.bar"""
for name_part in attr_name.split('.'):
if hasattr(obj, name_part):
obj = getattr(obj, name_part)
else:
raise AttributeError("module has no " + name_part + " attribute")
return obj | 32a563ea084ad25dc3017772d3b7eeac0906fc29 | 111,592 |
import re
def _version_info(module):
"""Helper function returns a tuple containing the version number
components for a given module.
"""
try:
version = module.__version__
except AttributeError:
version = str(module)
def cast_as_int(value):
try:
return int(value)
except ValueError:
return value
return tuple(cast_as_int(x) for x in re.split('[.+]', version)) | eb82c7d173c1edd31745c65f206ef2b4682ac253 | 111,603 |
def accuracy(output, labels):
""" Calculate accuracy.
Args:
output: output of a model.
labels: ground truth labels.
Returns:
float: accuracy score.
"""
if any([s > 1 for s in labels.shape]):
s = output.round() + labels
numerator = (s == 2).sum().double() + (s == 0).sum().double()
denominator = (s == 1).sum()
# print("output + labels: {}".format(s),
# "numerator: {}".format(numerator.item()),
# "denominator: {}".format(denominator.item()))
if denominator == 0:
return 0.0
return (numerator / denominator).item()
else:
return (output.round() == labels).sum().item() / output.numel() | 6391fdfd5c585aacd543a64c948424b7d0b07c3f | 111,611 |
import random
def get_train_test(percent_train):
"""Randomly choose test or train label
Parameters
----------
percent_train: float
the fraction of the training set
with respect to the full (training + test) set
Returns
-------
sample: string
'test' or 'train' set
"""
rando = random.uniform(0, 1)
if(rando < percent_train):
sample = 'train'
else:
sample = 'test'
return sample | 9730753decac292076033521fffe62006b10fed2 | 111,614 |
def clamp(minimum, value, maximum):
"""
Clamp the passed `value` to be between `minimum` and `maximum`, including.
"""
return max(minimum, min(maximum, value)) | dd99e9c7b211bcc17c9888afdddc88a9b59cb3df | 111,615 |
def prefix_with(constant, pieces):
""" From a sequence create another sequence where every second element
is from the original sequence and the odd elements are the prefix.
eg.: prefix_with(0, [1,2,3]) creates [0, 1, 0, 2, 0, 3] """
return [elem for piece in pieces for elem in [constant, piece]] | 27a1bf59759175cdfbaa647f3788adece2f3f636 | 111,629 |
def i2osp(x: int, xlen: int) -> bytes:
"""
Convert a nonnegative integer `x` to an octet string of a specified length `xlen`.
https://tools.ietf.org/html/rfc8017#section-4.1
"""
return x.to_bytes(xlen, byteorder='big', signed=False) | e7710a8334631ee6abc402f37e00835b1b0fa50e | 111,630 |
import re
def cleanText(t):
"""
Clean input text
:param: t: text string
:return: cleaned text
"""
encoded_string = t.encode("ascii", "ignore")
t = encoded_string.decode()
t = re.sub(r'(www).*[\s]*', '', t)
t = re.sub(r"[^A-Za-z0-9,!?*.;’´'\/]", " ", t)
t = re.sub(r",", " ", t)
t = re.sub(r"’", "'", t)
t = re.sub(r"´", "'", t)
t = re.sub(r"\.", " ", t)
t = re.sub(r"!", " ! ", t)
t = re.sub(r"\?", " ? ", t)
t = re.sub(r"\/", " ", t)
return t | efe74e2033db80271344320f91364c5aaa0f1170 | 111,631 |
import curses
def ensure_terminal_size() -> bool:
"""Helper method to ensure correct terminal size"""
if curses.LINES >= 24 and curses.COLS >= 80:
return True
return False | 4f3b68441d2b8bb7a5d02f8994fea7dc5f26e8ac | 111,632 |
import torch
def get_left_right_top_bottom(box, height, width):
"""
- box: Tensor of size [4]
- height: scalar, image hight
- width: scalar, image width
return: left, right, top, bottom in image coordinates
"""
left = (box[0] * width).type(torch.int32)
right = (box[2] * width).type(torch.int32)
top = (box[1] * height).type(torch.int32)
bottom = (box[3] * height).type(torch.int32)
return left, right, top, bottom | 9ecb3fb06203f6b2fe50e83b12da2992473fdc02 | 111,635 |
def prepare_numbers(numbers):
"""Prepares the numbers for the chatbot to interpret.
Parameters
----------
numbers : list
Numbers that the user has input into the chatbot
Returns
-------
numb : list
List of integers that the chatbot can use to put into the calculator.
"""
numb = []
for item in numbers:
numb.append(int(item))
return numb | 3f60538c993e2f544e25ca3b6a988856585284fb | 111,636 |
def incrementalAverageUpdate(avg, sample, sample_number):
"""
:param avg: the old average
:param sample: the new sample to update the average with
:param sample_number: the current sample number (#samples observed so far+1)
Updates an average incrementally.
"""
return avg + (sample - avg) / (sample_number * 1.) | 09145fcbce6343d341613b813af999bbfd5ee619 | 111,637 |
def package_name_from_repo(repository):
"""
Owner and project from repository.
>>> package_name_from_repo('https://github.com/NoRedInk/noredink.git')
('NoRedInk', 'noredink')
"""
repo_without_domain = repository.split('https://github.com/')[1].split('.git')[0]
(owner, project) = repo_without_domain.split('/')
return (owner, project) | 4eef01deb7ee77bfcfef8461eba1ba6402c171fe | 111,638 |
def next_batch(X, y, counter, batch_size):
""" Returns the next batch from the preprocessed data
Args:
X: EEG input data of size [batch_size, window_length, electrodes]
y: lables, size [batch_size]
counter (int): the batch number
Returns:
batch of data and corresponding lables
"""
start_index = counter * batch_size
end_index = start_index + batch_size
if end_index > X.shape[0]:
end_index = X.shape[0]
return X[start_index: end_index], y[start_index: end_index] | 825693bd088bfec117536461b22b1231bc97fea4 | 111,639 |
def textfile_contains(filename, marker):
"""
Return True if a textfile contains a string.
"""
try:
with open(filename, 'r', encoding='utf8') as file:
text = file.read();
if marker in text:
return True
except Exception as e:
print(e)
return False | c3cc966441fb65c9b5fbc0efdf56ba0f842f0565 | 111,642 |
def check_transaction_threw(client, transaction_hash):
"""Check if the transaction threw/reverted or if it executed properly
Returns None in case of success and the transaction receipt if the
transaction's status indicator is 0x0.
"""
receipt = client.web3.eth.getTransactionReceipt(transaction_hash)
if 'status' not in receipt:
raise ValueError(
'Transaction receipt does not contain a status field. Upgrade your client',
)
if receipt['status'] == 0:
return receipt
return None | 0f6fa3ea236a58a948c634b1dc35f25402ab74e2 | 111,643 |
def human_readable_int(x):
"""
Transforms the integer `x` into a string containing thousands separators.
"""
assert isinstance(x, int)
in_str = str(x)
digit_count = len(in_str)
out_str = ""
for (n_digit, digit) in enumerate(in_str):
if (n_digit > 0) and (((digit_count - n_digit) % 3) == 0):
out_str += ","
out_str += digit
return out_str | 49bd3fbd9be2cebf85c27b178f9683fa19f021d1 | 111,649 |
def find_val_in_col(value, column):
"""
Returns the Row value in which the "value" was found
"""
for n, cell in enumerate(column):
if cell.value == value:
return n + 1
return 0 | f5f7a1d5276b8b8c765edd069adab346673c0302 | 111,651 |
import re
def convert_string_to_snake_case(name):
""" Converts a string to Snake Case
:param name: A string
:return: A string in snake case
Example use case:
- Events from might have custom properties in camelCase like userId, and userEmail
- Use this to rename keys to user_id and user_email for better ease of reading in the database
Examples:
.. code-block:: python
# Example #1
input_string = 'MakeThisSnakeCase'
output_string = convert_string_to_snake_case(input_string)
output_string = 'make_this_snake_case'
# Example #2
input_string = 'Make This Snake Case'
output_string = convert_string_to_snake_case(input_string)
output_string = 'make_this_snake_case'
# Example #3
input_string = 'keep_this_snake_case'
output_string = convert_string_to_snake_case(input_string)
output_string = 'keep_this_snake_case'
"""
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
sl = re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
return sl.replace(' ', '') | 177530486b1e011f625731837773b029a31b14da | 111,653 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.