content
stringlengths 39
14.9k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
---|---|---|
def ass_vali(text):
"""
验证是否为合法ASS字幕内容
:param text: 文本内容
:return: True|False
"""
if "V4+ Styles" in text:
return True
else:
return False
|
925744ed632e3ae1fa35f475682e2d34266ad544
| 696,356 |
def solution(socks):
"""Return an integer representing the number of pairs of matching socks."""
# build a histogram of the socks
sock_colors = {}
for sock in socks:
if sock not in sock_colors.keys():
sock_colors[sock] = 1
else:
sock_colors[sock] += 1
# count the amount of pairs
pairs = 0
for count in sock_colors.values():
pairs += count // 2
return pairs
|
1e64be91018ee633f2637ff768346f9bc6f39603
| 696,358 |
def multi_valued(annotations):
"""Return set of multi-valued fields."""
return {name for name, tp in annotations.items() if getattr(tp, '__origin__', tp) is list}
|
09d2b61b96e3bc56758a27375c1e0616995d8554
| 696,360 |
import re
def get_cxx_close_block_regex(semicolon=False, comment=None, at_line_start=False):
###############################################################################
"""
>>> bool(get_cxx_close_block_regex().match("}"))
True
>>> bool(get_cxx_close_block_regex(at_line_start=True).match("}"))
True
>>> bool(get_cxx_close_block_regex().match(" } "))
True
>>> bool(get_cxx_close_block_regex(at_line_start=True).match(" }; "))
False
>>> bool(get_cxx_close_block_regex(at_line_start=True).match(" } "))
False
>>> bool(get_cxx_close_block_regex(comment="hi").match(" } "))
False
>>> bool(get_cxx_close_block_regex(comment="hi").match(" } // hi"))
True
>>> bool(get_cxx_close_block_regex(comment="hi").match("} // hi "))
True
>>> bool(get_cxx_close_block_regex(semicolon=True).match(" } "))
False
>>> bool(get_cxx_close_block_regex(semicolon=True).match(" } ; "))
True
>>> bool(get_cxx_close_block_regex(semicolon=True).match("};"))
True
>>> bool(get_cxx_close_block_regex(semicolon=True, comment="hi", at_line_start=True).match("}; // hi"))
True
>>> bool(get_cxx_close_block_regex(semicolon=True, comment="hi", at_line_start=True).match("}; // hi there"))
False
"""
semicolon_regex_str = r"\s*;" if semicolon else ""
line_start_regex_str = "" if at_line_start else r"\s*"
comment_regex_str = r"\s*//\s*{}".format(comment) if comment else ""
close_block_regex_str = re.compile(r"^{}}}{}{}\s*$".format(line_start_regex_str, semicolon_regex_str, comment_regex_str))
return re.compile(close_block_regex_str)
|
c62cd254aaa329358a33ba96fc8d23004c950d85
| 696,361 |
def encode_truncate(text, limit, encoding='utf8', return_encoded=True):
"""
Given a string, return a truncated version of the string such that
the UTF8 encoding of the string is smaller than the given limit.
This function correctly truncates even in the presence of Unicode code
points that encode to multi-byte encodings which must not be truncated
in the middle.
:param text: The (Unicode) string to truncate.
:type text: str
:param limit: The number of bytes to limit the UTF8 encoding to.
:type limit: int
:param encoding: Truncate the string in this encoding (default is ``utf-8``).
:type encoding: str
:param return_encoded: If ``True``, return the string encoded into bytes
according to the specified encoding, else return the string as a string.
:type return_encoded: bool
:returns: The truncated string.
:rtype: str or bytes
"""
assert(text is None or type(text) == str)
assert(type(limit) == int)
assert(limit >= 0)
if text is None:
return
# encode the given string in the specified encoding
s = text.encode(encoding)
# when the resulting byte string is longer than the given limit ..
if len(s) > limit:
# .. truncate, and
s = s[:limit]
# decode back, ignoring errors that result from truncation
# in the middle of multi-byte encodings
text = s.decode(encoding, 'ignore')
if return_encoded:
s = text.encode(encoding)
if return_encoded:
return s
else:
return text
|
e73bc332e16f932e609ff40299366e146947c430
| 696,366 |
def default_metric_cmp_fn(current_metric: float, prev_best: float) -> bool:
"""
The default function to compare metric values between current metric and previous best metric.
Args:
current_metric: metric value of current round computation.
prev_best: the best metric value of previous rounds to compare with.
"""
return current_metric > prev_best
|
e99b346e3196ba9987b490c220ef43817ab0ce1f
| 696,372 |
def find_idx_scalar(scalar, value):
"""
Retrieve indexes of the value in the nested list scalar.
The index of the sublist corresponds to a K value.
The index of the element corresponds to a kappa value.
Parameters:
scalar -- list, size 2^n x 2^n
value -- float
Return
indexes -- list of integer
"""
# Give sublist index and element index in scalar if element == value
indexes = [[sublist_idx, elem_idx] for sublist_idx,sublist in enumerate(scalar) for elem_idx, elem in enumerate(sublist) if elem==value]
return indexes
|
90032e41eb84084bf9f4b7e02c38ac950ade3f33
| 696,373 |
import struct
import socket
def int2ip(n):
"""Convert an long to IP string."""
packet_ip = struct.pack("!I", n)
return socket.inet_ntoa(packet_ip)
|
c35cc6a64b57f4879f9580c77abbb05686276824
| 696,374 |
from decimal import Decimal
from math import floor
def get_pow1000(num):
"""Determine exponent for which significand of a number is within the
range [1, 1000).
"""
# Based on algorithm from http://www.mail-archive.com/
# [email protected]/msg14433.html, accessed 2010/11/7
# by Jason Heeris 2009/11/18
dnum = Decimal(str(num))
if dnum == 0:
return 0
elif dnum < 0:
dnum = -dnum
return int(floor(dnum.log10() / 3))
|
f809994c5023196f7124a3f46bc494c4ba0f654a
| 696,376 |
def remove_spades(hand):
"""Returns a hand with the Spades removed."""
spadeless_hand = hand [:]
for card in hand:
if "Spades" in card:
spadeless_hand.remove(card)
return spadeless_hand
|
3b273ddd6c5011c6bb4a5a40ff0d2fc426b40dc5
| 696,378 |
def _quadratic_bezier(y_points, t):
"""
Makes a single quadratic Bezier curve weighted by y-values.
Parameters
----------
y_points : Container
A container of the three y-values that define the y-values of the
Bezier curve.
t : numpy.ndarray, shape (N,)
The array of values between 0 and 1 defining the Bezier curve.
Returns
-------
output : numpy.ndarray, shape (N,)
The Bezier curve for `t`, using the three points in `y_points` as weights
in order to shift the curve to match the desired y-values.
References
----------
https://pomax.github.io/bezierinfo (if the link is dead, the GitHub repo for the
website is https://github.com/Pomax/BezierInfo-2).
"""
one_minus_t = 1 - t
output = (
y_points[0] * one_minus_t**2 + y_points[1] * 2 * one_minus_t * t + y_points[2] * t**2
)
return output
|
7c5cf27ce2fadb0843039729dc0f01473dfa946c
| 696,382 |
import struct
def bytes_to_long(byte_stream):
"""Convert bytes to long"""
return struct.unpack(">Q", byte_stream)[0]
|
f5b7ec07b44b4c218a02c9cb9367e38fef311d30
| 696,383 |
def cast_tensor_type(tens, dtype):
"""
tens: pytorch tens
dtype: string, eg 'float', 'int', 'byte'
"""
if dtype is not None:
assert hasattr(tens, dtype)
return getattr(tens, dtype)()
else:
return tens
|
378154acebad9ff080090b6dfad803c03c9ea11b
| 696,384 |
def topo_param_string(p, exclude=['print_level', 'name'], sep=", "):
"""
Formats global parameters nicely for use in version control (for example).
"""
strings = ['%s=%s' % (name,val) for (name,val) in p.get_param_values()
if name not in exclude]
return sep.join(strings)
|
d05220ce36d8ba7a22d94a0daef164d74b4d4a87
| 696,385 |
def change_name_of_compressed_op(x: str):
"""
Splits op name and adds kernel:0 to it
:param x: Name of op
:return:
"""
return x.split('/')[0]+'/kernel'+':0'
|
6829a49458b6308e06f67021f561295f2b05bad2
| 696,386 |
def uprint(str):
"""Underlined <str> """
return "\033[4m{0}\033[0m".format(str)
|
80793e26ac44c4ae3b5724685a22aa4c0a79a89b
| 696,388 |
from typing import Dict
def merge_two_dicts(x: Dict, y: Dict) -> Dict:
"""
Given two dicts, merge them into a new dict as a shallow copy, e.g.
.. code-block:: python
z = merge_two_dicts(x, y)
If you can guarantee Python 3.5, then a simpler syntax is:
.. code-block:: python
z = {**x, **y}
See http://stackoverflow.com/questions/38987.
"""
z = x.copy()
z.update(y)
return z
|
6e4f45ffdb7e231f59b2fda1a3d0931cd1cc1a85
| 696,391 |
def wrap_code_block(message):
"""
Wrap a message in a discord code block
:param message: The message to wrap
:return: A message wrapped in a code block
"""
return "```\r\n{0}\r\n```".format(message)
|
48cf6f8c58a6260dbd68750c12339aa578302e4d
| 696,392 |
def isOverlap1D(box1, box2):
"""Check if two 1D boxes overlap.
Reference: https://stackoverflow.com/a/20925869/12646778
Arguments:
box1, box2: format: (xmin, xmax)
Returns:
res: bool, True for overlapping, False for not
"""
xmin1, xmax1 = box1
xmin2, xmax2 = box2
return xmax1 >= xmin2 and xmax2 >= xmin1
|
898331f7f0aced6a86b244e22ebb069423fee719
| 696,396 |
import unicodedata
def unc_to_url(unc: str, as_file: bool = False):
"""Convert UNC to file or smb URL."""
# normalize for the Alfred Workflow
unc = unicodedata.normalize("NFC", unc).strip() # pylint: disable=I1101
url = unc.replace("\\\\", "smb://").replace("\\", "/")
if as_file: # for Windows 10
url = url.replace("smb://", "file://")
url = url.replace(" ", "%20") # don't encode Umlauts
return url
|
ba8828707d2c0ff940ebaa17d95c1b73d1b43c6f
| 696,399 |
def determine_pos_neu_neg(compound):
"""
Based on the compound score, classify a sentiment into positive, negative, or neutral.
Arg:
compound: A numerical compound score.
Return:
A label in "positive", "negative", or "neutral".
"""
if compound >= 0.05:
return 'positive'
elif compound < 0.05 and compound > -0.05:
return 'neutral'
else:
return 'negative'
|
6c36913ed4399a8bede622a18c06b46a1fb94c0b
| 696,402 |
def starts(epsilon=0):
"""Returns a function that computes whether a temporal interval has the
same start time as another interval (+/- epsilon), and ends before it.
The output function expects two temporal intervals (dicts with keys 't1'
and 't2' for the start and end times, respectively). It returns ``True`` if
the first interval starts at the same time as the second interval (+/-
``epsilon``), and the first interval ends before the second interval.
Args:
epsilon: The maximum difference between the start time of the first
interval and the start time of the second interval.
Returns:
An output function that takes two temporal intervals and returns
``True`` if the first interval starts at the same time as the second
interval, and ends before the second interval ends.
"""
return lambda intrvl1, intrvl2: (abs(intrvl1['t1'] - intrvl2['t1']) <= epsilon
and intrvl1['t2'] < intrvl2['t2'])
|
c26d9d05dac253d010d4d689c80552eb81714929
| 696,404 |
def get_lon_lat_dims(dataarray):
"""
Get the name of lon and lat corresponding to an dataarray (based on the dimensions of the dataarray).
"""
# get correct grid
dims = dataarray.dims
lon_name = 'lon_rho'
lat_name = 'lat_rho'
for dim in dims:
if dim.startswith('eta') or dim.startswith('lon'):
lon_name = dim.replace('eta_', 'lon_')
if dim.startswith('xi') or dim.startswith('lat'):
lat_name = dim.replace('xi_', 'lat_')
assert lon_name.replace('lon_', '') == lat_name.replace('lat_', ''), 'Ey, lon_rho != lon_u altough eta_rho == eta_u'
return lon_name, lat_name
|
1716feffea50a1963de1425e537ab7f39e0da0a8
| 696,415 |
def rs_is_puiseux(p, x):
"""
Test if ``p`` is Puiseux series in ``x``.
Raise an exception if it has a negative power in ``x``.
Examples
========
>>> from sympy.polys.domains import QQ
>>> from sympy.polys.rings import ring
>>> from sympy.polys.ring_series import rs_is_puiseux
>>> R, x = ring('x', QQ)
>>> p = x**QQ(2,5) + x**QQ(2,3) + x
>>> rs_is_puiseux(p, x)
True
"""
index = p.ring.gens.index(x)
for k in p:
if k[index] != int(k[index]):
return True
if k[index] < 0:
raise ValueError('The series is not regular in %s' % x)
return False
|
a93ff5797d8e3b845099f9c8da2a5fd88c288ff6
| 696,417 |
def resultToString(result, white):
"""
The function returns if the game was won based on result and color of figures
Input:
result(str): result in format '1-0','1/2-1/2', '0-1'
white(bool): True if white, False if black
Output:
str: result of a game: 'won', 'lost', 'tie' or 'unknown'
"""
wonSet = {('1', True),
('0', False)}
tieSet = {('1/2', True),
('1/2', False)}
lostSet = {('1', False),
('0', True)}
if (result.split("-")[0], white) in wonSet:
return 'won'
elif (result.split("-")[0], white) in tieSet:
return 'tie'
elif (result.split("-")[0], white) in lostSet:
return 'lost'
else:
return 'unknown'
|
9294ca5fc67c9f33d263b977bd35847cef2f56cc
| 696,418 |
def check_uniprot(alias):
"""
Return True if the protein has UniProt identifier
"""
return len(alias) == 1 or alias.split(':')[0] == 'uniprotkb'
|
90fab83a02595ea5808ae8b9dcbec1993eb81404
| 696,422 |
def date_str(year, month, day, hour=0, minute=0, second=0., microsecond=None):
"""
Creates an ISO 8601 string.
"""
# Get microsecond if not provided
if microsecond is None:
if type(second) is float:
microsecond = int((second - int(second)) * 1000000)
else:
microsecond = 0
# Convert types
year = int(year)
month = int(month)
day = int(day)
hour = int(hour)
minute = int(minute)
second = int(second)
microsecond = int(microsecond)
# ISO 8601 template
tmp = '{year}-{month}-{day}T{hour}:{minute}:{second}.{microsecond}'
return tmp.format(year=year, month=month, day=day,
hour=hour, minute=minute, second=second, microsecond=microsecond)
|
a08bc5aee24f500ff3b4f18ba3bee6d808374136
| 696,429 |
def confirm_action(desc='Really execute?') -> bool:
"""
Return True if user confirms with 'Y' input
"""
inp = ''
while inp.lower() not in ['y', 'n']:
inp = input(desc + ' Y/N: ')
return inp == 'y'
|
4dd485e76e36c579b16c91d57edbde18ba52d3db
| 696,431 |
def remove(text, removeValue):
"""
Return a string where all remove value are removed from the text.
"""
return text.replace(removeValue, '')
|
cfc7f5f5ab212bea6e02423fd0fb1fc2947be7a2
| 696,434 |
def _tuple_replace(s, Lindices, Lreplace):
"""
Replace slices of a string with new substrings.
Given a list of slice tuples in C{Lindices}, replace each slice
in C{s} with the corresponding replacement substring from
C{Lreplace}.
Example:
>>> _tuple_replace('0123456789',[(4,5),(6,9)],['abc', 'def'])
'0123abc5def9'
"""
ans = []
Lindices = Lindices[:]
Lindices.sort()
if len(Lindices) != len(Lreplace):
raise ValueError('lists differ in length')
for i in range(len(Lindices) - 1):
if Lindices[i][1] > Lindices[i + 1][0]:
raise ValueError('tuples overlap')
if Lindices[i][1] < Lindices[i][0]:
raise ValueError('invalid tuple')
if min(Lindices[i][0], Lindices[i][1]) < 0 or \
max(Lindices[i][0], Lindices[i][1]) >= len(s):
raise ValueError('bad index')
j = 0
offset = 0
for i in range(len(Lindices)):
len1 = Lindices[i][1] - Lindices[i][0]
len2 = len(Lreplace[i])
ans.append(s[j:Lindices[i][0] + offset])
ans.append(Lreplace[i])
j = Lindices[i][1]
ans.append(s[j:])
return ''.join(ans)
|
2942023bac0ac81031f9c17ac421d13b872466d4
| 696,436 |
from datetime import datetime
def timestamp_seconds() -> str:
"""
Return a timestamp in 15-char string format: {YYYYMMDD}'T'{HHMMSS}
"""
now = str(datetime.now().isoformat(sep="T", timespec="seconds"))
ts: str = ""
for i in now:
if i not in (" ", "-", ":"):
ts += i
return ts
|
d4c03925949795e6f9993cc4a79cb088619e0527
| 696,439 |
def get_files_priorities(torrent_data):
"""Returns a dictionary with files priorities, where
filepaths are keys, and priority identifiers are values."""
files = {}
walk_counter = 0
for a_file in torrent_data['files']:
files[a_file['path']] = torrent_data['file_priorities'][walk_counter]
walk_counter += 1
return files
|
c142f73ef1087cee72bbca317e3ea07ebcc5bf8c
| 696,443 |
def _make_update_dict(update):
"""
Return course update item as a dictionary with required keys ('id', "date" and "content").
"""
return {
"id": update["id"],
"date": update["date"],
"content": update["content"],
}
|
f20efac269ad67b9f46f4994bf61e2397fb91d98
| 696,444 |
def is_resource(url):
"""
:param url: url to check;
:return: return boolean;
This function checks if a url is a downloadable resource. This is defined by the list of resources;
"""
if url:
resources = ['mod/resource', 'mod/assign', 'pluginfile']
for resource in resources:
if resource in url:
return True
|
39496ff5bb170746645d40d954a96c76b4c36a87
| 696,446 |
import re
def group_lines(lines, delimiter):
"""
Group a list of lines into sub-lists. The list is split at line matching the
`delimiter` pattern.
:param lines: Lines of string.
:parma delimiter: Regex matching the delimiting line pattern.
:returns: A list of lists.
"""
if not lines:
return []
lines_ = iter(lines)
delimiter_ = re.compile(delimiter)
result = []
result.append([next(lines_)])
for line in lines_:
if delimiter_.match(line):
result.append([])
result[-1].append(line)
return result
|
f77e643aa711b160dda97acf35c8be1cec7d703a
| 696,447 |
def _build_params(dt):
"""Takes a date and builds the parameters needed to scrape the dgm website.
:param dt: the `datetime` object
:returns: the `params` that contain the needed api information
"""
params = (('yr', dt.year),
('month', dt.month),
('dy', dt.day),
('cid', 'mc-0191cbfb6d82b4fdb92b8847a2046366'))
return params
|
477f763d81407f047ada9d4d16c0207ed0b5ad67
| 696,450 |
def _round_to_multiple_of(val: float, divisor: int, round_up_bias: float = 0.9) -> int:
""" Asymmetric rounding to make `val` divisible by `divisor`. With default
bias, will round up, unless the number is no more than 10% greater than the
smaller divisible value, i.e. (83, 8) -> 80, but (84, 8) -> 88. """
assert 0.0 < round_up_bias < 1.0
new_val = max(divisor, int(val + divisor / 2) // divisor * divisor)
return new_val if new_val >= round_up_bias * val else new_val + divisor
|
fdc644b8d4bd5d3fdf49c5d9892eaf67640fb61b
| 696,452 |
import random
def random_choice(array, probs=None):
"""
This function takes in an array of values to make a choice from,
and an pdf corresponding to those values. It returns a random choice
from that array, using the probs as weights.
"""
# If no pdf provided, assume uniform dist:
if probs == None:
index = int(random.random() * len(array))
return array[index]
# A common case, guaranteed to reach the Exit node;
# No need to sample for this:
if (set(probs[:-1]) == set([0.0])) and (probs[-1] == 1.0):
return array[-1]
# Sample a random value from using pdf
rdm_num = random.random()
i, p = 0, probs[0]
while rdm_num > p:
i += 1
p += probs[i]
return array[i]
|
2fc692773b50d7b940f72bf4deebede6ffd063f0
| 696,454 |
def parse_requirements(r):
"""Determine which characters are required and the number of them that
are required."""
req = {'d': 0, 'l': 0, 'u': 0, 's': 0}
for c in r:
if c == 'd':
req['d'] += 1
elif c == 'l':
req['l'] += 1
elif c == 'u':
req['u'] += 1
elif c == 's':
req['s'] += 1
else:
continue
return req
|
8c1f82a7136aec08471e672e4b676d725854f2d6
| 696,455 |
def peek(file, length=1):
"""Helper function for reading *length* bytes from *file* without advancing
the current position."""
pos = file.tell()
data = file.read(length)
file.seek(pos)
return data
|
fe901c4001320c9498b09a1d7caa6b4598a0386a
| 696,456 |
def sub_account_universal_transfer_history(self, **kwargs):
"""Query Universal Transfer History (For Master Account)
GET /sapi/v1/sub-account/universalTransfer
https://binance-docs.github.io/apidocs/spot/en/#query-universal-transfer-history-for-master-account
fromEmail and toEmail cannot be sent at the same time.
Return fromEmail equal master account email by default.
Only get the latest history of past 30 days.
Keyword Args:
fromEmail (str, optional)
toEmail (str, optional)
startTime (int, optional)
endTime (int, optional)
page (int, optional)
limit (int, optional): Default 10, max 20
recvWindow (int, optional): The value cannot be greater than 60000
"""
return self.limited_encoded_sign_request(
"GET", "/sapi/v1/sub-account/universalTransfer", kwargs
)
|
c552c4eeea8be9eeb0a662cbaa546085d7c5999a
| 696,457 |
def replace_del_alt(var):
"""
Issues occur with deletions hear the ends of the genome.
Currently - is used to represent an entire string of bases
being deleted. Here we replace the ALT with "N" the length
of REF.
"""
ref_length = len(var.REF)
if var.ALT[0] == '-':
fixed_alt = 'N' * ref_length
var.ALT[0] = fixed_alt
return var
else:
return var
|
f3d081a8dd12b8ca81bd8d5a8aca6bf6dbccc839
| 696,459 |
def pad(value: int, length: int = 2) -> str:
"""
Adds leading and trailing zeros to value ("pads" the value).
>>> pad(5)
05
>>> pad(9, 3)
009
:param value: integer value to pad
:param length: Length to pad to
:return: string of padded value"""
return "{0:0>{width}}".format(value, width=length)
|
0ac5c5cebf3cc97f25d0e21fdef9c45f06ce635d
| 696,463 |
from typing import List
import csv
def create_list_of_selected_jc() -> List:
"""
Return the "SelectedJournalsAndConferences.csv" as a list
"""
selected_jc = []
with open("SelectedJournalsAndConferences.csv", mode="r") as csv_file:
csv_reader = csv.DictReader(csv_file)
for row in csv_reader:
selected_jc.append(row["Name"])
selected_jc.pop(0)
return selected_jc
|
abe0f023ba77a4c8d22d6132ee029b104ceb8466
| 696,467 |
def lower_first_letter(sentence):
"""Lowercase the first letter of a sentence."""
return sentence[:1].lower() + sentence[1:] if sentence else ""
|
de0f79548d42983093f65970464ca84eed032300
| 696,468 |
def prefix_hash(s, p, P=53):
"""
Compute hashes for every prefix. Only [a-zA-Z] symbols are supported
Parameters
-------------
s : str
input string
p : List[int]
all powers of P. p[i] = P ** i
Returns
----------
h : List[int]
h[i] = hash(s[:i + 1])
"""
h = [0] * len(s)
p_ = len(p)
s_ = len(s) - len(p)
# increase p buf if needed
if s_ > 0:
p.extend([1] * s_)
if p_ == 0:
p_ += 1 # p**0 = 1
for i in range(p_, s_):
# p[-1] = 1
p[i] = p[i - 1] * P
for i, c in enumerate(s):
if c.islower():
code = ord(c) - ord("a")
else:
code = ord(c) - ord("A")
h[i] = h[i - 1] + (code + 1) * p[i]
return h
|
c9d7d4054c580257fab9336fa7881af3c9c074f4
| 696,469 |
def _IsPositional(arg):
"""Returns True if arg is a positional or group that contains a positional."""
if arg.is_hidden:
return False
if arg.is_positional:
return True
if arg.is_group:
for a in arg.arguments:
if _IsPositional(a):
return True
return False
|
34147b29533ba9a535ba363c264625222763fb72
| 696,471 |
def is_potential(obj):
"""Identifies if an object is a potential-form or potential-function"""
return hasattr(obj, "is_potential") and obj.is_potential
|
e84ad5fb59b8a6575eab6821e1b4bcedc1ddb0ab
| 696,474 |
def get_default_value(key):
""" Gives default values according to the given key """
default_values = {
"coordinates": 2,
"obabel_path": "obabel",
"obminimize_path": "obminimize",
"criteria": 1e-6,
"method": "cg",
"hydrogens": False,
"steps": 2500,
"cutoff": False,
"rvdw": 6.0,
"rele": 10.0,
"frequency": 10
}
return default_values[key]
|
89a12cbb20499a85fc7c6c092fc2ee90aff31ae3
| 696,475 |
def find_longest_common_substring(x: str, y: str) -> str:
"""
Finds the longest common substring between the given two strings in a
bottom-up way.
:param x: str
:param y: str
:return: str
"""
# Check whether the input strings are None or empty
if not x or not y:
return ''
m, n = len(x), len(y)
# Initialization
subproblems = [[0] * (n + 1) for i in range(m + 1)]
# Bottom-up calculation
for i in range(1, m + 1):
for j in range(1, n + 1):
x_curr, y_curr = x[i - 1], y[j - 1]
if x_curr == y_curr:
subproblems[i][j] = subproblems[i - 1][j - 1] + 1
# Find the maximum of the longest common suffix of possible prefixes, which
# is exactly the longest common substring
i_max, max_length = 0, subproblems[0][0]
for i in range(m + 1):
for j in range(n + 1):
if subproblems[i][j] > max_length:
i_max = i
max_length = subproblems[i][j]
return x[i_max - max_length:i_max]
# Overall running time complexity: O(mn)
|
878f41ead963a8171ec7d07509a8dae5aef7fb4b
| 696,476 |
def model_includes_pretrained(model):
"""
Checks if a model-class includes the methods to load pretrained models.
Arguments:
model Model-class to check.
Returns:
True if it includes the functionality.
"""
return hasattr(model, "has_pretrained_state_dict") and hasattr(
model, "get_pretrained_state_dict"
)
|
f19460c4a0ce731d4642ad7092f80910605278a8
| 696,478 |
def _get_other_dims(ds, dim):
"""Return all dimensions other than the given dimension."""
all_dims = list(ds.dims)
return [d for d in all_dims if d != dim]
|
4c8fc614442cbf4ee1a22aa8113532dcd2905e3c
| 696,479 |
def stag_pressure_ratio(M, gamma):
"""Stagnation pressure / static pressure ratio.
Arguments:
M (scalar): Mach number [units: dimensionless].
gamma (scalar): Heat capacity ratio [units: dimensionless].
Returns:
scalar: the stagnation pressure ratio :math:`p_0 / p` [units: dimensionless].
"""
return (1 + (gamma - 1) / 2 * M**2)**(gamma / (gamma - 1))
|
351b14716077386eadea04a4717ea9afec8fdcaf
| 696,481 |
import torch
def shift_v(im, shift_amount):
"""Shift the image vertically by shift_amount pixels,
use positive number to shift the image down,
use negative numbers to shift the image up"""
im = torch.tensor(im)
if shift_amount == 0:
return im
else:
if len(im.shape) == 3: # for a single image
new_image = torch.zeros_like(im)
new_image[:, :shift_amount, :] = im[:,-shift_amount:,:]
new_image[:,shift_amount:,:] = im[:,:-shift_amount,:]
return new_image
elif len(im.shape) == 4: # for batches of images
new_image = torch.zeros_like(im)
new_image[:, :, :shift_amount, :] = im[:, :, -shift_amount:, :]
new_image[:, :, shift_amount:, :] = im[:, :, :-shift_amount, :]
return new_image
|
cbd0eab7b3a0a64e7402e5eb14d0464ab7ba9ac5
| 696,484 |
def getPath(parent_map, start, goal):
"""
Definition
---
Method to generate path using backtracking
Parameters
---
parent_map : dict of nodes mapped to parent node_cost
start : starting node
goal : goal node
Returns
---
path: list of all the points from starting to goal position
"""
curr_node = goal
parent_node = parent_map[goal]
path = [curr_node]
while not parent_node == start:
curr_node = parent_node
parent_node = parent_map[curr_node]
path.append(curr_node)
path.append(start)
return path[::-1]
|
8a23ab5462b064744973f75c294e0814099961c7
| 696,489 |
from typing import List
def input_assert(message: str, choices: List[str]) -> str:
"""
Adds functionality to the python function `input` to limit the choices that can be returned
Args:
message: message to user
choices: list containing possible choices that can be returned
Returns:
input returned by user
"""
output = input(message).lower()
if output not in choices:
print(f"Wrong input! Your input should be one of the following: {', '.join(choices)}")
return input_assert(message, choices)
else:
return output
|
062b88356a977cdd119f7ee0c54b7e6a611f76f2
| 696,491 |
def rate(hit, num):
"""Return the fraction of `hit`/`num`."""
return hit / (num or 1.0)
|
b055fa6995f85ab223747dd369a464644046f7d7
| 696,493 |
def get_function_handle(method, var):
"""
Return a function handle to a given calculation method.
Parameters
----------
method : str
Identifier of the calculation method to return a handle to.
var : dict
Local variables needed in the threshold method.
Returns
-------
f_handle : function
Handle to calculation `method` defined in this globals scope.
"""
return globals()['wrap_calculate_using_' + method](var)
|
1e8dacfeaaa32a93fbfaad8507c976c4f2e126fb
| 696,496 |
def is_iterable(var):
""" Return True if the given is list or tuple.
"""
return (isinstance(var, (list, tuple)) or
issubclass(var.__class__, (list, tuple)))
|
f4c1d60d2e62688aedb776fb90d90049d93ad5e2
| 696,498 |
def relperm_parts_in_model(model,
phase_combo = None,
low_sal = None,
table_index = None,
title = None,
related_uuid = None):
"""Returns list of part names within model that are representing RelPerm dataframe support objects.
arguments:
model (model.Model): the model to be inspected for dataframes
phase_combo (str, optional): the combination of phases whose relative permeability behaviour is described.
Options include 'water-oil', 'gas-oil', 'gas-water', 'oil-water', 'oil-gas' and 'water-gas'
low_sal (boolean, optional): if True, indicates that the water-oil table contains the low-salinity data for
relative permeability and capillary pressure
table_index (int, optional): the index of the relative permeability table when multiple relative permeability
tables are present. Note, indices should start at 1.
title (str, optional): if present, only parts with a citation title exactly matching will be included
related_uuid (uuid, optional): if present, only parts relating to this uuid are included
returns:
list of str, each element in the list is a part name, within model, which is representing the support for a RelPerm object
"""
extra_metadata_orig = {
'relperm_table': 'true',
'phase_combo': phase_combo,
'low_sal': low_sal,
'table_index': table_index
}
extra_metadata = {k: str(v).lower() for k, v in extra_metadata_orig.items() if v is not None}
df_parts_list = model.parts(obj_type = 'Grid2dRepresentation',
title = title,
extra = extra_metadata,
related_uuid = related_uuid)
return df_parts_list
|
7d4d5d8ac7a2c763f3a0fe2589d6ff0713d0125b
| 696,503 |
def tagged_members(obj, meta=None, meta_value=None):
""" Utility function to retrieve tagged members from an object
Parameters
----------
obj : Atom
Object from which the tagged members should be retrieved.
meta : str, optional
The tag to look for, only member which has this tag will be returned
meta_value : optional
The value of the metadata used for filtering the members returned
Returns
-------
tagged_members : dict(str, Member)
Dictionary of the members whose metadatas corresponds to the predicate
"""
members = obj.members()
if meta is None and meta_value is None:
return members
elif meta_value is None:
return {key: member for key, member in members.items()
if member.metadata is not None and meta in member.metadata}
else:
return {key: member for key, member in members.items()
if member.metadata is not None and
meta in member.metadata and
member.metadata[meta] == meta_value}
|
7b1077e774a98bd59b6cb9a59c9745fbfa0b4168
| 696,506 |
def remove_irrelevant_labels(labels):
"""
Filters an array of labels, removing non "CAT" labels
:param labels: array of labels
:return: an array of labels containing only the top-level "CAT" labels
"""
filtered = filter(lambda x: "CAT" in x.upper(), labels)
return list(filtered)
|
bedeaa6b2dd1adfcef2eb7f1d4c7b34d9e7254f8
| 696,515 |
def lookup_ec2_to_cluster(session):
"""
Takes a session argument and will return a map of instanceid to clusterarn
:param session: boto 3 session for the account to query
:return: map of ec2 instance id to cluster arn
"""
ecs = session.client('ecs')
result = dict()
for cluster in ecs.list_clusters()['clusterArns']:
instances = ecs.list_container_instances(
cluster=cluster)['containerInstanceArns']
if instances:
ec2_to_cluster = [
(x['ec2InstanceId'], cluster)
for x in ecs.describe_container_instances(
cluster=cluster, containerInstances=instances)['containerInstances']
]
result.update(ec2_to_cluster)
return result
|
0b148264397e5e598675dfdcd6ac4528888ce107
| 696,517 |
def padded_hex(num, n=2):
"""
Convert a number to a #xx hex string (zero padded to n digits)
"""
return ("%x" % num).zfill(n)
|
2a9e401a824cdb856d29591ae282bdbbc64b79e5
| 696,522 |
import tkinter
def gui_input(prompt1, prompt2):
"""
Creates a window to collect Risk and Budget info from user
Parameters
----------
prompt1 : String
First question in input prompt
prompt2 : String
Second question in input prompt
Returns
-------
value1 : String
Value of response to the question asked in prompt1
value2 : String
Value of response to the question asked in prompt2
"""
# create tkinterwindow and set title and geometry of window
_root = tkinter.Tk()
_root.title('Wolves of DK St - Options Strategy Visualization')
_root.geometry("+600+400")
# Set text for input screen
tkinter.Label(_root, text='Welcome to the Options Strategy Visualization').grid(row=1, column=1, columnspan=2)
tkinter.Label(_root, text='Enter your desired probability of profit:').grid(row=3, column=1, columnspan=2)
tkinter.Label(_root, text=' ').grid(row=2, column=1, columnspan=2)
tkinter.Label(_root, text='0.1 = 10% chance of profit (Throw your money away)').grid(row=4, column=1, columnspan=2)
tkinter.Label(_root, text='0.5 = 50% chance of profit (gambling)').grid(row=5, column=1, columnspan=2)
tkinter.Label(_root, text='0.9 = 90% chance of profit (high chance for profit)').grid(row=6, column=1, columnspan=2)
tkinter.Label(_root, text=' ').grid(row=8, column=1, columnspan=2)
tkinter.Label(_root, text='Enter your desired budget (number, min $2000)').grid(row=9, column=1, columnspan=2)
tkinter.Label(_root, text='Please enter only numeric digits, no characters').grid(row=10, column=1, columnspan=2)
tkinter.Label(_root, text=' ').grid(row=13, column=1, columnspan=2)
# set prompt and input text; setup input collection to be saved to var1 and var2
var1 = tkinter.StringVar()
var2 = tkinter.StringVar()
label1 = tkinter.Label(_root, text=prompt1)
entry1 = tkinter.Entry(_root, textvariable=var1)
label1.grid(row=7, column=1)
entry1.grid(row=7, column=2)
label2 = tkinter.Label(_root, text=prompt2)
entry2 = tkinter.Entry(_root, textvariable=var2)
label2.grid(row=12, column=1)
entry2.grid(row=12, column=2)
# create an "Enter" button to conclude data collection and exit GUI
go = tkinter.Button(_root, text='Enter')#, command=store_data)
go.grid(row=14, column=1, columnspan=2)
go.bind("<Button-1>", lambda event: _root.destroy())
# this will block main method from advancing until the window is destroyed
_root.mainloop()
# after the window has been destroyed, we can't access
# the entry widget, but we _can_ access the associated
# variable
value1 = var1.get()
value2 = var2.get()
return value1, value2
|
1c770c56aba7ca7a793561ac2063aa7dae41b15e
| 696,527 |
def _remove_doc_types(dict_):
"""
Removes "doc_type" keys from values in `dict_`
"""
result = {}
for key, value in dict_.items():
value = value.copy()
value.pop('doc_type', None)
result[key] = value
return result
|
e5badc0a73edba3233816d4c99fa7f26845c77f5
| 696,528 |
def create_slices(start, stop, step=None, length=1):
""" Generate slices of time indexes
Parameters
----------
start : int
Index where first slice should start.
stop : int
Index where last slice should maximally end.
length : int
Number of time sample included in a given slice.
step: int | None
Number of time samples separating two slices.
If step = None, step = length.
Returns
-------
slices : list
List of slice objects.
"""
# default parameters
if step is None:
step = length
# slicing
slices = [slice(t, t + length, 1) for t in
range(start, stop - length + 1, step)]
return slices
|
c45979e18db9d3f554ae7d194ca001bc3976fa83
| 696,532 |
def wootric_url(route):
"""helper to build a full wootric API route, handling leading '/'
>>> wootric_url('v1/responses')
''https://api.wootric.com/v1/responses'
>>> wootric_url('/v1/responses')
''https://api.wootric.com/v1/responses'
"""
route = route.lstrip('/')
return f'https://api.wootric.com/{route}'
|
f48ebe6ac7fe05798230c5bc27681adcb03804ef
| 696,534 |
def check_xml(root):
"""Check xml file root, since jarvis4se version 1.3 it's <systemAnalysis>"""
if root.tag == "systemAnalysis":
return True
else:
return False
|
d2921e2b5784a26a7636b65f6d3fbcf1425f8448
| 696,542 |
def get_rotation(transform):
"""Gets rotation part of transform
:param transform: A minimum 3x3 matrix
"""
assert transform.shape[0] >= 3 \
and transform.shape[1] >= 3, \
"Not a transform? Shape: %s" % \
transform.shape.__repr__()
assert len(transform.shape) == 2, \
"Assumed 2D matrices: %s" % \
transform.shape.__repr__()
return transform[:3, :3]
|
c8fa40d883c3b8cbc7fe24ee38fe35cb6813f491
| 696,543 |
def check(s, ans):
"""
This is a predicate function to check whether a string is in a given answer.
:param s: str, the one need to be checked.
:param ans: str, the given answer.
:return: bool,
"""
if s in ans:
return True
return False
|
86af3d89634858f4839fc486580e95f1ba04b6a3
| 696,544 |
import struct
def _as_float(value):
"""
Truncate to single-precision float.
"""
return struct.unpack('f', struct.pack('f', value))[0]
|
7bf9b2e4d61b7a91f6c8334f0e7f093d55c6d614
| 696,545 |
from pathlib import Path
def ExistFile(path):
"""Check whether a file exists.
Args:
path: The path.
Returns:
bool: True if the file exists otherwise False.
"""
return Path(path).is_file()
|
b71856d8b8ffde2c768a4a4e16bc9303d9a92251
| 696,547 |
def generate_traits_list(traits: dict) -> list:
"""Returns a list of trait values
Arguments:
traits: a dict containing the current trait data
Return:
A list of trait data
"""
# compose the summary traits
trait_list = [traits['local_datetime'],
traits['canopy_height'],
traits['access_level'],
traits['species'],
traits['site'],
traits['citation_author'],
traits['citation_year'],
traits['citation_title'],
traits['method']
]
return trait_list
|
995c66208d3306958811420ba8ebb1bcd7a11ccf
| 696,548 |
from typing import List
def create_fhir_bundle(
resources: List[dict], bundle_type: str = "transaction"
) -> dict:
"""Creates a FHIR bundle from a list of FHIR resources
Parameters
----------
resources : List[dict]
List of FHIR resources
bundle_type : str, optional
FHIR Bundle type
https://www.hl7.org/fhir/bundle-definitions.html#Bundle.type,
by default "transaction"
Returns
-------
dict
FHIR Bundle
"""
return {
"resourceType": "Bundle",
"type": bundle_type,
"entry": [
{
"resource": resource,
"request": {"method": "POST", "url": resource["resourceType"]},
}
for resource in resources
],
}
|
70f94829b2e366eea97fd31245eb77e69aaaf066
| 696,549 |
def patch_cmass_output(lst, index=0):
"""
Parameters
----------
lst : list of tuples
output of afni.CenterMass()
index : int
index in the list of tuples
Returns
-------
tuple
one set of center of mass coordinates
"""
if len(lst) <= index:
raise IndexError("lst index out of range")
return lst[index]
|
98b637a6a922bdbbb84b99f78a47de1519443192
| 696,550 |
def replace_version(content, from_version, to_version):
"""
Replaces the value of the version specification value in the contents of
``contents`` from ``from_version`` to ``to_version``.
:param content: The string containing version specification
:param to_version: The new version to be set
:return: (result_content, number of occurrences)
"""
frm_str = str(from_version)
to_str = str(to_version)
count = content.count(frm_str)
result_setup_py = content.replace(frm_str, to_str, count)
return result_setup_py, count
|
dd792b6674c21dc6e11ef8013d88b9c210f9604f
| 696,553 |
def generate_train_config(model_spec, train_batch_spec, val_batch_spec, epoch_size,
n_epochs=100, lr=0.001):
""" Generates a spec fully specifying a run of the experiment
Args:
model_spec: a model spec
train_batch_spec: a batch spec for train
val_batch_spec: batch spec for validation
epoch_size: int
n_epochs: int
lr: learning rate - float
Returns:
train_spec
"""
train_spec = {
'model_spec': model_spec,
'train_batch_spec': train_batch_spec,
'val_batch_spec': val_batch_spec,
'train_spec': {
'epoch_size': epoch_size,
'n_epochs': n_epochs,
'lr': lr
}
}
return train_spec
|
0e19dab0263eda8505ddb830fd255b2a760d822c
| 696,554 |
def strip_path_prefix(ipath, prefix):
"""
Strip prefix from path.
Args:
ipath: input path
prefix: the prefix to remove, if it is found in :ipath:
Examples:
>>> strip_path_prefix("/foo/bar", "/bar")
'/foo/bar'
>>> strip_path_prefix("/foo/bar", "/")
'foo/bar'
>>> strip_path_prefix("/foo/bar", "/foo")
'/bar'
>>> strip_path_prefix("/foo/bar", "None")
'/foo/bar'
"""
if prefix is None:
return ipath
return ipath[len(prefix):] if ipath.startswith(prefix) else ipath
|
c9634c9b06466c7af07a39c97645f0c601fe3ce2
| 696,560 |
def link_header( header, link_delimiter=',', param_delimiter=';' ):
"""
Parsea en dicionario la respusta de las cabezera ``link``
Parameters
----------
header: string
contenido de la cabezera ``link``
link_delimiter: Optional[str]
caracter que separa los enlaces
param_delimiter: Optional[str]
caracter que separa el parametro ``rel`` del link
Returns
-------
dict
Note
----
enlace a la especificacion del header
`link header <https://tools.ietf.org/html/rfc5988>`_
"""
result = {}
links = header.split( link_delimiter )
for link in links:
segments = link.split( param_delimiter )
if len( segments ) < 2:
continue
link_part = segments[0].strip()
rel_part = segments[1].strip().split( '=' )[1][1:-1]
if not link_part.startswith( '<' ) and not link_part.endswith( '>' ):
continue
link_part = link_part[1:-1]
result[rel_part] = link_part
return result
|
eceab56c0c00fccb9860e85d1e4aa383fcdc5d30
| 696,561 |
import typing
import asyncio
async def process_concurrent(objs: typing.List[typing.Any], process: typing.Callable[[typing.Any], typing.Awaitable], workers: int = 5):
"""
Run a processing coroutine on a list of objects with multiple concurrent workers.
"""
# Divide and round up
step = (len(objs) - 1) // workers + 1
async def _proc_range(start, end):
for i in range(start, end):
await process(objs[i])
return asyncio.gather(*(_proc_range(i * step, min((i + 1) * step, len(objs))) for i in range(workers)))
|
74e983b7cf7480d14c51304b7cc6daaac75ea837
| 696,563 |
def prop_all(printer, ast):
"""Prints an all property "A ..."."""
prop_str = printer.ast_to_string(ast["prop"])
return f'A{prop_str}'
|
0a03f04d955251918a1ea7dcf3576f30cb790656
| 696,568 |
def yesno(val, yes='yes', no='no'):
"""
Return ``yes`` or ``no`` depending on value. This function takes the value
and returns either yes or no depending on whether the value evaluates to
``True``.
Examples::
>>> yesno(True)
'yes'
>>> yesno(False)
'no'
>>> yesno(True, 'available', 'not available')
'available'
"""
return yes if val else no
|
cfdbe3ffb53ed0239e39392873ab128506379107
| 696,571 |
from typing import Sequence
from typing import List
def list_insert_list(l:Sequence, to_insert:Sequence, index:int) -> List:
""" Insert `to_insert` into a shallow copy of `l` at position `index`.
This function is adapted from: http://stackoverflow.com/questions/7376019/
Parameters
----------
l : typing.Sequence
An iterable
to_insert : typing.Sequence
The items to insert
index : int
The location to begin the insertion
Returns
-------
updated_l : typing.List
A list with `to_insert` inserted into `l` at position `index`
"""
ret = list(l)
ret[index:index] = list(to_insert)
return ret
|
2f332cc70f64a740c7dd26867978121f4b68acb7
| 696,573 |
def ordered_sample(population, sample_size):
"""
Samples the population, taking the first `n` items (a.k.a `sample_size') encountered. If more samples are
requested than are available then only yield the first `sample_size` items
:param population: An iterator of items to sample
:param sample_size: The number of items to retrieve from the population
:return: A list of the first `sample_size` items from the population
"""
empty = True
results = []
for i, item in enumerate(population):
empty = False
if i >= sample_size:
break
results.append(item)
if empty:
raise ValueError('Population is empty')
return results
|
0aba56350b6acf44098ea247abb979c35df947e8
| 696,575 |
from pathlib import Path
def basename(var, orig = False):
"""Get the basename of a path"""
bname = Path(var).name
if orig or not bname.startswith('['):
return bname
return bname[bname.find(']')+1:]
|
16d8365d5be084eaa45921fc633e552e3224847b
| 696,576 |
def sort_table(i):
"""
Input: {
table - experiment table
sort_index - if !='', sort by this number within vector (i.e. 0 - X, 1 - Y, etc)
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
table - updated experient table
}
"""
table=i['table']
si=i['sort_index']
isi=int(si)
for sg in table:
x=table[sg]
y=sorted(x, key=lambda var: 0 if var[isi] is None else var[isi])
table[sg]=y
return {'return':0, 'table':table}
|
5f33731cf8bcc6ea34d2c62cdf0ba20dd97b9aa6
| 696,581 |
def len_(string):
""":yaql:len
Returns size of the string.
:signature: string.len()
:receiverArg string: input string
:argType string: string
:returnType: integer
.. code::
yaql> "abc".len()
3
"""
return len(string)
|
a73a32c80c1016e3ca2735d56aeec1f98aa83767
| 696,583 |
def _is_clustal_seq_line(line):
"""Returns True if line starts with a non-blank character but not 'CLUSTAL'
Useful for filtering other lines out of the file.
"""
return line and (not line[0].isspace()) and\
(not line.startswith('CLUSTAL')) and (not line.startswith('MUSCLE'))
|
78c9067fa02254409d33fdb9f243c74d549138ce
| 696,588 |
import random
import colorsys
def lincolor(num_colors, saturation=1, value=1, normalized=False):
"""Creates a list of RGB colors linearly sampled from HSV space with
randomised Saturation and Value
# Arguments
num_colors: Integer.
saturation: Float or `None`. If float indicates saturation.
If `None` it samples a random value.
value: Float or `None`. If float indicates value.
If `None` it samples a random value.
# Returns
List, for which each element contains a list with RGB color
# References
[Original implementation](https://github.com/jutanke/cselect)
"""
RGB_colors = []
hues = [value / num_colors for value in range(0, num_colors)]
for hue in hues:
if saturation is None:
saturation = random.uniform(0.6, 1)
if value is None:
value = random.uniform(0.5, 1)
RGB_color = colorsys.hsv_to_rgb(hue, saturation, value)
if not normalized:
RGB_color = [int(color * 255) for color in RGB_color]
RGB_colors.append(RGB_color)
return RGB_colors
|
6540aba364ae13d9cf1d51169674b119f0d3ff82
| 696,589 |
def get_surrounding(field, row, col, value):
"""Finds how many mines are in surrounding squares of a certain coordinate"""
count = 0
# checks surrounding squares
for i in range(row - 1, row + 2):
for k in range(col - 1, col + 2):
# checks if the current coordinate is on the field and is the value
if 0 <= i < field.shape[0] and 0 <= k < field.shape[1] and field[i, k] == value:
count += 1
return count
|
5ad8e11e7062ee7d44975b119b69f28937e4083a
| 696,590 |
import math
def water_saturation_vapour_pressure_iapws(t):
"""Returns the water vapour pressure according to W. Wagner and A. Pruss (1992) J. Phys. Chem. Reference Data, 22,
783–787.
See http://www.kayelaby.npl.co.uk/chemistry/3_4/3_4_2.html
Valid only above the triple point. The IAWPS formulation 1995 (Wagner and Pruß, 2002) is valid in the temperature
range 273.16 K < T < 647.096 K. See http://cires1.colorado.edu/~voemel/vp.html
:param t: water temperature (°C)
:return: water vapour pressure in Pascal (Pa)
"""
tc = 647.096 # K
pc = 22064000 # Pa
a1 = -7.85951783
a2 = 1.84408259
a3 = -11.7866497
a4 = 22.6807411
a5 = -15.9618719
a6 = 1.80122502
t += 273.15
tau = 1 - t/tc
return pc * math.exp((a1 * tau + a2 * tau**1.5 + a3 * tau**3 + a4 * tau**3.5 + a5 * tau**4 + a6 * tau**7.5) * tc / t)
|
aa424bc63b3165bc439dacbf8748f478654a15b2
| 696,592 |
def cleanPath(path):
"""
Cleans up raw path of pdf to just the name of the PDF (no extension or directories)
:path: path to pdf
:returns: The PDF name with all directory/extensions stripped
"""
filename = path.split("/")[-1]
filename = filename.split(".")[0]
return filename
|
0cafdf13cbdc784abaedb49b9b757054c3ff25f6
| 696,595 |
from typing import Union
def get_first_line(o, default_val: str) -> Union[str, None]:
"""
Get first line for a pydoc string
:param o: object which is documented (class or function)
:param default_val: value to return if there is no documentation
:return: the first line which is not whitespace
"""
doc: Union[str, None] = o.__doc__
if doc is None:
return default_val
lines = doc.split("\n")
for line in lines:
if line == "" or line.isspace():
continue
return line.strip()
return default_val
|
c7003dc1cc5e22ea08c35485e593fd539597637d
| 696,598 |
def capStrLen(string, length):
"""
Truncates a string to a certain length.
Adds '...' if it's too long.
Parameters
----------
string : str
The string to cap at length l.
length : int
The maximum length of the string s.
"""
if length <= 2:
raise Exception("l must be at least 3 in utils.capStrLen")
if len(string) <= length:
return string
return string[0 : length - 3] + "..."
|
a7b2e264d867d3f5263d7037fb91220128437021
| 696,599 |
def get_line_indentation_spacecount(line: str) -> int:
""" How many spaces is the provided line indented? """
spaces: int = 0
if (len(line) > 0):
if (line[0] == ' '):
for letter_idx in range(len(line)):
if (line[letter_idx + 1] != ' '):
spaces = letter_idx + 1
break
return spaces
|
b70c65431fada6367a12c1d38f0420bcd66f1d8a
| 696,605 |
def _is_possible_expansion(acro: str, full: str) -> bool:
"""
Check whether all acronym characters are present in the full form.
:param acro:
:param full:
:return:
"""
# Empty acronym is presented everywhere
if not acro:
return True
# Non-empty acronym is not presented in empty full form
if not full:
return False
# First char must be the same
if acro[0].lower() != full[0].lower():
return False
j = 0
# We then skip the first char, as it has already been checked
for i in range(1, len(acro)):
j += 1
while j < len(full):
if acro[i].lower() == full[j].lower():
break
j += 1
if j < len(full):
return True
return False
|
e76cace8592c99d4e5e965bcbf8cba17c7114ee1
| 696,609 |
def from_context(cm):
"""Extract the value produced by a context manager"""
with cm as x:
return x
|
2d0be1d9d8c66487898e7f2d0f6649b952289468
| 696,614 |
def flatten(arr):
"""Flatten array."""
return [item for sublist in arr for item in sublist]
|
16555e7d4c04a0c6ffec03fb4005ddf534a474df
| 696,617 |
def get_prefix_from_proxy_group(proxy_group):
"""
Return prefix by analyzing proxy_group name
Args:
proxy_group (str): proxy group name
Returns:
str: prefix if exists, empty string if not
"""
split_name = proxy_group.split("@")[0].split("-")
# if there's only two sections, there's no prefix
if len(split_name) <= 2:
return ""
return proxy_group.split("@")[0].split("-")[-3].strip()
|
04433d97dcecc4edd7288e1373d4d6bce5e07ee4
| 696,620 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.