content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from datetime import datetime
def datetime_fromisoformat(datestr: str):
"""Convert iso formatted datetime string to datetime object
This is only needed for compatibility, as datetime.fromisoformat()
was added in Python 3.7
"""
return datetime.strptime(datestr, "%Y-%m-%dT%H:%M:%S") | f912313eeeeae68bb1e2c85251fd118e3d0b6869 | 631,720 |
import re
def sanitize_results_filename(filename: str) -> str:
"""Sanitizes results file name.
Args:
filename: original filename
Returns:
sanitized filename
"""
return re.sub(r'[^\w\-\=]+', '_', filename) | 4641e8cd997df2917d4e269710a7ade2d2d636e5 | 631,721 |
import functools
import warnings
def Deprecated(message):
"""Returns a decorator with a given warning message."""
def Decorator(func):
"""Emits a deprecation warning when the decorated function is called.
Also adds the deprecation message to the function's docstring.
Args:
func: The function ... | 8a3ad3656f7c14aaa5cb8e229192ca15539055f5 | 631,722 |
import click
def get_checkpoint_by_class(db, class_path):
"""Returns checkpoint entry in `db` indicated by `class_path`.
Parameters
----------
class_path : str
Fully specified path to class (e.g. `terran.pose.openpose.OpenPose`)
of the model to get the checkpoint for.
Returns
... | e54fb99a9187394261710ae97402275c144a12e2 | 631,723 |
def distinct_powers(a, b):
"""Generate distinct terms in a**b"""
numbers = []
for i in range(a[0], a[1]+1):
for j in range(b[0], b[1]+1):
numbers.append(i**j)
# Set makes it the numbers values unique
return set(numbers) | 85b53a3d2c0e9b5199302aafb36e556ee79ec26e | 631,724 |
def get_network_bits(mask_binary):
"""
Returns number of network bits of given mask
:param mask_binary: Subnet Mask in binary
:return: Number of network bits
"""
count = 0
for i in mask_binary:
if int(i) == 1:
count += 1
return count | 858e01acc08a6383ca58af48b285e2f56fab60fe | 631,725 |
def request_authorized(request) -> bool:
"""Return ``true`` if ``request`` was authorized using :py:func:`authorize`."""
return getattr(request, "_oso_authorized", False) | 47bcb35c2450c4bb40611b9ede28609b5788ff83 | 631,727 |
def parse_file_name(file_name):
"""
Parse the filenames
VIS - ANN_XXXYY_Z_VI_fMM
The images has the following pattern
ANN_XXXYY_Z_VI_fMM like this example (A01_IOD87_B_VI_f01.png) where:
- NN is the client id
- XXXYY means inter-ocular distance (XXX) and distance (YY)
- Z is the co... | 19a5740cb4732661baa8bc08459d23ca88f3fa2c | 631,728 |
import unicodedata
def unicode_name(char, no_name=''):
"""Unicode registered name."""
names = []
for c in char:
try:
names.append(unicodedata.name(c))
except ValueError:
names.append(no_name)
return ', '.join(names) | 6a5c6c29b0c1e249b761415044510203ef45119b | 631,730 |
import os
def get_folder_and_file_name (file_path ):
"""Extracts folder and base name of a cloud"""
# extract the folder
cloud_folder = str(file_path.split ('/')[-2])
# extract the name of the cloud and split it by it's attributes, or tags
list_of_cloud_tags = os.path.basename(file_path.strip ('... | 69aa2f86b296f9a2c3bf4deaccd627c72113b058 | 631,732 |
def get_radolan_header_token():
"""Return array with known header token of radolan composites
Returns
-------
head : dict
with known header token, value set to None
"""
head = {'BY': None, 'VS': None, 'SW': None, 'PR': None,
'INT': None, 'GP': None, 'MS': None, 'LV': None,
... | 57fd05f83537a80d65f03a76ff3b4d961e56063b | 631,733 |
def encodeWord(word: str, isNormalVersionForLogicallyThinkingHuman: bool) -> str:
"""Encode single word into its numerical representation in given system (e.g. "koko" -> "3131")"""
map1 = {1:['w', 'e', 'r', 'u', 'i', 'o', 'a', 's', 'z', 'x', 'c', 'v', 'n', 'm', 'ę', 'ó', 'ą', 'ś', 'ń', 'ć', 'ż', 'ź'],
2: [... | 02da1f692bbfc7d50383d190a905d4a4d1595fef | 631,735 |
def get_durations(bpm):
"""
Function that generate a dictionary containing
the duration in seconds of various rhythmic figures.
:param bpm: beat per minutes
:return: rhythmic dictionary
"""
beat_time = 60 / bpm
return {
'1': beat_time * 4,
'2': beat_time * 2,
'4'... | 6844858f039064c29a76870a8b1af50b9e22e012 | 631,736 |
import json
def config_loader(json_input):
"""generic json parsers"""
json_file = open(json_input, 'r+')
return json.load(json_file) | d635880ddc63c25a6be124ea303e763e96cd58ac | 631,737 |
def fibonacci_by_index(index: int):
"""
Get the value at the index of the Fibonacci series.
Austin W. Milne @awbmilne <austin.milne@uwaterloo.ca>
Parameters
----------
index: number
The index of the Fibonacci series to return.
Returns
-------
The value from the Fibonacci ... | cc6608fb23ab95eccc67bc73665a35fbc519fc33 | 631,738 |
import sys
def __cmd_to_func(cmd):
""" Returns the function object in this module matching cmd. """
fiss_module = sys.modules[__name__]
# Returns None if string is not a recognized FISS command
func = getattr(fiss_module, cmd, None)
if func and not hasattr(func, 'fiss_cmd'):
func = None
... | 2e0aca69cf97de20e33d7632b2884264068fcca6 | 631,739 |
def _before_each(separator, iterable):
"""Inserts `separator` before each item in `iterable`.
Args:
separator: The value to insert before each item in `iterable`.
iterable: The list into which to intersperse the separator.
Returns:
A new list with `separator` before each item in `iterabl... | 9b3abe45d1c2f7c38e6999f25758a3b610dc374b | 631,740 |
def response_plain_text(output, endsession):
""" create a simple json plain text response """
return {
'outputSpeech': {
'type': 'PlainText',
'text': output
},
'shouldEndSession': endsession
} | 9de8be28e8cd65e3e2185352f1aed6aafb16c1e3 | 631,741 |
import requests
def cctop_submit(seq_str):
"""Submit a protein sequence string to CCTOP and return the job ID.
Args:
seq_str (str): Protein sequence as a string
Returns:
dict: Job ID on the CCTOP server
"""
url = 'http://cctop.enzim.ttk.mta.hu/php/submit.php?sequence={}&tmFilter... | 2dd023f8713326ab0a8bdcaadb2bd2c87eeebaf4 | 631,742 |
def part_a(puzzle_input):
"""
Calculate the answer for part_a.
We need to build a list since we do not know where 2017 will end up.
Args:
puzzle_input (list): Formatted as the provided input from the website.
Returns:
string: The answer for part_a.
"""
steps = int(''.join(... | 1575a5bac24f79131278d18ae71c29b266c1c2e6 | 631,743 |
import sys
import importlib
def _get_module(module_name):
"""
Gets a module by its name
:param module_name: Name of the module
:return: The loaded module
"""
the_module = sys.modules.get(module_name)
if the_module is None:
the_module = importlib.import_module(module_name)
retur... | a3758cac224893ca2fafeb2b8346b19722d5f946 | 631,744 |
def is_equivalent(object_list_1, object_list_2):
""" docstring tbd """
# Check if all of list 1 is equivalent with members of list 2
list_1_equivalence = {}
for list_1_object in object_list_1:
list_1_equivalence[list_1_object] = False
for list_2_object in object_list_2:
if ... | a4ae9a1c29158836683b0a9afa84866702de30bd | 631,745 |
import os
def list_dir(directory, is_absolute=True):
"""
List file names in directory
:param directory: Path of directory
:param is_absolute: If true returns complete path, else returns just the file/folder name
:return: List of file/folder names
"""
return [os.path.join(directory, f) if is_absolute els... | 0b196590c2f4540682682f430fa8a024aea72cf0 | 631,746 |
import os
def is_file_in(path, name):
"""Whether that name is a file in the directory at that path"""
path_to_name = os.path.join(path, name)
return os.path.isfile(path_to_name) | 8ab946c9cc3bca0b45b162a2919301d57c66eb1e | 631,747 |
import json
def get_param_as_float(filepath, param_name):
"""
Extracts parameter as float from json file. Does not check existance, misuse may lead to exceptions.
Call has_param first.
:param string filepath: path to json file
:param string param_name: keyword used for parameter in json file.
... | eb000503dbab217a7e95d1bf0ebda18ae67467de | 631,748 |
def hr_size(num, suffix="B") -> str:
"""
Human-readable data size
From https://stackoverflow.com/a/1094933
:param num: number of bytes
:param suffix: Optional size specifier
:return: Formatted string
"""
for unit in " KMGTPEZ":
if abs(num) < 1024.0:
return "%3.1f%s%s"... | 832ab92f3360617653856db98e36d38a30031df4 | 631,749 |
import json
def write_log_file(s3_client, bucket, logging_key, model_name):
"""Write the model used to generate the predictions to the logging path. This provides insight into which
model version was used to generate predictions on a given date"""
json_data = {"model_name": model_name}
log_file = 'tr... | 6e7b4db6cba4770ab20729ad25d69be148e18b6b | 631,750 |
import json
def metadata_dict_to_json(clean_metadata_dict):
"""
Returns structured JSON from input dictionary
---------------------------------------------
input: dictionary of file metadata
output: clean metadata json
"""
clean_metadata_json = json.dumps(clean_metadata_dict)
return c... | 87f0628c15ee10a64bc8ed2201dece73ed1cd828 | 631,751 |
def template_url(
url_template: str,
state_machine_name: str,
label: str,
) -> str:
"""
Templates a URL for an external service.
Adds the label and state machine to a url that contains placeholders in the
format `<label>` or '<state_machine>'.
"""
return url_template.replace(
... | 5358249abdf3e9480a9618fba2721c077123cb34 | 631,753 |
def convert_to_none(value):
"""Attempts to convert the passed in < value > to < None > if it matches any of the following
strings: "n/a", "N/A", "none", "None", "unknown" "Unknown" (i.e., a case-insensitive check).
If no match is obtained or an exception is encountered the < value > is returned unchanged.
... | eefd09bba6e1040b7357539aeff2ae3c814d184d | 631,754 |
import torch
def one_hot(labels, max_label=None):
"""Transform long labels into one-hot format.
Args:
labels: An N-D long tensor.
Returns:
An (N+1)-D long tensor.
"""
if max_label is None:
max_label = labels.max() + 1
shape = labels.shape
labels = labels.view(-1, 1)
one_hot_labels = tor... | 288b4ed66a3ac643054395085ddaa3a34a952561 | 631,755 |
import re
def camel_case_to_underscore(name):
"""
This function camel_case_to_underscores a Camel Case word to a underscore word
"""
temp = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', temp).lower() | 9bb977cc9aa99807ac3b31b3001705298d50aab4 | 631,756 |
def _is_not_lparen_and_rparen(lparens, rtok):
"""Tests if an RPAREN token is matched with something other than a plain old
LPAREN type.
"""
# note that any([]) is False, so this covers len(lparens) == 0
return rtok.type == "RPAREN" and any(x != "LPAREN" for x in lparens) | 60537fcf449bdfdf921eb6978cdbb63d873485b2 | 631,757 |
def undunder_keys(_dict):
"""Returns dict with the dunder keys converted back to nested dicts
eg::
>>> undunder_keys({'a': 'hello', 'b__c': 'world'})
{'a': 'hello', 'b': {'c': 'world'}}
:param _dict : (dict) flat dict
:rtype : (dict) nested dict
"""
def f(key, value):
... | ecbc1333e6d4610643c107327dc9833d1cfa1a5e | 631,759 |
def klGauss(x, y, sig2 = 1.):
"""Kullback-Leibler divergence for Gaussian distributions."""
return (x-y)*(x-y)/(2*sig2) | 46b0b26e0f6827257bf333c51b826a362e031cd2 | 631,760 |
def cw(u, v):
"""
Returns True if v is to the right of u, that is,
the shortest rotation from u to v is cw, turn right
False otherwise
"""
return ((u[0] * v[1] - u[1] * v[0]) < 0) | 65e6227706687de134b9abd515bd39c82d8853da | 631,762 |
def total_seconds(td):
"""
Return the total number of seconds contained in the duration as a float
"""
return (float(td.microseconds) + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6 | 1b1acde5ef2c7da1c36d6066db0f20e53f9e1d3b | 631,763 |
def sum_digits(n):
"""Sum all the digits of n.
>>> sum_digits(10) # 1 + 0 = 1
1
>>> sum_digits(4224) # 4 + 2 + 2 + 4 = 12
12
>>> sum_digits(1234567890)
45
"""
sum = 0
while n > 0:
sum += n%10 # mod will give the last digit
n = n//10 #removes last digit
return... | a598536e68b0bd23ca1fa5c6cd40916700022b51 | 631,764 |
def getChunkPartition(chunk_id):
""" return partition (if any) for the given chunk id.
Parition is encoded in digits after the initial 'c' character.
E.g. for: c56-12345678-1234-1234-1234-1234567890ab_6_4, the
partition would be 56.
For c-12345678-1234-1234-1234-1234567890ab_6_4, the
partition ... | 461ebdd552ad6881a6f4566b0d40399656720fcd | 631,765 |
def str_dict(d):
"""
Convert dict to key=value, key=value, .... string
:type d: dict
:rtype: str
"""
return ", ".join("%s=%s" % (k, d[k]) for k in d) | d72cee9ca9d51c62c81beea4e9f84f8b42ea5c22 | 631,766 |
import pickle
def pickle_stream(sklearn_model):
"""Returns a byte stream containing a pickled Scikit-Learn model """
return pickle.dumps(sklearn_model) | fbbb5ad74f830179e1a380d0d1d03886ef9ebba5 | 631,767 |
import json
import requests
def add_role_to_cloudcheckr(env, admin_api_key, account_name, role_arn):
"""
Uses the cross-account role created by the cloud formation stack to add it to CloudCheckr.
Uses the edit_credential Admin API call.
"""
if role_arn is None:
print("Role Arn from Cloudformation stack was no... | 03ee4511e8894ccbe4418e216379a0194b35bbf5 | 631,771 |
def get_duplicates(iterable):
"""Return a set of the elements which appear multiple times in iterable."""
seen, duplicates = set(), set()
for elem in iterable:
if elem in seen:
duplicates.add(elem)
else:
seen.add(elem)
return duplicates | 7e14f37a3819c6d7fe28c577173ba91aae2b687f | 631,773 |
def make_answer(df_exc, invcf_dict, bed_dict, sample_list):
"""
Making final result.
"""
def distinct_nm(cap_nm, vcf_nm):
"""
Comparing cap-pt nm and vcf nm,
then sorting out them by NM-matching into one of three types
: whole match(2) or partial match(1) or unmatch(0)
... | c6fef577b5765115d93347ae5c2834a1009122a7 | 631,774 |
def latlonbox(imrange):
""" generate kml latlonbox """
#<north>%s</north>
#<south>%s</south>
#<west>%s</west>
#<east>%s</east>
[lon0,lon1,lat0,lat1] = imrange
north = "<north>%s</north>" % str(lat1)
south = "<south>%s</south>" % str(lat0)
west = "<west>%s</west>" % str(lon0)
ea... | 12b8709d7512787ad06d3523d3742f2ed1c0896d | 631,775 |
from pathlib import Path
import re
def namelist_exists(fn: Path, nml: str) -> bool:
"""
Determines if a namelist exists in a file.
Does not check for proper format / syntax.
"""
pat = re.compile(r"^\s*&(" + nml + ")$")
with fn.open("rt") as f:
for line in f:
if pat.match(... | f1746fe8426c3c7af821723e8e76227f5ef0595b | 631,776 |
def get_preactivation_tensors(layers):
"""Get all valid layers for computing saturation."""
dense_outputs = []
for layer in layers:
if 'dense' in layer.name:
if '_input' in layer.name:
# HACK
continue
# Get pre-activation
if hasattr... | edc6a0bb9e3c732b205734018a69a8cdcfea81d8 | 631,777 |
def Get_LonghurstProvinceName4Num(input):
"""
Get full Longhurst Province for given number
"""
LonghurstProvinceDict = {
'ALSK': 'AlaskaDownwellingCoastalProvince',
'ANTA': 'AntarcticProvince',
'APLR': 'AustralPolarProvince',
'ARAB': 'NWArabianUpwellingProvince',
... | 41d62524c22e8534c51e9c20521abaaa38e2bfd6 | 631,778 |
def byteswap(*arrays):
"""
Swapping of bytes for provided arrays.
Notes
-----
arr.newbyteorder('S') swaps dtype interpretation, but not bytes in memory
arr.byteswap() swaps bytes in memory, but not dtype interpretation
arr.byteswap(True).newbyteorder('S') completely swaps both
Referenc... | 1fa1c0662fe525c1575365c7bcde5cf9f9ab96b3 | 631,779 |
def deduplicate(stix_obj_list):
"""Deduplicate a list of STIX objects to a unique set.
Reduces a set of STIX objects to unique set by looking
at 'id' and 'modified' fields - as a unique object version
is determined by the combination of those fields
Note: Be aware, as can be seen in the implementa... | 5dde3ee3641610b6838b3553550b9dc7c317fef2 | 631,780 |
import os
def search_for_directories(storage, usernames):
"""Searches the storage for subdirectories created by one of given usernames and returns a list of
their respective absolute path.
:param usernames: The usernames to be looked after in self.mountpoint.
:return: the directories starting with a ... | 8814a8aa78ca82f5ed8bd6ea4d2f072831971065 | 631,781 |
def swap(arr, axis):
""" swap arr[axis] and arr[-1] """
return arr[:axis] + [arr[-1]] + arr[axis + 1 : -1] + [arr[axis]] | 7cae8b12fddac90f2d7a147f60a02339bb8da8c9 | 631,782 |
import sys
def intToByte(arg: int) -> bytes:
""" Convert an int (value < 256) to a single byte bytes object
"""
return arg.to_bytes(
length=1, # Will raise if value overflows, eg arg > 255
byteorder=sys.byteorder, # for a single byte big/little endian does not matter.
signed=False # Since this represents ... | ee5239a1f191434253e7280c1604e43bbda86820 | 631,783 |
def fix_label_lists(tsv_file_lst_lsts):
"""
complex and anchor_files have first element of complex labels
for an ID
this list is imported as one string and needs to be
list of integers, which is done in this function
output is dict with ID as key and labels as value
labels are ints
"""
... | bbf192b00a8c19928194c91f613466f38a85ac47 | 631,784 |
def _io_similar(lhs, rhs):
"""
Returns True if @lhs and @rhs have the same signature, false otherwise. Note
that this does not check the identity of the underlying ports, just their
names and types. That is, the following holds
args = dict(...)
x = IO(**args)
y = IO(**args)
... | 1955090f82b2a968592d46c442ff976a6824a91f | 631,785 |
from typing import List
def read_txt_file(txt_fpath: str, strip_newlines: bool = False) -> List[str]:
"""
Args:
- txt_fpath: string representing path to txt file
Returns:
- txt_lines: list of strings, one per line of file
"""
with open(txt_fpath, "r") as f:
txt_lines = f.readlines... | 577259c5f9de13232f8e86ef953ae5356c572acc | 631,787 |
def num_bytes(byte_tmpl):
"""Given a list of raw bytes and template strings, calculate the total number
of bytes that the final output will have.
Assumes all template strings are replaced by 8 bytes.
>>> num_bytes([0x127, "prog_bytes"])
9
"""
total = 0
for b in byte_tmpl:
if i... | 390e74b214bb29925d5273c1685c03d9cbca9714 | 631,788 |
def table_name(request):
"""Various ways to represent a table in Tableau."""
return request.param | 21d57e1b993dddb6442440d4c7b773faf0a40d82 | 631,790 |
import numpy
def _(shape: numpy.ndarray):
"""
If a shape is an array of points, compute the minima/maxima
or let it pass through if it's 1 dimensional & length 4
"""
if (shape.ndim == 1) & (len(shape) == 4):
return shape
return numpy.array([*shape.min(axis=0), *shape.max(axis=0)]) | c8a0ae7470d7c2c7295ec717c1d7a5412f757827 | 631,791 |
from typing import List
def remove_duplicates_and_blank(hyp: List[int]) -> List[int]:
"""
remove duplicates and blank
"""
new_hyp: List[int] = []
cur = 0
while cur < len(hyp):
if hyp[cur] != 0:
new_hyp.append(hyp[cur])
prev = cur
while cur < len(hyp) and h... | dbaca85c8cf1bb0878a0a10a88c50eae15c43386 | 631,792 |
import sys
def is_frozen():
"""
Return True if running from the frozen (i.e. compiled form) of your app, or
False when running from source.
"""
return getattr(sys, 'frozen', False) | e487d666307901c3eb0add3a11ce4a01ccf163c4 | 631,793 |
import csv
import logging
def get_function_signature(hex_signature):
"""
Requests the function signature from the CSV file based on the hex_signature to get the text_signature
Args:
hex_signature: the 4-byte signature of the function as hex value (a string starting with 0x)
Returns:
sign... | 6b1c59443e4a1d592c4ef0343ba7f2b9254fd23b | 631,794 |
import json
def cancel_reply(id_, solver_name):
"""A reply saying a problem was canceled."""
return json.dumps({
"status": "CANCELLED",
"solved_on": "2013-01-18T10:26:00.020954",
"solver": solver_name,
"submitted_on": "2013-01-18T10:25:59.941674",
"type": "ising",
... | a868804e70deced45f51204b3d98db543b7dc99c | 631,795 |
def convert_time(time):
""" dealing with time.
"""
# seconds
if time <= 60.0:
time = time
# minutes
elif 60.0 < time < 3600.0:
time = time / 60.0
# hours
elif 3600.0 < time < 86400: # (3600.0 * 24, i.e. day)
time = time / 3600.0
# days
elif 86400.0 <= time... | 9d445d095c24e43ad268d94d32fad1b6822eeb7d | 631,796 |
def wireguard_config_stripped(wc):
"""Strip config for wg loadcon."""
c = []
c.append('[Interface]')
c.append('PrivateKey = ' + wc.interface['PrivateKey'])
if 'ListenPort' in wc.interface:
c.append('ListenPort = ' + str(wc.interface['ListenPort']))
c.append('')
for peer in wc.peers:
... | 385e54a8e924949fb16507f177067b1909a84ac4 | 631,797 |
def quantity_encoder(i: int) -> str:
"""Encode integer quantity `data`."""
return hex(i).rstrip('L') | 10bac5e276b2039a2329860107909cfa505e5e10 | 631,798 |
def detect_tab(path, max_header=1000):
"""Test whether `path` is in the tab format"""
has_begin = False
has_data = False
has_end = False
with path.open() as fd:
for _ in range(max_header):
line = fd.readline().strip()
if line.startswith("# BEGIN METADATA"):
... | ea565dd71143268eb197d92ad4c0b28586a663d8 | 631,799 |
def globalOutgassing(Fmod_out, Q, m):
"""
This function will calculate the outgassing flux (equation S9).
Inputs:
Fmod_out - the modern Earth's outgassing rate [mol C yr-1]
Q - pore space heat flow relative to modern Earth [dimensionless]
m - scaling parameter [dimensi... | c529a14cb60ec94af4f424843c44a023ac32c404 | 631,800 |
def _create_arguments_dictionary(parameter_extractors, environment, context):
"""Creates a dictionary of arguments (to pass to an action function) using the parameters and the
parameter_extractor_mapping as a guide and extracts the values from environment and context.
Arguments:
parameter_extractors ... | 875d2c9c50f3d0603ee33c5307beccaa5342249a | 631,801 |
def _get_overlap(word1, word2):
""" Returns the length of the overlap between word1 and word2.
The number of letters from the end of word1 that match the beginning of
word2.
"""
max_overlap = min(len(word1), len(word2))
max_found = 0
for size in range(1, max_overlap+1):
suffix = wor... | ba8ae3e2b1cf8207209f86c5001e900bbb2ee5d0 | 631,802 |
def curtail(data):
"""
"""
# Make a copy of the data.
variables = data.copy()
# Find all of the start and end dates.
starts = []
ends = []
for variable in variables.values():
starts.append(variable[0][0])
ends.append(variable[-1][0])
# Determine the latest start an... | c8da71403aa5424f068f58192562a7aa76dcdba2 | 631,803 |
def GetMulP(m, v):
""" Multiply a matrix with a vector representing a point.
Same as ``c4d.Matrix.Mul(v)``.
"""
return v * m | fcfbf4519238de35f166efb195daa1988dc26813 | 631,804 |
def get_attribute_element(attributes, element: str, enum):
"""
Constructs an Emum object of a given attribute
:rtype: FastEnum
:type enum: FastEnum
:type attributes: XML attributes
:param attributes: XML attributes of a certain XML node
:param elment: A String
:param enum: The Enum objec... | b88bc30bd5c0e2433d72d58f06277fdd84f8e8b2 | 631,805 |
def normalise(value: float, current_min: float, current_max: float, intended_min: float, intended_max: float) -> float:
"""
Function used to normalise a value to fit within a given range, knowing its actual range.
Uses standard MinMax normalisation.
:param value: Value to be normalised
:param curr... | a13aed0fd15043dcc976f69448702295c6ed2659 | 631,806 |
def _patched_computation_module(module, compute_list, compute_fn):
"""
Patch the module to compute a module's parameters, like FLOPs.
Calls compute_fn and appends the results to compute_list.
"""
ty = type(module)
typestring = module.__repr__()
class ComputeModule(ty):
orig_type = ... | 6b436276ca61fcc2984098e2252b0cef75253d0f | 631,807 |
import subprocess
import sys
def git_diff_parents(commit):
""""Compute the diff between a commit and its parents, ignoring uninteresting merge diff hunks"""
git_diff_out = subprocess.run(
['git', 'diff-tree', '--cc', commit],
check=True,
stdout=subprocess.PIPE,
stderr=sys.stder... | 0b9f845302ff1779e77f3c79ad42301d5beaaa4b | 631,808 |
import numpy
def get_directions(gx, gy):
"""
Parameters
----------
gx : matrix of the gradient in x-component
gy : matrix of the gradient in y-component
Returns
-------
matrix
Of directions
"""
assert gx.shape == gy.shape
height, width = gx.shape
dirs = numpy.z... | fca5f5bd38b61b37e37a3eabc11f292c1f81508c | 631,809 |
import csv
def read_annotation(ann_file):
"""
Read in a yolo annotation file.
These are individual files for each image, stored in labels/<image_name>.txt
"""
with open(ann_file) as file:
csv_ann = csv.reader(file,delimiter=' ')
ann_list = []
for row in csv_ann:
... | 6e9c9a6d8b03ed3e00736fe2c879055ad60217ac | 631,810 |
def find_spacer_cut(sequence, spacer):
"""find the cut site given the spacer"""
return sequence.find(spacer) | f0b6b7adf16eef559bf391aaeed6092dd5619140 | 631,811 |
def _unpack_msg(*msg):
"""
Convert all message elements to string
"""
l = []
for m in msg:
l.append(str(m))
return " ".join(l) | a8e1ac43d92b62d12f8de3bb002b102e047fcebd | 631,812 |
def is_letter(c):
"""
Checks if the given character is a letter.
:param c: The character to test.
:return: True if the character is a letter, False otherwise.
"""
return 'A' <= c <= 'Z' or 'a' <= c <= 'z' | c6e029ad5e0d80e21b9a44080cc5031ecc5146e2 | 631,813 |
import torch
def compute_kernel(x, y):
"""Computes a positive definite kernel function between x and y.
Args:
x(torch.FloatTensor): [-1, x_dim] tensor.
y(torch.FloatTensor): [-1, y_dim] tensor.
Returns:
torch.FloatTensor: kernel between x and y of [x_dim, y_dim].
"""
x_si... | 447a98b8ac710019bf0e93c94234cb4bcd27f025 | 631,814 |
def parseLengthWithUnits(string_to_parse):
"""
Parse an SVG value which may or may not have units attached.
There is a more general routine to consider in scour.py if more
generality is ever needed.
"""
u = 'px'
s = string_to_parse.strip()
if s[-2:] == 'px': # pixels, at a size of PX_PE... | 0486877099a4f7f1f3992220a320e9cb76535015 | 631,815 |
def convert_timedelta(duration):
"""converts date.timedelta object into hours and minutes string format HH:MM"""
seconds = duration.seconds
hours = seconds // 3600
if hours < 10:
hours = "0" + str(hours)
else:
hours = str(hours)
minutes = (seconds % 3600) // 60
if minutes < 1... | 27320025b2f0d70582492faeace8f0a95eda57e1 | 631,816 |
def get_combined_domain(X1, X2):
"""
Returns a list of the unique elements in two list-like objects. Note that
there's a lot of ways to make this function, but given how the rest of the
rank-turbulence divergence function is structured, it's nice to have this
self-contained version.
Parameters
... | 047c653e479709971f69a0071ce59332ea16ee41 | 631,817 |
def get_unique_from_list(source_list, compare_list):
"""
Extract unique entries from list.
Compare source_list to compare_list and return entries from source_list
and not in compare_list.
Parameters
----------
source_list : list
Input list to compare to base list
compare_list :... | 2cd4006021e1fef5276f334874411ac58ad9ce0b | 631,818 |
def guess_encoding(path):
"""Sample a file, seeing if the platform-dependent encoding works, and
trying latin_1 if it doesn't.
A more robust solution would be to use the chardet library,
but we want to try and keep this dependency-free."""
try:
e = None
with open(path, new... | ec9807c41d70f7d2141be27af8388eb28232aa53 | 631,819 |
import math
def crowding_replacement(random, population, parents, offspring, args):
"""Performs crowding replacement as a form of niching.
This function performs crowding replacement, which means that
the members of the population are replaced one-at-a-time with
each of the offspring. A random sa... | fa12202d5588b0827f9840ae2a008d881fac5029 | 631,820 |
import struct
def double_to_long_bits(value):
"""
https://gist.github.com/carlozamagni/187e478f516cac926682
:param value:
:return:
"""
return struct.unpack('Q', struct.pack('d', value))[0] | eea27c3ca0e698466681c565a2c6193d516d939a | 631,821 |
def calculateDistance(row, dest_geom, src_col='geometry', target_col='distance'):
"""
Calculates the distance between a single Shapely Point geometry and a GeoDataFrame with Point geometries.
Parameters
----------
dest_geom : shapely.Point
A single Shapely Point geometry to which the di... | 2875cffcd12f95ecf6e9b90dc689bcd20de222bd | 631,822 |
import math
def my_log(num):
"""
Floors the log function
:param num: the number
:return: log(num) floored to a very low number
"""
if num == 0.0:
return -9999999999
return math.log(num) | e420a883833b5d5a1f9d0dd65c30ff72cbf25ee6 | 631,823 |
def check_counters(_func=None, *,
expected_auth_counter=0, expected_failure_counter=0, expected_logoff_counter=0):
"""Decorator to check the handlers have been called the
correct number of times at the end of each test"""
def decorator_check_counters(func):
def wrapper(self):
... | b03504c62ef91eec83c07aae25046f9ce260f4fa | 631,824 |
def _multi_hash_upsert(cursor, key, keys, values):
"""
Upserts a set of hash values at the given key by combining the keys
and values arguments into a dictionary and performing hmset.
:param cursor:
:param key:
:param keys:
:param values:
:return:
"""
return cursor.hmset(key, dic... | b281f4156903535de5476171c5390469da6f2aa5 | 631,825 |
import argparse
def parse_cmd():
"""
Parses command line and returns path string.
Expected `python -f input.txt`.
"""
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--file',
dest='file',
required=True,
help=... | 77476034ec4ec30170bb71af2ac4d0bd62d04b83 | 631,826 |
def get_name(node):
"""Return name of node."""
return node.get('name') | 0564bd4d4f095145ab0dc1fd344e7e41dc577e6f | 631,828 |
def wavelength_to_standard(unit, values):
"""converts wavelength values to standardised representation"""
if unit == 'nm':
converted_values = values*1e-9
elif unit == 'um':
converted_values = values*1e-6
elif unit =='a':
converted_values = values*1e-10
else:
converted... | d1301b362025f7ee80afaa472aaf4ea3c4a04927 | 631,829 |
import socket
def get_hostname():
"""
Return the hostname for the current system
"""
return socket.getfqdn() | 4c4a0fde1b0c1b0c27800453e74e0abb6486715e | 631,830 |
from typing import Optional
import os
def get_latest_cmdstan(cmdstan_dir: str) -> Optional[str]:
"""
Given a valid directory path, find all installed CmdStan versions
and return highest (i.e., latest) version number.
Assumes directory consists of CmdStan releases, created by
function `install_cmd... | 8623529d262529bc25bd636612aedd44574d5f12 | 631,831 |
import jinja2
def render_template(path: str, data: dict) -> str:
"""
Renders a template with given data.
Parameters
----------
path: str
Path to the template
data:
The provided data for rendering
Returns
-------
template: str
Rendered template
"""
... | 0af0e93d940715cad2d7bb1588ef13260fffa060 | 631,833 |
def remove_block_comments(cql):
"""
:param cql:
:return:
"""
i = 0
while True:
start = cql.find("/*")
if start == -1:
break
end = cql.find("*/")
if end == -1:
print("ERROR: unclosed block comment")
break
cql = cql.repla... | e8c35e3fd44dc933b709e29a2622102a4b6650c2 | 631,834 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.