content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
import inspect
def get_report_details(report):
"""
Retrieve the docstring content for the given report module.
:param report: The report module object
:returns: the docstring for the given report module
"""
return [
obj for name, obj in inspect.getmembers(report) if name == '__doc__'
][0] | cf3f4f3850509f27331fafae9f0f1713083ee70f | 268,221 |
def to_localtime(ts):
"""Conbert timestamp in UTC timezone to local time.
Parameters
----------
ts: datetime.datetime
Timestamp in UTC format
Returns
-------
datetime.datetime
"""
return ts.astimezone() | 5cf68e6dc02518acb5b0a9ec904b24910443d4e4 | 448,950 |
def sortby(somelist, n):
"""
Suppose, for example, you have a list of tuples that you want to sort by the n-th field of each tuple.
"""
nlist = [(x[n], x) for x in somelist]
nlist.sort()
return [val for (key, val) in nlist] | 2ddc26a70197d170967172f6aa27d2d5444d6ab0 | 431,920 |
def readTable(filename):
"""Read a tab-delimited file, returning a list of lists."""
with open(filename, "r") as f:
rows = f.read().rstrip("\n").split("\n")
return [r.split("\t") for r in rows] | 0484d5771e1f70525f77f06ed806e93e37e9e2af | 218,099 |
import re
def replace_repeated_punc(s):
"""
Replace repeated punctuation and newline characters
:param s: text string
:return: modified text string
"""
s = re.sub(r'([^\w\d\s]|\n)(\s\1)+', r'_multi_punc_ \1', s)
return s | fd2d6105adcf81327af53a6db5c2403316230018 | 331,138 |
from typing import Dict
from typing import List
from typing import Optional
def extract_env_var(
container: Dict[str, List[Dict[str, str]]], name: str
) -> Optional[str]:
"""Extract env var from container definition.
Args:
container: Container definition.
name: Name of the environment variable.
Returns:
Enviornment variable value or `None` if var is not found.
"""
for entry in container.get("environment", []):
if entry["name"] == name:
return entry["value"]
return None | 214d016eec5b1cab016bdf137c76c94dbde8fcb0 | 212,154 |
def check(list1, list2):
"""
Checks if any value in list1 exists in list2
"""
for i in list1:
for n in list2:
if i == n:
return True
return False | 5fcde83fbc2af493b589cfc447f0a6a88cad4e41 | 57,858 |
def threading__thread_is_alive(thread):
"""Return whether the thread is alive (Python version compatibility shim).
On Python >= 3.8 thread.isAlive() is deprecated (removed in Python 3.9).
On Python <= 2.5 thread.is_alive() isn't present (added in Python 2.6).
"""
try:
return thread.is_alive()
except AttributeError:
return thread.isAlive() | 708b23b46a177a92817734b8b87f4124b22b876a | 439,672 |
def get_dict_path(obj, path):
"""Traverse a dict using a / seperated string.
Args:
obj (:obj:`dict`):
Dictionary to traverse using path.
path (:obj:`str`):
Nested dictionary keys seperated by / to traverse in obj.
Raises:
:exc:`ValueError`:
If a part of a path can not be found.
Returns:
:obj:`object`
"""
value = obj
parts = path.strip("/").split("/")
for idx, key in enumerate(parts):
try:
value = value[key]
except Exception:
current_parts = parts[:idx]
current_path = "/".join(current_parts)
if isinstance(value, dict):
valid_keys = list(value.keys())
else:
value_type = type(value).__name__
valid_keys = "NONE: key {k!r} is {t}, not dict."
valid_keys = valid_keys.format(k=current_parts[-1], t=value_type)
error = [
"Unable to find key {k!r} in path {p!r}",
"Valid keys at {c!r}:",
"{v!r}",
]
error = "\n ".join(error)
error = error.format(k=key, p=path, c=current_path, v=valid_keys)
raise ValueError(error)
return value | 3c0d962669d92d825243c08cca121a600df4ca2e | 224,835 |
def argsort(seq, reverse=False):
"""Return indices to get sequence sorted
"""
# Based on construct from
# http://stackoverflow.com/questions/3071415/efficient-method-to-calculate-the-rank-vector-of-a-list-in-python
# Thanks!
# cmp was not passed through since seems to be absent in python3
return sorted(range(len(seq)), key=seq.__getitem__, reverse=reverse) | c4182afbad1ab60f3c5393a23db761fc6a9630c7 | 168,139 |
from typing import Dict
import re
def extract_access_tokens(text: str) -> Dict[str, str]:
"""
Parses the given text for https URLs with an attached access token. Returns a dictionary mapping from
file to file with access token, like `knee.tar.gz` -> `?AWSAccessKeyId=...`
:param text: The text with https URLs
:return:
"""
result: Dict[str, str] = {}
for match in re.finditer(r'(https://fastmri-dataset.s3.amazonaws.com/)([._a-zA-Z0-9]+)(\?[a-zA-Z0-9=&%]+)', text):
file = match.group(2)
token = match.group(3)
if file in result:
raise ValueError(f"Input file contains multiple entries for file {file}")
print(f"Found access token for {file}: {token}")
result[file] = token
return result | 52a84a412d06bc3e7dc3dd16a260e547de117bf0 | 522,404 |
def dot(L, K):
"""returns the dot product of lists L and K"""
def dotHelp(L, K, accum):
if (L == [] or K == []):
return accum
return dotHelp(L[1:], K[1:], accum+L[0]*K[0])
return dotHelp(L, K, 0) | cbcd6f802a30bda3d55479f8a451c8951038fe8d | 151,720 |
def circuit(rel_x, rel_y, color='green', port=1, target_port=1):
"""helper method for setting Entity connections, eg. Entity(E.chest, connections=[circuit(0, 1)])"""
return port, color, rel_x, rel_y, target_port | 25736270c42ef216a46f4332e7770b9023d06fe4 | 64,728 |
def _check_version(module_name):
"""Get the version of an installed package"""
module = __import__(module_name)
return module.__version__ | 4088f6529d37ae684e979362f39f9eed82b1745b | 607,041 |
def time_for(s):
"""
Given a time stirng, returns a number of seconds that
corresponds to that time. For a plain number string
it returns the string as an int otherwise it converts
based on the last char of the string when it is one of
the following:
m -> Minutes
h -> hours
d -> days
w -> weeks
"""
try:
return int(s)
except:
pass
denom = s[-1]
m = 1
value = s[:-1]
if denom == 'm':
m = 60
elif denom == 'h':
m = 3600
elif denom == 'd':
m = 86400
elif denom == 'w':
m = 604800
else:
raise ValueError(
"Invalid time denomination! Must be m, h, d, w or nothing not {}".format(denom))
return int(value) * m | 68e21b8ea21000edc45749d117eac85e23cd126c | 350,010 |
import math
def rint(n):
"""rounds n to the nearest integer, towards even if a tie"""
n_int = int(math.floor(n))
if n == n_int + 0.5:
if n_int % 2:
return n_int + 1
return n_int
return int(round(n)) | e7fe2cb1a6024a3ffd3e64faae0e98255ec44c63 | 476,211 |
import json
def offers(request):
"""
Create Json response with offers menu
:param request: POST request from "Offers" dialogflow intent
:return: Json response that contains spoken and display prompt and also list as Dialogflow conversation item
"""
speech_text_pl = "Która opcja Cię interesuje?"
display_text_pl = "Która opcja Cię interesuje?"
list_pl = {
"intent": "actions.intent.OPTION",
"data": {
"@type": "type.googleapis.com/google.actions.v2.OptionValueSpec",
"listSelect": {
"items": [
{
"optionInfo": {
"key": "Przeglądaj oferty",
"synonyms": [
"Przejrzyj oferty"
]
},
"title": "Przeglądaj oferty"
},
{
"optionInfo": {
"key": "Wyszukaj oferty",
"synonyms": [
"Znajdź oferty",
"Znajdź ofertę"
]
},
"title": "Wyszukaj oferty"
},
{
"optionInfo": {
"key": "Wyszukaj ofertę po id",
"synonyms": [
"Znajdź ofertę po id"
]
},
"title": "Wyszukaj ofertę po id"
},
{
"optionInfo": {
"key": "Do kiedy jest ważna oferta",
"synonyms": [
"Ważnosć oferty",
"Do kiedy oferta będzie aktualna",
]
},
"title": "Do kiedy jest ważna oferta"
}
]
}
}
}
suggestions_pl = [{"title": "Oferty"}, {"title": "Zlecenia"}, {"title": "Zapytania"}, {"title": "Konto"},
{"title": "Inne"}]
speech_text_en = "Which option are you interested in?"
display_text_en = "Which option are you interested in?"
list_en = {
"intent": "actions.intent.OPTION",
"data": {
"@type": "type.googleapis.com/google.actions.v2.OptionValueSpec",
"listSelect": {
"items": [
{
"optionInfo": {
"key": "Browse offers",
"synonyms": [
"View offers",
"Display offers"
]
},
"title": "Browse offers"
},
{
"optionInfo": {
"key": "Search offers",
"synonyms": [
"Search active offers"
]
},
"title": "Search offers"
},
{
"optionInfo": {
"key": "Search offer after id",
"synonyms": [
"Search offer according to id"
]
},
"title": "Search offer after id"
},
{
"optionInfo": {
"key": "Until when is the offer valid",
"synonyms": [
"Offer valid",
"Until when is the offer valid?",
]
},
"title": "Until when is the offer valid"
}
]
}
}
}
suggestions_en = [{"title": "Offers"}, {"title": "Orders"}, {"title": "Inquiries"}, {"title": "Account"},
{"title": "Others"}]
with open('api/response.json') as json_file:
offers = json.load(json_file)
part_to_modify = offers['payload']['google']
if request.data['queryResult']['languageCode'] == 'pl':
part_to_modify['richResponse']['items'][0]['simpleResponse']['textToSpeech'] = speech_text_pl
part_to_modify['richResponse']['items'][0]['simpleResponse']['displayText'] = display_text_pl
part_to_modify['systemIntent'] = list_pl
part_to_modify['richResponse']['suggestions'] = suggestions_pl
elif request.data['queryResult']['languageCode'] == 'en':
part_to_modify['richResponse']['items'][0]['simpleResponse']['textToSpeech'] = speech_text_en
part_to_modify['richResponse']['items'][0]['simpleResponse']['displayText'] = display_text_en
part_to_modify['systemIntent'] = list_en
part_to_modify['richResponse']['suggestions'] = suggestions_en
offers['payload']['google'] = part_to_modify
return offers | 9d14ba6b962fd6fee2cb25566b3bbe8aea35fdfe | 50,491 |
def _is_begin_bulk(line_upper: str) -> bool:
"""
is this a:
'BEGIN BULK'
but not:
'BEGIN BULK SUPER=2'
'BEGIN BULK AUXMODEL=2'
'BEGIN BULK AFPM=2'
"""
is_begin_bulk = 'BULK' in line_upper and (
'AUXMODEL' not in line_upper and
'AFPM' not in line_upper and
'SUPER' not in line_upper)
return is_begin_bulk | 659c34bb9c4f1fe4cdab77bed4201cfe2fabdd68 | 402,614 |
def FHFP(w1,gas2,gas1):
"""
Uses the momentum and energy conservation equations to calculate
error in pressure and enthalpy given shock speed, upstream (gas1)
and downstream states (gas2). States are not modified by these routines.
FUNCTION SYNTAX:
[FH,FP] = FHFP(w1,gas2,gas1)
INPUT:
w1 = shock speed (m/s)
gas2 = gas object at working/downstream state
gas1 = gas object at initial/upstream state
OUTPUT:
FH,FP = error in enthalpy and pressure
"""
P1 = gas1.P
H1 = gas1.enthalpy_mass
r1 = gas1.density
P2 = gas2.P
H2 = gas2.enthalpy_mass
r2 = gas2.density
w1s = w1**2
w2s = w1s*(r1/r2)**2
FH = H2 + 0.5*w2s - (H1 + 0.5*w1s)
FP = P2 + r2*w2s - (P1 + r1*w1s)
return [FH, FP] | b64f70a7b2c3b45ba03a4b42cfb0ae8889020a38 | 170,881 |
from typing import Dict
def extract_commit_message_metadata(message: str) -> Dict[str, str]:
"""Extract extended metadata stored in the Git commit message.
For example, a commit that looks like this::
Do the thing!
Piper-Changelog: 1234567
Will return::
{"Piper-Changelog": "1234567"}
"""
metadata = {}
for line in message.splitlines():
if ":" not in line:
continue
key, value = line.split(":", 1)
metadata[key] = value.strip()
return metadata | 507a4116ce29c8d95f24561cda0ab1552c9bfb04 | 407,402 |
def trdestroy(tr):
"""Close a trace database, cleaning up memory and files"""
rc = tr.trdestroy()
return rc | 808eb0643591d1667589695226a7cb12619f05c7 | 444,278 |
import array
def decode_16_bit_2ch(data):
"""
Decode and deinterleave 16 bit 2 channel pcm audio
"""
d = array.array('h', data)
left = d[0::2]
right = d[1::2]
return left, right | 2ea82a9ba7703de1ccb9fa1c8180c049f15a72cd | 471,557 |
import base64
def _string_to_base64(string):
"""Encodes string to utf-8 and then base64"""
utf8_encoded = string.encode('utf-8')
return base64.urlsafe_b64encode(utf8_encoded) | 5303ab83fc07154ae8b13589c80dd4debc71ca23 | 255,678 |
import ipaddress
def build_subnet(subnet_str):
"""
Convert an IPv4/IPv6 subnet in string format (e.g. 192.168.1.0/24) into an
:class:`ipaddress.IPv4Network` or :class:`ipaddress.IPv6Network` object.
:param str subnet_str: subnet in string format.
:returns: :class:`ipaddress.IPv4Network` or :class:`ipaddress.IPv6Network`
object depends on input subnet address type, or None if input invalid.
"""
try:
network = ipaddress.IPv4Network(subnet_str)
except ipaddress.AddressValueError:
try:
network = ipaddress.IPv6Network(subnet_str)
except ipaddress.AddressValueError:
return None
return network | 0a1308d10895cc725f36acd124bae9eb7ef4fd7b | 349,160 |
def _contains(d, n):
"""True when dictionary contains name in keys."""
return d.get(n, None) is not None | 6ddc58ca92403b6fb1168907b6e802c987e91066 | 152,200 |
def __copy__(self) :
"""Return a copy of self"""
return type(self)(self); | 2179c5b5f5ccc86621af4c0ea16164731fd8e9fe | 103,353 |
import random
def randint(low, height=None):
"""
if height is none, then range is [0, low)
else range is [low, height)
usage:
>>> n = randint(0, 10)
>>> print 0 <= n < 10
True
>>> n = randint(3)
>>> print 0 <= n < 3
True
"""
if height:
return random.randint(low, height - 1)
else:
return random.randint(0, low - 1) | 6d52f0da73a5bd3ae1b9547bd2d4ca4fc933c822 | 447,894 |
def _tile_size(shape, out_shape, ndim):
"""Returns tile_size such that shape*tile_size = out_shape"""
size = [1] * ndim
for idx, (i, j) in enumerate(zip(shape, out_shape)):
if i != j:
size[idx] = j
return tuple(size) | 6f067243805b252cdabb3a9674d4d5d7fcea2703 | 653,942 |
def lam_to_nu(lam):
"""
Function to compute frequency (in Hz)
from Wavelength (in A)
-----------------------
Parameters:
-----------
lam : float
wavelength in A
-----------
returns
-----------
float :
frequency in Hz
"""
lam1 = lam*10**(-10)
freq = 299792458/lam1
return freq | 9f60edb0995535b063a956f4ba2972a113b8bebf | 196,893 |
import io
import tarfile
import base64
def get_tar_data(path):
"""Tar a path into a base64 string"""
tardata = io.BytesIO()
tar = tarfile.open(fileobj=tardata, mode="w")
tar.add(path, arcname="./")
return base64.b64encode(tardata.getvalue()).decode() | 1f228ef9759672eb74183ec6f0f00ada8ee02353 | 363,388 |
def safe_int(text, default):
"""try parse txt into an int else returns the default"""
try:
return int(text)
except (ValueError, TypeError):
return default | 0d3b70e509b203ef5b66dd3243264bfca9a837ea | 364,433 |
def number_valid(value):
"""Test for valid number
>>> number_valid(0)
True
>>> number_valid(-1)
True
>>> number_valid(1.12039123)
True
>>> number_valid('1.12039123')
True
>>> number_valid('x1.12039123')
False
>>> number_valid('t')
False
>>> number_valid('')
True
>>> number_valid(False) # not sure if this is what's we want
True
"""
if value == '':
return True
try:
float(value)
return True
except ValueError:
return False | 2d350a248be8f47e6f7c94a28fe2f72c54818e0a | 272,216 |
from operator import or_
def _apply_query_filter(table, key, values, query):
"""Apply a filter to the given ``query`` based on the ``table``,
``key``, and ``value``.
Parameters
----------
table : obj
The ``SQLAlchemy`` table object associated with the table to
apply the filter to.
key : str
The keyword for the column to filter on.
values : obj
The requested values of the ``key``.
query : obj
The ``SQLAlchemy`` ``query`` objecgt to perform the filtering
on.
Returns
-------
query : obj
The ``SQLAlchemy`` ``query`` object with filter applied.
"""
# Fields that accpet comma-separated lists and wildcards
csv_keys = ['rootname', 'targname', 'pr_inv_l', 'pr_inv_f']
# Fields that allow operators
operator_keys = ['date_obs', 'exptime']
# Parse the key/value pairs for comma-separated values
if key in csv_keys:
parsed_value = values[0].replace(' ', '').split(',')
parsed_value = [item.replace('*', '%') for item in parsed_value]
conditions = [getattr(table, key).like(val) for val in parsed_value]
query = query.filter(or_(*conditions))
# Parse the key/value pairs for operator keys
elif key in operator_keys:
if values['op'] == 'between':
if len(values) == 3:
if float(values['val1'].replace('-', '')) < float(values['val2'].replace('-', '')):
query = query.filter(getattr(table, key).between(values['val1'], values['val2']))
elif float(values['val1'].replace('-', '')) > float(values['val2'].replace('-', '')):
query = query.filter(getattr(table, key).between(values['val2'], values['val1']))
elif float(values['val1'].replace('-', '')) == float(values['val2'].replace('-', '')):
raise ValueError('Values submitted for field "{}" must be different.'.format(key))
else:
raise ValueError('Invalid values submitted for field "{}".'.format(key))
else:
query = query.filter(getattr(table, key).op('=')(values['val1']))
else:
query = query.filter(getattr(table, key).op(values['op'])(values['val1']))
# Else the filtering is straightforward
query = query.filter(getattr(table, key).in_(values))
return query | 478e73da72e052782af0043ef772a1ddc049993a | 475,523 |
def denorm_sin_cos(norm_sin_cos):
""" Undo normalization step of `encode_theta_np()`
This converts values from the range (0, 1) to (-1, 1)
by subtracting 0.5 and multiplying by 2.0.
This function does not take any steps to ensure
the input obeys the law:
sin ** 2 + cos ** 2 == 1
Since the values may have been generated by a neural network
it is important to fix this w.r.t. the provided values.
# Arguments
norm_sin2_cos2: normalized sin(2*theta) cos(2*theta)
# Returns
return actual sin(theta) cos(theta)
"""
return (norm_sin_cos - 0.5) * 2.0 | ef221561df856607fe1f4319ba6bea1269f7b82f | 491,867 |
def read_datasets_h5(h5):
"""
Simple read datasets from h5 handle into numpy arrays
"""
d = {}
for k in h5:
d[k] = h5[k][:]
return d | 1b11dcd3383a4cbf68b34726f5c4e04c40664d78 | 598,489 |
def _idx_range(arr, a, b):
"""Returns a boolean array which is True where arr is between
a and b.
Parameters
----------
arr : array
Array to find the range in.
a : float
First edge of the region.
b : float
Second edge of the region.
Returns
-------
: arr of bool
The resulting boolean array
"""
lower, upper = sorted([a,b])
idx = (lower<arr) & (arr<upper)
return idx | d4b2ec114444c44494430209590e8d63f7569b97 | 278,025 |
from pathlib import Path
def check_file_ext(filename, extension):
"""Checks whether filename ends with extension and adds it if not."""
is_path = False
if isinstance(filename, Path):
is_path = True
filename = str(filename)
elif isinstance(filename, str):
pass
else:
raise RuntimeError("Wrong input type for file extension check.")
if filename[-len(extension):] != extension:
filename += extension
if is_path:
filename = Path(filename)
return filename | bfab23259badc21ef457979e534263468c165105 | 550,094 |
def link_fix(text, name_dict):
"""
Replace old file names with new in markdown links.
"""
new_text = text
for old, new in name_dict.items():
new_text = new_text.replace(f']({old})', f']({new})')
return new_text | 0e17521856c4ca2077ced8cdde831a959e95d144 | 410,488 |
def get_eso_file_version(raw_version):
"""Return eso file version as an integer (i.e.: 860, 890)."""
version = raw_version.strip()
start = version.index(" ")
return int(version[(start + 1) : (start + 6)].replace(".", "")) | d456ce65585a8aad0c08d9e53b6aeb77132a0d49 | 49,109 |
def extract_all_wiki_links(entry):
"""
Extract all wikipedia links associated to an entry
:param entry: entry data
:return:
"""
if "sitelinks" in entry:
return entry['sitelinks'] | 58760d1971c68d18880345f7c4999fd844c61fe7 | 628,766 |
def extract_layout_switch(dic, default=None, do_pop=True):
"""
Extract the layout and/or view_id value
from the given dict; if both are present but different,
a ValueError is raised.
Futhermore, the "layout" might be got (.getLayout) or set
(.selectViewTemplate);
thus, a 3-tuple ('layout_id', do_set, do_get) is returned.
"""
if do_pop:
get = dic.pop
else:
get = dic.get
layout = None
layout_given = False
set_given = 'set_layout' in dic
set_layout = get('set_layout', None)
get_given = 'get_layout' in dic
get_layout = get('get_layout', None)
keys = []
for key in (
'layout', 'view_id',
):
val = get(key, None)
if val is not None:
if layout is None:
layout = val
elif val != layout:
earlier = keys[1:] and tuple(keys) or keys[0]
raise ValueError('%(key)r: %(val)r conflicts '
'%(earlier)r value %(layout)r!'
% locals())
keys.append(key)
layout_given = True
if layout is None:
layout = default
if set_layout is None:
set_layout = bool(layout)
return (layout, set_layout, get_layout) | 41a7a11e72ed70dee1456334a93a5cfe0651ec37 | 29,600 |
def color_producer(elevation):
""" This returns color depending on the elevation """
if elevation < 1500:
return 'green'
elif 1500 <= elevation < 3000:
return 'orange'
else:
return 'red' | 74e5f5ac8f90da8096062d420250bc306c58464f | 596,426 |
import time
def test_engine(engine):
""" Tests SQLAlchemy engine and returns response time """
if not engine:
return {'status': 'ERROR', 'error': 'No engine defined'}
try:
start = time.time()
connection = engine.connect()
if not connection.closed:
connection.close()
elapsed = '{:.3f}'.format(time.time() - start)
return {
'engine': str(engine),
'label': getattr(engine, 'label', '<unknown>'),
'status': 'OK',
'time': elapsed
}
except Exception as err:
return {'status': 'ERROR', 'error': str(err)} | ced48c2d21480124ff4673630a7070772d370335 | 65,416 |
import difflib
def closest_title(title, series):
"""
Return closest movie name in a given dataframe.
-------
Parameters:
title (string): Movie name
series: (pandas Series): Series to search for closest title
"""
matches = difflib.get_close_matches(title, series)
if matches:
return matches[0]
else:
return '' | 4052122f8cf141eff1ad59ccf019144f81392220 | 619,132 |
def moment(values, c, exponent):
"""Returns moment about the value c"""
total = 0.0
for value in values:
total += ((value-c)**exponent)
return total / len(values) | 43c3217e61665b608cc423f29f7cef858b57c1a4 | 124,662 |
def ft32m3(ft3):
"""ft^3 -> m^3"""
return 0.028316847*ft3 | 74f55f722c7e90be3fa2fc1f79f506c44bc6e9bc | 706,908 |
def strip_definition_from_video(vid_id):
"""Strip any sort of HD tag from the video"""
hd = ['[HD]', '[FHD]', '[SD]', '(SD)', '(HD)', '(FHD)']
for item in hd:
vid_id = vid_id.replace(item, '')
return vid_id | 996a37309e5c4de6d5bd5110a16f4dcdf6760bab | 657,788 |
def get_package_name(line):
"""Return a package name from a line in the ``requirements.txt``
file.
"""
idx = line.find('<')
if idx == -1:
idx = line.find('>')
if idx == -1:
idx = line.find('=')
if idx == -1:
return line
return line[:idx].strip() | d670f2d8759258e3b27400bb5a0e1f9bd132e8c1 | 413,860 |
def rad2equiv_evap(energy):
"""
Converts radiation in MJ m-2 day-1 to the equivalent evaporation in
mm day-1 assuming a grass reference crop using FAO equation 20.
Energy is converted to equivalent evaporation using a conversion
factor equal to the inverse of the latent heat of vapourisation
(1 / lambda = 0.408).
Arguments:
energy - energy e.g. radiation, heat flux [MJ m-2 day-1]
"""
# Determine the equivalent evaporation [mm day-1]
equiv_evap = 0.408 * energy
return equiv_evap | 7780ca2fc42cbbb1814aa5899aa1c2294453f45d | 688,609 |
def replace_special_characters(string: str):
"""Replace special characters in step id with -"""
parts = []
for word in string.split(' '):
part = ''
for c in word:
if c.isalnum():
part += c
elif part:
parts.append(part)
part = ''
if part:
parts.append(part)
return '-'.join(parts) | 075b0e0082df6031b2910b688c237ccb545183ec | 322,864 |
def get_with_default(install_config, parameter_name, default_value):
"""
:param install_config: A dict represents the install section inside the configuration file
:param parameter_name: Specific key inside the install section
:param default_value: Default value in cases that the key cannot be found
:return: The value of the key in the configuration file or default value if key cannot be found
"""
return install_config[parameter_name] if install_config and parameter_name in install_config else default_value | d4fbbb4311433b0f1f19b842a71e0d3157ede586 | 103,758 |
def get_sensor_network_flows(querier, query_window):
"""
Performs Prometheus queries relevant to sensor network flows
:param querier: An object containing information
needed to query the Prometheus API
:param query_window: The window over which rates are computed by Prometheus
:return: Json containing information about sensor network flows
"""
res = {}
for flow_type in ["incoming", "outgoing"]:
for protocol in ["L4_PROTOCOL_TCP", "L4_PROTOCOL_UDP"]:
metric = 'rox_sensor_network_flow_total_per_node'
query = f'({metric}{{Protocol="{protocol}",Type="{flow_type}"}})'
query_name = f'{flow_type}_{protocol}'
res[query_name] = querier.get_stats_for_query(query)
res[query_name]['description'] = f'Number of {flow_type} {protocol} network flows over pods'
metrics = [
"rox_sensor_network_flow_host_connections_added",
"rox_sensor_network_flow_host_connections_removed",
"rox_sensor_network_flow_external_flows"
]
for metric in metrics:
query = metric
rate_query = f'rate({metric}[{query_window}])'
query_name = metric
rate_query_name = f'{metric}_rate'
res[query_name] = {'value': querier.query_and_get_value(query)}
res[rate_query_name] = {'value': querier.query_and_get_value(rate_query)}
res[rate_query_name]['description'] = f'Average {metric}'
res[rate_query_name]['units'] = 'per seconds'
return res | 79161f7c93180846f17192325839e611159049b2 | 304,941 |
def normalize_ped_delay_row(zone_label, row):
"""
Normalize the given ped delay row, converting times to ISO 8601 format.
"""
t = row['t']
t_iso = t.isoformat()
data = row['data']
data['zone'] = zone_label
return {
't': t_iso,
'data': data
} | 61392947f19e7d608c48b966cd6244d364e8692d | 348,670 |
def get_repo_snoop_url(args):
"""Return the fully expanded url for snooping this repo or None.
:args: the namespace returned from the argparse parser
:returns: string url to snoop the repo, or None
"""
url = None
if args.repo_snoop_url_format:
url = args.repo_snoop_url_format.format(args.repo_url)
return url | d04ab20d09f06c81baf9a1ca737357aeeb2f1ba7 | 433,768 |
def get_violated_bounds(val, bounds):
""" This function tests a value against a lower and an upper bound,
returning which if either is violated, as well as a direction
that the value needs to move for feasibility.
Arguments:
val: Value to be tested
bounds: Tuple containing the lower, upper bounds
"""
lower = bounds[0]
upper = bounds[1]
if upper is not None:
if val > upper:
return (upper, -1)
if lower is not None:
if val < lower:
return (lower, 1)
return (None, 0) | ec0e810c3e232086bd604e1368c2698db2f99d2f | 165,002 |
def hour(clock):
"""Return the hour of clock time 'clock'."""
return clock[0] | e8d58c3892e7d364d228b5198691a6d7c7d1f244 | 269,194 |
def AdjustDateForYearBoundary(to_adjust, latest_date):
"""Handles end-of-year boundaries for dates that are parsed from strings
that don't include the year. latest_date is the latest date known from
processing an input. If to_adjust is after latest_date, to_adjust is
moved back a year.
For example, an input may have dates 12/31 and 01/01. This crosses the
year boundary so 01/01 is year X and 12/31 is year X-1.
"""
if to_adjust <= latest_date:
return to_adjust
return to_adjust.replace(year=to_adjust.year-1) | b1ab18e2a6b1e7169f9c4e415ab395efdc9efb87 | 536,647 |
def find_index(column_name, row, error_msg):
"""
Find what column has the specified label.
The search is case insensitive.
Args:
column_name: Column label to search for
row: The row with the headers for this table, typically the first.
error_msg: Error message to raise with ValueError.
Returns:
Index of the column with the specified name.
Raises:
ValueError: If no column named column_name can be found.
"""
for i, cell in enumerate(row):
if cell.strip().lower() == column_name.lower():
return i
else:
raise ValueError(error_msg) | 51f51f0ae5775c078dee596375df88ca2fec8041 | 351,256 |
import random
def _random_dataset(n_samples=10, n_features=10):
"""
Generates a random dataset by returning a tuple of sampleIds, featureIds,
and a list of vectors based on input parameters.
:param n_samples:
:param n_features:
:return: (sampleIds, featureIds, vectors) tuple
"""
sampleIds = ["sample_{}".format(x) for x in range(n_samples)]
featureIds = ["feature_{}".format(x) for x in range(n_features)]
vectors = [
[random.random() for x in range(len(featureIds))]
for x in range(len(sampleIds))]
return sampleIds, featureIds, vectors | b39a8ec0981ac2d19545739e2dc126e56e9d5459 | 407,709 |
def str2list(s, sep=',', d_type=int):
"""
Change a {sep} separated string into a list of items with d_type
:param s: input string
:param sep: separator for string
:param d_type: data type of each element
:return:
"""
if type(s) is not list:
s = [d_type(a) for a in s.split(sep)]
return s | 671bc6c5c9814a636d0c140cb11a3ecdb1124202 | 258,435 |
def split(s, sep=None, maxsplit=None):
"""对一个长字符串按特定子字符串进行分割
:param s: 原长字符串
:type s: str
:example s: "a b c d e f"
:param sep: 子字符串,为None时值为 " "
:type sep: str
:example sep: " "
:param maxsplit: 分割次数,为None时代表全部分割
:type maxsplit: int
:example maxsplit: 3
:rtype list
:return 按特定子字符串分割后的字符
:example ['a', 'b', 'c', 'd e f']
"""
if sep is None:
sep = " "
def _split():
"""切分字符串
"""
if maxsplit is not None and maxsplit == 0:
yield s
return
sep_length = len(sep)
length = len(s)
i, j = 0, 0
split_count = 0
while i < length:
if s[i:i + sep_length] == sep:
yield s[j:i]
i += sep_length
j = i
split_count += 1
if maxsplit and split_count >= maxsplit:
break
else:
i += 1
if j <= len(s):
yield s[j:]
return [sub for sub in _split()] | 7184746e0ebb15ea1d235a4fe1067f28466e636d | 679,922 |
def __subfields(t, d):
""" Unpack subfield data into tuples. """
# Remove extra trailing subfield delimiters, if neccessary, before
# splitting into subfields
subf = d.rstrip(b"\x1f").split(b"\x1f")
# No subfields means it's a control field, with no indicators and
# no subfield code
if len(subf) == 1:
return (t, None, None, (None, d.decode()))
return (t, chr(subf[0][0]), chr(subf[0][1])) + \
tuple([(chr(s[0]), s[1:].decode()) for s in subf[1:]]) | bd030682d1b4fb77a11b2d7a07d6785c27549033 | 159,976 |
def formatEdgeDestination(node1, node2):
"""
Gera uma string que representa um arco node1->node2
Recebe dois inteiros (dois vértices do grafo), e o formata com a notação de
aresta a->b onde a é o vértice de origem, e b o de destino.
Args:
node1 (int): número de um dos vértices ligados à aresta
node2 (int): número de um dos vértices ligados à aresta
Returns:
str: arco no formato "a->b"
Raises:
TypeError: caso os argumentos não sejam do tipo inteiro
"""
if not(isinstance(node1, int)) or not(isinstance(node2, int)):
raise TypeError('arguments node1 and node2 must be integers')
return '{:d}->{:d}'.format(node1, node2) | 517997fb634b0c9c12fc61d1e582f584786c6196 | 688,489 |
def sort_data(data, cols):
"""Sort `data` rows and order columns"""
return data.sort_values(cols)[cols + ['value']].reset_index(drop=True) | 33acbfd9be36d187120564f1792147b644b6c394 | 8,825 |
def chunks(l: list, n: int):
"""
Divide a list into n equal parts
:param l: list
:param n: number of chunks
:return: list of list of the original
"""
k, m = divmod(len(l), n)
return (l[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in range(n)) | d8242210e658049ba7a5a5727128db0ce180652b | 309,694 |
def is_generation_specified(query_params):
"""Return True if generation or if_generation_match is specified."""
generation = query_params.get("generation") is not None
if_generation_match = query_params.get("ifGenerationMatch") is not None
return generation or if_generation_match | e44d0a68346d4195e3b88eec81014552eabee3df | 195,715 |
def import_gff3(filepath):
"""
This function opens a GFF3-file in the location specified by the
variable 'filepath'. Looping over the file, the list variable
'feature_list' will be used to store short lists of DNA features.
This 2D list is returned.
:param filepath: string containing the location of the GFF3-file.
:return feature_list: a 2D list containing DNA features, their
type, start position, end position, coding strand and
translation frame.
"""
feature_list = []
with open(filepath, 'r') as infile:
iterdata = iter(infile.readlines())
next(iterdata)
for line in iterdata:
line = line.strip("\n").split("\t")
feature_list.append([line[0], line[2], int(line[3]), int(line[4]), line[5], line[6], line[-1]])
return feature_list | c1166a190ae947b7b8a1f01ec153ecf694bc2d91 | 433,313 |
def mib(num):
"""Return number of bytes for num MiB"""
return int(num * 1024 * 1024) | b646ebf6d1e9603c63d338ae28fd09599fe6eacd | 445,958 |
def freq(code):
"""
return a dic with the number of occurence of each char of the text given
in : code (str/list) > text from wich you want to extract frequency
out : dic (dic) > dic with the number of occurence of each char of the text given
>>>freq("eeebaaa")
{"e" : 3, "b" : 1, "a": 3}
"""
dic = {"e": 0 } #initialise dic so it is not empty
for i in range(len(code)):
if code[i] not in dic:
dic[code[i]] = 1
else:
dic[code[i]] += 1
return dic | 250ef9250e34fd0bbf880bf14e42cd43b7fd1b5d | 529,247 |
def diff(arr1, arr2):
""" Return difference between two arrays. """
return [i - j for i, j in zip(arr1, arr2)] | aff95236d09c68c3e5cfbe6fd65ad76c3c5ecd77 | 530,710 |
def is_prima_facie(c_and_e, c_true, e_true, events):
"""
Determines whether c is a prima facie cause of e.
Parameters:
c_and_e: number of times both events were true in a time window
c_true: number of times the cause was true in a time window
e_true: number of times the effect was true in a window
events: the total number of events
Returns:
boolean
"""
if c_true == 0:
return(False)
result = c_and_e / c_true > e_true / events
return(result) | da3b4346c579a8fe967dfc49157e61e7d2af2942 | 401,764 |
import time
import math
def elapsed_time(start):
"""Returns time elapsed since start as a string."""
now = time.time()
elapsed_s = now - start
elapsed_min = math.floor(elapsed_s / 60)
elapsed_s = elapsed_s % 60
return f'{elapsed_min}m {elapsed_s}s' | f996e17e5dec521ed28c849c5adee21db7a199e6 | 203,042 |
def sum_dicts_values(dict1, dict2):
"""Sums the value between tow dictionnaries (with the same keys) and return the sum"""
dict = {}
for k in dict1.keys():
try:
dict[k] = int(dict1[k]) + int(dict2[k])
except:
dict[k] = int(dict1[k])
return dict | 69e6d4debe93b301db929ee41ef21a06b9240dbe | 161,286 |
def local_radius(x, y):
"""Returns radius of the circle going through a point given it's local coordinates."""
if x != 0:
return (x**2 + y**2) / abs(2 * x)
else:
return y**2 | c6d2a720df19d2d66e82a934f55a79d69d1b6d5d | 224,344 |
def get_money_spent(keyboards, drives, b):
"""Hackerrank Problem: https://www.hackerrank.com/challenges/electronics-shop/problem
Monica wants to buy a keyboard and a USB drive from her favorite electronics store. The store has several models of
each. Monica wants to spend as much as possible for the 2 items, given her budget.
Given the price lists for the store's keyboards and USB drives, and Monica's budget, find and print the amount of
money Monica will spend. If she doesn't have enough money to both a keyboard and a USB drive, print -1 instead.
She will buy only the two required items.
Solve: Iterate through the keyboards and drives to see the maximum amount we can spend without going over total budget
Args:
keyboards (list): list of keyboard costs
drives (list): list of drive costs
b (int): budget
Returns:
int: the highest amount that can be spent, or -1 if not possible
"""
cost = -1
for keyboard in keyboards:
for drive in drives:
if cost < keyboard + drive <= b:
cost = keyboard + drive
return cost | ae6cef74c367df3e3d5f570d43cef2fdecd6b05b | 501,042 |
def weigh_wigner_d(d, w):
"""
The Wigner-d transform involves a sum where each term is a product of data, d-function, and quadrature weight.
Since the d-functions and quadrature weights don't depend on the data, we can precompute their product.
We have a quadrature weight for each value of beta and beta corresponds to the second axis of d,
so the weights are broadcast over the other axes.
:param d: a list of samples of the Wigner-d function, as returned by setup_d_transform
:param w: an array of quadrature weights, as returned by S3.quadrature_weights
:return: the weighted d function samples, with the same shape as d
"""
return [d[l] * w[None, :, None] for l in range(len(d))] | 0d5264fb461a80c9146151c98fb86bdc4bcd1ad9 | 436,763 |
def to_chw(im, order=(2, 0, 1)):
"""
Transpose the input image order. The image layout is HWC format
opened by cv2 or PIL. Transpose the input image to CHW layout
according the order (2,0,1).
Example usage:
.. code-block:: python
im = load_image('cat.jpg')
im = resize_short(im, 256)
im = to_chw(im)
:param im: the input image with HWC layout.
:type im: ndarray
:param order: the transposed order.
:type order: tuple|list
"""
assert len(im.shape) == len(order)
im = im.transpose(order)
return im | f0ef4141d3c1760ed03f603999d39a62557df75d | 519,719 |
def to_cxx(data):
"""Generates C++ code from a list of encoded bytes."""
text = '/* This file is generated. DO NOT EDIT!\n\n'
text += 'The byte array encodes effective tld names. See make_dafsa.py for'
text += ' documentation.'
text += '*/\n\n'
text += 'const unsigned char kDafsa[%s] = {\n' % len(data)
for i in range(0, len(data), 12):
text += ' '
text += ', '.join('0x%02x' % byte for byte in data[i:i + 12])
text += ',\n'
text += '};\n'
return text | 47c1333e7d8d2eb9a08660ec6a85e224d3c13e38 | 224,849 |
def summarize_mutation(mutation_name, event, inputs, outputs, isAsync=False):
"""
This function provides a standard representation of mutations to be
used when services announce themselves
"""
return dict(
name=mutation_name,
event=event,
isAsync=isAsync,
inputs=inputs,
outputs=outputs,
) | 269fbd8a94524ccf49313ae33111e44e45384658 | 295,237 |
def _get_available_parameters(parameters):
"""helper function to extract a parameter list from the result of quest.api.get_parameters
"""
if isinstance(parameters, dict):
available_parameters = parameters['parameters']
else: # if parameters is a DataFrame
available_parameters = set(parameters['parameter'])
if available_parameters:
available_parameters.discard(None)
available_parameters = list(available_parameters)
return available_parameters | 053e8081ffa071ca3d5bbd74e3a8e4142765903b | 358,196 |
def binary_search(arr, key):
"""Given a search key, this binary search function checks if a match found
in an array of integer.
Examples:
- binary_search([3, 1, 2], 2) => True
- binary_search([3, 1, 2], 0) => False
Reference: https://en.wikipedia.org/wiki/Binary_search_algorithm
Args:
arr (list): A list of integer
key (int) : Integer search key
Returns:
bool: True if key exists in arr, False otherwise
"""
arr.sort()
L = 0
R = len(arr) - 1
if L > R:
return False
mid = R//2
if key == arr[mid]:
return True
elif key < arr[mid]:
return binary_search(arr[:mid], key)
else:
return binary_search(arr[mid+1:], key) | b3c89d284b1efa970e6ee019a9a35f4f63cef71a | 307,118 |
def read_pair_align(read1, read2):
""" Extract read pair locations as a fragment oriented in increasing chromosome coordinates
:param read1: read #1 of pair in pysam AlignedSegment format
:param read2: read #2 of pair in pysam AlignedSegment format
:return 4-item array in the following format: [fragA-start, fragA-end, fragB-start, fragB-end]
with monotonically increasing chromosome coordinates
"""
r1pos = [x+1 for x in read1.positions]
r2pos = [x+1 for x in read2.positions]
if read1.mate_is_reverse and r1pos[0] < r2pos[0]: # read1 is earlier
read = [r1pos[0], r1pos[-1], r2pos[0], r2pos[-1]]
elif read2.mate_is_reverse and r2pos[0] < r1pos[0]: # read2 is earlier
read = [r2pos[0], r2pos[-1], r1pos[0], r1pos[-1]]
else:
read = []
# print("Skipping read pair from error in alignment.")
# print("%s--%s> <%s--%s" % tuple(read))
return read | f9d1476330a8cf1c9e836654d67a8bcda9e18eb7 | 27,933 |
import yaml
def _yaml_reader(yaml_file):
"""Import the YAML File for the YOLOv5 data as dict."""
with open(yaml_file) as file:
data = yaml.safe_load(file)
return data | fdbb318a5e8176dcf7072643d40fdc433de0b6d4 | 678,642 |
from typing import List
def fibo(nth: int) -> List[int]:
"""Fibonacci numbers up to the `nth` term starting with 0 and 1."""
fibos = [0, 1]
for _ in range(nth - 2): # - 2 because we already have the first two
fibos.append(fibos[-1] + fibos[-2])
return fibos | e960cd5cf3520be0de343d2e615d7bf3e87d1bea | 676,515 |
def sort(coll):
""" Sorts a collection and returns it. """
coll.sort()
return coll | 2ae8abfd420a10606df89fbfbfdc9e670044b2e8 | 514,617 |
def get_portchannel_members(pchannel):
"""Gets the members of an existing portchannel
Args:
pchannel (dict): port-channel dict
Returns:
list: empty if currently no members, otherwise
list of Ethernet interfaces that make up
the given port-channel
Note:
Specific for Ansible module(s). Not to be called otherwise.
"""
try:
members = pchannel['TABLE_member']['ROW_member']
except KeyError:
members = []
return members | f18103c24295c0376b9bc63b8de4c996bd4977c5 | 375,048 |
import random
import string
def random_lower_string() -> str:
"""generate random lowercase str"""
return "".join(random.choices(string.ascii_lowercase, k=32)) | 99088578fa07387365391e8d91f9e777345586d5 | 585,869 |
def to_list(dataframe, column):
"""
Converts a Pandas dataframe to a nested list in [X, Y, grid reference or UID] format.
:param dataframe: Pandas dataframe, data
:param column: string, column name containing the grid reference or UID
:return: list, nested list in [X, Y, grid reference or UID] format
"""
return dataframe.loc[:, [0, 1, column]].values.tolist() | 4aef2bae91f1fc9b07054c8550ac0300abd651b5 | 331,333 |
import warnings
def _get_secret_keys(config, secrets_config_key='SECRETS', secrets_list=None):
"""
Finds all of the configuration values that should be secret
"""
keys = []
if secrets_config_key is not None:
configuration_keys = config.get(secrets_config_key)
if configuration_keys is None:
warnings.warn('ultra-config was unable to find any configuration for '
'{0}. Please set {0}=[] in your configuration or pass '
'`secrets_config_key=None` if you wish to manually set '
'the configuration keys to decrypt'.format(secrets_config_key))
configuration_keys = []
keys.extend(configuration_keys)
secrets_list = secrets_list or []
keys.extend(secrets_list)
return keys | 1390da52b7e5cdbae26023931dd03bc54a4cbb8c | 641,368 |
from bs4 import BeautifulSoup
def extract_text(html: str) -> str:
"""Extract plaintext from HTML."""
soup = BeautifulSoup(html, 'html.parser')
plaintexts = [p.text for p in soup.find_all(['h1', 'h2', 'h3', 'p'])]
return ' '.join(plaintexts) | b2c3b3c53577a8020319d59b4064b027c71a03ec | 590,976 |
import ipaddress
def is_valid_ip(v):
"""Check if is a valid IP address
:param str v: A string value
:return: IP address version if valid, else 0
:rtype: int
"""
try:
ip = ipaddress.ip_address(v)
except ValueError:
version = 0
else:
version = ip.version
return version | 8db7ac88cebfe0afeee859cc22b66105ffb66a8d | 583,529 |
def prettify_prediction_interpretation(interpretation_info, prediction_interpretation, config):
"""
Convert the prediction interpretation to a pretty markdown string.
The text coloring only supports up to 6 colors, i.e. up to 6 classes of labels. If you want more, it's easy
to add.
Format per instance:
* original text
* marked text: each token is preceded by a colored @ with a color corresponding to the class of the filter
that "chose" an ngram containing this token.
* a table of all the prediction data:
filter name | filter identity class | passes | ngram | activation | slots
- filter name format: w{ngram size}.f{filter index} ex. w3.f4 = filter number
4 among the filters processing ngrams of size 3
- passes: whether the ngram passes the threshold of this filter
- activation: the final activation of the filter on this ngram. note that this number does NOT equal the sum of
the slot activations, because it includes the filter bias weight and is after the ReLU layer (non-negative)
- slots: the slot activation vector, i.e. the token-level activations gathered from breaking the filter-ngram
dot-product into k dot-products (for ngram of length k)
"""
output_str = "# Prediction info"
def mark_span(sentence, span_start, span_end, color):
mark = f'<span style="background-color: {color}">@</span>'
marked_ngram = []
for token in sentence[span_start:span_end]:
if mark in token:
marked_ngram.append(token)
else:
marked_ngram.append(mark + token)
return sentence[:span_start] + marked_ngram + sentence[span_end:]
colors = ["#FFFF00", "#6698FF", "#E56717", "#00FF7F", "#FFA07A", "#FF8C00"] # add more colors here
class_to_color = {}
for cl, color in zip(list(config["class_to_str"]), colors):
class_to_color[cl] = color
identity_classes = interpretation_info["threshold_info"]["identity_classes"]
thresholds = interpretation_info["threshold_info"]["thresholds"]
for pinfo in prediction_interpretation:
sen = pinfo["sentence"]
table = "filter | filter class | passes | ngram | activation | slots\n"
table += ":-- | :-- | :-- | :-- | :-- | :--\n"
for wix, w_size in enumerate(config["ngram_sizes"]):
for fix in range(config["num_filters"]):
fname = "w" + str(w_size) + ".f" + str(fix)
ngram = " ".join(pinfo[fname]["chosen_ngram"])
ngram_span = pinfo[fname]["chosen_ngram_span"]
c = identity_classes[fname]
passes = "x" if pinfo[fname]["activation"] > thresholds[wix, fix] else " "
if passes == "x":
sen = mark_span(sen, ngram_span[0], ngram_span[1], class_to_color[str(c)])
l = " | ".join(
[fname, config["class_to_str"][str(c)], passes, "`" + ngram + "`",
"{0:.2f}".format(pinfo[fname]["activation"]),
str(["{0:.2f}".format(i) for i in pinfo[fname]["slot_activations"]])]) + "\n"
table += l
header = "## Original input: \n"
header += "``` " + " ".join(pinfo["sentence"]) + " ``` \n\n"
header += "## Marked input: \n"
header += "<pre>" + " ".join(sen) + "</pre> \n\n"
header += "Gold: " + pinfo["gold_str"] + ", Prediction: " + pinfo["prediction_str"] + "\n\n"
output_str += "\n" + header + "\n" + table
return output_str | 5cba8f28eeeaa2ea9a75c63b5f884d2ad6eb7976 | 546,067 |
def _coords(shape):
"""
Return a list of lists of coordinates of the polygon. The list consists
firstly of the list of exterior coordinates followed by zero or more lists
of any interior coordinates.
"""
assert shape.geom_type == 'Polygon'
coords = [list(shape.exterior.coords)]
for interior in shape.interiors:
coords.append(list(interior.coords))
return coords | dd63ff6700111ad09b64b28baef7876988821b83 | 97,707 |
def atomic_prop(entry, molTuple):
"""Return true if atom fits F5 (atomic property) entry, False otherwise"""
molecule, atomIndex = molTuple
#determine atom properties
propList = []
nonRing = True
for count, ring in enumerate(molecule.ringList):
if atomIndex in ring:
nonRing = False
propList.append('RG%s' % (str(len(ring))))
propList.append(molecule.aromaticList[count])
if nonRing:
propList.append('NR')
#separate properties by comma
entry = entry[1:-1].split(',')
propList = propList[:]
for index in range(len(entry)):
entry[index] = entry[index].split('.')
matchCount = 0
for condition in entry:
for count, prop in enumerate(propList):
if prop in condition:
matchCount += 1
del propList[count]
break
if matchCount == len(entry):
return True
else:
return False | 590a0b170081c4b345552804dc9bfdc52db90087 | 612,230 |
from typing import Tuple
def rgb_to_hex_int(rgb: Tuple[int]) -> int:
""" Converts an RGB tuple to a hex value using the method [1].
Parameters
----------
rgb : tuple of int
Like (r, g, b) where the colour is represented as integer RGB components
between 0 and 255.
Returns
-------
hex_int : int
Returns an integer like 0xff0000 given the input (255, 0, 0).
Notes
-----
In Python 0xff0000 is a shorthand for writing hexadecimal integer values. These are
converted to base 10 integer representation. This reference [1] was useful when
implementing this function.
[1] https://stackoverflow.com/questions/3380726/converting-a-rgb-color-tuple-to-a-six-digit-code-in-python
"""
def clamp(x):
return max(0, min(x, 255))
string_value = "0x{0:02x}{1:02x}{2:02x}".format(*list(map(clamp, rgb)))
hex_int = int(string_value, 0)
return hex_int | e468345d3d75280c67a19b0a27b5bdf4f9c14bc0 | 285,246 |
def input_require_int(raw_input):
"""
Utility function that requires a given input to be an integer greater zero.
In case the given input is not an integer or zero or negative, the user is requested to provide a valid input.
:param raw_input: the initial user input
:type raw_input: str
:return: a number greater zero the user inserted
:rtype: int
"""
while True:
try:
if int(raw_input) > 0:
return int(raw_input)
else:
raise ValueError
except ValueError:
raw_input = input("Please input a valid number\n") | 4e95c178bd8da8556818a10830df82086f43ff4c | 267,584 |
def translate_points(points, translation):
"""
Returns the points translated according to translation.
"""
return points + translation | 6fc11502b47249c9b97e8e5a9d88f19c8db23fcd | 675,765 |
def lists_diff(list1, list2):
"""
Get the difference of two list and remove None values.
>>> list1 = ["a", None, "b", "c"]
>>> list2 = [None, "b", "d", "e"]
>>> list(filter(None.__ne__, set(list1) - set(list2)))
['c', 'a']
"""
return list(filter(None.__ne__, set(list1) - set(list2))) | 3a90a0bc85657d17abc600258bef26f36a18de73 | 245,580 |
def denormalize_image(image):
""" Undo normalization of image. """
image = (image / 2) + 0.5
return image | c49a1465d89e317a1c8013969fbee913bf705f4a | 7,744 |
def _get_page_source(browser, url):
"""
Get Wikidot page source with a Selenium-powered browser driver.
:param browser: Selenium webdriver.
:param url: Url to the page to fetch from.
:return: A tuple in the following order: (text_page_title, text_page_source)
"""
browser.get(url)
elem_more_options_button = browser.find_element_by_id('more-options-button')
elem_more_options_button.click()
elem_view_source_button = browser.find_element_by_id('view-source-button')
elem_view_source_button.click()
text_page_source = browser.find_element_by_class_name('page-source').text
text_page_title = browser.find_element_by_id('page-title').text
return text_page_title, text_page_source | 37358a8e1c04b0b9aa596f47117dd74bbfff8ddb | 80,441 |
Subsets and Splits