content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_correction(shape):
"""
Get correction value depending on position of head.
Argument: shape - dlib.predictor values
Returns: corr - int
"""
# Get corners of eyes
x_A1 = shape.part(0).x # Right corner of right eye
y_A1 = shape.part(0).y
x_A2 = shape.part(1).x # Left corner of ... | 432a2ad16ec419fddd1df6080d4403b6b4598ca0 | 667,553 |
def reformater_gi_nummer(ident: str) -> str:
"""
Nogle hjørneafskæringer for hyppigt brugte navne.
"""
if ident.startswith("gi"):
ident = ident.replace("gi", "G.I.", 1)
if ident.startswith("GI"):
ident = ident.replace("GI", "G.I.", 1)
if ident.startswith("gm"):
ident = i... | 2528e7710b2f58252441843164bc649cb068d90d | 667,554 |
def hp_state_english(raw_table, base_index):
""" Convert HP state to English """
value = raw_table[base_index]
if value == 0:
return "Stop"
if value == 1:
return "Heating mode"
if value == 2:
return "Heating mode+comp"
if value == 4:
return "Cooling mode"
if ... | 7c589c58912b45e0743b80a8353e0606cf2b623f | 667,556 |
import re
def isIdentifier(s):
"""Returns True if string s is valid python identifier (variable, attribute etc)
Returns False otherwise
how to determine if string is valid python identifier
r'^[a-zA-Z_]\w*$'
r'^[a-zA-Z_][a-zA-Z_0-9]*$' #equivalent \w is shorthand for [a-zA-Z_0-9]
... | 8230ef302fc470a2a49f72bbf9b678e790cacef9 | 667,557 |
def disjoint(L1, L2):
"""returns non-zero if L1 and L2 have no common elements"""
used = dict([(k, None) for k in L1])
for k in L2:
if k in used:
return 0
return 1 | 9d3232769c7224a8acb88045eda15c5855fb5cf2 | 667,558 |
def exclude(ex1, ex2):
"""Return the number on the interval [1,3] that is neither ex1 nor ex2
Parameters
----------
ex1 : int
The first number to exclude (1, 2 or 3)
ex2 : int
The second number to exclude (1, 2 or 3)
Returns
-------
int
The number (1, 2 or 3) no... | 136ca08fc0283757e922c27f132c1a59e6de5e1b | 667,559 |
def perm_args(parser):
"""This is a helper method of the method parse_cmd_arguments to add
an argument group for special options regarding the Permuted MNIST experime.
Args:
parser: Object of class :class:`argparse.ArgumentParser`.
Returns:
The created argument group, in case more opti... | 23b46d92353971568ec167ecb41261ad1b5c25a2 | 667,560 |
def get_unique_value_from_summary(test_summary, index):
""" Gets list of unique target names
"""
result = []
for test in test_summary:
target_name = test[index]
if target_name not in result:
result.append(target_name)
return sorted(result) | 24ff66f24e646869f8250b02265997e09fe6f263 | 667,561 |
import sys
import subprocess
def _start_bot_process():
"""
Function to run a bot for testing in a subprocess
"""
args = [sys.executable, 'tests/behavior_tests/bots/responder.py', ]
return subprocess.Popen(args) | 1354acf2a3473a906a6acb1477ac5b4e7629f935 | 667,562 |
def build_texts_from_keens(keens):
"""
Collects available text from keens in a list and returns it
:param keens: dict of iid: keen_iid
:return: texts: dict of iid: list of strings with text collected from each keen.
The title of the keen is always in the first position of the list
"""
texts ... | df446bb50bd98d224316fa90087be87a3db96e08 | 667,563 |
def calculate_hounsfield_unit_parameterless(mu):
"""
Given linear attenuation coefficients the function calculates the corresponding Hounsfield units.
:param mu: Attenuation coefficient to determine corresponding Hounsfield unit.
:return: Hounsfield unit corresponding to mu
"""
HU = mu * 65536-... | 3785d9b73910e84c5265bc190272adcb4b257327 | 667,564 |
def dot(v1, v2):
"""Returns dot product of v1 and v2 """
assert len(v1) == len(v2), 'Vector dimensions should be equal'
return sum(p * q for p, q in zip(v1, v2)) | a1339a70bf9007f24bc8bbfbe445f05fa964dd6d | 667,565 |
def set_cell(sudoku, y, x, value):
""" Sets the current cell to the input value
"""
sudoku[y][x] = value
return sudoku | 1b93384f3cdf38789a190d85b346b0cfb56faed4 | 667,566 |
import re
def format_pattern(route: str):
"""
This method formats the route to a regex pattern.
https://github.com/bottlepy/bottle/blob/16a131de2ed3c9b7fe6bcfcff71a85a71bfe9342/bottle.py#L377
"""
route = route.strip().lstrip('$^/ ').rstrip('$^ ')
route = re.sub(r':([a-zA-Z_]+)(?P<uniq... | d70c4cc02813511405a6e71f78d3a06e0a2c1062 | 667,567 |
def ema(s, n):
"""
returns an n period exponential moving average for
the time series s
s is a list ordered from oldest (index 0) to most
recent (index -1)
n is an integer
returns a numeric array of the exponential
moving average
"""
ema = []
j = 1
#get n sma first and... | 84e6981f5b80c487e99b8881bb08761fc76d7504 | 667,568 |
def beam_search_recover_one_caption(step_words, step_prevs,
step_word_logprobs, timestep, ith, beam_width=5):
"""
step_words: list, len=seq_len, item.shape=(batch*beam_width,)
step_prevs: list, len=seq_len, item.shape=(batch*beam_width,)
step_word_logprobs: list, len=seq_len, item.shape=(batch*beam_width,)
... | e519664c23baaef4b71af35440c27aeef1825f43 | 667,569 |
def categorize_transcript_recovery(info):
"""
full --- means that every exon in the tID was covered!
fused --- full, but assembled exon match start > 0, meaning
likely fusion of overlapped transcripts
5missX --- means that the assembled one is missing beginning X exons
3missY --- means... | 535f535886baa8a6e36c1951e8f7a9cceb9f70fa | 667,570 |
import os
def get_size(file_name):
"""
Get the file size of file_name
:param file_name: Name of the file to measure
:return: size of the file if it exists otherwise returns 0
"""
return os.path.getsize(file_name) if os.path.isfile(file_name) else 0 | 3d03e3c969883c00aa702626f6944237f7b0db5a | 667,571 |
def purge_duplicates(list_in):
"""Remove duplicates from list while preserving order.
Parameters
----------
list_in: Iterable
Returns
-------
list
List of first occurences in order
"""
_list = []
for item in list_in:
if item not in _list:
_list.appen... | 04308c3a2e8852af0d37dc697cd240bda76c9cc9 | 667,572 |
import yaml
def read_yaml_file(filepath):
"""Return contents of a yaml file.
Parameters
----------
filepath : string
The full path to the yaml file.
Returns
-------
list of dictionaries
The contents of the yaml file where each dictionary corresponds
to a line in t... | 27111c678ea3640172bcaccff6688f60650a960d | 667,573 |
def _surf70(phi1, phi2, phi3, phi4):
"""Compute area of a south fire trapeze
Parameters
----------
phi1 : float
Level-set at south west point
phi2 : float
Level-set at south east point
phi3 : float
Level-set at north east point
phi4 : float
Level-set at north... | c4f166bccd0a290b37469f3f616bd568f90f1259 | 667,575 |
def dummy_model(request, _schema, session):
"""return dummy table
"""
table = _schema['dummy']
def teardown():
session.query(table).delete()
session.commit()
request.addfinalizer(teardown)
return table | 3797a2d94f33521379beac111050f8c5c056e2b9 | 667,576 |
def standard_gatenames_chp_conversions():
"""
A dictionary converting the gates with standard names to CHP native operations.
See :function:`standard_gatename_unitaries`.
Note that the native operations are assumed to act on qubit 0 or qubits 0 and 1,
depending on whether it is a one-qubit or two-... | bdd6a4dafe9685af3b748fb59f92ff096ea0f239 | 667,577 |
def hparams_frames_per_second(hparams):
"""Compute frames per second as a function of HParams."""
return hparams.sample_rate / hparams.spec_hop_length | a46feb8438363d425ac6f7dcb9d80f11d27a5816 | 667,578 |
import os
import json
def output_data(output, payloads, datatype, start_time, end_time):
"""
Write a the :payloads: dict (provider name => [data payload]) to json files in :output:.
"""
def _file_name(output, provider, datatype, start_time, end_time):
"""
Generate a filename from the g... | 455db7d9726645de31af91b1f453b090d1dab431 | 667,579 |
def class_to_json(obj):
"""Return the dictionary"""
return obj.__dict__ | 1faf41fc3fcdf95f2f5e6a53d6c8f1d1e863189b | 667,580 |
import json
def translate_classes(classes, json_file):
"""
Convert torch model outputs to human-readable categories
Parameters
----------
classes : array-like
Numerical class output of the neural network
json_file : str
Path to json file with category/class mapping
Return... | 3c6cdcf59802bb5aaba0827aad65643d66f2d53a | 667,582 |
def recall_score(true_entities, pred_entities):
"""Compute the recall."""
nb_correct = len(true_entities & pred_entities)
nb_true = len(true_entities)
score = nb_correct / nb_true if nb_true > 0 else 0
return score | 7851d329efc0f6e69fb7d7082e9941c2b47c52b1 | 667,583 |
from typing import List
from typing import Tuple
from typing import Optional
def has_winner(field: List[List[int]]) -> Tuple[bool, Optional[Tuple[int, int]], Optional[Tuple[int, int]]]:
"""
Checks game for winning (or tie) positions
:param field: playing field matrix
:return: Overall answer & position... | 442935063a143981fb91056a14adda52c016f066 | 667,584 |
import os
def archive(path, timestamp):
"""
Append a timestamp to an existing file's name.
:param path: Path to a file that should be archived
:type path: ``str``
:param timestamp: timestamp
:type timestamp: ``str``
:return: path to the archived file
:rtype: ``str``
"""
new_p... | 600c6672afe5d69097ad12df37e84f3f9feac3f5 | 667,585 |
def likely_inchi_match(inchi_1, inchi_2, min_agreement=3):
"""Try to match defective inchi to non-defective ones.
Compares inchi parts seperately. Match is found if at least the first 'min_agreement' parts
are a good enough match.
The main 'defects' this method accounts for are missing '-' in the inchi.... | 504a92bee20f4c6418434c8475ed9675751eea35 | 667,586 |
def masked_status_eq(masked_status):
""" Returns a function that matches to the masked status. """
return lambda m: m.get_masked_status() == masked_status | f3df74c6a8c867a0532e1514bb2b7bdbb0e451eb | 667,587 |
def get_input_file_name():
"""
input file name for experiment
"""
full_file= '/home/groups/fau-bigdata-datasets/medicare/non-aggregated/Medicare_PUF_PartD_2013to2017.csv.gz'
sample = '/home/jhancoc4/medicare-data/sample_part_d_2013_2017_individual.csv'
return sample | b4561c2ad5661e0f69731022ae870022f0351fa2 | 667,588 |
def safe_repr(obj, short=False):
"""
Helper class to provide backport support for `assertIn` and `assertIsInstance`
for python 2.6
"""
MAX_LENGTH = 80
try:
result = repr(obj)
except Exception:
result = object.__repr__(obj)
if not short or len(result) < MAX_LENGTH:
... | 912fbef815386e401630e853e1dcfd2a4ee9119e | 667,589 |
import torch
def cosine_similarity(new_embeds, baseline_embeds):
"""Computes the cosine similarity for given embeddings.
Given two embeddings of dimension [embedding_size] x [speaker_batch] x [utterances_per_speaker],
calculates the cosine similarity and returns a 1d tensor of size speaker_batch x
u... | 5822da7f4a8e804ff82255db3b446f23c29e1ae3 | 667,590 |
from typing import Dict
from typing import Any
def deep_merge_dictionaries(
first_dict: Dict[str, Any], *other_dicts: Dict[str, Any]
) -> Dict[str, Any]:
"""
Merge N dictionaries together, recursively
:param first_dict: Left hand dictionary
:param other_dicts: Right hand dictionaries
:return: ... | 90a04487aa4106f17b9e685b60adf88b578a066a | 667,591 |
import os
def nearby_file(named_file, extension):
"""Return the name of that file, changed to use that extension
>>> os.path.basename(nearby_file('whyp.pyc', '.txt')) == 'whyp.txt'
True
"""
return os.path.splitext(named_file)[0] + extension | b83575f80f1642005c0a891065e1f049fea8712f | 667,592 |
def translate_matrix(m, v):
"""Translates a matrix by (x, y)."""
(a, b, c, d, e, f) = m
(x, y) = v
return (a, b, c, d, x * a + y * c + e, x * b + y * d + f) | 761139800c561e4ede3ef1c7d9dc9e495e5d3671 | 667,593 |
def credential_exist(cls,site_name):
"""
method that checks if a credential account exists from the credential list
Args:
site_name: Site_name to search if it exists
Returns:
Boolean: True or false depending if the credential exists
"""
for credential in cls.credentials_list:
if ... | 4348bec6f9e4ed0fccb68395c73de393c6036f9f | 667,594 |
import math
def _compute_output_resolution(input_spatial_resolution, kernel_size, stride,
total_padding):
"""Computes output resolution, given input resolution and layer parameters.
Note that this computation is done only over one dimension (eg, x or y).
If any of the inputs is N... | 2b23132a2933d73317b3d3fe9162f6c1b63ec231 | 667,595 |
import numpy
def d1(S, K, t, r, sigma, q):
"""Calculate the d1 component of the Black-Scholes-Merton PDE.
:param S: underlying asset price
:type S: float
:param K: strike price
:type K: float
:param sigma: annualized standard deviation, or volatility
:type sigma: float
:param t: time ... | 252f5eea638f06d9f1ad507d4032adc7f5ae213f | 667,596 |
import re
def check_password(passw):
"""Checks if password is strong (at least 8 characters, both upper
and lowercase letters, at least one digit) using regex."""
lowre = re.compile(r'[a-z]+')
upre = re.compile(r'[A-Z]+')
digre = re.compile(r'\d+')
if lowre.search(passw) and upre.search(passw) and digre.searc... | 031256586d063fb99c6cf245204da98abbc5a216 | 667,597 |
def tag_data(df, tag, var='auto_tag'):
"""Return data with specified tag."""
return df[df[var].eq(tag)] | 36774aa62ff095520576b4babccad963f6cb20d0 | 667,598 |
import torch
def bool_to_strings(bool_data):
"""Convert a vector of [True, False, False, True, ...] to '1001...' ."""
def conversion(entry):
if isinstance(bool_data, torch.Tensor):
entry = entry.item()
return str(int(entry))
mapping = map(conversion, bool_data)
return ''.j... | c31a14c46cab11aae01a73571cde27838cd2caff | 667,599 |
import numpy as np
def tensor_eye(atlas):
"""
:param atlas: list of atlases
:return: the identity matrix of a tensor
"""
a = np.ones(atlas[0].shape)
b = np.zeros(atlas[0].shape)
# the new matrix is 1 on the diagonal and 0 in the other positions
X = [a, b, b]
Y = [b, a, b]
Z =... | 57386fbae5a5a212e323b0c80437dc5aae4a6c0c | 667,600 |
def file_to_list(filename,skip='#'):
"""
Read the filename and append all the lines that do not start
with the skip string, to a list.
Args:
filename (str): name of the file
skip (str): first elements of the skipped lines
"""
lines = []
with open(filename) as f:
for ... | 25a63d90eafad59597475b3f0827522f3ea655bf | 667,601 |
import os
import pickle
import numpy as np
def load_cifar10(DIR):
"""
Input - path to cifar10 directory
Output - X_train, y_train, X_test, y_test
"""
img_data, img_label = [], []
for batch in range(1,6):
with open(os.path.join(DIR, f'data_batch_{batch}'), mode='rb') as file:
... | 6c75f3f8b7670447a861fd97fb643a7009d3bb34 | 667,602 |
import shlex
import subprocess
import json
def run_mkmod_command(cmd, outjson):
"""Runs mkmod assuming the command contained an --output_json parameter
and retrives that json information
args:
:cmd (str) - command string
:outjson (str) - path to expected output file
returns:
... | 35ce8553d208b37c66d45e2c5c07b60622804864 | 667,603 |
def Substarction(matrix_1, matrix_2): # вычитание
"""
Функция, которая вычитает две матрицы
:params matrix_1: матрица, уменьшаемое
:params matrix_2: матрица, вычитаемое
:return matrix_out: матрица, разность
"""
matrix_out = []
for i in range(len(matrix_1)):
if (len(... | 22d2f19026f887b2af547783f0ae4a4d2a8b39c1 | 667,604 |
import os
def getFileContent(fn):
"""
get the content from the file
@ In, fn, str, file name
@ Out, getFileContent, None or Str, the content of the file, None if the file does not exist
"""
content = None
if not os.path.exists(fn):
print("Can not open file " + fn)
else:
with open(fn, "rb... | 2a2276b0559595c85105d0c2231350ff6b50da14 | 667,605 |
from typing import OrderedDict
import json
def json_to_ordered_dict(file):
"""
Reads a timeline.json file output by Tensorflow/libcupti and returns and OrderedDict object
:param file: .json file.
:return: OrderedDict
"""
with open(file, mode='r') as f:
def _as_ordered_dict(val):
... | 5feaaf9c2bbc33bb3826ed599aa3200b4bac07ed | 667,606 |
def _get_metadata_file_(instrument):
""" returns the metadata associated to the given instruement """
return eval("_%s_METADATA_FILE"%instrument.upper()) | 43ffdeff1d6eb275c59ec694664a2ba15cf5949d | 667,607 |
import torch
def invert_pose(T01):
"""Invert homogeneous matrix as a rigid transformation
T^-1 = [R^T | -R^T * t]
Parameters
----------
T01: torch.FloatTensor (B44)
Input batch of transformation tensors.
Returns
----------
T10: torch.FloatTensor (B44)
Inverted batc... | d933fb5e9b1b218f42816ed1c686a6fac8f4047b | 667,608 |
def data(reader, chunk=100):
"""Creates a pandas DataFrame that is a subset of the entire file
based on chunk
Parameters
----------
reader : pd.DataFrame
A pandas.DataFrame, use grab_files.reader
chunk : int
The number of rows to grab in the first chunk.
Future versions ... | 1ea39b2ca767e389c7c6bde83b3e9a6324f3d187 | 667,609 |
def split_path(path):
"""Split a path into a list of path components."""
return path.split('/') | d629db063c19d7a4f50eb84755fc71f3114b1e7d | 667,610 |
def join(seq, separator=","):
"""
Description
----------
Concatenate all values in a sequence into a string separated by the separator value.
Parameters
----------
seq : (list or tuple) - sequence of values to concatenate\n
separator : any, optional - value to separate the values in the... | fc011f84210d198a650ac10233741508e03f3b77 | 667,611 |
import torch
def compute_face_normals(vertices, faces):
"""
Compute each face normal
"""
pts = vertices[faces]
cross_product = torch.cross(pts[:, 1] - pts[:, 0], pts[:, 2] - pts[:, 1], dim=1)
normals = cross_product / cross_product.square().sum(1).sqrt()[..., None]
return normals | 57c91ccfe01c81fe294d695607f0c70572dd598e | 667,612 |
def removeNonAsciiChars(str_in):
"""Remove all non-ascii characters in the string"""
if str_in is None:
return ""
return str_in.encode("ascii", "ignore").decode() | aaacb023d855a35845b4e0ebe443e9d1d9d8e396 | 667,613 |
def verify_min_max(minimum, maximum):
"""
:type minimum: int
:param minimum: Minimum speed in MB per second
:type maximum: int
:param maximum: Maximum speed in MB per second
:return: Fixed minimum, maximum
:rtype: tuple
"""
minimum = int(minimum)
maximum = int(maximum)
if ... | e1fdf589b0a31c78cf01c9b51b07d11a3303b559 | 667,614 |
def splitStringIntoChunks( string, length=25 ):
"""
Split string into chunks of defined size
"""
if len(string) <= length:
return [ string ]
else:
return [ string[ 0+i : length+i ] \
for i in range( 0, len( string ), length ) ] | ff91557d06927727868fd8b157272286b72f1d5f | 667,615 |
def setify(diff_list):
"""Take a list of lists and make it a set of tuples."""
s = set()
for diff in diff_list:
s.add(tuple(diff))
return s | 64f0e94c7c6b726b5bb7bae0b269a3c9e8053775 | 667,616 |
import codecs
def read_only_relations_into_set(inpath):
"""
Only read the relation of a given relation dataset into a set.
Args:
inpath (str): Path to relation dataset.
Returns:
set: Set of dataset relation types.
"""
relations = set()
with codecs.open(inpath, 'rb', 'utf-8') as infile:
line = infile.r... | b9ecb376130673ca05d82ee30f1b5cc23e843d30 | 667,617 |
def data_availability(tags):
"""
:param tags: errors tagged as true
:type tags: pd.DataFrame
:return: availability
:rtype: pd.Series
"""
return ~tags.any(axis=1) | 460f32125817547fbd0d3263f56d7f445d51368b | 667,618 |
def parse_peak_labels(peak_labels, chromosome_num, cell_type):
"""
:param peak_labels:
:param chromosome_num:
:param cell_type:
:param cpNum_data:
:return:
"""
labels = []
label_table = ['regions', 'peakStat', 'cellType']
#parse the text file to python list
for peak in peak... | 284cf9b4349a5146acd90e47561fe01adaead31c | 667,619 |
def get_uuid(connection):
"""Retreive UUID from OVN DB connection JSON."""
return connection["_uuid"][1] | 30e6c5eb3346d8d6e2eedffdc7115abf205a0ddb | 667,621 |
import sys
import os
def get_cuda_version():
"""Get the CUDA version
Examples:
>>> get_cuda_version()
'CUDA Version 8.0.61'
"""
if sys.platform == 'win32':
raise NotImplementedError("Implement this!")
elif sys.platform == 'linux':
path = '/usr/local/cuda/version.tx... | 8eb666a2ff7d586ec2bce8324ea9e709c299fdfd | 667,623 |
def parse_fs_statsfile(statsfile):
"""opens a fs generated stats file and returns
a dict of roi keys with [mean, std, nvox], for
each roi
"""
roidict = {}
for line in open(statsfile):
if line[0] == '#':
continue
tmp = line.split()
roi = tmp[4]
mean = e... | f9185fbd00e945171edc45bce18c3ae7034e23dc | 667,624 |
def _preprocess(urls):
"""Can be used to inject routes in the future"""
return urls | e83499a41fa6cc1a338b4a1ca0d9ed24c53a36d4 | 667,625 |
import re
def xrt_find_devtoolset(ansible_facts):
"""
Get the latest installed Red Hat Developer Toolset from installed package.
Args:
ansible_facts (dict): Ansible facts.
Returns:
str: Package path.
"""
devtoolset_match = re.compile(r"^devtoolset-\d+$").match
filtered =... | 2af165a0a292cd81f63d2af0ad3de4c3d1ea1875 | 667,626 |
def _prod(op1, op2):
"""Product of two operators, allowing for one of them to be None."""
if op1 is None or op2 is None:
return None
else:
return op1 * op2 | 2a1048b995b680b43d67d8f3c237fc42f5d16bc6 | 667,627 |
import math
def midi_to_freq(midi):
"""
:param int midi: MIDI note (e.g. 69)
:return: Frequency in Hz (e.g. 440.0)
:rtype: float
"""
return 440.0 * math.pow(2.0, (midi - 69) / 12) | 9edce8e0932f72fd45c9080af9a76b48f5cdaeb9 | 667,628 |
def _format_83(f):
"""Format a single float into a string of width 8, with ideally 3 decimal
places of precision. If the number is a little too large, we can
gracefully degrade the precision by lopping off some of the decimal
places. If it's much too large, we throw a ValueError"""
if -999.999 < f <... | 1b3956b31f417319b403db83ebd152df0fb5c732 | 667,629 |
from typing import Dict
from typing import Optional
from typing import cast
def _padding_from_match(groups: Dict[str, Optional[str]]) -> int:
"""deduces padding from REGEX match"""
start = groups["start"]
start = cast(str, start)
padding = len(start)
return padding | 9f091f223e222cf3504402e632a211896c12cf3b | 667,630 |
import numpy
def markRegion(D, X, eps):
"""
Find all points in dataset 'D' within distance 'eps' of point 'X'
This function calculates the distance between a point X and every
other point in the dataset, and then returns only those points,
which are within threshold distance 'eps'.
... | c60d16742c17398cdf6dbbb1eec95b8b04b46acd | 667,632 |
from typing import OrderedDict
def get_modules(premodules):
"""premodules is a list of strings for file like object where each line is a module, first value is module name
and subsequent values are observations in that module. All are separated by tabs.
"""
modules = OrderedDict()
for line in prem... | 37f25f5b314a4e23930d627d3735472bda25ec27 | 667,633 |
import torch
def n_mpjpe(predicted, target):
"""
Normalized MPJPE (scale only), adapted from:
https://github.com/hrhodin/UnsupervisedGeometryAwareRepresentationLearning/blob/master/losses/poses.py
"""
assert predicted.shape == target.shape # [1, 1703, 17, 3]
norm_predicted = torch.mean(torch.... | 276b37a44b05e91b911ed97948c01e85863e73e1 | 667,634 |
import subprocess
def datporod(gnomoutfile):
"""Run datporod and return the estimated Porod volume.
Returns:
Radius of gyration found in the input file
I0 found in the input file
Vporod: the estimated Porod volume
"""
results = subprocess.check_output(['datporod', gnomoutfi... | 72f1fd1412bb4b8891103f42c32778518f1ed6c7 | 667,635 |
def _fmt(string: str) -> bytes:
"""Return a string that escapes 'C printf' side effects."""
return string.encode("utf-8").replace(b"%", b"%%") | f275a69a49ff2a135296cad0d3ba17583272a31e | 667,636 |
def get_timestamp(api_answer):
"""Получение timestamp для отсчёта времени от последней проверки."""
try:
current_timestamp = api_answer['current_date']
except KeyError:
raise KeyError
return current_timestamp | 480ed263244e19f7373bcb1403dd5ce92d030fad | 667,637 |
def is_subset(list1, list2):
"""Returns true if list 1 is a subset of list 2
(assumes neither list has any repeats)
"""
for item in list1:
if not item in list2:
return False
return True | a1ec2576d04cbf0a79d341e9ff1d802915730757 | 667,638 |
import configparser
def ini_read_crop(file_ini):
""" Konfiguracja FotoKilofa """
# słownik wyjściowy
dict_return = {}
config = configparser.ConfigParser()
config.read(file_ini, encoding="utf8")
try:
crop_on = config.getint('Crop', 'on')
except:
crop_on = "0"
dict_ret... | 4e0bd8efecebbcdb6dadea101a7af2e91e34f2fc | 667,639 |
import inspect
def get_args(frame):
"""Gets dictionary of arguments and their values for a function
Frame should be assigned as follows in the function itself: frame = inspect.currentframe()
"""
args, _, _, values = inspect.getargvalues(frame)
return dict((key, value) for key, value in values.ite... | 87bb968522657c762962e58a9c90023e97bc118e | 667,640 |
import glob
import os
def listdir_recursive(dname: str, relpath=True):
"""Lists all files found in {dname} with relative path
Args:
dname (str): Absolute path to directory
Returns:
List[str]: List of all files with relative path to dname
"""
files = [
fpath
for fp... | 128c0fb0f5f26a2475ae63dc9ddad90b0db78902 | 667,641 |
import re
def get_valid_filename(s: str) -> str:
"""Returns a valid filename given an input. Removes any characters unable to be in a filename"""
s = str(s).strip()
return re.sub(r'(?u)[^-\w.\[\]()\' ]', '', s) | 56d8d70a2d4e5514ad101d820698402c021c65ce | 667,642 |
from pathlib import Path
import json
import os
def create_incident_field(path: Path, incident_to_associate: str) -> str:
"""
Creates an incident field
Args:
path: A path of the pack
incident_to_associate: an incident type to associate the incident field
Returns:
The path to t... | 631acd2eacd1dc292129a632400b45092ec9f44e | 667,643 |
def single(value, dice):
"""
Score the dice based on a single value (1-6).
"""
points = 0
for die in dice:
if die == value:
points += value
return points | 03fd02f7f0f642c7aff9ea274630e9880bcd2caa | 667,644 |
def get_descendant_by_address(tree_node, relative_address):
"""
Get the descendant node with given address relative to the given tree node.
A relative address with respect to a tree node is a list of successive children to traverse to reach the desired
descendant. For example:
[0] is the address o... | 7bea0634b015b742a0ef9b2c5e802f81494c6b75 | 667,645 |
import time
def timestamp():
"""Get timestamp"""
return int(time.time()) | 5c7fa888c208b906da8a4286c8b7c7f6e4e0eece | 667,646 |
from typing import List
def k_closest(points: List[List[int]], k: int) -> List[List[int]]:
"""
Sort the points by distance, then take the closest K points.
"""
points.sort(key=lambda p: p[0] ** 2 + p[1] ** 2)
return points[:k] | b2e1cb87509429378ab4c2f228777d582e552a89 | 667,647 |
import re
def build_file_id(file_title, file_to_id_map, existing_ids):
"""
Generates a unique id for a file, based on its title.
"""
file_id = base_id = re.sub(r"[\[\]\(\)#]", "", file_title.lower().replace("_", "-").replace(" ", "-"))
count = 1
while file_id in existing_ids or file_id in list... | 7184caa92c32f1738c6f49c3fc447f2245463603 | 667,648 |
def metadata(obj, **kwargs):
"""Add metadata to an xarray object.
Args:
da (xarray.DataArray or xarray.Dataset): xarray object.
Returns:
xarray.DataArray or xarray.Dataset : Same as caller
"""
for key,value in kwargs.items():
obj.attrs[key] = value
return obj | c2de15b1deafb43dda524b5633f0a7dc376326ea | 667,649 |
def fix_fredbloggs_login(fredbloggs, testclient):
"""Make all requests using this fixture be logged in as an fred bloggs"""
testclient.login(fredbloggs.username, "test_password")
return fredbloggs | 33af33cb01265843ce592b1b06e2f0e0b2bc20fe | 667,650 |
def getDateTimeByName(entity, name):
"""Returns the DateTime property with the given name.
Args:
entity: Instance of a timeline model.
name: The name of a specific property in the given timeline model.
Returns:
The requested DateTime property, or None if there is no such property set.
"""
if h... | 9ec2c8e2868fce85a0ddacecadc35090ba6e185f | 667,651 |
import re
def _extract_subscription_url(url):
"""Extract the first part of the URL, just after subscription:
https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/
"""
match = re.match(r".*/subscriptions/[a-f0-9-]+/", url, re.IGNORECASE)
if not match:
raise ValueE... | 4043738342b001d3958ddff7b6d21b23c57ba1a5 | 667,652 |
import logging
def retry_decorator(tmethod):
"""Decorates a transaction method with retry handling"""
def retry(self, *args, **kwargs):
if self.query_count:
return tmethod(self, *args, **kwargs)
else:
strike = 0
while True:
try:
... | 1bc83609e3ab43cfbaa5212aee7bbf40dc9ef5f7 | 667,653 |
def do_currency(value, currency=u"€"):
"""format currency aware"""
return u'{0:.2f} {1}'.format(value, currency).replace(".",",") | 5dda04f124660d6294f6340f40e828ba2e025c51 | 667,654 |
def estimate_gva(regions, in_million=True):
"""Functions to estimate the Gross Value Added for each sector in each province.
Parameters
- regions - pandas DataFrame with provincial/regional data
Outputs
- list with GVA values per sector in each province
"""
if in_million == True:
... | f86c47c33ece45f4585f4aee596826318ad67e69 | 667,655 |
def max_divide(a: int, b: int) -> int:
"""
Returns a after dividing it with the greatest possible power of b.
>>> max_divide(729,3)
1
>>> max_divide(7543,2)
7543
>>> max_divide(486,3)
2
"""
while a % b == 0:
a //= b
return a | 0081ae0cd245fc00287af7bc55c27202365f9d10 | 667,656 |
def width(particle):
"""
width of a particle object, in GeV
"""
# for K0, K~0, return width=0
if(particle.width==None):
return 0.
return abs(particle.width)/1000. | 13678d7ebdd101debf127a657c850802d8a7ff66 | 667,657 |
def is_magic(name: str) -> bool:
"""Check magic name."""
name = name.rsplit('.', maxsplit=1)[-1]
return name[:2] == name[-2:] == '__' | 9328d182b31a5028bb76c4d41b0e5ddc9cf0e5ab | 667,658 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.