content
stringlengths 39
14.9k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
---|---|---|
def tau_for_x(x, beta):
"""Rescales tau axis to x -1 ... 1"""
if x.min() < -1 or x.max() > 1:
raise ValueError("domain of x")
return .5 * beta * (x + 1) | 1d7b868dfadb65e6f98654276763fd4bff2c20ff | 708,835 |
def minmax(data):
"""Solution to exercise R-1.3.
Takes a sequence of one or more numbers, and returns the smallest and
largest numbers, in the form of a tuple of length two. Do not use the
built-in functions min or max in implementing the solution.
"""
min_idx = 0
max_idx = 0
for idx, num in enumerate(data):
if num > data[max_idx]:
max_idx = idx
if num < data[min_idx]:
min_idx = idx
return (data[min_idx], data[max_idx]) | 9715bef69c120f6d1afb933bd9030240f556eb20 | 708,838 |
def childs_page_return_right_login(response_page, smarsy_login):
"""
Receive HTML page from login function and check we've got expected source
"""
if smarsy_login in response_page:
return True
else:
raise ValueError('Invalid Smarsy Login') | e7cb9b8d9df8bd5345f308e78cec28a20919370e | 708,843 |
def vec_sum(a, b):
"""Compute the sum of two vector given in lists."""
return [va + vb for va, vb in zip(a, b)] | d85f55e22a60af66a85eb6c8cd180007351bf5d9 | 708,848 |
def dequote(str):
"""Will remove single or double quotes from the start and end of a string
and return the result."""
quotechars = "'\""
while len(str) and str[0] in quotechars:
str = str[1:]
while len(str) and str[-1] in quotechars:
str = str[0:-1]
return str | e6377f9992ef8119726b788c02af9df32c722c28 | 708,851 |
def setup_i2c_sensor(sensor_class, sensor_name, i2c_bus, errors):
""" Initialise one of the I2C connected sensors, returning None on error."""
if i2c_bus is None:
# This sensor uses the multipler and there was an error initialising that.
return None
try:
sensor = sensor_class(i2c_bus)
except Exception as err:
# Error initialising this sensor, try to continue without it.
msg = "Error initialising {}:\n{}".format(sensor_name, err)
print(msg)
errors += (msg + "\n")
return None
else:
print("{} initialised".format(sensor_name))
return sensor | 62633c09f6e78b43fca625df8fbd0d20d866735b | 708,853 |
def argparse_textwrap_unwrap_first_paragraph(doc):
"""Join by single spaces all the leading lines up to the first empty line"""
index = (doc + "\n\n").index("\n\n")
lines = doc[:index].splitlines()
chars = " ".join(_.strip() for _ in lines)
alt_doc = chars + doc[index:]
return alt_doc | f7068c4b463c63d100980b743f8ed2d69b149a97 | 708,854 |
from typing import List
from typing import Tuple
def merge_overlapped_spans(spans: List[Tuple[int, int]]) -> List[Tuple[int, int]]:
"""
Merge overlapped spans
Parameters
----------
spans: input list of spans
Returns
-------
merged spans
"""
span_sets = list()
for span in spans:
span_set = set(range(span[0], span[1]))
if not span_sets:
span_sets.append(span_set)
elif span_sets[-1] & span_set:
if span_set - span_sets[-1]:
span_sets[-1] = span_sets[-1] | span_set
else:
span_sets.append(span_set)
merged_spans = list()
for span_set in span_sets:
merged_spans.append((min(span_set), max(span_set) + 1))
return merged_spans | 0ea7f2a730274f7a98f25b8df22754ec79e8fce7 | 708,856 |
def vectorproduct(a,b):
"""
Return vector cross product of input vectors a and b
"""
a1, a2, a3 = a
b1, b2, b3 = b
return [a2*b3 - a3*b2, a3*b1 - a1*b3, a1*b2 - a2*b1] | adb9e7c4b5150ab6231f2b852d6860cd0e5060a0 | 708,863 |
def int_to_ip(ip):
"""
Convert a 32-bit integer into IPv4 string format
:param ip: 32-bit integer
:return: IPv4 string equivalent to ip
"""
if type(ip) is str:
return ip
return '.'.join([str((ip >> i) & 0xff) for i in [24, 16, 8, 0]]) | 8ceb8b9912f10ba49b45510f4470b9cc34bf7a2f | 708,864 |
def PolyMod(f, g):
"""
return f (mod g)
"""
return f % g | 53b47e993e35c09e59e209b68a8a7656edf6b4ce | 708,867 |
def both_block_num_missing(record):
"""
Returns true of both block numbers are missing
:param record: dict - The record being evaluated
:return: bool
"""
rpt_block_num = record.get("rpt_block_num", "") or ""
rpt_sec_block_num = record.get("rpt_sec_block_num", "") or ""
# True, if neither address has a block number.
if rpt_block_num == "" and rpt_sec_block_num == "":
return True
return False | 63e2fdaef78dbc3c6560a4b015ed022583f30d05 | 708,868 |
def live_ferc_db(request):
"""Use the live FERC DB or make a temporary one."""
return request.config.getoption("--live_ferc_db") | f0540c8e3383572c5f686ea89011d9e1ab0bf208 | 708,873 |
import json
def format_parameters(parameters: str) -> str:
"""
Receives a key:value string and retuns a dictionary string ({"key":"value"}). In the process strips trailing and
leading spaces.
:param parameters: The key-value-list
:return:
"""
if not parameters:
return '{}'
pairs = []
for item in parameters.split(','):
try:
key, value = item.split(':')
except ValueError:
raise ValueError(f"Got unexpected parameters {item}.")
pairs.append((key.strip(), value.strip()))
return json.dumps(dict(pairs)) | 95f115b9000d495db776798700cfdf35209cfbd4 | 708,875 |
def Format_Phone(Phone):
"""Function to Format a Phone Number into (999)-999 9999)"""
Phone = str(Phone)
return f"({Phone[0:3]}) {Phone[3:6]}-{Phone[6:10]}" | 8e46c35bca9d302d86909457c84785ad5d366c15 | 708,876 |
def register_and_login_test_user(c):
"""
Helper function that makes an HTTP request to register a test user
Parameters
----------
c : object
Test client object
Returns
-------
str
Access JWT in order to use in subsequent tests
"""
c.post(
"/api/auth/register",
json={
"username": "test",
"password": "secret",
"first_name": "tim",
"last_name": "apple",
"email": "[email protected]",
"birthday": "1990-01-01",
},
)
setup_resp = c.post(
"/api/auth/login", json={"username": "test", "password": "secret"}
)
setup_resp_json = setup_resp.get_json()
setup_access_token = setup_resp_json["access_token"]
return setup_access_token | b76f7f6afa9af453246ae304b1b0504bd68b8919 | 708,877 |
def get_data_file_args(args, language):
"""
For a interface, return the language-specific set of data file arguments
Args:
args (dict): Dictionary of data file arguments for an interface
language (str): Language of the testbench
Returns:
dict: Language-specific data file arguments
"""
if language in args:
return args[language]
return args["generic"] | 11e30b92316bad9a46b87bd9188f97d5e8860377 | 708,879 |
import re
def check_string_capitalised(string):
""" Check to see if a string is in all CAPITAL letters. Boolean. """
return bool(re.match('^[A-Z_]+$', string)) | f496d79fafae4c89c3686856b42113c4818f7ed8 | 708,880 |
import textwrap
def ped_file_parent_missing(fake_fs):
"""Return fake file system with PED file"""
content = textwrap.dedent(
"""
# comment
FAM II-1\tI-1\t0\t1\t2
FAM I-1 0\t0\t1\t1
"""
).strip()
fake_fs.fs.create_file("/test.ped", create_missing_dirs=True, contents=content)
return fake_fs | 9df19ab925984236aa581c9b8843591f05d3b7b4 | 708,881 |
import itertools
import six
def partition(predicate, iterable):
"""Use `predicate` to partition entries into falsy and truthy ones.
Recipe taken from the official documentation.
https://docs.python.org/3/library/itertools.html#itertools-recipes
"""
t1, t2 = itertools.tee(iterable)
return (
six.moves.filterfalse(predicate, t1),
six.moves.filter(predicate, t2),
) | 5777203d9d34a9ffddc565129d8dda3ec91efc8e | 708,883 |
def check_struc(d1, d2,
errors=[], level='wf'):
"""Recursively check struct of dictionary 2 to that of dict 1
Arguments
---------
d1 : dict
Dictionary with desired structure
d2 : dict
Dictionary with structre to check
errors : list of str, optional
Missing values in d2. Initial value is [].
level : str, optional
Level of search. Inital value is 'wf' (wind farm) for top-level
dictionary.
Returns
-------
errors : list of str
Missing values in d2.
"""
for k1, v1 in d1.items(): # loop through keys and values in first dict
if k1 not in d2.keys(): # if key doesn't exist in d2
errors.append('{} not in dictionary'.format('.'.join([level,k1])))
elif isinstance(v1, dict): # otherwise, if item is a dict, recurse
errors = check_struc(v1, d2[k1],
errors=errors, # pass in accumulated errros
level='.'.join([level, k1])) # change level
return errors | aa835e7bbd6274e73d0b3d45d1ec4d617af0a167 | 708,884 |
def GMLstring2points(pointstring):
"""Convert list of points in string to a list of points. Works for 3D points."""
listPoints = []
#-- List of coordinates
coords = pointstring.split()
#-- Store the coordinate tuple
assert(len(coords) % 3 == 0)
for i in range(0, len(coords), 3):
listPoints.append([float(coords[i]), float(coords[i+1]), float(coords[i+2])])
return listPoints | e755d344d163bdcdb114d0c9d614a1bbd40be29f | 708,887 |
def ToOrdinal(value):
"""
Convert a numerical value into an ordinal number.
@param value: the number to be converted
"""
if value % 100//10 != 1:
if value % 10 == 1:
ordval = '{}st'.format(value)
elif value % 10 == 2:
ordval = '{}nd'.format(value)
elif value % 10 == 3:
ordval = '{}rd'.format(value)
else:
ordval = '{}th'.format(value)
else:
ordval = '{}th'.format(value)
return ordval | 774bac5fd22714ba3eb4c9dd2b16f4236e2f5e8c | 708,888 |
def recall_at(target, scores, k):
"""Calculation for recall at k."""
if target in scores[:k]:
return 1.0
else:
return 0.0 | 0c3f70be3fb4cfde16d5e39b256e565f180d1655 | 708,889 |
import math
def dcg(r, k=None):
"""The Burges et al. (2005) version of DCG.
This is what everyone uses (except trec_eval)
:param r: results
:param k: cut-off
:return: sum (2^ y_i - 1) / log (i +2)
"""
result = sum([(pow(2, rel) - 1) / math.log(rank + 2, 2) for rank, rel in enumerate(r[:k])])
return result | d93c500ba55411807570c8efebdeaa49ce7fe288 | 708,890 |
async def detect_objects(computervision_client, image_url):
"""Detect objects from a remote image"""
detect_objects_results_local = \
computervision_client.detect_objects(image_url)
return detect_objects_results_local.objects | 9adb2a3b2c08f99187159ad6a22047bbf3d4c30a | 708,891 |
def fcard(card):
"""Create format string for card display"""
return f"{card[0]} {card[1]}" | ca3866011b418bf35e1b076afd7134926a9382f9 | 708,892 |
def resetChapterProgress(chapterProgressDict, chapter, initRepeatLevel):
"""This method resets chapter progress and sets initial level for repeat routine.
Args:
chapterProgressDict (dict): Chapter progress data.
chapter (int): Number of the chapter.
initRepeatLevel (int): Initial level for repeat routine.
Returns:
dictionary: Return Reseted chapter progress dictionary with initial level set.
"""
chapterProgressDict[chapter]["status"] = "Not started"
chapterProgressDict[chapter]["progress"]["current"] = 0
chapterProgressDict[chapter]["correct"] = {"correct":0, "subtotal":0, "rate":''}
chapterProgressDict[chapter]["repeatLevel"] = initRepeatLevel
return chapterProgressDict | e02d6e97f556a2c080c2bc273255aacedf7bb086 | 708,893 |
def format_gro_coord(resid, resname, aname, seqno, xyz):
""" Print a line in accordance with .gro file format, with six decimal points of precision
Nine decimal points of precision are necessary to get forces below 1e-3 kJ/mol/nm.
@param[in] resid The number of the residue that the atom belongs to
@param[in] resname The name of the residue that the atom belongs to
@param[in] aname The name of the atom
@param[in] seqno The sequential number of the atom
@param[in] xyz A 3-element array containing x, y, z coordinates of that atom
"""
return "%5i%-5s%5s%5i % 13.9f % 13.9f % 13.9f" % (resid,resname,aname,seqno,xyz[0],xyz[1],xyz[2]) | ceeeeeafe4f7484fa17ee4ebd79363209c8f7391 | 708,895 |
def fix_legacy_database_uri(uri):
""" Fixes legacy Database uris, like postgres:// which is provided by Heroku but no longer supported by SqlAlchemy """
if uri.startswith('postgres://'):
uri = uri.replace('postgres://', 'postgresql://', 1)
return uri | aa3aa20110b7575abf77534d08a35dccb04b731d | 708,896 |
from datetime import datetime
def unix_utc_now() -> int:
"""
Return the number of seconds passed from January 1, 1970 UTC.
"""
delta = datetime.utcnow() - datetime(1970, 1, 1)
return int(delta.total_seconds()) | b9768b60cf6f49a7cccedd88482d7a2b21cf05a2 | 708,898 |
def invert_dict(d):
"""
Invert dictionary by switching keys and values.
Parameters
----------
d : dict
python dictionary
Returns
-------
dict
Inverted python dictionary
"""
return dict((v, k) for k, v in d.items()) | c70bfdb5ffa96cf07b1a4627aa484e3d5d0f4fea | 708,900 |
def option_to_text(option):
"""Converts, for example, 'no_override' to 'no override'."""
return option.replace('_', ' ') | 4b7febe0c4500aa23c368f83bbb18902057dc378 | 708,903 |
import contextlib
import socket
def get_available_port() -> int:
"""Finds and returns an available port on the system."""
with contextlib.closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
sock.bind(('', 0))
_, port = sock.getsockname()
return int(port) | c86de127fb237662052b8ce010e99d271836e1ef | 708,905 |
def prettyprint_float(val, digits):
"""Print a floating-point value in a nice way."""
format_string = "%." + f"{digits:d}" + "f"
return (format_string % val).rstrip("0").rstrip(".") | ba62671d9cb8061744fbf1e070e76c31d0ba185d | 708,906 |
import re
def is_doi(identifier: str) -> bool:
"""Validates if identifier is a valid DOI
Args:
identifier (str): potential doi string
Returns:
bool: true if identifier is a valid DOI
"""
doi_patterns = [
r"(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?![\"&\'])\S)+)",
r"(10.\d{4,9}/[-._;()/:A-Z0-9]+)",
r"(10.\d{4}/\d+-\d+X?(\d+)\d+<[\d\w]+:[\d\w]*>\d+.\d+.\w+;\d)",
r"(10.1021/\w\w\d+)",
r"(10.1207/[\w\d]+\&\d+_\d+)",
]
for pattern in doi_patterns:
match = bool(re.match(pattern, identifier))
if match:
return True
return False | 5c0bfe0527adbf53e89d302ee05feb80d285db64 | 708,910 |
def dfa_intersection(dfa_1: dict, dfa_2: dict) -> dict:
""" Returns a DFA accepting the intersection of the DFAs in
input.
Let :math:`A_1 = (Σ, S_1 , s_{01} , ρ_1 , F_1 )` and
:math:`A_2 = (Σ, S_2 , s_{02} , ρ_2 , F_2 )` be two DFAs.
Then there is a DFA :math:`A_∧` that runs simultaneously both
:math:`A_1` and :math:`A_2` on the input word and
accepts when both accept.
It is defined as:
:math:`A_∧ = (Σ, S_1 × S_2 , (s_{01} , s_{02} ), ρ, F_1 × F_2 )`
where
:math:`ρ((s_1 , s_2 ), a) = (s_{X1} , s_{X2} )` iff
:math:`s_{X1} = ρ_1 (s_1 , a)` and :math:`s_{X2}= ρ_2 (s_2 , a)`
Implementation proposed guarantees the resulting DFA has only
**reachable** states.
:param dict dfa_1: first input DFA;
:param dict dfa_2: second input DFA.
:return: *(dict)* representing the intersected DFA.
"""
intersection = {
'alphabet': dfa_1['alphabet'].intersection(dfa_2['alphabet']),
'states': {(dfa_1['initial_state'], dfa_2['initial_state'])},
'initial_state': (dfa_1['initial_state'], dfa_2['initial_state']),
'accepting_states': set(),
'transitions': dict()
}
boundary = set()
boundary.add(intersection['initial_state'])
while boundary:
(state_dfa_1, state_dfa_2) = boundary.pop()
if state_dfa_1 in dfa_1['accepting_states'] \
and state_dfa_2 in dfa_2['accepting_states']:
intersection['accepting_states'].add((state_dfa_1, state_dfa_2))
for a in intersection['alphabet']:
if (state_dfa_1, a) in dfa_1['transitions'] \
and (state_dfa_2, a) in dfa_2['transitions']:
next_state_1 = dfa_1['transitions'][state_dfa_1, a]
next_state_2 = dfa_2['transitions'][state_dfa_2, a]
if (next_state_1, next_state_2) not in intersection['states']:
intersection['states'].add((next_state_1, next_state_2))
boundary.add((next_state_1, next_state_2))
intersection['transitions'][(state_dfa_1, state_dfa_2), a] = \
(next_state_1, next_state_2)
return intersection | ea69f3cda2bd28f5b70d1724ffdd628daf1beffa | 708,912 |
import re
def find_links(text, image_only=False):
"""
Find Markdown links in text and return a match object.
Markdown links are expected to have the form [some txt](A-url.ext)
or .
Parameters
----------
text : str
Text in which to search for links.
image_only : bool
If ``True``, find only markdown image links, i.e. those that
begin with an exclamation mark.
Returns
-------
list
List of ``re.Match`` objects, one for each link found. Each object
has two named groups, 'link_text', which contains the the part between
the square brackets, and 'link',which is the URL (or file name for an
image).
"""
if image_only:
markdown_link = \
re.compile(r"!\[(?P<link_text>.+?\n*?.*?)\]\((?P<link_url>.+?)\)",
flags=re.MULTILINE)
else:
markdown_link = \
re.compile(r"!?\[(?P<link_text>.+?\n*?.*?)\]\((?P<link_url>.+?)\)",
flags=re.MULTILINE)
groups = [m for m in markdown_link.finditer(text)]
return groups | 5f96672b48d3d911faf2e398c86f622676263d73 | 708,913 |
def manhattan_distance(origin, destination):
"""Return the Manhattan distance between the origin and the destination.
@type origin: Location
@type destination: Location
@rtype: int
>>> pt1 = Location(1,2)
>>> pt2 = Location(3,4)
>>> print(manhattan_distance(pt1, pt2))
4
"""
return (abs(origin.row - destination.row) +
abs(origin.column - destination.column)) | 0bcfd7767e44b0dcc47890dc4bcb2c054abb4bde | 708,915 |
def pot_rho_linear(SP, t, rho0=1025, a=2e-4, b=7e-4, SP0=35, t0=15):
"""
Potential density calculated using a linear equation of state:
Parameters
----------
SP : array-like
Salinity [g/kg]
t : array-like
Temperature [°C]
rho0 : float, optional
Constant density [kg/m^3]
a : float, optional
Thermal expansion coefficient [1/°C]
b : float, optional
saline expansion coefficient [kg/g]
SP0 : float, optional
Constant salinity [g/kg]
t0 : float, optional
Constant temperature [°C]
Returns
-------
pot_rho : ndarray
Potential density [kg/m^3]
"""
return rho0 * (1 - a * (t - t0) + b * (SP - SP0)) | 47dd8248239d2147ff50d1b179d3fc4392c173cb | 708,919 |
def num_zeros_end(num):
"""
Counts the number of zeros at the end
of the number 'num'.
"""
iszero = True
num_zeros = 0
i = len(num)-1
while (iszero == True) and (i != 0):
if num[i] == "0":
num_zeros += 1
elif num[i] != "0":
iszero = False
i -= 1
return num_zeros | f227cce65e26a0684a10755031a4aeff2156015a | 708,920 |
import ipaddress
def is_ip_network(network, strict=False):
"""Returns True/False if a string is a valid network."""
network = str(network)
try:
ipaddress.ip_network(network, strict)
return True
except ValueError:
return False | 84206586412b76816fa845a75fc6c121bfdf0989 | 708,924 |
def sao_isomorficas(texto1: str, texto2: str) -> bool:
"""
>>> sao_isomorficas('egg', 'add')
True
>>> sao_isomorficas('foo', 'bar')
False
>>> sao_isomorficas('eggs', 'add')
False
"""
# Algoritmo O(n) em tempo e memória
letras_encontradas = {}
if len(texto1) != len(texto2):
return False
for caractere_1, caractere_2 in zip(texto1, texto2):
try:
letra = letras_encontradas[caractere_1]
except KeyError:
letras_encontradas[caractere_1] = caractere_2
else:
if letra is not caractere_2:
return False
return True | a1f2c00a50b69cb18c32a299d50cbd3a35dcbe5e | 708,930 |
def lonlat2px_gt(img, lon, lat, lon_min, lat_min, lon_max, lat_max):
"""
Converts a pair of lon and lat to its corresponding pixel value in an
geotiff image file.
Parameters
----------
img : Image File, e.g. PNG, TIFF
Input image file
lon : float
Longitude
lat : float
Latitude
lon_min, lat_min : float
lower left coordinate of geotiff
lon_max, lat_max : float
upper right coordinate of geotiff
Returns
-------
Row : float
corresponding pixel value
Col : float
corresponding pixel value
"""
w, h = img.size
londiff = lon_max - lon_min
latdiff = lat_max - lat_min
mw = w / londiff
mh = h / latdiff
row = (-lat + lat_max) * mh
col = (lon - lon_min) * mw
return row, col | 39c1aeb63d38fdac383c510913f50f177d274a04 | 708,934 |
async def async_setup_entry(hass, entry):
"""Set up Jenkins from a config entry."""
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(entry, "sensor")
)
return True | c46912d11630c36effc07eed3273e42325c9b2b8 | 708,936 |
def de_dupe_list(input):
"""de-dupe a list, preserving order.
"""
sam_fh = []
for x in input:
if x not in sam_fh:
sam_fh.append(x)
return sam_fh | bbf1936f21c19195369e41b635bf0f99704b3210 | 708,937 |
import ipaddress
def _item_to_python_repr(item, definitions):
"""Converts the given Capirca item into a typed Python object."""
# Capirca comments are just appended to item strings
s = item.split("#")[0].strip()
# A reference to another network
if s in definitions.networks:
return s
# IPv4 address / network
try:
return ipaddress.IPv4Address(s)
except ValueError:
pass
try:
return ipaddress.IPv4Network(s, strict=False)
except ValueError:
pass
# IPv6 address / network
try:
return ipaddress.IPv6Address(s)
except ValueError:
pass
try:
return ipaddress.IPv6Network(s, strict=False)
except ValueError:
pass
raise ValueError("Unknown how to convert {s}".format(s=s)) | 9881e304e923eb2cea8223224273f4c9ef81696b | 708,944 |
from functools import reduce
def replace(data, replacements):
""" Allows to performs several string substitutions.
This function performs several string substitutions on the initial ``data`` string using a list
of 2-tuples (old, new) defining substitutions and returns the resulting string.
"""
return reduce(lambda a, kv: a.replace(*kv), replacements, data) | 37b2ad5b9b6d50d81a8c1bcded9890de3c840722 | 708,949 |
def get_filename(file_fullpath):
"""
Returns the filename without the full path
:param file_fullpath:
:return: Returns the filename
"""
filename = file_fullpath.split("/")[-1].split(".")[0]
return filename | 903cb26c89d1d18c9ebafe1a468c7fa66c51f119 | 708,953 |
def calculate_accuracy(y_true, y_pred):
"""Calculates the accuracy of the model.
Arguments:
y_true {numpy.array} -- the true labels corresponding to each input
y_pred {numpy.array} -- the model's predictions
Returns:
accuracy {str} -- the accuracy of the model (%)
"""
correctpred, total = 0, 0
for index in range(len(y_pred)):
if(y_pred[index] == y_true[index]):
correctpred = correctpred + 1
total = total+1
return 'accuracy='+str((correctpred*100)/total) | 1ea14f8e4f50d13e2ae557aeec466c5372b99171 | 708,957 |
def remove_prefix(string, prefix):
"""
This function removes the given prefix from a string, if the string does
indeed begin with the prefix; otherwise, it returns the string
unmodified.
"""
if string.startswith(prefix):
return string[len(prefix):]
else:
return string | 73cffca0e9938ea48f3781c7821fcbcf56e0cf25 | 708,960 |
def minute_info(x):
"""
separates the minutes from time stamp. Returns minute of time.
"""
n2 = x.minute
return n2/60 | c166bb8f759a5eed1b45b2dd8f228206357deb28 | 708,962 |
from bs4 import BeautifulSoup
def remove_html_tags(text):
"""Removes HTML Tags from texts and replaces special spaces with regular spaces"""
text = BeautifulSoup(text, 'html.parser').get_text()
text = text.replace(u'\xa0', ' ')
return text | 7f31a18d81ebc80b202ac697eb7b19fe206aed95 | 708,963 |
def split_str_to_list(input_str, split_char=","):
"""Split a string into a list of elements.
Args:
input_str (str): The string to split
split_char (str, optional): The character to split the string by. Defaults
to ",".
Returns:
(list): The string split into a list
"""
# Split a string into a list using `,` char
split_str = input_str.split(split_char)
# For each element in split_str, strip leading/trailing whitespace
for i, element in enumerate(split_str):
split_str[i] = element.strip()
return split_str | 2b13868aed1869310a1398886f6777ddceb6c777 | 708,964 |
import re
def formatRFC822Headers(headers):
""" Convert the key-value pairs in 'headers' to valid RFC822-style
headers, including adding leading whitespace to elements which
contain newlines in order to preserve continuation-line semantics.
"""
munged = []
linesplit = re.compile(r'[\n\r]+?')
for key, value in headers:
vallines = linesplit.split(value)
while vallines:
if vallines[-1].rstrip() == '':
vallines = vallines[:-1]
else:
break
munged.append('%s: %s' % (key, '\r\n '.join(vallines)))
return '\r\n'.join(munged) | 4c7dd97c9079daf144acf83241ebe9f025020611 | 708,965 |
import re
def snake_case(string: str) -> str:
"""Convert upper camelcase to snake case."""
return re.sub(r"(?<!^)(?=[A-Z])", "_", string).lower() | fe8592bcfa1f2233a07308741de5f912fd7055b3 | 708,967 |
def var_text(vname, iotype, variable):
"""
Extract info from variable for vname of iotype
and return info as HTML string.
"""
if iotype == 'read':
txt = '<p><i>Input Variable Name:</i> <b>{}</b>'.format(vname)
if 'required' in variable:
txt += '<br><b><i>Required Input Variable</i></b>'
else:
txt = '<p><i>Output Variable Name:</i> <b>{}</b>'.format(vname)
txt += '<br><i>Description:</i> {}'.format(variable['desc'])
txt += '<br><i>Datatype:</i> {}'.format(variable['type'])
if iotype == 'read':
txt += '<br><i>Availability:</i> {}'.format(variable['availability'])
txt += '<br><i>IRS Form Location:</i>'
formdict = variable['form']
for yrange in sorted(formdict.keys()):
txt += '<br>{}: {}'.format(yrange, formdict[yrange])
txt += '</p>'
return txt | 04fdb1727c8eb783f7fb2c0324852e80673e8b77 | 708,971 |
def makemarkers(nb):
""" Give a list of cycling markers. See http://matplotlib.org/api/markers_api.html
.. note:: This what I consider the *optimal* sequence of markers, they are clearly differentiable one from another and all are pretty.
Examples:
>>> makemarkers(7)
['o', 'D', 'v', 'p', '<', 's', '^']
>>> makemarkers(12)
['o', 'D', 'v', 'p', '<', 's', '^', '*', 'h', '>', 'o', 'D']
"""
allmarkers = ['o', 'D', 'v', 'p', '<', 's', '^', '*', 'h', '>']
longlist = allmarkers * (1 + int(nb / float(len(allmarkers)))) # Cycle the good number of time
return longlist[:nb] | a1dc00cdb831b3b622670a5f36ba956273379b16 | 708,974 |
def _get_only_relevant_data(video_data):
"""
Method to build ES document with only the relevant information
"""
return {
"kind": video_data["kind"],
"id": video_data["id"],
"published_at": video_data["snippet"]["publishedAt"],
"title": video_data["snippet"]["title"],
"description": video_data["snippet"]["description"],
"thumbnail_url": video_data["snippet"]["thumbnails"]["default"]["url"],
"channel_title": video_data["snippet"]["channelTitle"],
} | b5d2a0cf2c5b7121c92e95adb524379d7cf3eb9c | 708,975 |
def binary_find(N, x, array):
"""
Binary search
:param N: size of the array
:param x: value
:param array: array
:return: position where it is found. -1 if it is not found
"""
lower = 0
upper = N
while (lower + 1) < upper:
mid = int((lower + upper) / 2)
if x < array[mid]:
upper = mid
else:
lower = mid
if array[lower] <= x:
return lower
return -1 | ed6e7cc15de238381dbf65eb6c981676fd0525f5 | 708,983 |
def deque_to_yaml(representer, node):
"""Convert collections.deque to YAML"""
return representer.represent_sequence("!collections.deque", (list(node), node.maxlen)) | 5ff503b4f21af58cf96d26171e078ddd5d754141 | 708,987 |
from typing import Callable
def some_func(string: str, function: Callable) -> bool:
"""Check if some elements in a string match the function (functional).
Args:
string: <str> string to verify.
function: <callable> function to call.
Returns:
True if some of elements are in the sequence are True.
Examples:
>>> assert some_func('abcdefg&%$', str.isalpha)
>>> assert not some_func('&%$=', str.isalpha)
"""
return any(map(function, string)) and not all(map(function, string)) | e67af6613975a6757905087397ff8b68e83ddbf6 | 708,988 |
import math
def fuel_requirement(mass: int) -> int:
"""Fuel is mass divide by three, round down and subtract 2"""
return math.floor(mass / 3) - 2 | 5899d9260fe7e353c3a1d882f624257d5009248d | 708,990 |
import json
import hashlib
def hashify(params, max_length=8):
"""
Create a short hashed string of the given parameters.
:param params:
A dictionary of key, value pairs for parameters.
:param max_length: [optional]
The maximum length of the hashed string.
"""
param_str = json.dumps(params, separators=(',', ':'), sort_keys=True)
param_hash = hashlib.md5(param_str.encode('utf-8')).hexdigest()
return param_hash[:max_length] | e4a97a28fc2d0564da3e6b22f32735b4a2534c3e | 709,000 |
from typing import Optional
from typing import Any
def geq(column: str, value: Optional[Any]) -> str:
"""
>>> geq("col", None)
'1'
>>> geq("col", 1)
'col >= 1'
>>> geq("col", "1")
"col >= '1'"
"""
if not value:
return "1"
if isinstance(value, str):
return f"{column} >= '{value}'"
return f"{column} >= {value}" | 9216b8e2480232840ad37d8fe0e5c0f07b88873f | 709,006 |
def longest_match(list1, list2):
"""
Find the length of the longest substring match between list1 and list2.
>>> longest_match([], [])
0
>>> longest_match('test', 'test')
4
>>> longest_match('test', 'toast')
2
>>> longest_match('supercalifragilisticexpialidocious', 'mystical californication')
5
"""
m = len(list1)
n = len(list2)
data = [[0 for col in range(n+1)] for row in range(m+1)]
for a in range(1, m+1):
for b in range(1, n+1):
if list1[a-1] == list2[b-1]:
data[a][b] = 1 + data[a-1][b-1]
else:
data[a][b] = 0
maxes = [max(row) for row in data]
return max(maxes) | 4a84dacbb0d59fc7f9c4b59e87e55c72416b8c80 | 709,007 |
def pylm_component(name):
"""Decorator for registering a class to lightmetrica"""
def pylm_component_(object):
# Get base class
base = object.__bases__[0]
base.reg(object, name)
return object
return pylm_component_ | 531c7e3f224b824b438011d4be348a76154b3444 | 709,009 |
def fill(bitdef, value):
"""
Fill undefined bits with a value.
For example ``1..0100.1`` becomes ``111010011`` when filled with 1s.
Args:
bitdef (str): The bitdef to fill.
value (str): The value to fill with, "0" or "1".
Returns:
str: The filled bitdef.
"""
output = ""
for bit in bitdef:
if bit == ".":
output += value
else:
output += bit
return output | eef3ac59a2a7c4d1a25851a2ca14b3ffed6d1463 | 709,020 |
from typing import Dict
def hash_dict(data: Dict) -> int:
"""
Hashes a Dictionary recursively.
List values are converted to Tuples.
WARNING: Hashing nested dictionaries is expensive.
"""
cleaned_dict: Dict = {}
def _clean_dict(data: Dict) -> Dict:
d: Dict = {}
for k, v in data.items():
if isinstance(v, list) or isinstance(v, set):
d[k] = tuple(v)
elif isinstance(v, dict):
d[k] = hash_dict(v)
else:
d[k] = v
return d
cleaned_dict = _clean_dict(data)
return hash(tuple(sorted(cleaned_dict.items()))) | 42b579151c90a42fadf2b53751978eec421ea03c | 709,022 |
def vector_to_diagonal(v):
"""Converts a vector to a diagonal matrix with vector elements
as the diagonal elements of the matrix"""
diag_matrix = [[0 for i in range(len(v))] for j in range(len(v))]
for i in range(len(v)):
diag_matrix[i][i] = v[i]
return diag_matrix | 6cbaf54a083633a47af92acc7f69421ed68a1c0b | 709,023 |
def compose_redis_key(vim_name, identifier, identifier_type="vdu"):
"""Compose the key for redis given vim name and vdu uuid
Args:
vim_name (str): The VIM name
identifier (str): The VDU or VNF uuid (NFVI based)
identifier_type (str): the identifier type. Default type is vdu. Also vnf is supported.
Returns:
str: the key for redis
"""
if identifier_type == "vnf":
return "{}:vnf#{}".format(vim_name.lower(), identifier)
else:
return "{}:{}".format(vim_name.lower(), identifier) | e9a03cf9ff704fea8b9cdf75c59695568e366649 | 709,026 |
def convert_price_text(t):
"""
convert "$175/month' to 175
:param t:
:return: price, unit (i.e. 175, 'month')
"""
tok = t.split('$')[1]
if '/' in tok:
price, unit = tok.split('/')
else:
price = tok
unit = None
return float(price.strip().strip('$').replace(',', '')), unit | b42d26dcd4eb1b2c2f8c5a63ddc9d48469e30a52 | 709,029 |
def force_orders(self, **kwargs):
"""User's Force Orders (USER_DATA)
GET /fapi/v1/forceOrders
https://binance-docs.github.io/apidocs/futures/en/#user-39-s-force-orders-user_data
Keyword Args:
symbol (str, optional)
autoCloseType (str, optional): "LIQUIDATION" for liquidation orders, "ADL" for ADL orders.
startTime (int, optional)
endTime (int, optional)
limit (int, optional): Default 50; max 100.
recvWindow (int, optional)
Notes:
If "autoCloseType" is not sent, orders with both of the types will be returned
If "startTime" is not sent, data within 7 days before "endTime" can be queried
"""
payload = {**kwargs}
url_path = "/fapi/v1/forceOrders"
return self.sign_request("GET", url_path, payload) | 6e848820e17e54df0f275ec4087d9c609d4e08fa | 709,031 |
from datetime import datetime
def now(mydateformat='%Y%m%dT%H%M%S'):
""" Return current datetime as string.
Just a shorthand to abbreviate the common task to obtain the current
datetime as a string, e.g. for result versioning.
Args:
mydateformat: optional format string (default: '%Y%m%dT%H%M%S')
Returns:
datetime.now(), formated to string with argument mydateformat, e.g.
YYYYMMDDThhmmss ==> 20131007H123456
"""
return datetime.now().strftime(mydateformat) | f4f98116700888a4be273143d635c62859c96e03 | 709,032 |
def replace_dict(d, **kwargs):
"""
Replace values by keyword on a dict, returning a new dict.
"""
e = d.copy()
e.update(kwargs)
return e | be1cc21be5320eeea13307dd4ed5025b51339eec | 709,033 |
def pageHeader(
headline="",
tagline=""):
"""
*Generate a pageHeader - TBS style*
**Key Arguments:**
- ``headline`` -- the headline text
- ``tagline`` -- the tagline text for below the headline
**Return:**
- ``pageHeader`` -- the pageHeader
"""
pageHeader = """
<div class="page-header" id=" ">
<h1>%(headline)s<br><small>%(tagline)s</small></h1>
</div>""" % locals()
return pageHeader | 7d9e91df8af2fff92b0b7096cd1a13198d899e15 | 709,034 |
def seconds_to_timestamp(seconds):
"""
Convert from seconds to a timestamp
"""
minutes, seconds = divmod(float(seconds), 60)
hours, minutes = divmod(minutes, 60)
return "%02d:%02d:%06.3f" % (hours, minutes, seconds) | 8b9806f05fe4796baae51001e69455e82fb51eed | 709,042 |
def timeframe_int_to_str(timeframe: int) -> str:
"""
Convert timeframe from integer to string
:param timeframe: minutes per candle (240)
:return: string representation for API (4h)
"""
if timeframe < 60:
return f"{timeframe}m"
elif timeframe < 1440:
return f"{int(timeframe / 60)}h"
else:
return f"{int(timeframe / 1440)}d" | 75778742dea8204c74a47bfe92c25aef43ebbad8 | 709,047 |
import threading
def spawn_thread(func, *args, **kwds):
"""
Utility function for creating and starting a daemonic thread.
"""
thr = threading.Thread(target=func, args=args, kwargs=kwds)
thr.setDaemon(True)
thr.start()
return thr | afaace7e02870390acb297106ac9d35c9a931a59 | 709,060 |
import torch
def compute_acc(pred, labels):
"""
Compute the accuracy of prediction given the labels.
"""
return (torch.argmax(pred, dim=1) == labels).float().sum() / len(pred) | 1b1ad83b9b4ae06f2bc80209e4e7339a421a39f3 | 709,062 |
def pres_from_hybrid(psfc, hya, hyb, p0=100000.):
"""Return pressure field on hybrid-sigma coordinates,
assuming formula is
p = a(k)*p0 + b(k)*ps.
"""
return hya*p0 + hyb*psfc | 4ebd90fb807ab9ea4c2b45d27da6f8b420c107f7 | 709,064 |
def encounter_media(instance, filename):
"""Return an upload file path for an encounter media attachment."""
if not instance.encounter.id:
instance.encounter.save()
return 'encounter/{0}/{1}'.format(instance.encounter.source_id, filename) | 79e4d8fae1d41edf362e99e6da11442a71565aa0 | 709,072 |
from datetime import datetime
def MicrosecondsToDatetime(microseconds):
"""Returns a datetime given the number of microseconds, or None."""
if microseconds:
return datetime.utcfromtimestamp(float(microseconds) / 1000000)
return None | 69fd3dc3b8d1a97e7a64037cabe988365b2c6e63 | 709,075 |
def intersection_indices(a, b):
"""
:param list a, b: two lists of variables from different factors.
returns a tuple of
(indices in a of the variables that are in both a and b,
indices of those same variables within the list b)
For example, intersection_indices([1,2,5,4,6],[3,5,1,2]) returns
([0, 1, 2], [2, 3, 1]).
"""
bind = {}
for i, elt in enumerate(b):
if elt not in bind:
bind[elt] = i
mapA = []
mapB = []
for i, itm in enumerate(a):
if itm in bind:
mapA.append(i)
mapB.append(bind.get(itm))
return mapA, mapB | 55264faaa4fd5e6dc5365b675ebd3b7f6a1e1280 | 709,078 |
def calculate_recall(tp, n):
"""
:param tp: int
Number of True Positives
:param n: int
Number of total instances
:return: float
Recall
"""
if n == 0:
return 0
return tp / n | b8a36488af59e036acdb50821716ae34287e6b8f | 709,081 |
def quote_spaces(arg):
"""Generic function for putting double quotes around any string that
has white space in it."""
if ' ' in arg or '\t' in arg:
return '"%s"' % arg
else:
return str(arg) | e0171c3b0eee18c7fcc44cbdfe007949feabba9a | 709,083 |
def _emit_params_file_action(ctx, path, mnemonic, cmds):
"""Helper function that writes a potentially long command list to a file.
Args:
ctx (struct): The ctx object.
path (string): the file path where the params file should be written.
mnemonic (string): the action mnemomic.
cmds (list<string>): the command list.
Returns:
(File): an executable file that runs the command set.
"""
filename = "%s.%sFile.params" % (path, mnemonic)
f = ctx.new_file(ctx.configuration.bin_dir, filename)
ctx.file_action(output = f,
content = "\n".join(["set -e"] + cmds),
executable = True)
return f | adafb75e24b2023ad2926e4248e8b2e1e6966b8e | 709,087 |
import textwrap
def ignore_firstline_dedent(text: str) -> str:
"""Like textwrap.dedent(), but ignore first empty lines
Args:
text: The text the be dedented
Returns:
The dedented text
"""
out = []
started = False
for line in text.splitlines():
if not started and not line.strip():
continue
if not started:
started = True
out.append(line)
return textwrap.dedent("\n".join(out)) | 04bde49e72e07552f2f88e9112546d00b85a2879 | 709,088 |
def determineDocument(pdf):
""" Scans the pdf document for certain text lines and determines the type of investment vehicle traded"""
if 'turbop' in pdf or 'turboc' in pdf:
return 'certificate'
elif 'minil' in pdf:
return 'certificate'
elif 'call' in pdf or 'put' in pdf:
return 'warrant'
else:
return 'stock' | e6c5adc10168321fd6a534dd8e9fbf2e8ccb1615 | 709,093 |
def dot_to_underscore(instring):
"""Replace dots with underscores"""
return instring.replace(".", "_") | cf9441702ffb128678a031eabb4fa48be881cae5 | 709,096 |
def rstrip_tuple(t: tuple):
"""Remove trailing zeroes in `t`."""
if not t or t[-1]:
return t
right = len(t) - 1
while right > 0 and t[right - 1] == 0:
right -= 1
return t[:right] | a10e74ea4a305d588fbd1555f32dda1d4b95266e | 709,098 |
def clamp(min_v, max_v, value):
"""
Clamps a value between a min and max value
Args:
min_v: Minimum value
max_v: Maximum value
value: Value to be clamped
Returns:
Returns the clamped value
"""
return min_v if value < min_v else max_v if value > max_v else value | 1a9aaf3790b233f535fb864215444b0426c17ad8 | 709,101 |
import re
def number_format(number_string, fill=2):
"""
add padding zeros to make alinged numbers
ex.
>>> number_format('2')
'02'
>>> number_format('1-2')
'01-02'
"""
output = []
digits_spliter = r'(?P<digit>\d+)|(?P<nondigit>.)'
for token in [m.groups() for m in re.finditer(digits_spliter, number_string)]:
if token[0] is None:
output.append(token[1])
else:
output.append(token[0].zfill(2))
return ''.join(output) | ee44167b4597fbe7c9f01fa5b26e02d7608c3677 | 709,103 |
def read_shear_catalog_type(stage):
"""
Determine the type of shear catalog a stage is using as input.
Returns a string, e.g. metacal, lensfit.
Also sets shear_catalog_type in the stage's configuration
so that it is available later and is saved in output.
"""
with stage.open_input('shear_catalog', wrapper=True) as f:
shear_catalog_type = f.catalog_type
stage.config['shear_catalog_type'] = shear_catalog_type
return shear_catalog_type | 26dd03f3a2ef66acab47741df044ac8f2a92bbfb | 709,112 |
def set_diff(seq0, seq1):
"""Return the set difference between 2 sequences as a list."""
return list(set(seq0) - set(seq1)) | ff10464acc65b60e9355e8971c45fbca8025fda6 | 709,114 |
def str_product(string):
""" Calculate the product of all digits in a string """
product = 1
for i in string:
product *= int(i)
return product | c0c7442ac53aaf49760feffa7d08408d7520d9b4 | 709,117 |
import csv
def ConvertCSVStringToList(csv_string):
"""Helper to convert a csv string to a list."""
reader = csv.reader([csv_string])
return list(reader)[0] | fa244d2a1c8c50b2b097883f964f1b5bb7ccf393 | 709,119 |
def find_object_with_matching_attr(iterable, attr_name, value):
"""
Finds the first item in an iterable that has an attribute with the given name and value. Returns
None otherwise.
Returns:
Matching item or None
"""
for item in iterable:
try:
if getattr(item, attr_name) == value:
return item
except AttributeError:
pass
return None | e37b7620bf484ce887e6a75f31592951ed93ac74 | 709,121 |
def common(list1, list2):
"""
This function is passed two lists and returns a new list containing
those elements that appear in both of the lists passed in.
"""
common_list = []
temp_list = list1.copy()
temp_list.extend(list2)
temp_list = list(set(temp_list))
temp_list.sort()
for i in temp_list:
if (i in list1) and (i in list2):
common_list.append(i)
return common_list | 021605a2aad6c939155a9a35b8845992870100f0 | 709,123 |
import json
def image_fnames_captions(captions_file, images_dir, partition):
"""
Loads annotations file and return lists with each image's path and caption
Arguments:
partition: string
either 'train' or 'val'
Returns:
all_captions: list of strings
list with each image caption
all_img_paths: list of paths as strings
list with each image's path to file
"""
with open(captions_file, 'r') as f:
annotations = json.load(f)
all_captions = []
all_img_paths = []
for annot in annotations['annotations']:
caption = '<start> ' + annot['caption'] + ' <end>'
image_id = annot['image_id']
full_coco_image_path = images_dir / ('COCO_{}2014_'.format(partition) + \
'{:012d}.jpg'.format(image_id))
all_img_paths.append(full_coco_image_path)
all_captions.append(caption)
return all_captions, all_img_paths | f592decefaded079fca92091ad795d67150b4ca8 | 709,133 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.