content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
def split_string(string):
"""
Convert a string of names separated by commas and “and” to a list.
A string of the structure "Name1, Name2 and Name3" is converted to
a list where each item corresponds to a name.
"""
return(string.split(',')[:-1] + string.split(',')[-1].split('and'))
|
529e59fc80b6b66fd91afab74795095c019db53d
| 467,361 |
def bedroom_count(sfmain, site):
""" (float, float) -> int
Return 3, 2, or 1 indicating the number of bedrooms a backyard house could have
based on the size of the lot (site), and the size of the main house (sfmain).
The area of the main structure plus the backyard house should be less than
the size of the site. The typical backyard house area for a 3 br
is 1200 sf, 2 br is 700 sf, 1 br is 400 sf.
>>> bedroom_count(2400,7200)
3
>>> bedroom_count(700, 5000)
0
"""
if sfmain >= 2400 and (sfmain + 1200)*2 <= site:
br = 3
return br
elif sfmain >= 1400 and (sfmain + 700)*2 <= site:
br = 2
return br
elif sfmain >= 800 and (sfmain + 400)*2 <= site:
br = 1
return br
else:
br = 0
return br
|
61f793ca0be3a60e70486fe75a6e99b7759e5110
| 551,122 |
def varchar(anon, obj, field, val):
"""
Returns random data for a varchar field.
"""
return anon.faker.varchar(field=field)
|
1cd56a9748c678c8b5ac988a04ace56a7aff2ba8
| 462,276 |
def point_in_triangle(all_points, triangle):
"""Returns True if the point is inside the triangle
and returns False if it falls outside.
- The argument *point* is a tuple with two elements
containing the X,Y coordinates respectively.
- The argument *triangle* is a tuple with three elements each
element consisting of a tuple of X,Y coordinates.
It works like this:
Walk clockwise or counterclockwise around the triangle
and project the point onto the segment we are crossing
by using the dot product.
Finally, check that the vector created is on the same side
for each of the triangle's segments.
"""
# Unpack arguments
# x, y = point
x, y = all_points[:, 0], all_points[:, 1]
ax, ay = triangle[0]
bx, by = triangle[1]
cx, cy = triangle[2]
# Segment A to B
side_1 = (x - bx) * (ay - by) - (ax - bx) * (y - by)
# Segment B to C
side_2 = (x - cx) * (by - cy) - (bx - cx) * (y - cy)
# Segment C to A
side_3 = (x - ax) * (cy - ay) - (cx - ax) * (y - ay)
# All the signs must be positive or all negative
return all_points[~((side_1 < 0.0) == (side_2 < 0.0)) == (side_3 < 0.0)]
|
6e6067e3d7f356d5707eff19566f94576d029ddf
| 311,610 |
import yaml
def getSecrets(filepath):
"""
Load secret database parameters.
:param filepath: path to a .yaml file
Returns dict.
"""
with open(filepath, 'r') as f:
secrets = yaml.safe_load(f)
return secrets
|
103a28e8baa43a62f66a3820da7ac71a4e93d9c0
| 369,881 |
import re
def remove_extra_whitespace(line):
""" Removes all line breaking characters.
Collapses consecutive spaces into just one space """
line = line.lstrip()
line = re.sub('[\n\r\f\v\t]', ' ', line)
line = re.sub(' +', ' ', line )
return line
|
31c8d83aeb5fbcdac9c2d7be820849294debb9d2
| 299,232 |
def calc_mean_score(movies):
"""Helper method to calculate mean of list of Movie namedtuples,
round the mean to 1 decimal place"""
ratings = [m.score for m in movies]
mean = sum(ratings) / max(1, len(ratings))
return round(mean, 1)
|
6f837ff251e6221227ba4fa7da752312437da90f
| 483 |
def a_edge_reversed(s, initial, initial_reversed):
"""
If an a-edge can be validly reversed, return the result of the reversal.
Otherwise, return None.
"""
# precondition for validity:
if s.endswith('A'):
s2 = s[:-1]
# postcondition for validity:
if initial in s2 or initial_reversed in s2:
return s2
|
d75fd34708b1fd5db2b0dbba882a5797dcb4d25e
| 516,077 |
def parse_header(line, numeric_vals=True):
"""
Parse a line of the form:
#param=val\tparam=val\tparam=val...
Return a dictionary of params: vals
"""
line = line.strip()
if line[0] == '#':
line = line[1:]
params = {}
for pair in line.split('\t'):
k, v = pair.split('=')
if numeric_vals:
params[k] = float(v)
else:
params[k] = v
return params
|
98c3ff35a7a86beddd0b6cb4c4315986ed13725f
| 644,113 |
def sort_datasplit(split):
"""Sorts a single split of the SidechainNet data dict by ascending length."""
sorted_len_indices = [
a[0]
for a in sorted(enumerate(split['seq']), key=lambda x: len(x[1]), reverse=False)
]
for datatype in split.keys():
split[datatype] = [split[datatype][i] for i in sorted_len_indices]
return split
|
742ff27b88b84a88c8da0f6ecbc99fc72cd0b951
| 150,783 |
import requests
def login(connection, verbose=False):
"""
Authenticate a user and create an HTTP session on the web server where the user’s MicroStrategy sessions are stored.
This request returns an authorization token (X-MSTR-AuthToken) which will be submitted with subsequent requests.
The body of the request contains the information needed to create the session. The loginMode parameter in the body
specifies the authentication mode to use. You can authenticate with one of the following authentication modes:
Standard (1), Anonymous (8), or LDAP (16). Authentication modes can be enabled through the System Administration
REST APIs, if they are supported by the deployment.
:param connection: MicroStrategy REST API connection object
:param verbose: Verbosity of request response; defaults to False
:return: Complete HTTP response object
"""
response = requests.post(url=connection.base_url + '/auth/login',
data={'username': connection.username,
'password': connection.password,
'loginMode': connection.login_mode,
'applicationType': connection.application_code},
verify=connection.ssl_verify)
if verbose:
print(response.url)
return response
|
befa855d52e444d8ff414c39a11ddd9acff2fe89
| 70,198 |
def anonymize_number(number):
""" Anonymize 3 last digits of a number, provided as string. """
if number.isdigit() and len(number) >= 3:
return number[:-3] + "xxx"
else:
# Not a number or e.g. "unknown" if caller uses CLIR
return number
|
6a0ea207387a294829dff2d0927c9338cb6be459
| 401,570 |
from typing import List
def get_target(predictions: List, target: str):
"""
Return only the info for the targets.
"""
targets = []
for result in predictions:
if result["name"] == target:
targets.append(result)
return targets
|
e430807a99745b375b62126e24e6e480799ffb9a
| 141,239 |
def guidance_UV(index):
"""Return Met Office guidance regarding UV exposure based on UV index"""
if 0 < index < 3:
guidance = "Low exposure. No protection required. You can safely stay outside"
elif 2 < index < 6:
guidance = "Moderate exposure. Seek shade during midday hours, cover up and wear sunscreen"
elif 5 < index < 8:
guidance = "High exposure. Seek shade during midday hours, cover up and wear sunscreen"
elif 7 < index < 11:
guidance = "Very high. Avoid being outside during midday hours. Shirt, sunscreen and hat are essential"
elif index > 10:
guidance = "Extreme. Avoid being outside during midday hours. Shirt, sunscreen and hat essential."
else:
guidance = None
return guidance
|
07e1544a9f2683457d79ec9f0d9e84b7640d9d9c
| 623,625 |
def map_booleans_ynu(target_val):
""" Map boolean values to `Y`, `N`, `Unknown`.
Args:
target_val (any): value to check if it represents a boolean / indicator.
Returns:
str: `Y`, `N`, `Unknown`
"""
if target_val in [False, 0, '0', 'f', 'F', 'false', 'False', 'FALSE', 'n', 'N', 'no', 'No', 'NO']:
return 'N'
elif target_val in [True, 1, '1', 't', 'T', 'true', 'True', 'TRUE', 'y', 'Y', 'yes', 'Yes', 'YES']:
return 'Y'
else:
return 'Unknown'
|
af9b778a45e6b8e74e5a9b215fa96f5d1036e66b
| 377,164 |
def get_xmlns_string(ns_set):
"""Build a string with 'xmlns' definitions for every namespace in ns_set.
Args:
ns_set (iterable): set of Namespace objects
"""
xmlns_format = 'xmlns:{0.prefix}="{0.name}"'
return "\n\t".join([xmlns_format.format(x) for x in ns_set])
|
52f4ec0075dfd916940fd55706127bc87130f9ef
| 417,325 |
def get_object_id_value(spall_dict):
"""
get the best value for OBJID
:param spall_dict:
:return:
"""
if "BESTOBJID" in spall_dict.keys():
return spall_dict["BESTOBJID"]
else:
return spall_dict["OBJID"]
|
a0809d787115c8ef64eba373c9c5c65438cc839a
| 678,332 |
def associate_predecessors(graph, node=""):
"""
Returns a dictionary with outer key 'predecessors' securing a value
list of dictionaries associating the source, target and
edge_attribute with the corresponding Vertex.name strings for each
predecessor to the passed node.
"""
return {
"predecessors": [
{
"source": pred,
"target": node,
"edge_attribute": graph.pred[node][pred]["edge_attribute"],
}
for pred in graph.pred[node]
]
}
|
f014d9a0e36a128df3a966a6ebc05f10bcccb0f5
| 202,535 |
import json
def validate_nb_filter_params(filter_params):
"""
Validate NetBox inventory filter parameters JSON file
"""
# Ensure NetBox inventory filter parameters is present
with open(filter_params, "r") as filepath:
try:
# Attempt to load the JSON data into Python objects
json.load(filepath)
return True
except json.decoder.JSONDecodeError as exception:
# Print specific file and error condition, mark failure
print(f"{filter_params}: {exception}")
return False
|
a20b7a5c02eb9a0a717c63e9cbfd1a87bc1b125a
| 554,758 |
def search_key(lines,key,strict=False,get_value=False):
""" Search through the list of text lines for the line containing the key
if strict: match line == key
else: line contains key
if get_value==True, also return the value"""
i = 0
while True:
if (strict and lines[i].strip()==key) or (not strict and lines[i].find(key)>-1):
break
else:
i += 1
line = lines[i]
if get_value:
try:
val = float(line[line.rfind(':')+1:].strip())
return i, val
except:
return i, None
return i
|
65617d8246c721660b94e04815ce4f6a5cdaa7dc
| 336,743 |
def _get_full_customization_args(customization_args, ca_specs):
"""Populates the given customization_args dict with default values
if any of the expected customization_args are missing.
"""
for ca_spec in ca_specs:
if ca_spec.name not in customization_args:
customization_args[ca_spec.name] = {
'value': ca_spec.default_value
}
return customization_args
|
48c37f7ab3a48970cb9ed65c279c2e00c5245e58
| 687,968 |
def get_syllables_word_end(words):
"""Get a list of syllables from a list of words extracting word boundaries
:param words: List of dictonaries of syllables for each word in a line
:return: List of dictionaries of syllables with an extra is_word_end key
:rtype: list
"""
syllables = []
for word in words:
if "symbol" in word:
continue
for i, syllable in enumerate(word["word"]):
if i == len(word["word"]) - 1:
syllable["is_word_end"] = True
syllables.append(syllable)
return syllables
|
bed9834e29a3af1c566dfae603ab6ea76c4b6fce
| 445,920 |
def delete_subdir(config):
""" Remove subdir from config """
if not config:
return config
if 'subdir' in config:
del config['subdir']
return config
|
3b032d681ac213032e42d78ac56db1d441c9dba6
| 44,378 |
def parse_dox_html(stream):
"""Parse the HTML files produced by Doxygen, extract the key/value block we
add through header.html and return a dict ready for the Jinja template.
The HTML files produced by Doxygen with our custom header and footer files
look like this:
@code
<!--
key1: value1
key2: value2
...
-->
<html>
<head>
...
</head>
<body>
...
</body>
</html>
@endcode
The parser fills the dict from the top key/value block, and add the content
of the body to the dict using the "content" key.
We do not use an XML parser because the HTML file might not be well-formed,
for example if the documentation contains raw HTML.
The key/value block is kept in a comment so that it does not appear in Qt
Compressed Help output, which is not postprocessed by ourself.
"""
dct = {}
body = []
def parse_key_value_block(line):
if line == "<!--":
return parse_key_value_block
if line == "-->":
return skip_head
key, value = line.split(': ', 1)
dct[key] = value
return parse_key_value_block
def skip_head(line):
if line == "<body>":
return extract_body
else:
return skip_head
def extract_body(line):
if line == "</body>":
return None
body.append(line)
return extract_body
parser = parse_key_value_block
while parser is not None:
line = stream.readline().rstrip()
parser = parser(line)
dct['content'] = '\n'.join(body)
return dct
|
596cae0e26e6d218dde53c5674387890071d0866
| 301,883 |
def _get_boundary_date_string(date_sr, boundary, date_format='%Y-%m-%d'):
"""
Returns the first or last date of the series date_sr based on the
value passed in boundary.
date_sr: Series consisting of date
boundary: Allowed values are 'first' or 'last'
date_format: Format to be used for converting date into String
"""
return date_sr.describe().loc[boundary].strftime(format='%Y-%m-%d')
|
93ac0f29259e92411d9cd3f21a546394bf2924c6
| 633,064 |
def find_digits_in_str(string: str) -> str:
"""Find digits in a given string.
Args:
string: str, input string with the desired digits
Returns:
digits: str, found in the given string
"""
return "".join(x for x in string if x.isdigit())
|
7b9e824f8100d6289a8ed135b50e10d3b3046ed1
| 26,402 |
def is_reverse_o2o(field):
"""
A little helper to check if the given field is reverse-o2o. The field is
expected to be some sort of relation field or related object.
"""
return not hasattr(field, 'rel') and field.field.unique
|
f7921de55406a7b7c72d5769bb80ecef30ee505e
| 571,707 |
import boto
from typing import Optional
def get_aws_zone_from_boto() -> Optional[str]:
"""
Get the AWS zone from the Boto config file, if it is configured and the
boto module is available.
"""
try:
zone = boto.config.get('Boto', 'ec2_region_name')
if zone is not None:
zone += 'a' # derive an availability zone in the region
return zone
except ImportError:
pass
return None
|
eebbe2bb15f9c95def8e1e68f95c08c5a7a29137
| 645,705 |
import hashlib
def candidate_foundation(candidate_type, candidate_transport, base_address):
"""
See RFC 5245 - 4.1.1.3. Computing Foundations
"""
key = '%s|%s|%s' % (candidate_type, candidate_transport, base_address)
return hashlib.md5(key.encode('ascii')).hexdigest()
|
dea4527f25b75fa8f470002fd6c9f7c73b28277d
| 448,157 |
def parse_yotta_json_for_build_name(yotta_json_content):
"""! Function parse .yotta.json to fetch set yotta target
@param yotta_json_content Content of .yotta_json file
@return String with set yotta target name, None if no target found
"""
try:
return yotta_json_content['build']['target'].split(',')[0]
except KeyError:
return None
|
90938aa555f0d186016d857dff3ac0f2da18a4e9
| 154,490 |
def dict_indexer(d, key):
""":yaql:operator indexer
Returns value of a dictionary by given key.
:signature: left[right]
:arg left: input dictionary
:argType left: dictionary
:arg right: key
:argType right: keyword
:returnType: any (appropriate value type)
.. code::
yaql> {"a" => 1, "b" => 2}["a"]
1
"""
return d[key]
|
231a49534dfbcbed61cde7ab25ddf2ae651db3e7
| 243,147 |
from typing import Iterable
import math
def deg2rad(degs):
"""Convert degree iterables to radian iterables"""
if isinstance(degs, Iterable):
rads = []
for a in degs:
rads.append(a * math.pi / 180)
else:
rads = degs * math.pi / 180
return rads
|
1138c016ca4688325f6d900d27226fdc291529c5
| 397,783 |
def _return_request(req):
"""A dummy api call that simply returns the request."""
return req
|
c0e8307ff18cbc5ed98be5dd41ca80d30b94a8be
| 504,382 |
def _splits_label_and_features(example, label_tensors):
"""
Split the features and labels in a tfrecord example or sequence example.
:param example: tfrecord example or sequence of example
:param label_tensors: metadata of label tensors
:return: feature partition and label partition of the example / sequence example.
"""
label_names = [x.name for x in label_tensors]
return example, {label_key: example.pop(label_key) for label_key in label_names}
|
69e44d79aaeee86d318a1f245140cbebf1df1130
| 385,709 |
def guc_matches(cursor, guc, value):
"""Check if setting matches the specified value"""
cursor.execute("SELECT current_setting(%s) = %s", (guc, value))
return cursor.fetchone()[0]
|
c53bafe2a86d13439900efd3a81f19bde3ef5668
| 529,166 |
from typing import List
from typing import Any
from typing import Tuple
import random
def split_data(data: List[Any],
sizes: Tuple[float, float, float] = (0.8, 0.1, 0.1),
seed: int = 0) -> Tuple[List[Any], List[Any], List[Any]]:
"""
Randomly splits data into train, val, and test sets according to the provided sizes.
:param data: The data to split into train, val, and test.
:param sizes: The sizes of the train, val, and test sets (as a proportion of total size).
:param seed: Random seed.
:return: Train, val, and test sets.
"""
# Checks
assert len(sizes) == 3
assert all(0 <= size <= 1 for size in sizes)
assert sum(sizes) == 1
# Shuffle
random.seed(seed)
random.shuffle(data)
# Determine split sizes
train_size = int(sizes[0] * len(data))
train_val_size = int((sizes[0] + sizes[1]) * len(data))
# Split
train = data[:train_size]
val = data[train_size:train_val_size]
test = data[train_val_size:]
return train, val, test
|
2b10c2d1e0185f950feddb83ce338baf1a690150
| 103,064 |
def threshold_restart(
probability_threshold, current_probability, initial_temperature, **kwargs
):
"""Restarts the system by resetting the temperature to its highest value
once the acceptance probability function has gone underneath a given
threshold.
Args:
probability_threshold (float): A float located between 0 and 1,
that gives the threshold underneath which the system should
restart.
current_probability (float): The system's current acceptance
probability.
initial_temperature (float): The system's maximal temperature.
Returns:
tuple of bool and float: Whether or not the system should restart
and the system's maximal temperature.
"""
assert 0 <= probability_threshold <= 1, (
"Probability threshold should be located between 0 " "and 1."
)
return current_probability < probability_threshold, initial_temperature
|
0aae5b16b7b8114a369f83622c209836c86a8657
| 552,627 |
def total_returns(P_end, P_start):
"""
:param P_end: 策略最终股票和现金的总价值
:param P_start: 策略开始股票和现金的总价值
:return: 策略收益
"""
rtn = 1.0 * (P_end - P_start) / P_start
return rtn
|
7e324d0e3f15203cf474245acad69004fe57c3d6
| 423,261 |
def get_dicom_time_from(dtime):
"""Format the current time inside the input datetime to a dicom str format"""
try:
res = dtime.strftime("%H%M%S.%f")
return res
except Exception:
print("get_dicom_time_from: could not convert")
return '000000.000000'
|
8b6fcb7030bf4da1824229763e4f88c8162fed0a
| 234,345 |
import platform
def get_platform_info() -> str:
"""Returns a string with the platform information."""
return '''
System platform information:
system : %s
node : %s
release : %s
machine : %s
processor: %s
summary : %s
version : %s
Python platform information:
version : %s (implem: %s)
compiler : %s
''' % (platform.system(), platform.node(), platform.release(),
platform.machine(), platform.processor(), platform.platform(),
platform.version(), platform.python_version(),
platform.python_implementation(), platform.python_compiler())
|
11f6a8489e16cd209bc8d18d4e1e8c602f0c7579
| 571,669 |
def email_bodies(emails):
"""Return a list of email text bodies from a list of email objects"""
body_texts = []
for eml in emails:
body_texts.extend(list(eml.walk())[1:])
return body_texts
|
ce3af334cafeb53630b72b45d12877a27cbc4433
| 232,604 |
import hashlib
def generate_service_id(service_name, host, port):
"""Create the service id for consul
:param str service_name: the service name
:param str host: the service address
:param int port: the port on which the service listens to
:rtype: str
:return: the service id
"""
service_info = "{}-{}-{}".format(service_name, host, port).encode("utf-8")
return "{}".format(hashlib.md5(service_info).hexdigest())
|
5dc0f09dd499d1ace44feeb4b1dcb331a47d5f82
| 427,843 |
def _parse_present_bias_parameter(optim_paras, params):
"""Parse present-bias parameter which is 1 by default.
Examples
--------
An example where present-bias parameter is specified:
>>> tuples = [("beta", "beta")]
>>> index = pd.MultiIndex.from_tuples(tuples, names=["category", "name"])
>>> params = pd.Series(data=0.4, index=index)
>>> optim_paras = {"delta": 0.95}
>>> _parse_present_bias_parameter(optim_paras, params)
{'delta': 0.95, 'beta': 0.4, 'beta_delta': 0.38}
And one where present-bias parameter is not specified:
>>> params = pd.Series(dtype="float64")
>>> optim_paras = {"delta": 0.95}
>>> _parse_present_bias_parameter(optim_paras, params)
{'delta': 0.95, 'beta': 1, 'beta_delta': 0.95}
"""
beta = params.get(("beta", "beta"), 1)
optim_paras["beta"] = beta
optim_paras["beta_delta"] = beta * optim_paras["delta"]
return optim_paras
|
0e7032b2f7969353eb28a77a6cded678c0234bcf
| 176,870 |
def merge_blanks(*arg):
"""
merges all non blank elements of l, separated by a blank
Parameters
----------
*arg : elements to be merged : str
Returns
-------
string with merged elements of arg : str
"""
return " ".join(x for x in arg if x)
|
5dd8dc6caf8b76cd4d89c8ea424d3215fd6862c5
| 507,162 |
def _check_preferred_compat_mode(preferred_mode, supported_modes):
"""Checks whether the LPAR's preferred mode is supported
:param preferred_mode: preferred compat mode of the LPAR
:param supported_modes: proc compat modes supported by the dest host
:returns: True if the preferred mode is supported and False otherwise
"""
if preferred_mode == 'default':
return True
return preferred_mode in supported_modes
|
9afaf96afa0d6976833ac90193590f608ff96388
| 373,600 |
def get_paths(level=15):
"""
Generates a set of paths for modules searching.
Examples
========
>>> get_paths(2)
['sympy/__init__.py', 'sympy/*/__init__.py', 'sympy/*/*/__init__.py']
>>> get_paths(6)
['sympy/__init__.py', 'sympy/*/__init__.py', 'sympy/*/*/__init__.py',
'sympy/*/*/*/__init__.py', 'sympy/*/*/*/*/__init__.py',
'sympy/*/*/*/*/*/__init__.py', 'sympy/*/*/*/*/*/*/__init__.py']
"""
wildcards = ["/"]
for i in range(level):
wildcards.append(wildcards[-1] + "*/")
p = ["sympy" + x + "__init__.py" for x in wildcards]
return p
|
11989806e9923011f6760fbdc92a48bf3d5f99fe
| 451,098 |
def command (line):
"""Converts `line` into a `(direction, magnitude)` submarine command."""
direction, magnitude = line.split()
return direction, int(magnitude)
|
dbb4412c0456358b0283c90948ffa673cb078aba
| 462,020 |
async def upstream_forward(url, data, conn):
"""
Send a DNS request over HTTPS using POST method.
Params:
url - url to forward queries to
data - normal DNS packet data to forward
conn - HTTPS connection to upstream DNS server
Returns:
A normal DNS response packet from upstream server
Notes:
Using DNS over HTTPS POST format as described here:
https://tools.ietf.org/html/draft-ietf-doh-dns-over-https-12
https://developers.cloudflare.com/1.1.1.1/dns-over-https/wireformat/
"""
# Await upstream response
while True:
async with conn.post(url, data=data) as response:
if response.status == 200:
return await response.read()
print('%s (%d): IN %s, OUT %s' % (url, response.status, data, await response.read()))
|
a09fdd115beb2afb8c501301fef8ef641f202aa2
| 381,088 |
from typing import OrderedDict
def get_ordered_dic(unordered_dic):
"""Returns a dictionary ordered by the length of its keys
Args:
unordered_dic: Dictionary of stuff to order
Returns:
type, OrderedDict: Ordered dictionary by key-length
"""
return OrderedDict(sorted(unordered_dic.items(), key=lambda t: -len(t[0])))
|
c4519d7a74670a52de78a92e46f0542a8c2a80cf
| 429,228 |
def cost_rule(mod, project, point, period):
"""
**Constraint Name**: DRNew_Cost_Constraint
**Enforced Over**: m.DR_NEW_PTS*m.PERIODS
For each segment on the piecewise linear curve, the cost variable is
constrained to be equal to or larger than the calculated value on the
curve. Depending on the cumulative build (*DRNew_Energy_Capacity_MWh*)
only one segment is active at a time. The supply curve is assumed to be
convex, i.e. costs increase at an increasing rate as you move up the
curve.
"""
return mod.DRNew_Cost[project, period] \
>= mod.dr_new_supply_curve_slope[project, point] \
* mod.DRNew_Energy_Capacity_MWh[project, period] \
+ mod.dr_new_supply_curve_intercept[project, point]
|
386d3cd958481485a9669f70a9c6db7f942f7007
| 388,627 |
def _FindTag(template, open_marker, close_marker):
"""Finds a single tag.
Args:
template: the template to search.
open_marker: the start of the tag (e.g., '{{').
close_marker: the end of the tag (e.g., '}}').
Returns:
(tag, pos1, pos2) where the tag has the open and close markers
stripped off and pos1 is the start of the tag and pos2 is the end of
the tag. Returns (None, None, None) if there is no tag found.
"""
open_pos = template.find(open_marker)
close_pos = template.find(close_marker, open_pos)
if open_pos < 0 or close_pos < 0 or open_pos > close_pos:
return (None, None, None)
return (template[open_pos + len(open_marker):close_pos],
open_pos,
close_pos + len(close_marker))
|
62b056aca29554a4bb76fb00df152e5e524b1f7f
| 191,293 |
def xml_tree_equivalence(e1, e2):
"""
Rough XML comparison function based on https://stackoverflow.com/a/24349916/1294458.
This is necessary to provide some sort of structural equivalence of a generated XML
tree; however there is no XML deserialisation implementation yet. A naive text comparison
fails because it seems it enforces ordering, which seems to vary between python versions
etc. Strictly speaking, I think, only the *leaf-list* element mandates ordering.. this
function uses simple sorting on tag name, which I think, should maintain the relative
order of these elements.
"""
if e1.tag != e2.tag:
return False
if e1.text != e2.text:
return False
if e1.tail != e2.tail:
return False
if e1.attrib != e2.attrib:
return False
if len(e1) != len(e2):
return False
e1_children = sorted(e1.getchildren(), key=lambda x: x.tag)
e2_children = sorted(e2.getchildren(), key=lambda x: x.tag)
if len(e1_children) != len(e2_children):
return False
return all(xml_tree_equivalence(c1, c2) for c1, c2 in zip(e1_children, e2_children))
|
bdd135de65e0ecdf9f6d9d22f03b4b5dc06c476c
| 40,505 |
def get_candidate_file_name(
monotonous: bool,
agg_point: bool,
both: bool = False,
) -> str:
"""Get canonical filename for candidate set sizes."""
if both:
return f"candidate_sizes{'_mono' if monotonous else ''}_k_point"
else:
return f"candidate_sizes{'_mono' if monotonous else ''}_{'_point' if agg_point else '_k'}"
|
85b27f7767fd495a46459553b96160691a3dbeda
| 699,438 |
def access_control_allow_origin_star(func):
"""Decorator that adds Access-Control-Allow-Origin: * to any HTTPResponse
allowing cross-site XHR access to the handler."""
def allow_origin_access_star_wrapper(request, *args, **kwds):
response = func(request, *args, **kwds)
response["Access-Control-Allow-Origin"] = "*"
return response
return allow_origin_access_star_wrapper
|
1b2a236cb4205b38d521f8d068fff8860d176977
| 360,089 |
def lte(x, y):
"""Creates an SMTLIB less than or equal to statement formatted string
Parameters
----------
x, y: float
First and second numerical arguments to include in the expression
"""
return "(<= " + x + " " + y + ")"
|
96d51fb1d7a7f96f99c96b025ec4938e5ef19dea
| 687,654 |
from typing import List
def get_range(min_max: List[int]) -> range:
"""Returns a range with the turtles min max choices.
If the input is None then range(-25, 26) is returned.
Parameters
----------
min_max : List[int]
Returns
-------
min_max : range
"""
if min_max is None:
return range(-25, 26)
minimum = min_max[0]
maximum = min_max[1]
if minimum == maximum:
raise ValueError('min and max must be different')
if minimum > maximum:
raise ValueError('min must be lower than max')
return range(minimum, maximum)
|
c446656d7b41ae9c87bb57a5b7cb1a695ac5e68d
| 634,922 |
def full_igram_list(slclist):
"""Create the list of all possible igram pairs from slclist"""
return [
(early, late)
for (idx, early) in enumerate(slclist[:-1])
for late in slclist[idx + 1 :]
]
|
5ceec606f5aad9463c890e0bf483d87700a4df23
| 326,237 |
def subtract_number(x, y):
"""This function will subtract 2 numbers"""
return x - y
|
32868ec101c36f5fb7267361a6da4eb017e38a47
| 37,367 |
def altair_fix(html: str, i: int):
"""
Replaces certain keywords in the JavaScript needed to show altair plots.
Allows multiple altair plots to be rendered with vega on a single page
"""
# convert beautiful soup tag to a string
html = str(html)
keywords = ["vis", "spec", "embed_opt", "const el"]
for word in keywords:
html = html.replace(word, f"{word}{str(i)}")
return f'<div id="vis{i}"></div>\n' + html
|
765a732f1971364dd3c0bb88568d3fb523cbe845
| 215,784 |
import re
def check_empty_strings(*args):
"""
Function checks strings whether they are empty
:param args: strings
:return: True if all strings are not empty
else False
"""
for i in args:
if re.match(r'^[\s]*$', i):
return False
return True
|
2ccac15502e42dd647d7a5e9830a6bbcf3ddf16a
| 390,316 |
from pathlib import Path
def read_single_line(fpath, lineno):
"""
Read a single line from a given path
"""
if not isinstance(lineno, int):
raise ValueError(
"When reading a single line from file, lineno should be a number"
)
if not Path(fpath).exists():
raise FileExistsError(
"When reading a single line from file: the file doesnt exist!"
)
with open(fpath, "r") as f:
for i, line in enumerate(f):
if i == lineno:
return line
|
098a2ea6cb5f8fce1555a483316eb2ee7e8adb9f
| 331,375 |
def amplitude_calc(x, p, beta=1, alpha=0):
"""
Simple amplitude calculation of position and momentum coordinates
relative to twiss beta and alpha.
J = (gamma x^2 + 2 alpha x p + beta p^2)/2
= (x_bar^2 + px_bar^2)/ 2
where gamma = (1+alpha^2)/beta
"""
return (1+alpha**2)/beta/2 * x**2 + alpha*x*p + beta/2*p**2
|
805f185c2c171454b8e9c130e385b85fad2296a6
| 473,597 |
def parse_range(stash_range):
"""
Parse stash range syntax
>>> in_range = parse_range('0, 3-5, 8-')
>>> for i in range(11):
... print('{0} {1}'.format(i, in_range(i)))
0 True
1 False
2 False
3 True
4 True
5 True
6 False
7 False
8 True
9 True
10 True
"""
def minmax(raw):
if '-' in raw:
(low, high) = map(str.strip, raw.split('-'))
return (int(low) if low else 0,
int(high) if high else None)
else:
return (int(raw), int(raw))
def in_range(num):
for (low, high) in ranges:
if high is None and low <= num:
return True
elif low <= num <= high:
return True
return False
if stash_range:
ranges = list(map(minmax, stash_range.split(',')))
return in_range
else:
return lambda _: True
|
5f25285632caecf6c29a3f8395e1098614d84f63
| 463,636 |
def parameterized(dec):
"""
Meta decorator.
Decorate a decorator that accepts the decorated function as first argument,
and then other arguments with this decorator, to be able to pass it
arguments.
Source: http://stackoverflow.com/a/26151604
>>> @parameterized
... def multiply(f, n):
... def dec(*args, **kwargs):
... return f(*args, **kwargs) * n
... return dec
>>> @multiply(5)
... def add(a, b):
... return a + b
>>> add(3, 2)
25
"""
def layer(*args, **kwargs):
def repl(f):
return dec(f, *args, **kwargs)
return repl
return layer
|
9200eaec3ecf2405fc7e3bca0cce187659af4540
| 105,674 |
import requests
def get_cached(SERVER_URL, max_number=5):
"""
It asks for the server for X amount of data cached on the server.
:param SERVER_URL: string
A string that contains the server address.
:param max_number: int
The amount of information the user desire from cached data.
:return: json
It returns a JSON containing the last X amount of data.
"""
return requests.get(f'{SERVER_URL}/weather?max={max_number}').json()
|
66d4e7a463b10e5370d89eb61a40c648d5651c99
| 57,523 |
def get_strings(filename):
"""
Read strings from files generated by an IDAPython script and store them in a list for further processing.
"""
list_strings= []
with open(filename,'rU') as f:
list_strings= [line[:-1] for line in f.readlines()]
return list_strings
|
1f01bce01bd601e9bf25c8673fdcc97443384719
| 34,398 |
def error_event(event, failure, why):
"""
Convert event to error with failure and why
"""
return {"isError": True, "failure": failure,
"why": why, "original_event": event, "message": ()}
|
400d343dd8815bd087b3a678db316c697f3a11fa
| 507,129 |
def _bool(xml_boolean):
"""Converts strings "true" and "false" from XML files to Python bool"""
assert xml_boolean in ["true", "false"], \
"The boolean string must be \"true\" or \"false\""
return {"true": True, "false": False}[xml_boolean]
|
27803aace78f1ee1ecaa5c271955218dfcd0458a
| 662,399 |
def to_binary(n, N):
"""
Get binary representation of input n
:param n: Integer of which to get binary representation
:param N: Length of bitstring
:return: str
"""
return bin(n).replace('0b', '').zfill(N)
|
d7e8ac34d5205b9692410d4380a492b75dd275f0
| 616,197 |
def _default_validator(value):
"""A default validator, return False when value is None or an empty string. """
if not value or not str(value).strip():
return False
return True
|
3b282943215bec1af3ac07f0436093a8ba375ff3
| 348,932 |
def getCenterPoint(detection_box):
"""
Finds the center point of a detection box given the edge points of the box
"""
#Compensates for the OpenCV defenition of 'positive y is down' in the second calculation
x, y = (detection_box[0]+detection_box[2])/2, 1-((detection_box[1]+detection_box[3])/2)
return x, y
|
e97e5c2a6e85411f0e01ebc5fa53c11c3d931b85
| 199,129 |
import re
def _camel_to_snake(camel_string: str) -> str:
"""
Use regex to change camelCased string to snake_case
Args:
camel_string(str)
Returns:
A snake_cased string
"""
result = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", camel_string)
result = re.sub("(.)([0-9]+)", r"\1_\2", result)
result = re.sub("([a-z0-9])([A-Z])", r"\1_\2", result)
return result.lower()
|
b29dc3a9b1177b01ba8b10461d2ac7be68ba84d6
| 622,098 |
def dims_to_targetshape(data_dims, batch_size=None, placeholder=False):
"""Prepends either batch size/None (for placeholders) to a data shape tensor.
Args:
data_dims: list, indicates shape of the data, ignoring the batch size.
For an RGB image this could be [224, 224, 3] for example.
batch_size: scalar, indicates the batch size for SGD.
placeholder: bool, indicates whether the returned dimensions are going to
be used to construct a TF placeholder.
Returns:
shape: A tensor with a batch dimension prepended to the data shape.
"""
if batch_size is not None and batch_size != 0:
shape = [batch_size]
elif placeholder is True:
shape = [None]
else:
shape = [-1]
shape.extend(data_dims)
return shape
|
30cc97cdeca53e835fc51288e943235a12269146
| 39,576 |
def get_patient_fastqs(job, patient_dict, sample_type):
"""
Convenience function to return only a list of fq_1, fq_2 for a sample type.
:param dict patient_dict: dict of patient info
:param str sample_type: key in sample_type to return
:return: fastqs[sample_type]
:rtype: list[toil.fileStore.FileID]
"""
return [patient_dict[sample_type + '_fastq_1'], patient_dict[sample_type + '_fastq_2']]
|
1c9e47c2eb923849aad6be1c9f16a126b00afe2a
| 220,424 |
def _IBeamProperties(h_web, t_web, w_flange, t_flange, w_base, t_base):
"""Computes uneven I-cross section area, CG
See: http://www.amesweb.info/SectionalPropertiesTabs/SectionalPropertiesTbeam.aspx
INPUTS:
----------
h_web : float (scalar/vector), web (I-stem) height
t_web : float (scalar/vector), web (I-stem) thickness
w_flange : float (scalar/vector), flange (I-top) width/height
t_flange : float (scalar/vector), flange (I-top) thickness
w_base : float (scalar/vector), base (I-bottom) width/height
t_base : float (scalar/vector), base (I-bottom) thickness
OUTPUTS:
-------
area : float (scalar/vector), T-cross sectional area
y_cg : float (scalar/vector), Position of CG along y-axis (extending from base up through the T)
"""
# Area of T cross section is sum of the two rectangles
area_web = h_web * t_web
area_flange = w_flange * t_flange
area_base = w_base * t_base
area = area_web + area_flange + area_base
# Y-position of the center of mass (Yna) measured from the base
y_cg = (
(t_base + h_web + 0.5 * t_flange) * area_flange + (t_base + 0.5 * h_web) * area_web + 0.5 * t_base * area_base
) / area
return area, y_cg
|
96745aedadc7ce8946d982b75e5e779c729641ef
| 460,956 |
def mid_point(x1, y1, x2, y2):
"""
mid_point will find the mid point of a line segment when four coordinates are given.
It will return the mid point as a tuple.
:param x1: x-coordinate of left vertex
:param y1: y-coordinate of left vertex
:param x2: x-coordinate of right vertex
:param y2: y-coordinate of right vertex
:return: mid point of the line as tuple
"""
# Find the midpoint of given x, y coordinates
midpoint = ((x1 + x2) / 2, (y1 + y2) / 2)
# Return mid point as tuple
return midpoint
|
1fa00ef37a014c7450ffd4a98a531f639c24c6b2
| 460,053 |
import re
def delete_comments(file_content):
"""Removes all comments from the given string.
:param str file_content: file content
:return str: same content without comments
"""
string_temp = re.sub(r'--.*\n', '', file_content) # Removing comments
string_temp = re.sub(r'\n+', ' ', string_temp) # Replace new line with space
string_temp = re.sub(r' +', ' ', string_temp) # Replace >1 spaces with 1 space
return string_temp
|
b89cfb4dc884fea93c59c23e2da4f2d8c4b79fe7
| 96,280 |
def find_closest_number_divisible_by_m(n, m, answer_type='lower'):
"""Return the closest integer to n that is divisible by m. answer_type can either be 'closer', 'lower' (only returns
values lower than n), or 'higher (only returns values higher than m)."""
if n % m == 0:
return n
else:
q = int(n / m)
lower = q * m
higher = (q + 1) * m
if answer_type == 'lower':
return lower
elif answer_type == 'higher':
return higher
elif answer_type == 'closer':
return lower if (n - lower) < (higher - n) else higher
else:
raise Exception('answer_type should be lower, higher, or closer, had : %s' % answer_type)
|
72922c051ee0fd0e079fb0903177a7cbf6300beb
| 533,463 |
import torch
def to_one_hot_encode(target, classes):
"""Convert target values to one-hot encoded vector
:param target: The expected output or our labels
:type target: typing.Union[torch.Tensor]
:param classes: Number of classes
:type classes: int
:return: one hot encoded vectors of target
:rtype: torch.Tensor"""
one_hot = torch.zeros(target.shape[0], classes)
target = target.long()
for i in range(one_hot.shape[0]):
one_hot[i, target[i]] = 1
return one_hot
|
3cb0fca5d644cf063cc46e6e5e19a4da870f068a
| 399,149 |
def get_new_coordinates(coordinates, direction):
"""
Returns the coordinates of direction applied to the provided coordinates.
Args:
coordinates: tuple of (x, y)
direction: a direction string (like "northeast")
Returns:
tuple: tuple of (x, y) coordinates
"""
x, y = coordinates
if direction in ("north", "northwest", "northeast"):
y += 1
if direction in ("south", "southwest", "southeast"):
y -= 1
if direction in ("northwest", "west", "southwest"):
x -= 1
if direction in ("northeast", "east", "southeast"):
x += 1
return (x, y)
|
3470213e8ac401995ce99b3edc8bc0fd4a80e905
| 262,499 |
def dict_without_none_entries(dictionary):
"""
Return the shallow copy of the dictionary excluding the items that have None values.
"""
return {key: value for key, value in dictionary.items() if value is not None}
|
0633b8692dccc9da25fb87063603c557e057f27c
| 418,616 |
def sort_words(arguments, words):
"""
Takes a dict of command line arguments and a list of words to be sorted.
Returns a sorted list based on `alphabetical`, `length` and `reverse`.
"""
if arguments.get('--alphabetical', False):
words.sort()
elif arguments.get('--length', False):
words.sort(key=len)
if arguments.get('--reverse', False):
words.reverse()
return words
|
a6c0af4fe254c24d0f6d977e3ff80457ca4da2f0
| 688,651 |
def get_default_attr(obj, name, default):
"""Like getattr but return `default` if the attr is None or False.
By default, getattr(obj, name, default) returns default only if
attr does not exist, here, we return `default` even if attr evaluates to
None or False.
"""
value = getattr(obj, name, default)
if value:
return value
else:
return default
|
4932beac6b33e2995088a222a15c9d281e772be5
| 608,704 |
import struct
def _unpack_structure(string, structure):
""" Unpack a structure from a string """
fmt = '>' + ''.join([i[1] for i in structure]) # NEXRAD is big-endian
lst = struct.unpack(fmt, string)
return dict(zip([i[0] for i in structure], lst))
|
6422bb8bbe9bf0568ad64295f7afd0782a13f36c
| 356,612 |
import random
def rand_sampling(ratio, stop, start=1) :
"""
random sampling from close interval [start, stop]
Args :
ratio (float): percentage of sampling
stop (int): upper bound of sampling interval
start (int): lower bound of sampling interval
Returns :
A random sampling list
"""
assert 0 <= ratio and ratio <= 100, 'The ratio must be between 0 and 100.'
assert stop >= start, 'Invalid interval'
sample_pool = [i for i in range(start, stop + 1)]
select_num = int(len(sample_pool) * ratio)
return sorted(random.sample(sample_pool, select_num))
|
9b54c6b364e71a97d7cd9fa392790c4afde2bae0
| 701,836 |
def get_int_with_default(val, default):
"""Atempts to comvert input to an int. Returns default if input is None or unable to convert to
an int.
"""
if val is None:
return default
try:
return int(val)
except ValueError:
pass
return default
|
474b7b7d7c8b2ccd4966740aefbbcd5a5e3a956a
| 661,107 |
import random
def interchanging_mutation(genome):
"""Performs Interchanging Mutation on the given genome. Two position
are randomly chosen and they values corresponding to these positions
are interchanged.
Args:
genome (required): The genome that is to be mutated.
Returns:
The mutated genome.
"""
alleleA = random.randint(0, len(genome)-1)
alleleB = random.randint(0, len(genome)-1)
# Alleles should not be the same
while alleleA == alleleB:
alleleB = random.randint(0, len(genome)-1)
temp_gene = genome[alleleA]
genome[alleleA] = genome[alleleB]
genome[alleleB] = temp_gene
return genome
|
ae816f0a7619b516c31e27949f22c7a920c9c437
| 668,646 |
def route_distance(route):
"""
returns the distance traveled for a given tour
route - sequence of nodes traveled, does not include
start node at the end of the route
"""
dist = 0
prev = route[-1]
for node in route:
dist += node.euclidean_dist(prev)
prev = node
return dist
|
227b6476f6abd9efdf690062e0d4034c4ece2408
| 553 |
def filter_list_by_prefix(_list, prefix, negation: bool = False):
"""
filter out items from a list of strings based on a prefix. negation=True returns the
strings which do not contain the prefix.
:param _list: list of strings to filter
:param prefix: substring to search for
:param negation: pass True if you want strings which don't contain the prefix
:return: filtered list
"""
if negation:
return [item for item in _list if not item.startswith(prefix)]
else:
return [item for item in _list if item.startswith(prefix)]
|
a0bd9d1d16261298e16c094d166280aade27cd72
| 508,583 |
def _arch_file_filter(arch_members, fname=None):
"""Filter func to return one archive member with name 'fname' of an archive
"""
return [f for f in arch_members if f.name == fname]
|
6a19c3b8f7d2faa410a21922b5a5f6f3e0fd380c
| 33,397 |
from typing import Dict
from typing import Set
def _indicate_uncalled_modules(
statistics: Dict[str, Dict[str, str]],
stat_name: str,
uncalled_modules: Set[str],
uncalled_indicator: str = "N/A",
) -> Dict[str, Dict[str, str]]:
"""
If a module is in the set of uncalled modules, replace its statistics
with the specified indicator, instead of using the existing string.
Assumes the statistic is already formatting in string form.
Args:
statistics (dict(str, dict(str, str))) : the statistics to
format. Organized as a dictionary over modules, which are
each a dictionary over statistic types. Expects statistics
have already been converted to strings.
stat_name (str) : the name of the statistic being modified
uncalled_modules set(str) : a set of names of uncalled modules.
indicator (str) : the string that will be used to indicate
unused modules. Defaults to 'N/A'.
Returns:
dict(str, dict(str, str)) : the modified statistics
"""
stats_out = {mod: stats.copy() for mod, stats in statistics.items()}
for mod in uncalled_modules:
if mod not in stats_out:
stats_out[mod] = {}
stats_out[mod][stat_name] = uncalled_indicator
return stats_out
|
56592b113019b6d262a7540a2590397afa429cb0
| 84,377 |
def is_same_tree(p, q):
"""
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
Args:
p: TreeNode
q: TreeNode
Returns:
bool
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
if p and q:
return p.val == q.val and is_same_tree(p.left, q.left) and is_same_tree(p.right, q.right)
return p is q
|
10d459ce2efcb2c37cbe6879d940f8e9406f6e5b
| 443,897 |
def get_dataset_name(tier, release_tag, deid_stage):
"""
Helper function to create the output prod dataset name based on the given criteria
This function should return a name for the final dataset only (not all steps along the way)
The function returns a string in the form: [C|R]{release_tag}[_base|_clean]
:param tier: controlled or registered tier intended for the output dataset
:param release_tag: release tag for dataset in the format of YYYYQ#R#
:param deid_stage: deid stage (deid, base or clean)
:return: a string for the dataset name
"""
tier = tier[0].upper()
release_tag = release_tag.upper()
deid_stage = f'_{deid_stage}' if deid_stage == 'base' else ''
dataset_name = f"{tier}{release_tag}{deid_stage}"
return dataset_name
|
5bab8f9ea92303ab805c9a864945aaed652a4a7d
| 168,765 |
def user_to_dict(user):
"""
Convert an instance of the User model to a dict.
:param user: An instance of the User model.
:return: A dict representing the user.
"""
return {
'id': user.id,
'demoId': user.demoId,
'email': user.email,
'username': user.username,
'roles': user.roles
}
|
d3e41fc8f377faf35c3a64ce8716fac6e35a611e
| 682,161 |
def mod_pow(base, power, mod=None):
"""
Implements divide and conquere binary exponetiation algorithm
Complexity: O(log power)
source: https://cp-algorithms.com/algebra/binary-exp.html
Params:
@base: base number which needs to be multiplied
@power: power to which base should be raised
@mod: modulas with which number should be mod'ed
returns: (base^power)%mod
"""
if mod:
base %= mod
result = 1
while power > 0:
if power & 1:
result *= base
if mod:
result %= mod
base *= base
if mod:
base %= mod
power //= 2
return result
|
9eba57c0586d9a6e8fe03db61e977ec3c60cbd9c
| 300,984 |
def rreplace(s, old, new, occurrence=1):
""" Replace portion of a string (from the right side). Handy utility to
change a filename extension, e.g. rreplace('a/b/c.fits', 'fits', 'im') -> 'a/b/c.im'
Parameters
----------
s : str
The string to process
old : str
The substring to replace
new : str
Whet to replace the 'old' substring with
occurrence : int
The number of occurrences to replace
Default: 1
"""
li = s.rsplit(old, occurrence)
return new.join(li)
|
a81d566c76e6a2a62132453fbb3f089437dd8e58
| 471,932 |
def validate_clientvpnendpoint_selfserviceportal(value):
"""
Validate SelfServicePortal for ClientVpnEndpoint.
Property: ClientVpnEndpoint.SelfServicePortal
"""
VALID_CLIENTVPNENDPOINT_SELFSERVICEPORTAL = ("disabled", "enabled")
if value not in VALID_CLIENTVPNENDPOINT_SELFSERVICEPORTAL:
raise ValueError(
"ClientVpnEndpoint.SelfServicePortal must be one of: {}".format(
", ".join(VALID_CLIENTVPNENDPOINT_SELFSERVICEPORTAL)
)
)
return value
|
0b78a7017aba3b414ab1aa3b51d4e17cf81727f8
| 102,226 |
def all_notes_line_up(a_list, b_list):
"""
Takes two lists of NoteNode objects. These may be NoteList objects.
Returns 2 lists.
The first list contains the NoteNode objects in a_list that are unmatched in b_list.
The second list contains the NoteNode objects in b_list that are unmatched in a_list.
"""
a_list = [x for x in a_list if not x.is_rest] # copy NoteList to list
b_list = [x for x in b_list if not x.is_rest] # copy NoteList to list
# remove matched notes
for a_note in a_list[:]:
for b_note in b_list[:]:
if (a_note.start, a_note.end) == (b_note.start, b_note.end):
# remove the matched pair from their respective lists
a_list.remove(a_note)
b_list.remove(b_note)
break
return a_list, b_list
|
6d38de53025f6cfeb6b5e665a6ed9c535cf95792
| 79,327 |
def averageListEntry(datalist):
"""
Return the average value of a Python List
:param datalist:
:return: average of list
"""
return sum(datalist)/len(datalist)
|
300cfc7e73d28d9868d586e952637ed929129f72
| 623,697 |
import re
def make_choices_tuple(type_class):
"""Creates a tuple of tuples object used as the choices attribute for
a CharField that we want to limit choices.
Args:
type_class: A class with the attributes defining the types.
"""
return tuple([
(type_name, type_name) for type_name in dir(type_class)
if not re.match(r'__*', type_name)
])
|
169a7714124be033a2bb188d8a1eac86087e9637
| 70,089 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.