content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def contains_message(response, message):
"""
Inspired by django's self.assertRaisesMessage
Useful for confirming the response contains the provided message,
"""
if len(response.context['messages']) != 1:
return False
full_message = str(list(response.context['messages'])[0])
return... | 4afcdba84603b8b53095a52e769d0a8e3f7bbb17 | 4,037 |
import re
def since(version):
"""A decorator that annotates a function to append the version
of skutil the function was added. This decorator is an adaptation of PySpark's.
Parameters
----------
version : str, float or int
The version the specified method was added to skutil.
Exam... | e6b29b5e4c67ba4a213b183a0b79a1f16a85d81c | 4,038 |
def striptag(tag):
"""
Get the short representation of a fully qualified tag
:param str tag: a (fully qualified or not) XML tag
"""
if tag.startswith('{'):
return tag.rsplit('}')[1]
return tag | f0193e3f792122ba8278e599247439a91139e72b | 4,039 |
def equal(* vals):
"""Returns True if all arguments are equal"""
if len(vals) < 2:
return True
a = vals[0]
for b in vals[1:]:
if a != b:
return False
return True | dbd947016d2b84faaaa7fefa6f35975da0a1b5ec | 4,041 |
def get_command(tool_xml):
"""Get command XML element from supplied XML root."""
root = tool_xml.getroot()
commands = root.findall("command")
command = None
if len(commands) == 1:
command = commands[0]
return command | 8d50b2675b3a6089b15b5380025ca7def9e4339e | 4,043 |
import re
def ParseTimeCommandResult(command_result):
"""Parse command result and get time elapsed.
Args:
command_result: The result after executing a remote time command.
Returns:
Time taken for the command.
"""
time_data = re.findall(r'real\s+(\d+)m(\d+.\d+)', command_result)
time_in_seconds... | fc92d4b996716ddb2253bf4eb75ed9860c43b2d7 | 4,047 |
def get_grains_connected_to_face(mesh, face_set, node_id_grain_lut):
"""
This function find the grain connected to the face set given as argument.
Three nodes on a grain boundary can all be intersected by one grain
in which case the grain face is on the boundary or by two grains. It
is therefore su... | cb4adff2d6ffe3c32e2a1fc8058e6ad1fed9b2c9 | 4,050 |
def argmin(x):
"""
Returns the index of the smallest element of the iterable `x`.
If two or more elements equal the minimum value, the index of the first
such element is returned.
>>> argmin([1, 3, 2, 0])
3
>>> argmin(abs(x) for x in range(-3, 4))
3
"""
argmin_ = None
min_... | 8d6778182bf3c18ffa6ef72093bf19a818d74911 | 4,051 |
def find_spot(entry, list):
"""
return index of entry in list
"""
for s, spot in enumerate(list):
if entry==spot:
return s
else:
raise ValueError("could not find entry: "+ str(entry)+ " in list: "+ str(list)) | e218822e5e56a62c40f5680751c1360c56f05f4a | 4,052 |
def geom_to_tuple(geom):
"""
Takes a lat/long point (or geom) from KCMO style csvs.
Returns (lat, long) tuple
"""
geom = geom[6:]
geom = geom.replace(" ", ", ")
return eval(geom) | 003f25a0ebc8fd372b63453e4782aa52c0ad697c | 4,054 |
def get_reg_part(reg_doc):
"""
Depending on source, the CFR part number exists in different places. Fetch
it, wherever it is.
"""
potential_parts = []
potential_parts.extend(
# FR notice
node.attrib['PART'] for node in reg_doc.xpath('//REGTEXT'))
potential_parts.extend(
... | 33f4c2bb9a4e2f404e7ef94a3bfe3707a3b1dd93 | 4,056 |
def group_masses(ip, dm: float = 0.25):
"""
Groups masses in an isotope pattern looking for differences in m/z greater than the specified delta.
expects
:param ip: a paired list of [[mz values],[intensity values]]
:param dm: Delta for looking +/- within
:return: blocks grouped by central mass
... | 918fc4f20fee7c2955218e3c435f9e672dc55f7d | 4,066 |
import math
def point_based_matching(point_pairs):
"""
This function is based on the paper "Robot Pose Estimation in Unknown Environments by Matching 2D Range Scans"
by F. Lu and E. Milios.
:param point_pairs: the matched point pairs [((x1, y1), (x1', y1')), ..., ((xi, yi), (xi', yi')), ...]
:ret... | 2d691bbf04d14e3e5b0f9273a7501d934bd0eef4 | 4,069 |
def bind_port(socket, ip, port):
""" Binds the specified ZMQ socket. If the port is zero, a random port is
chosen. Returns the port that was bound.
"""
connection = 'tcp://%s' % ip
if port <= 0:
port = socket.bind_to_random_port(connection)
else:
connection += ':%i' % port
... | 5613bae6726e2f006706b104463917e48d7ab7ca | 4,071 |
def update_target_graph(actor_tvars, target_tvars, tau):
""" Updates the variables of the target graph using the variable values from the actor, following the DDQN update
equation. """
op_holder = list()
# .assign() is performed on target graph variables with discounted actor graph variable values
f... | 15f0d192ff150c0a39495b0dec53f18a8ae01664 | 4,072 |
def extract_shebang_command(handle):
"""
Extract the shebang_ command line from an executable script.
:param handle: A file-like object (assumed to contain an executable).
:returns: The command in the shebang_ line (a string).
The seek position is expected to be at the start of the file and will b... | 27174f96f2da3167cf7a7e28c4a2f1cec72c773c | 4,076 |
def create_graph(num_islands, bridge_config):
"""
Helper function to create graph using adjacency list implementation
"""
adjacency_list = [list() for _ in range(num_islands + 1)]
for config in bridge_config:
source = config[0]
destination = config[1]
cost = config[2]
... | b961f5ee2955f4b8de640152981a7cede8ca80b0 | 4,078 |
def get_timepoint( data, tp=0 ):
"""Returns the timepoint (3D data volume, lowest is 0) from 4D input.
You can save memory by using [1]:
nifti.dataobj[..., tp]
instead: see get_nifti_timepoint()
Works with loop_and_save().
Call directly, or with niftify().
Ref:
[1]: http:/... | f5a718e5d9f60d1b389839fc0c637bee32b500bf | 4,079 |
def method_from_name(klass, method_name: str):
"""
Given an imported class, return the given method pointer.
:param klass: An imported class containing the method.
:param method_name: The method name to find.
:return: The method pointer
"""
try:
return getattr(klass, method_name)
... | 97274754bd89ede62ee5940fca6c4763efdbb95c | 4,080 |
def convert(origDict, initialSpecies):
"""
Convert the original dictionary with species labels as keys
into a new dictionary with species objects as keys,
using the given dictionary of species.
"""
new_dict = {}
for label, value in origDict.items():
new_dict[initialSpecies[label]] =... | 5143f31acd1efdf1790e68bade3a1f8d8977bcde | 4,083 |
def command_ltc(bot, user, channel, args):
"""Display current LRC exchange rates from BTC-E"""
r = bot.get_url("https://btc-e.com/api/2/ltc_usd/ticker")
j = r.json()['ticker']
return bot.say(channel, "BTC-E: avg:$%s last:$%s low:$%s high:$%s vol:%s" % (j['avg'], j['last'], j['low'], j['high'], j['vol']... | 7aa411b6708e54b09cf2b9aef9c8b01899b95298 | 4,085 |
def union_exprs(La, Lb):
"""
Union two lists of Exprs.
"""
b_strs = set([node.unique_str() for node in Lb])
a_extra_nodes = [node for node in La if node.unique_str() not in b_strs]
return a_extra_nodes + Lb | 2bd634a22b27314f6d03c8e52c0b09f7f4b692db | 4,087 |
import re
import itertools
def compile_read_regex(read_tags, file_extension):
"""Generate regular expressions to disern direction in paired-end reads."""
read_regex = [re.compile(r'{}\.{}$'.format(x, y))\
for x, y in itertools.product(read_tags, [file_extension])]
return read_regex | e677b8ff622eb31ea5f77bc662845ba0aef91770 | 4,088 |
from typing import List
def get_bank_sizes(num_constraints: int,
beam_size: int,
candidate_counts: List[int]) -> List[int]:
"""
Evenly distributes the beam across the banks, where each bank is a portion of the beam devoted
to hypotheses having met the same number of c... | 7a515b1e7762d01b7f7a1405a943f03babe26520 | 4,091 |
def datetime_to_hours(dt):
"""Converts datetime.timedelta to hours
Parameters:
-----------
dt: datetime.timedelta
Returns:
--------
float
"""
return dt.days * 24 + dt.seconds / 3600 | e7373cbb49e21340fef1590a655059fd39c6ce88 | 4,104 |
import http
def build_status(code: int) -> str:
"""
Builds a string with HTTP status code and reason for given code.
:param code: integer HTTP code
:return: string with code and reason
"""
status = http.HTTPStatus(code)
def _process_word(_word: str) -> str:
if _word == "OK":
... | 9730abf472ddc3d5e852181c9d60f8c42fee687d | 4,109 |
def benedict_bornder_constants(g, critical=False):
""" Computes the g,h constants for a Benedict-Bordner filter, which
minimizes transient errors for a g-h filter.
Returns the values g,h for a specified g. Strictly speaking, only h
is computed, g is returned unchanged.
The default formula for the ... | ca40941b4843b3d71030549da2810c9241ebdf72 | 4,111 |
import re
def remove_special_message(section_content):
"""
Remove special message - "medicinal product no longer authorised"
e.g.
'me di cin al p ro du ct n o lo ng er a ut ho ris ed'
'me dic ina l p rod uc t n o l on ge r a uth ori se d'
:param section_content: content of a section
:ret... | 37d9cbd697a98891b3f19848c90cb17dafcd6345 | 4,114 |
def apply_function_elementwise_series(ser, func):
"""Apply a function on a row/column basis of a DataFrame.
Args:
ser (pd.Series): Series.
func (function): The function to apply.
Returns:
pd.Series: Series with the applied function.
Examples:
>>> df = pd.Da... | d2af0a9c7817c602b4621603a8f06283f34ae81a | 4,115 |
def BitWidth(n: int):
""" compute the minimum bitwidth needed to represent and integer """
if n == 0:
return 0
if n > 0:
return n.bit_length()
if n < 0:
# two's-complement WITHOUT sign
return (n + 1).bit_length() | 46dcdfb0987268133d606e609d39c641b9e6faab | 4,116 |
import socket
def tcp_port_open_locally(port):
"""
Returns True if the given TCP port is open on the local machine
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(("127.0.0.1", port))
return result == 0 | f5c801a5016085eedbed953089742e184f514db5 | 4,120 |
def wrap(text, width=80):
"""
Wraps a string at a fixed width.
Arguments
---------
text : str
Text to be wrapped
width : int
Line width
Returns
-------
str
Wrapped string
"""
return "\n".join(
[text[i:i + width] for i in range(0, len(text), w... | 793840a1cae51397de15dd16051c5dfffc211768 | 4,121 |
def get_list_channels(sc):
"""Get list of channels."""
# https://api.slack.com/methods/channels.list
response = sc.api_call(
"channels.list",
)
return response['channels'] | d31271bcc065b4a212e298c6283c4d658e5547da | 4,129 |
def lowercase_words(words):
"""
Lowercases a list of words
Parameters
-----------
words: list of words to process
Returns
-------
Processed list of words where words are now all lowercase
"""
return [word.lower() for word in words] | b6e8658f35743f6729a9f8df229b382797b770f6 | 4,137 |
def isempty(s):
"""
return if input object(string) is empty
"""
if s in (None, "", "-", []):
return True
return False | 9c3ffd6ab818e803c1c0129588c345361c58807f | 4,139 |
def clamp(val, min_, max_):
"""clamp val to between min_ and max_ inclusive"""
if val < min_:
return min_
if val > max_:
return max_
return val | 31f2441ba03cf765138a7ba9b41acbfe21b7bda7 | 4,140 |
def get_ip(request):
"""Determines user IP address
Args:
request: resquest object
Return:
ip_address: requesting machine's ip address (PUBLIC)
"""
ip_address = request.remote_addr
return ip_address | 84e1540bc8b79fd2043a8fb6f107f7bcd8d7cc8c | 4,141 |
from typing import Generator
import pkg_resources
def get_pip_package_list(path: str) -> Generator[pkg_resources.Distribution, None, None]:
"""Get the Pip package list of a Python virtual environment.
Must be a path like: /project/venv/lib/python3.9/site-packages
"""
packages = pkg_resources.find_dis... | 9e73e27c2b50186dedeedd1240c28ef4f4d50e03 | 4,151 |
def _get_reverse_complement(seq):
"""
Get the reverse compliment of a DNA sequence.
Parameters:
-----------
seq
Returns:
--------
reverse_complement_seq
Notes:
------
(1) No dependencies required. Pure python.
"""
complement_seq = ""
for i in seq... | 31408767c628ab7b0e6e63867e37f11eb6e19560 | 4,152 |
def check_table(conn, table, interconnect):
"""
searches if Interconnect exists in table in database
:param conn: connect instance for database
:param table: name of table you want to check
:param interconnect: name of the Interconnect you are looking for
:return: results of SQL query searching... | 0888146d5dfe20e7bdfbfe078c58e86fda43d6a5 | 4,153 |
def read_tab(filename):
"""Read information from a TAB file and return a list.
Parameters
----------
filename : str
Full path and name for the tab file.
Returns
-------
list
"""
with open(filename) as my_file:
lines = my_file.readlines()
return lines | 8a6a6b0ec693130da7f036f4673c89f786dfb230 | 4,155 |
def int2(c):
""" Parse a string as a binary number """
return int(c, 2) | dd1fb1f4c194e159b227c77c4246136863646707 | 4,156 |
def properties(classes):
"""get all property (p-*, u-*, e-*, dt-*) classnames
"""
return [c.partition("-")[2] for c in classes if c.startswith("p-")
or c.startswith("u-") or c.startswith("e-") or c.startswith("dt-")] | 417562d19043f4b98068ec38cc010061b612fef3 | 4,157 |
def _setter_name(getter_name):
""" Convert a getter name to a setter name.
"""
return 'set' + getter_name[0].upper() + getter_name[1:] | d4b55afc10c6d79a1432d2a8f3077eb308ab0f76 | 4,158 |
def thumbnail(img, size = (1000,1000)):
"""Converts Pillow images to a different size without modifying the original image
"""
img_thumbnail = img.copy()
img_thumbnail.thumbnail(size)
return img_thumbnail | 4eb49869a53d9ddd42ca8c184a12f0fedb8586a5 | 4,161 |
def repetitions(seq: str) -> int:
"""
[Easy] https://cses.fi/problemset/task/1069/
[Solution] https://cses.fi/paste/659d805082c50ec1219667/
You are given a DNA sequence: a string consisting of characters A, C, G,
and T. Your task is to find the longest repetition in the sequence. This is
a ma... | 4dde2ec4a6cd6b13a54c2eafe4e8db0d87381faa | 4,177 |
def get_lines(filename):
"""
Returns a list of lines of a file.
Parameters
filename : str, name of control file
"""
with open(filename, "r") as f:
lines = f.readlines()
return lines | 1307b169733b50517b26ecbf0414ca3396475360 | 4,182 |
def normalize_type(type: str) -> str:
"""Normalize DataTransfer's type strings.
https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransfer-getdata
'text' -> 'text/plain'
'url' -> 'text/uri-list'
"""
if type == 'text':
return 'text/plain'
elif type == 'url':
return 'tex... | 887c532218a7775ea55c6a39953ec244183af455 | 4,183 |
def filterLinesByCommentStr(lines, comment_str='#'):
"""
Filter all lines from a file.readlines output which begins with one of the
symbols in the comment_str.
"""
comment_line_idx = []
for i, line in enumerate(lines):
if line[0] in comment_str:
comment_line_idx.append(i)
... | 8a6ce56187afc2368ec81d11c38fe7af2eacb14f | 4,184 |
def GetFlagFromDest(dest):
"""Returns a conventional flag name given a dest name."""
return '--' + dest.replace('_', '-') | 021ab8bca05afbb2325d865a299a2af7c3b939c9 | 4,187 |
def ganache_url(host='127.0.0.1', port='7445'):
"""Return URL for Ganache test server."""
return f"http://{host}:{port}" | 9de6e2c26c0e1235a14c8dd28040fcdfb8a36a7f | 4,188 |
def unwrap(func):
"""
Returns the object wrapped by decorators.
"""
def _is_wrapped(f):
return hasattr(f, '__wrapped__')
unwrapped_f = func
while (_is_wrapped(unwrapped_f)):
unwrapped_f = unwrapped_f.__wrapped__
return unwrapped_f | 17aa0c8cc91578fd1187784ad0396ed91c5ec9b8 | 4,189 |
def tlam(func, tup):
"""Split tuple into arguments
"""
return func(*tup) | 0e3a9b93b36795e6c11631f8c8852aba59724f88 | 4,191 |
def get_N_intransit(tdur, cadence):
"""Estimates number of in-transit points for transits in a light curve.
Parameters
----------
tdur: float
Full transit duration
cadence: float
Cadence/integration time for light curve
Returns
-------
n_intransit: int
Number of... | d126b5590a8997b8695c1a86360421f2bf4b8357 | 4,195 |
def extract_keys(keys, dic, drop=True):
"""
Extract keys from dictionary and return a dictionary with the extracted
values.
If key is not included in the dictionary, it will also be absent from the
output.
"""
out = {}
for k in keys:
try:
if drop:
ou... | 15a66fff5207df18d8ece4959e485068f1bd3c9c | 4,196 |
import sqlite3
def getStations(options, type):
"""Query stations by specific type ('GHCND', 'ASOS', 'COOP', 'USAF-WBAN')
"""
conn = sqlite3.connect(options.database)
c = conn.cursor()
if type == "ALL":
c.execute("select rowid, id, name, lat, lon from stations")
else:
c.execute(... | 59d45a79542e68cd691cf848f3d4fe250389732c | 4,197 |
import random
import string
def random_string_fx() -> str:
"""
Creates a 16 digit alphanumeric string. For use
with logging tests.
Returns:
16 digit alphanumeric string.
"""
result = "".join(random.sample(string.ascii_letters, 16))
return result | 835c2dc2716c6ef0ad37f5ae03cfc9dbe2e16725 | 4,200 |
def report_cots_cv2x_bsm(bsm: dict) -> str:
"""A function to report the BSM information contained in an SPDU from a COTS C-V2X device
:param bsm: a dictionary containing BSM fields from a C-V2X SPDU
:type bsm: dict
:return: a string representation of the BSM fields
:rtype: str
"""
report =... | df0aa5ae4b50980088fe69cb0b776abbf0b0998d | 4,203 |
import random
def random_function(*args):
"""Picks one of its arguments uniformly at random, calls it, and returns the result.
Example usage:
>>> random_function(lambda: numpy.uniform(-2, -1), lambda: numpy.uniform(1, 2))
"""
choice = random.randint(0, len(args) - 1)
return args[choi... | 3f8d11becc52fde5752671e3045a9c64ddfeec97 | 4,205 |
def is_rescue_entry(boot_entry):
"""
Determines whether the given boot entry is rescue.
:param BootEntry boot_entry: Boot entry to assess
:return: True is the entry is rescue
:rtype: bool
"""
return 'rescue' in boot_entry.kernel_image.lower() | ba456c2724c3ad4e35bef110ed8c4cc08147b42c | 4,208 |
import math
def rad_to_gon(angle: float) -> float:
"""Converts from radiant to gon (grad).
Args:
angle: Angle in rad.
Returns:
Converted angle in gon.
"""
return angle * 200 / math.pi | cbf7070a9c3a9796dfe4bffe39fdf2421f7279ed | 4,210 |
def detected(numbers, mode):
"""
Returns a Boolean result indicating whether the last member in a numeric array is the max or
min, depending on the setting.
Arguments
- numbers: an array of numbers
- mode: 'max' or 'min'
"""
call_dict = {'min': min, 'max': max}
if mode not in ca... | b0a5b19e7d97db99769f28c4b8ce998dbe318c5b | 4,211 |
from typing import Any
def fqname_for(obj: Any) -> str:
"""
Returns the fully qualified name of ``obj``.
Parameters
----------
obj
The class we are interested in.
Returns
-------
str
The fully qualified name of ``obj``.
"""
if "<locals>" in obj.__qualname__:
... | 6d4e5db255715c999d1bb40533f3dbe03b948b07 | 4,215 |
def symbol_size(values):
""" Rescale given values to reasonable symbol sizes in the plot. """
max_size = 50.0
min_size = 5.0
# Rescale max.
slope = (max_size - min_size)/(values.max() - values.min())
return slope*(values - values.max()) + max_size | a33f77ee8eeff8d0e63035c5c408a0788b661886 | 4,216 |
def hexColorToInt(rgb):
"""Convert rgb color string to STK integer color code."""
r = int(rgb[0:2],16)
g = int(rgb[2:4],16)
b = int(rgb[4:6],16)
color = format(b, '02X') + format(g, '02X') + format(r, '02X')
return int(color,16) | 59b8815d647b9ca3e90092bb6ee7a0ca19dd46c2 | 4,218 |
def insert_at_index(rootllist, newllist, index):
""" Insert newllist in the llist following rootllist such that newllist is at the provided index in the resulting llist"""
# At start
if index == 0:
newllist.child = rootllist
return newllist
# Walk through the list
curllist = rootllist
for i in ran... | 767cde29fbc711373c37dd3674655fb1bdf3fedf | 4,219 |
def priority(n=0):
"""
Sets the priority of the plugin.
Higher values indicate a higher priority.
This should be used as a decorator.
Returns a decorator function.
:param n: priority (higher values = higher priority)
:type n: int
:rtype: function
"""
def wrapper(cls):
cls... | 58ab19fd88e9e293676943857a0fa04bf16f0e93 | 4,221 |
def sanitize_option(option):
"""
Format the given string by stripping the trailing parentheses
eg. Auckland City (123) -> Auckland City
:param option: String to be formatted
:return: Substring without the trailing parentheses
"""
return ' '.join(option.split(' ')[:-1]).strip() | ece0a78599e428ae8826b82d7d00ffc39495d27f | 4,222 |
import pickle
def from_pickle(input_path):
"""Read from pickle file."""
with open(input_path, 'rb') as f:
unpickler = pickle.Unpickler(f)
return unpickler.load() | 4e537fcde38e612e22004007122130c545246afb | 4,229 |
def get_only_metrics(results):
"""Turn dictionary of results into a list of metrics"""
metrics_names = ["test/f1", "test/precision", "test/recall", "test/loss"]
metrics = [results[name] for name in metrics_names]
return metrics | 1b0e5bb8771fdc44dcd22ff9cdb174f77205eadd | 4,230 |
def pkcs7_unpad(data):
"""
Remove the padding bytes that were added at point of encryption.
Implementation copied from pyaspora:
https://github.com/mjnovice/pyaspora/blob/master/pyaspora/diaspora/protocol.py#L209
"""
if isinstance(data, str):
return data[0:-ord(data[-1])]
else:
... | 4b43b80220e195aa51c129b6cbe1f216a94360cd | 4,233 |
def _chk_y_path(tile):
"""
Check to make sure tile is among left most possible tiles
"""
if tile[0] == 0:
return True
return False | cf733c778b647654652ae5c651c7586c8c3567b8 | 4,235 |
import re
def alphanum_key(string):
"""Return a comparable tuple with extracted number segments.
Adapted from: http://stackoverflow.com/a/2669120/176978
"""
convert = lambda text: int(text) if text.isdigit() else text
return [convert(segment) for segment in re.split('([0-9]+)', string)] | 0e5e3f1d6aa43d393e1fb970f64e5910e7dc53fc | 4,236 |
def weight_point_in_circle(
point: tuple,
center: tuple,
radius: int,
corner_threshold: float = 1.5
):
"""
Function to decide whether a certain grid coordinate should be a full, half or empty tile.
Arguments:
point (tuple): x, y of the point to be tested
... | db0da5e101184975385fb07e7b22c5e8a6d4fd47 | 4,251 |
def get_arrival_times(inter_times):
"""Convert interevent times to arrival times."""
return inter_times.cumsum() | 7197fc6315d3eaca118ca419f23aed7c0d7cd064 | 4,254 |
def contains_vendored_imports(python_path):
"""
Returns True if ``python_path`` seems to contain vendored imports from botocore.
"""
# We're using a very rough heuristic here: if the source code contains
# strings that look like a vendored import, we'll flag.
#
# Because Python is dynamic, t... | 90ed6939d7f43cac29eb66c3e27e911b9cc62532 | 4,255 |
def precip_units(units):
"""
Return a standardized name for precip units.
"""
kgm2s = ['kg/m2/s', '(kg/m^2)/s', 'kg/m^2/s', 'kg m^-2 s^-1',
'kg/(m^2 s)', 'kg m-2 s-1']
mmday = ['mm/day', 'mm day^-1']
if units.lower() in kgm2s:
return 'kg m^-2 s^-1'
elif units.lower() in... | e5f94c3dd41b68d2e7b6b7aa1905fd5508a12fab | 4,258 |
def read_user(msg):
"""Read user input.
:param msg: A message to prompt
:type msg: ``str``
:return: ``True`` if user gives 'y' otherwhise False.
:rtype: ``bool``
"""
user_input = input("{msg} y/n?: ".format(msg=msg))
return user_input == 'y' | 662e95002130a6511e6e9a5d6ea85805f6b8f0f5 | 4,261 |
def stringify_parsed_email(parsed):
"""
Convert a parsed email tuple into a single email string
"""
if len(parsed) == 2:
return f"{parsed[0]} <{parsed[1]}>"
return parsed[0] | 6552987fe6a06fdbb6bd49e5d17d5aadaae3c832 | 4,267 |
def base_to_str( base ):
"""Converts 0,1,2,3 to A,C,G,T"""
if 0 == base: return 'A'
if 1 == base: return 'C'
if 2 == base: return 'G'
if 3 == base: return 'T'
raise RuntimeError( 'Bad base: %d' % base ) | f1c98b7c24fae91c1f809abe47929d724c886168 | 4,268 |
def is_array_of(obj, classinfo):
"""
Check if obj is a list of classinfo or a tuple of classinfo or a set of classinfo
:param obj: an object
:param classinfo: type of class (or subclass). See isinstance() build in function for more info
:return: flag: True or False
"""
flag = False
if is... | 5fecce974b5424cff7d5e6a4a9f9bd1482e10e85 | 4,276 |
from textwrap import dedent
def make_check_stderr_message(stderr, line, reason):
"""
Create an exception message to use inside check_stderr().
"""
return dedent("""\
{reason}:
Caused by line: {line!r}
Complete stderr: {stderr}
""").format(stderr=stderr, line=line, reason=reason) | a6510e8036ab27e6386e6bc8e6c33727849282c0 | 4,277 |
def list_in_list(a, l):
"""Checks if a list is in a list and returns its index if it is (otherwise
returns -1).
Parameters
----------
a : list()
List to search for.
l : list()
List to search through.
"""
return next((i for i, elem in enumerate(l) if elem == a), -1) | 494d9a880bcd2084a0f50e292102dc8845cbbb16 | 4,280 |
def _GenerateGstorageLink(c, p, b):
"""Generate Google storage link given channel, platform, and build."""
return 'gs://chromeos-releases/%s-channel/%s/%s/' % (c, p, b) | e5e4a0eb9e27b0f2d74b28289c8f02dc0454f438 | 4,285 |
def _has_desired_permit(permits, acategory, astatus):
"""
return True if permits has one whose
category_code and status_code match with the given ones
"""
if permits is None:
return False
for permit in permits:
if permit.category_code == acategory and\
permit.status_co... | 4cac23303e2b80e855e800a7d55b7826fabd9992 | 4,287 |
def get_input(request) -> str:
"""Get the input song from the request form."""
return request.form.get('input') | de237dc0ad3ce2fa6312dc6ba0ea9fe1c2bdbeb3 | 4,294 |
def get_gs_distortion(dict_energies: dict):
"""Calculates energy difference between Unperturbed structure and most favourable distortion.
Returns energy drop of the ground-state relative to Unperturbed (in eV) and the BDM distortion that lead to ground-state.
Args:
dict_energies (dict):
... | 2f23103ccac8e801cb6c2c4aff1fb4fc08341e78 | 4,300 |
from typing import Counter
def get_vocabulary(list_):
"""
Computes the vocabulary for the provided list of sentences
:param list_: a list of sentences (strings)
:return: a dictionary with key, val = word, count and a sorted list, by count, of all the words
"""
all_the_words = []
for tex... | d6c357a5768c2c784c7dfe97743d34795b2695c0 | 4,310 |
import math
def split(value, precision=1):
"""
Split `value` into value and "exponent-of-10", where "exponent-of-10" is a
multiple of 3. This corresponds to SI prefixes.
Returns tuple, where the second value is the "exponent-of-10" and the first
value is `value` divided by the "exponent-of-10".
... | 776ded073807773b755dcd7ab20c47d1f33ca1e1 | 4,312 |
def load_secret(name, default=None):
"""Check for and load a secret value mounted by Docker in /run/secrets."""
try:
with open(f"/run/secrets/{name}") as f:
return f.read().strip()
except Exception:
return default | 1aac980ad6bc039964ef9290827eb5c6d1b1455f | 4,321 |
import re
def convert_as_number(symbol: str) -> float:
"""
handle cases:
' ' or '' -> 0
'10.95%' -> 10.95
'$404,691,250' -> 404691250
'$8105.52' -> 8105.52
:param symbol: string
:return: float
"""
result = symbol.strip()
if... | cea1d6e894fa380ecf6968d5cb0ef1ce21b73fac | 4,323 |
import operator
def most_recent_assembly(assembly_list):
"""Based on assembly summaries find the one submitted the most recently"""
if assembly_list:
return sorted(assembly_list, key=operator.itemgetter('submissiondate'))[-1] | 1d7ecf3a1fa862e421295dda0ba3d89863f33b0f | 4,327 |
def evenly_divides(x, y):
"""Returns if [x] evenly divides [y]."""
return int(y / x) == y / x | dbf8236454e88805e71aabf58d9b7ebd2b2a6393 | 4,333 |
def compOverValueTwoSets(setA={1, 2, 3, 4}, setB={3, 4, 5, 6}):
"""
task 0.5.9
comprehension whose value is the intersection of setA and setB
without using the '&' operator
"""
return {x for x in (setA | setB) if x in setA and x in setB} | 2b222d6c171e0170ace64995dd64c352f03aa99b | 4,336 |
def is_numpy_convertable(v):
"""
Return whether a value is meaningfully convertable to a numpy array
via 'numpy.array'
"""
return hasattr(v, "__array__") or hasattr(v, "__array_interface__") | 163da2cf50e2172e1fc39ae8afd7c4417b02a852 | 4,341 |
from datetime import datetime
def get_fake_datetime(now: datetime):
"""Generate monkey patch class for `datetime.datetime`, whose now() and utcnow() always returns given value."""
class FakeDatetime:
"""Fake datetime.datetime class."""
@classmethod
def now(cls):
"""Return... | f268640c6459f4eb88fd9fbe72acf8c9d806d3bc | 4,342 |
def compress_pub_key(pub_key: bytes) -> bytes:
"""Convert uncompressed to compressed public key."""
if pub_key[-1] & 1:
return b"\x03" + pub_key[1:33]
return b"\x02" + pub_key[1:33] | 05824112c6e28c36171c956910810fc1d133c865 | 4,346 |
def _(text):
"""Normalize white space."""
return ' '.join(text.strip().split()) | f99f02a2fe84d3b214164e881d7891d4bfa0571d | 4,347 |
def _infer_title(ntbk, strip_title_header=True):
"""Infer a title from notebook metadata.
First looks in metadata['title'] and if nothing is found,
looks for whether the first line of the first cell is an H1
header. Optionally it strips this header from the notebook content.
"""
# First try the... | e8152f0c160d2cb7af66b1a20f4d95d4ea16c703 | 4,349 |
def get_recommendations(commands_fields, app_pending_changes):
"""
:param commands_fields:
:param app_pending_changes:
:return: List of object describing command to run
>>> cmd_fields = [
... ['cmd1', ['f1', 'f2']],
... ['cmd2', ['prop']],
... ]
>>> app_fields = {
... ... | 03fa583a5d4ea526cfeaa671418488218e1b227f | 4,354 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.