content
stringlengths 35
416k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
---|---|---|
def is_mongo_configured(accessor):
"""
works out if mongodb is configured to run with trackerdash
i.e. first time running
"""
return accessor.verify_essential_collections_present() | c0487f6d899e6cee4f6bbb31bffbd17890812c30 | 3,946 |
import ast
def maybe_get_docstring(node: ast.AST):
"""Get docstring from a constant expression, or return None."""
if (
isinstance(node, ast.Expr)
and isinstance(node.value, ast.Constant)
and isinstance(node.value.value, str)
):
return node.value.value
elif (
isinstance(node, ast.Expr)
and isinstance(node.value, ast.Str)
):
return node.value.s | 23171c739f3c9ae6d62ecf3307ac7c3409852d6b | 3,947 |
def _find(xs, predicate):
"""Locate an item in a list based on a predicate function.
Args:
xs (list) : List of data
predicate (function) : Function taking a data item and returning bool
Returns:
(object|None) : The first list item that predicate returns True for or None
"""
for x in xs:
if predicate(x):
return x
return None | 94d8dd47e54e1887f67c5f5354d05dc0c294ae52 | 3,949 |
def version_for(plugin):
# (Plugin) -> Optional[str]
"""Determine the version of a plugin by its module.
:param plugin:
The loaded plugin
:type plugin:
Plugin
:returns:
version string for the module
:rtype:
str
"""
module_name = plugin.plugin.__module__
try:
module = __import__(module_name)
except ImportError:
return None
return getattr(module, "__version__", None) | 6d7c4ccc868d11d28c92d1264d52488e22d7f5e5 | 3,952 |
def _extract_action_num_and_node_id(m):
"""Helper method: Extract *action_num* and *node_id* from the given regex
match. Convert *action_num* to a 0-indexed integer."""
return dict(
action_num=(int(m.group('action_num')) - 1),
node_id=m.group('node_id'),
) | f1e5f0b81d6d82856b7c00d67270048e0e4caf38 | 3,953 |
import re
def get_uid_cidx(img_name):
"""
:param img_name: format output_path / f'{uid} cam{cidx} rgb.png'
"""
img_name = img_name.split("/")[-1]
assert img_name[-8:] == " rgb.png"
img_name = img_name[:-8]
m = re.search(r'\d+$', img_name)
assert not m is None
cidx = int(m.group())
img_name = img_name[:-len(str(cidx))]
assert img_name[-4:] == " cam"
uid = img_name[0:-4]
return uid, cidx | 29363f4fc686fa972c2249e5e1db1a333625be36 | 3,954 |
import os
def file_get_size_in_bytes(path: str) -> int:
"""Return the size of the file in bytes."""
return int(os.stat(path).st_size) | e9692259d2f5cb8f536cb8c6a0ae53e0b7c6efd1 | 3,958 |
def git2pep440(ver_str):
"""
Converts a git description to a PEP440 conforming string
:param ver_str: git version description
:return: PEP440 version description
"""
dash_count = ver_str.count('-')
if dash_count == 0:
return ver_str
elif dash_count == 1:
return ver_str.split('-')[0] + "+dirty"
elif dash_count == 2:
tag, commits, sha1 = ver_str.split('-')
return "{}.post0.dev{}+{}".format(tag, commits, sha1)
elif dash_count == 3:
tag, commits, sha1, _ = ver_str.split('-')
return "{}.post0.dev{}+{}.dirty".format(tag, commits, sha1)
else:
raise RuntimeError("Invalid version string") | 7c4a5185305627c22118722b73b2facfa830875a | 3,959 |
import math
def iucr_string(values):
"""Convert a central value (average) and its s.u. into an IUCr compliant number representation.
:param values: pair of central value (average) and s.u.
:type values: tuple((float, float))
:return: IUCr compliant representation
:rtype: str
"""
if values[1] == 0 or values[1] is None: # No or zero s.u. given
return str(values[0])
sig_pos = math.floor(math.log10(abs(values[1]))) # position of first significant digit
sig_3 = math.trunc(abs(values[1]) * 10 ** (2 - sig_pos)) / 10 ** (2 - sig_pos) # 1st three significant s.u. digits
sig_3 *= 10 ** -(sig_pos + 1) # s.u. moved directly behind decimal separator (final range: 0.100-0.999)
if sig_3 < 0.195: # round to two digits (final s.u. range: 0.10-0.19)
su = round(abs(values[1]), 1 - sig_pos)
avg = round(values[0], 1 - sig_pos)
sig_len = 2
elif sig_3 < 0.950: # round to one digit (final s.u. range: 0.2-0.9)
su = round(abs(values[1]), -sig_pos)
avg = round(values[0], -sig_pos)
sig_len = 1
else: # round to two digits and move forward (final s.u.: 0.10)
sig_pos += 1
su = round(abs(values[1]), 1 - sig_pos)
avg = round(values[0], 1 - sig_pos)
sig_len = 2
if sig_pos > 0: # only integral part for s.u. >= 1.95
sign_shift = -1 if values[0] < 0 else 0
avg_str = ('{:' + str(sig_pos + sign_shift) + '.0f}').format(avg).strip()
su_str = ('{:' + str(sig_pos) + '.0f}').format(su)
else: # fractional and possibly integral part for s.u. < 1.95
avg_str = ('{:.' + str(-sig_pos + sig_len - 1) + 'f}').format(avg)
su_str = '{:.0f}'.format(abs(su / 10 ** (sig_pos - sig_len + 1)))
return '{:s}({:s})'.format(avg_str, su_str) | c6c6602aa0ba481ed5467ed62df59a16f26a8091 | 3,960 |
def sse_pack(d):
"""For sending sse to client. Formats a dictionary into correct form for SSE"""
buf = ''
for k in ['retry','id','event','data']:
if k in d.keys():
buf += '{}: {}\n'.format(k, d[k])
return buf + '\n' | a497c7ab919115d59d49f25abfdb9d88b0963af3 | 3,961 |
def filter_dictionary(dictionary, filter_func):
"""
returns the first element of `dictionary` where the element's key pass the filter_func.
filter_func can be either a callable or a value.
- if callable filtering is checked with `test(element_value)`
- if value filtering is checked with `element_value == filter_func`
:param dictionary:
:param test:
:return:
>>> filter_dictionary({'arg': 'test'}, 'test')
'arg'
>>> filter_dictionary({}, 'test')
>>> def is_test(value):
... return value == 'test'
>>> filter_dictionary({'arg': 'test'}, is_test)
'arg'
"""
if not callable(filter_func):
test_func = lambda x: x == filter_func
else:
test_func = filter_func
for key, value in dictionary.iteritems():
if test_func(value):
return key | f5fa77a51241323845eb9a59adc9df7f662f287b | 3,964 |
def spike_lmax(S, Q):
"""Maximum spike given a perturbation"""
S2 = S * S
return ((1.0 / Q) + S2) * (1 + (1.0 / S2)) | ba845e3255e4d3eb5116d279a209f4424062603b | 3,965 |
def _get_urls():
"""Stores the URLs for histology file downloads.
Returns
-------
dict
Dictionary with template names as keys and urls to the files as values.
"""
return {
"fsaverage": "https://box.bic.mni.mcgill.ca/s/znBp7Emls0mMW1a/download",
"fsaverage5": "https://box.bic.mni.mcgill.ca/s/N8zstvuRb4sNcSe/download",
"fs_LR_64k": "https://box.bic.mni.mcgill.ca/s/6zKHcg9xXu5inPR/download",
} | 697cf29b3caaeda079014fd342fbe7ad4c650d30 | 3,966 |
import struct
def guid_bytes_to_string(stream):
"""
Read a byte stream to parse as GUID
:ivar bytes stream: GUID in raw mode
:returns: GUID as a string
:rtype: str
"""
Data1 = struct.unpack("<I", stream[0:4])[0]
Data2 = struct.unpack("<H", stream[4:6])[0]
Data3 = struct.unpack("<H", stream[6:8])[0]
Data4 = stream[8:16]
return "%08x-%04x-%04x-%s-%s" % (Data1, Data2, Data3, "".join("%02x" % x for x in Data4[0:2]), "".join("%02x" % x for x in Data4[2:])) | 23f013b48806d1d2d4b4bec4ab4a5fcf6fc2e6b0 | 3,967 |
from typing import List
def two_loops(N: List[int]) -> List[int]:
"""Semi-dynamic programming approach using O(2n):
- Calculate the product of all items before item i
- Calculate the product of all items after item i
- For each item i, multiply the products for before and after i
L[i] = N[i-1] * L[i-1] if i != 0 else 1
R[j] = N[j+1] * R[j+1] if j != (len(N) - 1) else 1
A[i] = L[i] * R[i]
N[0] = 3
N[1] = 7
N[2] = 1
N[3] = 4
N[4] = 8
N[5] = 9
L[0] = 1 = 1
L[1] = (1) * 3 = 3
L[2] = (3) * 7 = 21
L[3] = (21) * 1 = 21
L[4] = (21) * 4 = 84
L[5] = (84) * 8 = 672
R[5] = 1 = 1
R[4] = (1) * 9 = 9
R[3] = (9) * 8 = 72
R[2] = (72) * 4 = 288
R[1] = (288) * 1 = 288
R[0] = (288) * 7 = 2016
A = [L[0]*R[0], L[1]*R[1], L[2]*R[2], L[3]*R[3], L[4]*R[4], L[5]*R[5]]
A = [2016, 864, 6048, 1512, 756, 672]
"""
items_len = len(N)
of_left = [1 for _ in range(items_len)]
of_right = [1 for _ in range(items_len)]
for i in range(items_len):
j = (items_len - 1) - i # Invert i; start counting from len(N) to 0.
of_left[i] = N[i-1] * of_left[i-1] if i != 0 else 1
of_right[j] = N[j+1] * of_right[j+1] if i != 0 else 1
return list(map(lambda p: p[0] * p[1], zip(of_left, of_right))) | 3620aa19833b2e967b2c295fa53ba39bf3b6b70d | 3,968 |
def rgb_to_hex(r, g, b):
"""Turn an RGB float tuple into a hex code.
Args:
r (float): R value
g (float): G value
b (float): B value
Returns:
str: A hex code (no #)
"""
r_int = round((r + 1.0) / 2 * 255)
g_int = round((g + 1.0) / 2 * 255)
b_int = round((b + 1.0) / 2 * 255)
r_txt = "%02x" % r_int
b_txt = "%02x" % b_int
g_txt = "%02x" % g_int
return r_txt + g_txt + b_txt | a5181c475c798bbd03020d81da10d8fbf86cc396 | 3,969 |
def odd(x):
"""True if x is odd."""
return (x & 1) | 9cd383ea01e0fed56f6df42648306cf2415f89e9 | 3,971 |
import glob
import os
def get_file_paths_by_pattern(pattern='*', folder=None):
"""Get a file path list matched given pattern.
Args:
pattern(str): a pattern to match files.
folder(str): searching folder.
Returns
(list of str): a list of matching paths.
Examples
>>> get_file_paths_by_pattern('*.png') # get all *.png files in folder
>>> get_file_paths_by_pattern('*rotate*') # get all files with 'rotate' in name
"""
if folder is None:
return glob.glob(pattern)
else:
return glob.glob(os.path.join(folder, pattern)) | 467485dd4b162654bd73cf412c93558fa43a5b8e | 3,972 |
import re
def remove_conjunction(conjunction: str, utterance: str) -> str:
"""Remove the specified conjunction from the utterance.
For example, remove the " and" left behind from extracting "1 hour" and "30 minutes"
from "for 1 hour and 30 minutes". Leaving it behind can confuse other intent
parsing logic.
Args:
conjunction: translated conjunction (like the word "and") to be
removed from utterance
utterance: Full request, e.g. "set a 30 second timer"
Returns:
The same utterance with any dashes replaced by spaces.
"""
pattern = r"\s\s{}".format(conjunction)
remaining_utterance = re.sub(pattern, "", utterance, flags=re.IGNORECASE)
return remaining_utterance | 67313565c7da2eadc4411854d6ee6cb467ee7159 | 3,973 |
def othertitles(hit):
"""Split a hit.Hit_def that contains multiple titles up, splitting out the hit ids from the titles."""
id_titles = hit.Hit_def.text.split('>')
titles = []
for t in id_titles[1:]:
fullid, title = t.split(' ', 1)
hitid, id = fullid.split('|', 2)[1:3]
titles.append(dict(id = id,
hitid = hitid,
fullid = fullid,
title = title))
return titles | fa5bbb47d26adbc61817e78e950e81cc05eca4a6 | 3,974 |
from typing import List
def read_plaintext_inputs(path: str) -> List[str]:
"""Read input texts from a plain text file where each line corresponds to one input"""
with open(path, 'r', encoding='utf8') as fh:
inputs = fh.read().splitlines()
print(f"Done loading {len(inputs)} inputs from file '{path}'")
return inputs | 27b00f4dfcdf4d76e04f08b6e74c062f2f7374d0 | 3,975 |
def distance_constraints_too_complex(wordConstraints):
"""
Decide if the constraints on the distances between pairs
of search terms are too complex, i. e. if there is no single word
that all pairs include. If the constraints are too complex
and the "distance requirements are strict" flag is set,
the query will find some invalid results, so further (slow)
post-filtering is needed.
"""
if wordConstraints is None or len(wordConstraints) <= 0:
return False
commonTerms = None
for wordPair in wordConstraints:
if commonTerms is None:
commonTerms = set(wordPair)
else:
commonTerms &= set(wordPair)
if len(commonTerms) <= 0:
return True
return False | 43429fd64dbf5fa118e2cbf1e381686e1a8518c9 | 3,976 |
def _file_path(ctx, val):
"""Return the path of the given file object.
Args:
ctx: The context.
val: The file object.
"""
return val.path | 7c930f2511a0950e29ffc327e85cf9b2b3077c02 | 3,977 |
def Mapping_Third(Writelines, ThirdClassDict):
"""
:param Writelines: 将要写入的apk的method
:param ThirdClassDict: 每一个APK对应的第三方的字典
:return: UpDateWritelines
"""
UpDateWriteLines = []
for l in Writelines:
if l.strip() in list(ThirdClassDict.keys()):
UpDateWriteLines.extend(ThirdClassDict[l.strip()])
else:
UpDateWriteLines.extend([l])
return UpDateWriteLines | eb94db36d06104007cbbacf8884cf6d45fee46b5 | 3,978 |
def total_angular_momentum(particles):
"""
Returns the total angular momentum of the particles set.
>>> from amuse.datamodel import Particles
>>> particles = Particles(2)
>>> particles.x = [-1.0, 1.0] | units.m
>>> particles.y = [0.0, 0.0] | units.m
>>> particles.z = [0.0, 0.0] | units.m
>>> particles.vx = [0.0, 0.0] | units.ms
>>> particles.vy = [-1.0, 1.0] | units.ms
>>> particles.vz = [0.0, 0.0] | units.ms
>>> particles.mass = [1.0, .5] | units.kg
>>> particles.total_angular_momentum()
quantity<[0.0, 0.0, 1.5] m**2 * kg * s**-1>
"""
# equivalent to:
# lx=(m*(y*vz-z*vy)).sum()
# ly=(m*(z*vx-x*vz)).sum()
# lz=(m*(x*vy-y*vx)).sum()
return (particles.mass.reshape((-1,1)) *particles.position.cross(particles.velocity)).sum(axis=0) | 8eca23b7b1a8fc8a7722543f9193f0e4a3397f24 | 3,979 |
def find_contiguous_set(target_sum: int, values: list[int]) -> list[int]:
"""Returns set of at least 2 contiguous values that add to target sum."""
i = 0
set_ = []
sum_ = 0
while sum_ <= target_sum:
sum_ += values[i]
set_.append(values[i])
if sum_ == target_sum and len(set_) >= 2:
return set_
i += 1
return [] | 64b6c1f99946856a33a79fed3d43395a5a9c1000 | 3,981 |
def move_character(character: dict, direction_index=None, available_directions=None) -> tuple:
"""
Change character's coordinates.
:param character: a dictionary
:param direction_index: a non-negative integer, optional
:param available_directions: a list of strings, optional
:precondition: character keys must contain "X-coordinate" and "Y-coordinate"
:precondition: character values must be integers
:precondition: direction_index must be a non-negative integer validated by validate_option function or None
:precondition: availabe_directions each item must be either "north", "south", "east" or "west", or None
:postcondition: updates character X or Y coordinate based on direction choice if availabe_directions is not None
:postcondition: makes character X or Y coordinate be equal to the previous coordinates
:return: new character's coordinates as a tuple
>>> protagonist = {"Y-coordinate": 1, "X-coordinate": 1, "Previous coordinates": (0, 1)}
>>> move_character(protagonist, 0, ["south", "west"])
(2, 1)
>>> protagonist = {"Y-coordinate": 1, "X-coordinate": 1, "Previous coordinates": (0, 1)}
>>> move_character(protagonist)
(0, 1)
"""
directions_dictionary = {"north": -1, "south": 1, "west": -1, "east": 1}
if available_directions is not None:
direction = available_directions[direction_index]
character["Previous coordinates"] = character["Y-coordinate"], character["X-coordinate"]
if direction in "north south":
character["Y-coordinate"] += directions_dictionary[direction]
else:
character["X-coordinate"] += directions_dictionary[direction]
else:
character["Y-coordinate"] = character["Previous coordinates"][0]
character["X-coordinate"] = character["Previous coordinates"][1]
return character["Y-coordinate"], character["X-coordinate"] | cc5cc3115437d0dc4e9b7ba7845565ee8147be30 | 3,982 |
def scrap_insta_description(inst) -> str:
"""
Scrap description from instagram account HTML.
"""
description = inst.body.div.section.main.div.header.section.find_all(
'div')[4].span.get_text()
return description | 898fa0d1cb44606374b131b8b471178a22ab74ed | 3,983 |
import six
import os
def file_size(f):
"""
Returns size of file in bytes.
"""
if isinstance(f, (six.string_types, six.text_type)):
return os.path.getsize(f)
else:
cur = f.tell()
f.seek(0, 2)
size = f.tell()
f.seek(cur)
return size | f999382958a972abbcf593c02e8e8e3609d8f44a | 3,984 |
def __get_from_imports(import_tuples):
""" Returns import names and fromlist
import_tuples are specified as
(name, fromlist, ispackage)
"""
from_imports = [(tup[0], tup[1]) for tup in import_tuples
if tup[1] is not None and len(tup[1]) > 0]
return from_imports | 28df8225ad9440386342c38657944cfe7ac3d3ca | 3,985 |
import logging
import os
import sys
def logger():
"""
Setting upp root and zeep logger
:return: root logger object
"""
root_logger = logging.getLogger()
level = logging.getLevelName(os.environ.get('logLevelDefault', 'INFO'))
root_logger.setLevel(level)
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setLevel(level)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
stream_handler.setFormatter(formatter)
root_logger.addHandler(stream_handler)
zeep_logger = logging.getLogger('proarc')
zeep = logging.getLevelName(os.environ.get('logLevelZeep', 'CRITICAL'))
zeep_logger.setLevel(zeep)
return root_logger | b7f3af5555eae953825c42aed18869deafa9f38d | 3,986 |
def some_function(t):
"""Another silly function."""
return t + " python" | 2bd8adc315e97409758f13b0f777ccd17eb4b820 | 3,987 |
import random
import hmac
def hash_password(password, salthex=None, reps=1000):
"""Compute secure (hash, salthex, reps) triplet for password.
The password string is required. The returned salthex and reps
must be saved and reused to hash any comparison password in
order for it to match the returned hash.
The salthex string will be chosen randomly if not provided, and
if provided must be an even-length string of hexadecimal
digits, recommended length 16 or
greater. E.g. salt="([0-9a-z][0-9a-z])*"
The reps integer must be 1 or greater and should be a
relatively large number (default 1000) to slow down brute-force
attacks."""
if not salthex:
salthex = ''.join([ "%02x" % random.randint(0, 0xFF)
for d in range(0,8) ])
salt = []
for p in range(0, len(salthex), 2):
salt.append(int(salthex[p:p+2], 16))
salt = bytes(salt)
if reps < 1:
reps = 1
msg = password.encode()
for r in range(0,reps):
msg = hmac.HMAC(salt, msg, digestmod='MD5').hexdigest().encode()
return (msg.decode(), salthex, reps) | cac468818560ed52b415157dde71d5416c34478c | 3,988 |
import argparse
def _parse_args():
"""
Parse arguments for the CLI
"""
parser = argparse.ArgumentParser()
parser.add_argument(
'--fovs',
type=str,
required=True,
help="Path to the fov data",
)
parser.add_argument(
'--exp',
type=str,
required=True,
help="Path to experiment file",
)
return parser.parse_args() | ecea45baba3c89e3fd81613a256c5be300e01051 | 3,989 |
def calculate_ani(blast_results, fragment_length):
"""
Takes the input of the blast results, and calculates the ANI versus the reference genome
"""
sum_identity = float(0)
number_hits = 0 # Number of hits that passed the criteria
total_aligned_bases = 0 # Total of DNA bases that passed the criteria
total_unaligned_fragments = 0
total_unaligned_bases = 0
conserved_dna_bases = 0
for query in blast_results:
identity = blast_results[query][2]
queryEnd = blast_results[query][7]
queryStart = blast_results[query][6]
perc_aln_length = (float(queryEnd) - float(queryStart)) / fragment_length[query]
if float(identity) > float(69.9999) and float(perc_aln_length) > float(0.69999):
sum_identity += float(identity)
number_hits += 1
total_aligned_bases += fragment_length[query]
else:
total_unaligned_fragments += 1
total_unaligned_bases += fragment_length[query]
if float(identity) > float(89.999):
conserved_dna_bases += fragment_length[query]
return sum_identity, number_hits, total_aligned_bases, total_unaligned_fragments, total_unaligned_bases | 09b649dda337d2b812f5c5fd9ec75b34737e3f15 | 3,992 |
def mixed_social_welfare(game, mix):
"""Returns the social welfare of a mixed strategy profile"""
return game.expected_payoffs(mix).dot(game.num_role_players) | 72c465211bdc79c9fcf2b1b9d8c7dd5abae5d8df | 3,993 |
def init_app(app):
"""init the flask application
:param app:
:return:
"""
return app | 6e460eb1fdc19553c6c4139e60db06daec507a2d | 3,995 |
def _rec_filter_to_info(line):
"""Move a DKFZBias filter to the INFO field, for a record.
"""
parts = line.rstrip().split("\t")
move_filters = {"bSeq": "strand", "bPcr": "damage"}
new_filters = []
bias_info = []
for f in parts[6].split(";"):
if f in move_filters:
bias_info.append(move_filters[f])
elif f not in ["."]:
new_filters.append(f)
if bias_info:
parts[7] += ";DKFZBias=%s" % ",".join(bias_info)
parts[6] = ";".join(new_filters or ["PASS"])
return "\t".join(parts) + "\n" | 496056126bdf390a6213dfad5c40c4a14ec35caa | 3,996 |
def classNumber(A):
""" Returns the number of transition classes in the matrix A """
cos = 0
if type(A[0][0]) == list:
cos = len(A)
else:
cos = 1
return cos | a71bce468f7429746bfe246d94f5dcebb85c41d4 | 3,997 |
def fix_CompanySize(r):
"""
Fix the CompanySize column
"""
if type(r.CompanySize) != str:
if r.Employment == "Independent contractor, freelancer, or self-employed":
r.CompanySize = "0 to 1 Employees"
elif r.Employment in [
"Not employed, but looking for work",
"full-time",
"Not employed, and not looking for work",
"part-time",
"Retired",
]:
r.CompanySize = "Not Applicable"
return r | bd34bb3e72920fb7ef37279a743198387b1c4717 | 3,998 |
def upper_camel_to_lower_camel(upper_camel: str) -> str:
"""convert upper camel case to lower camel case
Example:
CamelCase -> camelCase
:param upper_camel:
:return:
"""
return upper_camel[0].lower() + upper_camel[1:] | e731bbee45f5fc3d8e3e218837ccd36c00eff734 | 3,999 |
def get(isamAppliance, cert_dbase_id, check_mode=False, force=False):
"""
Get details of a certificate database
"""
return isamAppliance.invoke_get("Retrieving all current certificate database names",
"/isam/ssl_certificates/{0}/details".format(cert_dbase_id)) | 34ade7c42fcc1b1409b315f8748105ee99157986 | 4,000 |
import random
def t06_ManyGetPuts(C, pks, crypto, server):
"""Many clients upload many files and their contents are checked."""
clients = [C("c" + str(n)) for n in range(10)]
kvs = [{} for _ in range(10)]
for _ in range(200):
i = random.randint(0, 9)
uuid1 = "%08x" % random.randint(0, 100)
uuid2 = "%08x" % random.randint(0, 100)
clients[i].upload(str(uuid1), str(uuid2))
kvs[i][str(uuid1)] = str(uuid2)
good = total = 0
# verify integrity
for i, (c, kv) in enumerate(zip(clients, kvs)):
for k, v in kv.items():
vv = c.download(k)
if vv == v:
good += 1
total += 1
return float(good) / total | 384aa2b03169da613b25d2da60cdd1ec007aeed5 | 4,002 |
import xxhash
def hash_array(kmer):
"""Return a hash of a numpy array."""
return xxhash.xxh32_intdigest(kmer.tobytes()) | 9761316333fdd9f28e74c4f1975adfca1909f54a | 4,004 |
def PyCallable_Check(space, w_obj):
"""Determine if the object o is callable. Return 1 if the object is callable
and 0 otherwise. This function always succeeds."""
return int(space.is_true(space.callable(w_obj))) | e5b8ee9bbbdb0fe53d6fc7241d19f93f7ee8259a | 4,006 |
def idxs_of_duplicates(lst):
""" Returns the indices of duplicate values.
"""
idxs_of = dict({})
dup_idxs = []
for idx, value in enumerate(lst):
idxs_of.setdefault(value, []).append(idx)
for idxs in idxs_of.values():
if len(idxs) > 1:
dup_idxs.extend(idxs)
return dup_idxs | adc8a0b0223ac78f0c8a6edd3d60acfaf7ca4c04 | 4,007 |
def aslist(l):
"""Convenience function to wrap single items and lists, and return lists unchanged."""
if isinstance(l, list):
return l
else:
return [l] | 99ccef940229d806d27cb8e429da9c85c44fed07 | 4,008 |
import argparse
def get_args():
"""Parse command line arguments and return namespace object"""
parser = argparse.ArgumentParser(description='Transcode some files')
parser.add_argument('-c', action="store", dest="config", required=True)
parser.add_argument('-l', action="store", dest="limit", type=int, default=None)
parser.add_argument('-p', action="store", dest="processes", type=int)
parser.add_argument('-q', action="store_true", dest="quiet")
return parser.parse_args() | 8d811d1ff9437eef6fe5031618f9561248e40940 | 4,009 |
import os
def _write(info, directory, format, name_format):
"""
Writes the string info
Args:
directory (str): Path to the directory where to write
format (str): Output format
name_format (str): The file name
"""
#pylint: disable=redefined-builtin
file_name = name_format
file_path = os.path.join(
directory, f"{file_name}.{format}")
os.makedirs(os.path.dirname(file_path), exist_ok=True)
with open(file_path,'w',encoding='utf-8') as f:
f.write(info)
return file_path | c8f595769607151aa771b4d8d841b4beee77bc9e | 4,010 |
def enough_data(train_data, test_data, verbose=False):
"""Check if train and test sets have any elements."""
if train_data.empty:
if verbose:
print('Empty training data\n')
return False
if test_data.empty:
if verbose:
print('Empty testing data\n')
return False
return True | f11014d83379a5df84a67ee3b8f1e85b23c058f7 | 4,011 |
def compute_time_overlap(appointment1, appointment2):
"""
Compare two appointments on the same day
"""
assert appointment1.date_ == appointment2.date_
print("Checking for time overlap on \"{}\"...".
format(appointment1.date_))
print("Times to check: {}, {}".
format(appointment1.time_range_, appointment2.time_range_))
latest_start = max(appointment1.start_time_, appointment2.start_time_)
earliest_end = min(appointment1.end_time_, appointment2.end_time_)
delta = (earliest_end - latest_start).seconds
overlap = max(0, delta)
if overlap == 0:
print("No time overlap.")
return False
print("\033[93mFound time overlap.\033[0m")
return True | c459ef52d78bc8dd094d5be9c9f4f035c4f9fcaa | 4,012 |
import hashlib
def hash64(s):
"""Вычисляет хеш - 8 символов (64 бита)
"""
hex = hashlib.sha1(s.encode("utf-8")).hexdigest()
return "{:x}".format(int(hex, 16) % (10 ** 8)) | e35a367eac938fdb66584b52e1e8da59582fdb9a | 4,014 |
def inc(x):
""" Add one to the current value """
return x + 1 | c8f9a68fee2e8c1a1d66502ae99e42d6034b6b5c | 4,015 |
import os
import hashlib
def hash_file(filename):
"""
computes hash value of file contents, to simplify pytest assert statements for
complex test cases that output files. For cross-platform compatibility, make sure
files are read/written in binary, and use unix-style line endings, otherwise hashes
will not match despite content being same in ASCII.
Args:
filename
Returns:
hashnumber
"""
if os.path.isfile(filename) is False:
raise Exception("File not found for hash operation")
# open file for reading in binary mode
with open(filename, "rb") as file:
return hashlib.sha512(file.read()).hexdigest() | e26f92869a44c0e60fcd58764069b0c7828dee95 | 4,018 |
def predict_to_score(predicts, num_class):
"""
Checked: the last is for 0
===
Example: score=1.2, num_class=3 (for 0-2)
(0.8, 0.2, 0.0) * (1, 2, 0)
:param predicts:
:param num_class:
:return:
"""
scores = 0.
i = 0
while i < num_class:
scores += i * predicts[:, i - 1]
i += 1
return scores | ee4038583404f31bed42bed4eaf6d0c25684c0de | 4,019 |
import time
def offsetTimer():
"""
'Starts' a timer when called, returns a timer function that returns the
time in seconds elapsed since the timer was started
"""
start_time = time.monotonic()
def time_func():
return time.monotonic() - start_time
return time_func | 348105a408ccedd1fcb840b73d5a58dfd59dd8cc | 4,022 |
import os
def _get_sender(pusher_email):
"""Returns "From" address based on env config and default from."""
use_author = 'GITHUB_COMMIT_EMAILER_SEND_FROM_AUTHOR' in os.environ
if use_author:
sender = pusher_email
else:
sender = os.environ.get('GITHUB_COMMIT_EMAILER_SENDER')
return sender | 09167bfd09ff031d60b4ca033fbb0cad206393f9 | 4,023 |
from datetime import datetime
def parse_iso8601(dtstring: str) -> datetime:
"""naive parser for ISO8061 datetime strings,
Parameters
----------
dtstring
the datetime as string in one of two formats:
* ``2017-11-20T07:16:29+0000``
* ``2017-11-20T07:16:29Z``
"""
return datetime.strptime(
dtstring,
'%Y-%m-%dT%H:%M:%SZ' if len(dtstring) == 20 else '%Y-%m-%dT%H:%M:%S%z') | 415a4f3a9006109e31ea344cf99e885a3fd2738d | 4,026 |
def splinter_session_scoped_browser():
"""Make it test scoped."""
return False | a7587f6edff821bab3052dca73929201e98dcf56 | 4,028 |
def maskStats(wins, last_win, mask, maxLen):
"""
return a three-element list with the first element being the total proportion of the window that is masked,
the second element being a list of masked positions that are relative to the windown start=0 and the window end = window length,
and the third being the last window before breaking to expidite the next loop
"""
chrom = wins[0].split(":")[0]
a = wins[1]
L = wins[2]
b = a + L
prop = [0.0,[],0]
try:
for i in range(last_win, len(mask[chrom])):
x, y = mask[chrom][i][0], mask[chrom][i][1]
if y < a:
continue
if b < x:
return prop
else: # i.e. [a--b] and [x--y] overlap
if a >= x and b <= y:
return [1.0, [[0,maxLen]], i]
elif a >= x and b > y:
win_prop = (y-a)/float(b-a)
prop[0] += win_prop
prop[1].append([0,int(win_prop * maxLen)])
prop[2] = i
elif b <= y and a < x:
win_prop = (b-x)/float(b-a)
prop[0] += win_prop
prop[1].append([int((1-win_prop)*maxLen),maxLen])
prop[2] = i
else:
win_prop = (y-x)/float(b-a)
prop[0] += win_prop
prop[1].append([int(((x-a)/float(b-a))*maxLen), int(((y-a)/float(b-a))*maxLen)])
prop[2] = i
return prop
except KeyError:
return prop | b5d75d2e86f1b21bf35cbc69d360cd1639c5527b | 4,030 |
import re
def is_youtube_url(url: str) -> bool:
"""Checks if a string is a youtube url
Args:
url (str): youtube url
Returns:
bool: true of false
"""
match = re.match(r"^(https?\:\/\/)?(www\.youtube\.com|youtu\.be)\/.+$", url)
return bool(match) | 97536b8e7267fb5a72c68f242b3f5d6cbd1b9492 | 4,031 |
def time_nanosleep():
""" Delay for a number of seconds and nanoseconds"""
return NotImplementedError() | 9ec91f2ef2656b5a481425dc65dc9f81a07386c2 | 4,032 |
def item_len(item):
"""return length of the string format of item"""
return len(str(item)) | 7d68629a5c2ae664d267844fc90006a7f23df1ba | 4,033 |
def is_numeric(array):
"""Return False if any value in the array or list is not numeric
Note boolean values are taken as numeric"""
for i in array:
try:
float(i)
except ValueError:
return False
else:
return True | 2ab0bb3e6c35e859e54e435671b5525c6392f66c | 4,034 |
import platform
import os
def get_develop_directory():
"""
Return the develop directory
"""
if platform.system() == "Windows":
return os.path.dirname(os.path.realpath(__file__)) + "\\qibullet"
else:
return os.path.dirname(os.path.realpath(__file__)) + "/qibullet" | 5654b3c5b2417e8429a3ec2ca310567a185d78a1 | 4,036 |
def contains_message(response, message):
"""
Inspired by django's self.assertRaisesMessage
Useful for confirming the response contains the provided message,
"""
if len(response.context['messages']) != 1:
return False
full_message = str(list(response.context['messages'])[0])
return message in full_message | 4afcdba84603b8b53095a52e769d0a8e3f7bbb17 | 4,037 |
import re
def since(version):
"""A decorator that annotates a function to append the version
of skutil the function was added. This decorator is an adaptation of PySpark's.
Parameters
----------
version : str, float or int
The version the specified method was added to skutil.
Examples
--------
>>> @since('0.1.5')
... def some_fun():
... '''Some docstring'''
... return None
...
>>>
>>> some_fun.__doc__ # doctest: +SKIP
'Some docstring\n\n.. versionadded:: 0.1.5'
.. versionadded:: 0.1.5
"""
indent_p = re.compile(r'\n( +)')
def deco(f):
indents = indent_p.findall(f.__doc__)
indent = ' ' * (min(len(m) for m in indents) if indents else 0)
f.__doc__ = f.__doc__.rstrip() + "\n\n%s.. versionadded:: %s" % (indent, version)
return f
return deco | e6b29b5e4c67ba4a213b183a0b79a1f16a85d81c | 4,038 |
def striptag(tag):
"""
Get the short representation of a fully qualified tag
:param str tag: a (fully qualified or not) XML tag
"""
if tag.startswith('{'):
return tag.rsplit('}')[1]
return tag | f0193e3f792122ba8278e599247439a91139e72b | 4,039 |
def equal(* vals):
"""Returns True if all arguments are equal"""
if len(vals) < 2:
return True
a = vals[0]
for b in vals[1:]:
if a != b:
return False
return True | dbd947016d2b84faaaa7fefa6f35975da0a1b5ec | 4,041 |
def get_command(tool_xml):
"""Get command XML element from supplied XML root."""
root = tool_xml.getroot()
commands = root.findall("command")
command = None
if len(commands) == 1:
command = commands[0]
return command | 8d50b2675b3a6089b15b5380025ca7def9e4339e | 4,043 |
def get_elements(xmldoc, tag_name, attribute):
"""Returns a list of elements"""
l = []
for item in xmldoc.getElementsByTagName(tag_name) :
value = item.getAttribute(attribute)
l.append( repr( value ) )
return l | 2cda65802d0dc1ebbb7796f6a43fa9bacfbe852e | 4,044 |
import os
def get_tests_directory() -> str:
"""
Returns the path of the top level directory for tests.
Returns: The path of the top level directory for tests.
This is useful for constructing paths to the test files.
"""
module_file_path = os.path.abspath(__file__)
return os.path.dirname(module_file_path) | 35b445342ea6cf6c6f659118d32b0b8c9724a7e8 | 4,046 |
import re
def ParseTimeCommandResult(command_result):
"""Parse command result and get time elapsed.
Args:
command_result: The result after executing a remote time command.
Returns:
Time taken for the command.
"""
time_data = re.findall(r'real\s+(\d+)m(\d+.\d+)', command_result)
time_in_seconds = 60 * float(time_data[0][0]) + float(time_data[0][1])
return time_in_seconds | fc92d4b996716ddb2253bf4eb75ed9860c43b2d7 | 4,047 |
def getNumberOfPublicIp():
"""Get the total number of public IP
return: (long) Number of public IP
"""
#No need to calculate this constant everytime
return 3689020672
# Real implementation:
#ranges = getValidPublicIpRange()
#number_of_ip = 0
#for range in ranges:
# number_of_ip = number_of_ip + (range[1] - range[0] + 1)
#return number_of_ip | 79221376f64d0a44da06746bc28f0bb7db808b0f | 4,048 |
import socket
def check_reverse_lookup():
"""
Check if host fqdn resolves to current host ip
"""
try:
host_name = socket.gethostname().lower()
host_ip = socket.gethostbyname(host_name)
host_fqdn = socket.getfqdn().lower()
fqdn_ip = socket.gethostbyname(host_fqdn)
return host_ip == fqdn_ip
except socket.error:
pass
return False | 4979ba32d03782258f322ec86b2cd1c24fb4de2c | 4,049 |
def get_grains_connected_to_face(mesh, face_set, node_id_grain_lut):
"""
This function find the grain connected to the face set given as argument.
Three nodes on a grain boundary can all be intersected by one grain
in which case the grain face is on the boundary or by two grains. It
is therefore sufficient to look at the set of grains contained by any
three nodes in the face set and take the intersection of these sets.
:param mesh: The mesh
:type mesh: :class:`Mesh`
:param face_set: The face set to find grains connected to
:type: face_set: :class:`ElementSet`
:return: The grain identifiers that intersect the face.
:rtype: list of ints
"""
grains_connected_to_face = []
grains = face_set.name[4:].split("_")
if len(grains) == 2:
return [int(g) for g in grains]
triangle_element = mesh.elements[face_set.ids[0]]
for node_id in triangle_element.vertices:
grains_with_node_id = node_id_grain_lut[node_id]
grains_connected_to_face.append(set(grains_with_node_id))
return list(set.intersection(*grains_connected_to_face)) | cb4adff2d6ffe3c32e2a1fc8058e6ad1fed9b2c9 | 4,050 |
def argmin(x):
"""
Returns the index of the smallest element of the iterable `x`.
If two or more elements equal the minimum value, the index of the first
such element is returned.
>>> argmin([1, 3, 2, 0])
3
>>> argmin(abs(x) for x in range(-3, 4))
3
"""
argmin_ = None
min_ = None
for (nItem, item) in enumerate(x):
if (argmin_ is None) or (item < min_):
argmin_ = nItem
min_ = item
return argmin_ | 8d6778182bf3c18ffa6ef72093bf19a818d74911 | 4,051 |
def find_spot(entry, list):
"""
return index of entry in list
"""
for s, spot in enumerate(list):
if entry==spot:
return s
else:
raise ValueError("could not find entry: "+ str(entry)+ " in list: "+ str(list)) | e218822e5e56a62c40f5680751c1360c56f05f4a | 4,052 |
import os
def getPath(path=__file__):
"""
Get standard path from path. It supports ~ as home directory.
:param path: it can be to a folder or file. Default is __file__ or module's path.
If file exists it selects its folder.
:return: dirname (path to a folder)
.. note:: It is the same as os.path.dirname(os.path.abspath(path)).
"""
if path.startswith("~"):
path = os.path.expanduser("~") + path[1:]
if "." in path: # check extension
return os.path.dirname(os.path.abspath(path)) # just use os
else:
return os.path.abspath(path) | ef1a0997de2febea075b9ce44414c533806f6125 | 4,053 |
def geom_to_tuple(geom):
"""
Takes a lat/long point (or geom) from KCMO style csvs.
Returns (lat, long) tuple
"""
geom = geom[6:]
geom = geom.replace(" ", ", ")
return eval(geom) | 003f25a0ebc8fd372b63453e4782aa52c0ad697c | 4,054 |
import sys
def argumentParser(listOfArguments):
"""Parses arguments"""
argumentParserFilter = {}
for argument in listOfArguments:
if argument in sys.argv:
argumentParserFilter[listOfArguments[argument]] = True
else:
argumentParserFilter[listOfArguments[argument]] = False
return argumentParserFilter | 939cfea9c6b4f8deec08b4afb73427183b551ccc | 4,055 |
def get_reg_part(reg_doc):
"""
Depending on source, the CFR part number exists in different places. Fetch
it, wherever it is.
"""
potential_parts = []
potential_parts.extend(
# FR notice
node.attrib['PART'] for node in reg_doc.xpath('//REGTEXT'))
potential_parts.extend(
# e-CFR XML, under PART/EAR
node.text.replace('Pt.', '').strip()
for node in reg_doc.xpath('//PART/EAR')
if 'Pt.' in node.text)
potential_parts.extend(
# e-CFR XML, under FDSYS/HEADING
node.text.replace('PART', '').strip()
for node in reg_doc.xpath('//FDSYS/HEADING')
if 'PART' in node.text)
potential_parts.extend(
# e-CFR XML, under FDSYS/GRANULENUM
node.text.strip() for node in reg_doc.xpath('//FDSYS/GRANULENUM'))
potential_parts = [p for p in potential_parts if p.strip()]
if potential_parts:
return potential_parts[0] | 33f4c2bb9a4e2f404e7ef94a3bfe3707a3b1dd93 | 4,056 |
def my_join(x):
"""
:param x: -> the list desired to join
:return:
"""
return ''.join(x) | bffc33247926c2b1ebe1930700ed0ad9bcb483ec | 4,058 |
def template(spec_fn):
"""
>>> from Redy.Magic.Classic import template
>>> import operator
>>> class Point:
>>> def __init__(self, p):
>>> assert isinstance(p, tuple) and len(p) is 2
>>> self.x, self.y = p
>>> def some_metrics(p: Point):
>>> return p.x + 2 * p.y
>>> @template
>>> def comp_on_metrics(self: Point, another: Point, op):
>>> if not isinstance(another, Point):
>>> another = Point(another)
>>> return op(*map(some_metrics, (self, another)))
>>> class Space(Point):
>>> @comp_on_metrics(op=operator.lt)
>>> def __lt__(self, other):
>>> ...
>>> @comp_on_metrics(op=operator.eq)
>>> def __eq__(self, other):
>>> ...
>>> @comp_on_metrics(op=operator.gt)
>>> def __gt__(self, other):
>>> ...
>>> @comp_on_metrics(op=operator.le)
>>> def __le__(self, other):
>>> ...
>>> @comp_on_metrics(op=operator.ge)
>>> def __ge__(self, other):
>>> ...
>>> p = Space((0, 1))
>>> p > (1, 2)
>>> p < (3, 4)
>>> p >= (5, 6)
>>> p <= (7, 8)
>>> p == (9, 10)
"""
def specify(*spec_args, **spec_kwds):
def call(_):
def inner(*args, **kwds):
return spec_fn(*spec_args, *args, **spec_kwds, **kwds)
return inner
return call
return specify | a8fd64926cdbec73c1a31c20a27174c86af3405e | 4,060 |
def iou_set(set1, set2):
"""Calculate iou_set """
union = set1.union(set2)
return len(set1.intersection(set2)) / len(union) if union else 0 | f0087b640e8b9a87167d7e2b645aca3c565e09c1 | 4,061 |
import time
def time_measured(fkt):
"""
Decorator to measure execution time of a function
It prints out the measured time
Parameters
----------
fkt : function
function that shall be measured
Returns
-------
None
"""
def fkt_wrapper(*args, **kwargs):
t1 = time.time()
return_vals = fkt(*args, **kwargs)
t2 = time.time()
print("Job needed: {} seconds".format(t2-t1))
return return_vals
return fkt_wrapper | 43fe9fa24fdd27f15e988f5997424dd91f7d92c9 | 4,062 |
def test_find_codon(find_codon):
"""
A function to test another function that looks for a codon within
a coding sequence.
"""
synapto_nuc = ("ATGGAGAACAACGAAGCCCCCTCCCCCTCGGGATCCAACAACAACGAGAACAACAATGCAGCCCAGAAGA"
"AGCTGCAGCAGACCCAAGCCAAGGTGGACGAGGTGGTCGGGATTATGCGTGTGAACGTGGAGAAGGTCCT"
"GGAGCGGGACCAGAAGCTATCGGAACTGGGCGAGCGTGCGGATCAGCTGGAGCAGGGAGCATCCCAGTTC"
"GAGCAGCAGGCCGGCAAGCTGAAGCGCAAGCAATGGTGGGCCAACATGAAGATGATGATCATTCTGGGCG"
"TGATAGCCGTTGTGCTGCTCATCATCGTTCTGGTGTCGCTTTTCAATTGA")
assert find_codon('ATG', synapto_nuc) == 0
assert find_codon('AAT', synapto_nuc) == 54
assert find_codon('TGT', synapto_nuc) == -1
assert find_codon('TGC', synapto_nuc) == -1
return None | 1e8906441d7812fbaefd7688a1c02876210ba8b8 | 4,063 |
def compose_paths(path_0, path_1):
"""
The binary representation of a path is a 1 (which means "stop"), followed by the
path as binary digits, where 0 is "left" and 1 is "right".
Look at the diagram at the top for these examples.
Example: 9 = 0b1001, so right, left, left
Example: 10 = 0b1010, so left, right, left
How it works: we write both numbers as binary. We ignore the terminal in path_0, since it's
not the terminating condition anymore. We shift path_1 enough places to OR in the rest of path_0.
Example: path_0 = 9 = 0b1001, path_1 = 10 = 0b1010.
Shift path_1 three places (so there is room for 0b001) to 0b1010000.
Then OR in 0b001 to yield 0b1010001 = 81, which is right, left, left, left, right, left.
"""
mask = 1
temp_path = path_0
while temp_path > 1:
path_1 <<= 1
mask <<= 1
temp_path >>= 1
mask -= 1
path = path_1 | (path_0 & mask)
return path | cffb984c5bacf16691648e0910988495149087ad | 4,065 |
def group_masses(ip, dm: float = 0.25):
"""
Groups masses in an isotope pattern looking for differences in m/z greater than the specified delta.
expects
:param ip: a paired list of [[mz values],[intensity values]]
:param dm: Delta for looking +/- within
:return: blocks grouped by central mass
:rtype: list
"""
num = 0
out = [[[], []]]
for ind, val in enumerate(ip[0]):
out[num][0].append(ip[0][ind])
out[num][1].append(ip[1][ind])
try:
if ip[0][ind + 1] - ip[0][ind] > dm:
num += 1
out.append([[], []])
except IndexError:
continue
return out | 918fc4f20fee7c2955218e3c435f9e672dc55f7d | 4,066 |
import os
def get_compliment(file_list, file):
"""Returns a file path from the provided list that has the same name as the
file passed as the second arugment.
:param file_list: A list of paths with the same filetype.
:type file_list: list
:param file: A single path with an opposite filetype.
:type file: str
:return: A file path
:return type: str, None if nothing found
"""
compliment = os.path.splitext(file)[0]
for path in file_list:
if os.path.splitext(path)[0] == compliment:
return path | 9841207dc2ead05a1fde42baeea72e05323fb6ea | 4,067 |
def load_string_list(file_path, is_utf8=False):
"""
Load string list from mitok file
"""
try:
with open(file_path, encoding='latin-1') as f:
if f is None:
return None
l = []
for item in f:
item = item.strip()
if len(item) == 0:
continue
l.append(item)
except IOError:
print('open error %s' % file_path)
return None
else:
return l | 600c2678fdcdf6d5fa4894dd406f74c1ae4e5a96 | 4,068 |
import math
def point_based_matching(point_pairs):
"""
This function is based on the paper "Robot Pose Estimation in Unknown Environments by Matching 2D Range Scans"
by F. Lu and E. Milios.
:param point_pairs: the matched point pairs [((x1, y1), (x1', y1')), ..., ((xi, yi), (xi', yi')), ...]
:return: the rotation angle and the 2D translation (x, y) to be applied for matching the given pairs of points
"""
x_mean = 0
y_mean = 0
xp_mean = 0
yp_mean = 0
n = len(point_pairs)
if n == 0:
return None, None, None
for pair in point_pairs:
(x, y), (xp, yp) = pair
x_mean += x
y_mean += y
xp_mean += xp
yp_mean += yp
x_mean /= n
y_mean /= n
xp_mean /= n
yp_mean /= n
s_x_xp = 0
s_y_yp = 0
s_x_yp = 0
s_y_xp = 0
for pair in point_pairs:
(x, y), (xp, yp) = pair
s_x_xp += (x - x_mean)*(xp - xp_mean)
s_y_yp += (y - y_mean)*(yp - yp_mean)
s_x_yp += (x - x_mean)*(yp - yp_mean)
s_y_xp += (y - y_mean)*(xp - xp_mean)
rot_angle = math.atan2(s_x_yp - s_y_xp, s_x_xp + s_y_yp)
translation_x = xp_mean - (x_mean*math.cos(rot_angle) - y_mean*math.sin(rot_angle))
translation_y = yp_mean - (x_mean*math.sin(rot_angle) + y_mean*math.cos(rot_angle))
return rot_angle, translation_x, translation_y | 2d691bbf04d14e3e5b0f9273a7501d934bd0eef4 | 4,069 |
def bind_port(socket, ip, port):
""" Binds the specified ZMQ socket. If the port is zero, a random port is
chosen. Returns the port that was bound.
"""
connection = 'tcp://%s' % ip
if port <= 0:
port = socket.bind_to_random_port(connection)
else:
connection += ':%i' % port
socket.bind(connection)
return port | 5613bae6726e2f006706b104463917e48d7ab7ca | 4,071 |
def update_target_graph(actor_tvars, target_tvars, tau):
""" Updates the variables of the target graph using the variable values from the actor, following the DDQN update
equation. """
op_holder = list()
# .assign() is performed on target graph variables with discounted actor graph variable values
for idx, variable in enumerate(target_tvars):
op_holder.append(
target_tvars[idx].assign(
(variable.value() * tau) + ((1 - tau) * actor_tvars[idx].value())
)
)
return op_holder | 15f0d192ff150c0a39495b0dec53f18a8ae01664 | 4,072 |
def strtime(millsec, form="%i:%02i:%06.3f"):
"""
Time formating function
Args:
millsec(int): Number of milliseconds to format
Returns:
(string)Formated string
"""
fc = form.count("%")
days, milliseconds = divmod(millsec, 86400000)
hours, milliseconds = divmod(millsec, 3600000)
minutes, milliseconds = divmod(millsec, 60000)
seconds = float(milliseconds) / 1000
var = {1: (seconds), 2: (minutes, seconds), 3: (hours, minutes, seconds),
4: (days, hours, minutes, seconds)}
return form % var[fc] | 9a1cff92086491941d8b27857169bf7744da8324 | 4,073 |
import argparse
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser(description='Run train or eval scripts for Gated2Depth')
parser.add_argument("--base_dir", help="Path to dataset", required=True)
parser.add_argument("--train_files_path", help="Path to file with train file names", required=False)
parser.add_argument("--eval_files_path",
help="Path to file with validation/evaluation file names. Required if running both in train and eval mode",
required=True)
parser.add_argument("--data_type", choices=['real', 'synthetic'], help="[real|synthetic].", default='real',
required=True)
parser.add_argument("--results_dir", help="Path to results directory (train or eval)",
default='gated2depth_results', required=False)
parser.add_argument("--model_dir", help="Path to model directory",
default='gated2depth model', required=False)
parser.add_argument("--exported_disc_path", help="Path to exported discriminator. Used to train "
"a generator with a pre-trained discriminator",
default=None, required=False)
parser.add_argument("--mode", choices=['train', 'eval'], help="[train/eval]",
default='train', required=False)
parser.add_argument('--use_multiscale', help='Use multiscale loss function',
action='store_true', required=False)
parser.add_argument('--smooth_weight', type=float, help='Smoothing loss weight',
default=0.5, required=False)
parser.add_argument('--adv_weight', type=float, help='Adversarial loss weight',
default=0., required=False)
parser.add_argument('--lrate', type=float, help='Learning rate',
default=0.0001, required=False)
parser.add_argument('--min_distance', type=float, help='minimum distance',
default=3., required=False)
parser.add_argument('--max_distance', type=float, help='maximum distance',
default=150., required=False)
parser.add_argument('--use_3dconv', help='Use 3D convolutions architecture',
action='store_true', required=False)
parser.add_argument('--gpu', dest='gpu', help='GPU id', default='0', required=False)
parser.add_argument('--num_epochs', type=int, dest='num_epochs',
help='Number of training epochs', default=2)
parser.add_argument('--show_result', help='Show result image during evaluation',
action='store_true', required=False)
args = parser.parse_args()
return args | afb3f6d55b87c917225811f3716b9ecf1fcb494e | 4,074 |
def plugin_last():
"""This function should sort after other plug-in functions"""
return "last" | d2d6c00bc8d987363bd4db0013950d9b3f524c2f | 4,075 |
def extract_shebang_command(handle):
"""
Extract the shebang_ command line from an executable script.
:param handle: A file-like object (assumed to contain an executable).
:returns: The command in the shebang_ line (a string).
The seek position is expected to be at the start of the file and will be
reset afterwards, before this function returns. It is not an error if the
executable contains binary data.
.. _shebang: https://en.wikipedia.org/wiki/Shebang_(Unix)
"""
try:
if handle.read(2) == b'#!':
data = handle.readline()
text = data.decode('UTF-8')
return text.strip()
else:
return ''
finally:
handle.seek(0) | 27174f96f2da3167cf7a7e28c4a2f1cec72c773c | 4,076 |
import json
def clone_master_track(obj, stdata, stindex, stduration):
"""
ghetto-clone ('deep copy') an object using JSON
populate subtrack info from CUE sheet
"""
newsong = json.loads(json.dumps(obj))
newsong['subsong'] = {'index': stindex, 'start_time': stdata['index'][1][0], 'duration': stduration}
newsong['tags']['artist'] = stdata.get('PERFORMER', newsong['tags'].get('artist'))
newsong['tags']['title'] = stdata.get('TITLE', newsong['tags'].get('title'))
newsong['tags']['tracknum'] = stindex
newsong['tags']['trackstr'] = stindex
return newsong | 6721a87abfc88d9dd75f597ff24caf5857be594a | 4,077 |
def create_graph(num_islands, bridge_config):
"""
Helper function to create graph using adjacency list implementation
"""
adjacency_list = [list() for _ in range(num_islands + 1)]
for config in bridge_config:
source = config[0]
destination = config[1]
cost = config[2]
adjacency_list[source].append((destination, cost))
adjacency_list[destination].append((source, cost))
#print("adjacency_list",adjacency_list)
return adjacency_list | b961f5ee2955f4b8de640152981a7cede8ca80b0 | 4,078 |