content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
import logging
def get_topic(sns, topic_arn):
"""
Purpose:
Return an SNS Topic by ARN
Args:
sns (SNS Resource Object): SNS Object owning the Topic
topic_arn (String): ARN of the Topic
Return:
topic (SNS Topic Object): Topic object for the topic in
SNS
"""
try:
return sns.Topic(topic_arn)
except Exception as err:
logging.exception(f"Exception Getting Topic: {err}")
raise | 715f5014f415fda4c9a9cf024d607ba17e582b0d | 489,098 |
def extract_fingerprints_size (fingerprint_type, fingerprints):
""" Extract fingerprints' size with the given type
from a given list """
fingerprints_size = list()
for i in fingerprints:
if (i[2] == fingerprint_type):
fingerprints_size.append(i[1])
return fingerprints_size | 4354541785423c0d3af35f852e15924bf3050b8f | 558,478 |
def GeBuildConfigAllBoards(ge_build_config):
"""Extract a list of board names from the GE Build Config.
Args:
ge_build_config: Dictionary containing the decoded GE configuration file.
Returns:
A list of board names as strings.
"""
return [b['name'] for b in ge_build_config['boards']] | a64cd6aac932f898fd38614a0914638b0f02612b | 622,684 |
def camera_name_from_calibrator(calibrator):
"""
Returns the name of the camera associated with the given camera calibrator.
"""
return calibrator.split('/')[2] | 8f35c4987f02f5eb62101ac2c9af2edcb8a4746a | 26,472 |
def ret_normalized_vec(vec, length):
"""Normalize a vector in L2 (Euclidean unit norm).
Parameters
----------
vec : list of (int, number)
Input vector in BoW format.
length : float
Length of vector
Returns
-------
list of (int, number)
L2-normalized vector in BoW format.
"""
if length != 1.0:
return [(termid, val / length) for termid, val in vec]
else:
return list(vec) | 9bbb1de11975fdc282e4ecc5e2a6d72f57cd30f9 | 619,432 |
def get_schedule_list(schedule_dict, plan_name):
"""returns list of schedules which are defined for given plan."""
return([scheduel_name for scheduel_name in schedule_dict.keys() if schedule_dict[scheduel_name]["plan"]==plan_name]) | 1b9554052e804a741b5540c854dbcff7f389b8ce | 142,200 |
import collections
def _call_counter(mocked_obj):
"""Return count of call for given params from mock
eg if mock called 3 times:
1) mock(a=[1],b=[],c=[])
2) mock(a=[1],b=[],c=[])
3) mock(a=[],b=[],c=[1])
return {
'a': 2
'c': 1
}
"""
res = collections.defaultdict(int)
for call_item in mocked_obj.call_args_list:
params = call_item[1]
for param in params:
if params[param]:
res[param] += 1
return res | 3dd8060641c041599b04ebc93ee137edb7410781 | 191,815 |
def get_xml_element_contents(element):
"""
Converts the contents of an xml element into a string, with all
child xml nodes unchanged.
"""
return "".join([c.toxml() for c in element.childNodes]) | 1b23fbb122b1ee950d6592a57409b973442afea8 | 494,245 |
def find_smallest_angle(angle1, angle2, absolute_value=False):
"""Find the smallest angle between two provided azimuth angles.
@param: - angle1 - first angle in degrees between 0 and 360 degrees
@param: - angle2 - first angle in degrees between 0 and 360 degrees
@param: - absolute_value - if true, return absolute value of result
"""
diff = angle1 - angle2
diff = (diff + 180) % 360 - 180
if absolute_value:
diff = abs(diff)
return diff | c1f3581a7d43d344f81f204ba9f30df32601429e | 592,253 |
def convert_by_vocab(vocab, items, unk_info):
"""Converts a sequence of [tokens|ids] using the vocab."""
output = []
for item in items:
if item in vocab:
output.append(vocab[item])
else:
output.append(unk_info)
return output | bf7b8cfab2e55a0c980efe055057194badf8ab09 | 664,992 |
def is_cybox(entity):
"""Returns true if `entity` is a Cybox object"""
try:
return entity.__module__.startswith("cybox.")
except AttributeError:
return False | fc644dbf5c0394618986ba0a1ab66f2d1c837dca | 126,567 |
def first_not_none(iterable):
"""Select the first item from an iterable that is not None.
The idea is that you can use this to specify a list of fall-backs to use
for configuration options.
"""
for item in iterable:
if item is not None:
return item
return None | 800c55e5f427cf0a707e19e71dbac8065019d639 | 600,668 |
def read_expected_errors(test):
""" Read the expected stderr error output expected for Test
'test', as found in the file test.errors. Returns a list of
strings, one per line, or an empty list if the file does not
exist. """
try:
errorfile = open(test.errors)
except IOError:
expected_error = []
else:
expected_error = errorfile.readlines()
errorfile.close()
return expected_error | 3598df1fcd85b62719dc7e0199459e00ac5998d1 | 158,331 |
def retrieve_test_data(test_suite, index):
"""
Tries to retrieve test data from the loaded test_suite module
:param test_suite: Imported module with tests available
:param index: index of test_data for getting the sequence
:return: Dictionary of related test data. Keys as strings Keys(<sequence>,<version>,...)
"""
try:
data = test_suite.test_data
except AttributeError:
# Try legacy API
return test_suite.TEST_SEQUENCE
try:
sequence = data[index]
except KeyError as e:
raise ValueError("Invalid test index parsed: {}".format(index)) from e
return sequence | c49514c57658beb8b2212f632edc4e15ced72df2 | 556,046 |
def ensure_trailing_slash(expression):
"""
Add a trailing slash to rsync source/destination locations.
:param expression: The rsync source/destination expression (a string).
:returns: The same expression with exactly one trailing slash.
"""
if expression:
# Strip any existing trailing slashes.
expression = expression.rstrip('/')
# Add exactly one trailing slash.
expression += '/'
return expression | 3a3d7d34f0c1265dca246fcb109febc55f21a6ac | 245,390 |
def cp_to_str(cp):
"""
Convert a code point (int) to a string.
"""
return "%04X" % cp | ebdf6f67f64b1235bc4eb1ea95dc275bc1d4611e | 403,275 |
def match_form(wrapped_form, filters):
"""Matches filters values with <FormElement> attributes using predefined matching types
example_filters = {
'id': 'searchbox',
'name': 'name,
'action': 'action',
'has_fields': ['field1', 'field2'],
}
:param wrapped_form: class::`FormElement <FormElement>` object
:param filters: dict
:return: bool
"""
for name, value in filters.items():
if name == 'has_fields':
if not getattr(wrapped_form, name)(value):
return False
elif getattr(wrapped_form, name)() != value:
return False
return True | d84fe52d696acddc994c2d78560f6eb17ad11b14 | 499,358 |
def _subsum(
digit_pos_to_extract: int, denominator_addend: int, precision: int
) -> float:
# only care about first digit of fractional part; don't need decimal
"""
Private helper function to implement the summation
functionality.
@param digit_pos_to_extract: digit position to extract
@param denominator_addend: added to denominator of fractions in the formula
@param precision: same as precision in main function
@return: floating-point number whose integer part is not important
"""
sum = 0.0
for sum_index in range(digit_pos_to_extract + precision):
denominator = 8 * sum_index + denominator_addend
exponential_term = 0.0
if sum_index < digit_pos_to_extract:
# if the exponential term is an integer and we mod it by the denominator before
# dividing, only the integer part of the sum will change; the fractional part will not
exponential_term = pow(
16, digit_pos_to_extract - 1 - sum_index, denominator
)
else:
exponential_term = pow(16, digit_pos_to_extract - 1 - sum_index)
sum += exponential_term / denominator
return sum | 66153809cfd003dd4f15db118260af59ddc16191 | 251,090 |
def conn_from_flowtuple(ft):
"""Convert the flow tuple into a dictionary (suitable for JSON)"""
sip, sport, dip, dport, offset, relts = ft
return {"src": sip, "sport": sport,
"dst": dip, "dport": dport,
"offset": offset, "time": relts} | 12e5335bec9e0d895139e289daf2353b48328f73 | 468,690 |
def get_ls(omega_list):
"""Return the array of the Solar longitude of each OMEGA/MEx observation in omega_list.
Parameters
==========
omega_list : array of OMEGAdata
The input array of OMEGA observations.
Returns
=======
ls : ndarray
The array of the omega_list Ls.
"""
ls = []
for omega in omega_list:
ls.append(omega.ls)
return ls | c8be1927a55ff9aac0134d52691b3b2bdd049724 | 700,284 |
import torch
def batch_mvp(m, v):
"""Batched matrix vector product.
Args:
m: A tensor of size (batch_size, d, m).
v: A tensor of size (batch_size, m).
Returns:
A tensor of size (batch_size, d).
"""
v = v.unsqueeze(dim=-1) # (batch_size, m, 1)
mvp = torch.bmm(m, v) # (batch_size, d, 1)
mvp = mvp.squeeze(dim=-1) # (batch_size, d)
return mvp | 810da2273dc568a63f18a9cca1caf4c448796778 | 569,654 |
import csv
def read_csv(filename):
"""
Reads a csv.
"""
raw_records = []
with open(filename, 'r') as f:
reader = csv.reader(f, dialect='excel')
for row in reader:
raw_records.append(row)
return raw_records | 0e2619467dde6d042933c8879d0a94bf0cd316fb | 243,950 |
def quote_literal(text):
"""
Escape the literal and wrap it in [single] quotations.
"""
return "'" + text.replace("'", "''") + "'" | d034c24f3affe5e1364dcd56e6c663b40e2bc284 | 516,140 |
def H(request) -> int:
"""Default image height."""
return 32 | 9c244f176bfa26153d6769d778af00a25031a0ec | 509,182 |
def _as_nested_lists(vertices):
""" Convert a nested structure such as an ndarray into a list of lists. """
out = []
for part in vertices:
if hasattr(part[0], "__iter__"):
verts = _as_nested_lists(part)
out.append(verts)
else:
out.append(list(part))
return out | c69bd2084aa8e76a53adf3e25286a8dd7ae23176 | 1,347 |
import warnings
def get_integer(val=None, name="value", min_value=0, default_value=0):
"""Returns integer value from input, with basic validation
Parameters
----------
val : `float` or None, default None
Value to convert to integer.
name : `str`, default "value"
What the value represents.
min_value : `float`, default 0
Minimum allowed value.
default_value : `float` , default 0
Value to be used if ``val`` is None.
Returns
-------
val : `int`
Value parsed as an integer.
"""
if val is None:
val = default_value
try:
orig = val
val = int(val)
except ValueError:
raise ValueError(f"{name} must be an integer")
else:
if val != orig:
warnings.warn(f"{name} converted to integer {val} from {orig}")
if not val >= min_value:
raise ValueError(f"{name} must be >= {min_value}")
return val | 9c967a415eaac58a4a4778239859d1f6d0a87820 | 706,960 |
def get_task_id_service_name(service_name):
"""Converts the provided service name to a sanitized name as used in task ids.
For example: /test/integration/foo => test.integration.foo"""
return service_name.lstrip("/").replace("/", ".") | eed6d8e6cc0e453399247165884c7b8c7ca025a2 | 231,803 |
def extract_doi_links(urls):
"""
Try to find a DOI from a given list of URLs.
:param urls: A list of URLs.
:returns: First matching DOI URL, or ``None``.
"""
doi_urls = [url for url in urls if "/doi/" in url]
if len(doi_urls) > 0:
return ("http://dx.doi.org" +
doi_urls[0][doi_urls[0].find("/doi/") + 4:])
else:
return None | 2076949fdf96c27e0d80644319d9583811620744 | 75,441 |
import math
def squarest_grid_size(num_images):
"""Calculates the size of the most square grid for num_images.
Calculates the largest integer divisor of num_images less than or equal to
sqrt(num_images) and returns that as the width. The height is
num_images / width.
Args:
num_images: The total number of images.
Returns:
A tuple of (height, width) for the image grid.
"""
square_root = math.sqrt(num_images)
if square_root.is_integer():
width = int(square_root)
else:
width = math.floor(square_root)
while not num_images % width == 0:
width -= 1
return num_images // width, width | e936c8e543436a75e1a11c75ed9c6b502d0da713 | 450,868 |
import re
def get_cycle_time_seconds(string):
"""
Parses the string to get the corresponding number of seconds, for example,
if string="20 Seconds" then returns 20,
if string="2 Minutes" then returns 120.
@param string the text presumably obtained by get_cycle_time.
@return the number of seconds. None if the string cannot be parsed.
"""
mo = re.match(r"(\d+)\s+(Seconds|Minutes)", string)
if mo is not None:
value = int(mo.group(1))
units = mo.group(2)
if units == "Seconds":
seconds = value
else:
seconds = 60 * value
return seconds
else:
return None | 2f175112c28f918fbf555abd80deddabc0bbec5e | 545,673 |
import six
def bool_(val):
"""Like `bool`, but the string 'False' evaluates to `False`."""
if isinstance(val, six.string_types) and val.lower() == 'false':
return False
return bool(val) | 19684ddfc319e3a87233127273f3e21392281ed6 | 597,737 |
def bubble_sort(nums_array: list) -> list:
"""
Bubble Sort Algorithm
:param nums_array: list
:return nums_array: list
"""
is_sorted = True
for i in range(0, len(nums_array) - 1):
for j in range(0, len(nums_array) - i - 1):
if nums_array[j] > nums_array[j + 1]:
is_sorted = False
temp = nums_array[j]
nums_array[j] = nums_array[j + 1]
nums_array[j + 1] = temp
if is_sorted:
break
return nums_array | aee298686e0cb25a15be4281a2c41c75d7cbe1e3 | 511,939 |
def get_weights(cbf):
"""Retrieve the latest gain corrections and their corresponding update times."""
weights, times = {}, {}
for sensor_name in cbf.sensor:
if sensor_name.endswith('_gain_correction_per_channel'):
sensor = cbf.sensor[sensor_name]
input_name = sensor_name.split('_')[1]
reading = sensor.get_reading()
weights[input_name] = reading.value
times[input_name] = reading.timestamp
return weights, times | 84887af7eda90fccb46242051a0f5b1d91a8e983 | 23,645 |
def dowt2di(Do, WT):
"""Calculate pipe inner diameter from outer diameter and wall thickness.
"""
return Do - 2 * WT | 7b3846d93cbc43e7b6f724f4ceda1d05a02c0470 | 421,612 |
def list_things(iot_client, old_certificate_arn):
"""
Creates a list of all things attached to the old certificate
:param iot_client: the boto client to connect and execute
IoT APIs
:param old_certificate_arn: the old certificate arn
:return: list of things
"""
things_list = []
response = iot_client.list_principal_things(
principal=old_certificate_arn
)
things_list.append(response['things'])
while 'nextToken' in response:
response = iot_client.list_principal_things(
nextToken=response['nextToken'],
principal=old_certificate_arn
)
things_list.append(response['things'])
return things_list | 24153de7b6552c98abe1383f908bfe311e44bf46 | 173,756 |
def dagger(x):
"""
Hermitian conjugate state
:param x: state
:return: Hermitian conjugate state
"""
return x.T.conj() | 87ed3c03d61f5bb5d3ab3977b6aeb9f4d197bfaf | 481,097 |
def transceive(spi,csPin,busyPin,cmd: int,len: int) -> bytearray:
"""
Method to receive data by an SPI slave after sending a command.
Parameters
-----
spi : spi object from busio.SPI
csPin : control slave pin from board.D##
cmd : opcode of command
len : number of bytes to receive
Returns
-----
arr : bytearray of length len with received bytes
"""
# wait until BUSY goes low
while busyPin.value:
pass
arr = bytearray(len)
csPin = False
spi.writeto(bytes([cmd]))
spi.readinto(arr)
csPin = True
return arr | 45b92a583ec654764abf97c3a12ae051d650ae86 | 65,520 |
def forward_matcher(xlinear_model, X, **kwargs):
"""Forward through the matcher to get the leaf id.
Args:
xlinear_model: The input xlinear model.
X: Input feature matrix.
kwargs: The config.
Returns:
The matching matrix.
"""
csr_codes = None
model_chain = xlinear_model.model.model_chain
for layer_id in range(len(model_chain) - 1):
cur_model = model_chain[layer_id]
level_pred = cur_model.predict(
X,
csr_codes=csr_codes,
only_topk=kwargs["beam_size"],
post_processor=kwargs["post_processor"],
)
csr_codes = level_pred
return csr_codes | 59884897c4eeae790220d3a110c5828db60ab9ff | 471,372 |
def command_category(command, default='\u200bOther'):
"""Return the category that a command would fall into, using the module the command was defined in."""
_, category, *rest = command.module.split('.', 2)
return category if rest else default | 08356c6577d30458d6c3299d665c5e6e688ce619 | 254,151 |
def getCentralRect(width, height, divisor=1):
"""Select central rectangle with reduced size.
MMstudio-like.
1: 2048 1536 ( 0, 0, 2048, 1536)
2: 1024 768 (512, 384, 1536, 1152)
4: 512 384 (768, 576, 1280, 960)
8: 256 192 (896, 672, 1152, 864)
16: 128 96 (960, 720, 1088, 816)
32: 64 48 (992, 744, 1056, 792)
64: 32 24 (1008, 756, 1040, 780)
128: 16 12 (1016, 762, 1032, 774)
256: 8 6 (1020, 765, 1028, 771)
512: 4 2 (1022, 767, 1026, 769)
1024: 2 0 (1023, 768, 1025, 768)
LeicaDFC 295 available resolutions
2048 1536
1600 1200
1280 1024
1024 768
640 480
"""
centerx = width / 2
centery = height / 2
roi = (
centerx - centerx / divisor,
centery - centery / divisor,
width / divisor,
height / divisor)
return roi | bb6f28bb5812da553dfa4cb8aa27e73880e49371 | 580,467 |