content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def wav2nu(wav,inputunit):
"""wavelength to wavenumber
Args:
wav: wavelength
inputunit: unit of wavelength
Returns:
wavenumber (cm-1)
"""
if inputunit=="nm":
return 1.e7/wav[::-1]
elif inputunit=="AA":
return 1.e8/wav[::-1]
else:
pr... | 2860c5277f87542e0858ee96281fb0722d27426a | 657,698 |
import re
def _make_clean(string):
"""From https://stackoverflow.com/a/3305731"""
return re.sub(r"\W+|^(?=\d)", "_", string) | 5922bfd7043062b5d7ab35a15eb90bdd0c90a926 | 657,699 |
import pickle
def load_data(file):
"""Load (preprocessed) data from file."""
with open(file, 'rb') as dr:
X = pickle.load(dr)
gene_names = pickle.load(dr)
return X, gene_names | 8e1729e2cf9b76ce47ae4fcbbecda97f235cdb8e | 657,700 |
def unique_array(items):
"""
If an item is duplicated, it appends a numeric suffix to it.
f(items=(a, b, a, c)) => (a, b, a1, c)
"""
counts = dict()
result = list()
for i in items:
counts[i] = counts.get(i, -1) + 1
result.append(str(i) + str(counts[i]) if counts[i] > 0 el... | f9ca20559ae2a9cbe8d10fe5c9c84cc57fe12836 | 657,702 |
def _log_likelihood_2d(xy_enumerated, gl, wc_fct, scale_fct):
"""Compute the likelihood on a 2D grid of 2 Wilson coefficients.
This function is necessary because multiprocessing requires a picklable
(i.e. top-level) object for parallel computation.
"""
number, (x, y) = xy_enumerated
pp = gl.par... | efd4a1227b8dea9b84ca51ac61e07094a41cde6e | 657,703 |
import argparse
def parse_args():
"""Parse Arguments for configuration file"""
parser = argparse.ArgumentParser(description='CLI to store Actisense-NGT Gateway values to InfluxDB and publish via MQTT')
parser.add_argument('--config', '-c', type=str, required=True, help='JSON configuraton file with path')... | b6d1146525ca2f4421b58e9451d72c1c17937b55 | 657,704 |
import os
def read_data_files(path):
"""
Given path to the data files,
returns the list of file paths.
"""
file_names = os.listdir(path)
# convert the file_names to full (not-relative) paths
file_paths = [os.path.join(path,name) for name in file_names]
return file_paths | c05c01a0eceeaadf927c6dcabe38b98fef093928 | 657,705 |
def is_jpeg(data: bytes) -> bool:
"""
Check if the data is a JPEG image.
Parameters:
data (bytes): The data to check.
Returns:
True if the data is a JPEG image, False otherwise.
"""
return data[6:10] in (b"JFIF", b"Exif") | 9f30ba5ac2e08f199e7d649994f67b5ad49bac7a | 657,706 |
def get_flight(fls, dest, num, type):
"""
Добавить данные о работнике.
"""
fls.append(
{
"flight_destination": dest,
"flight_number": num,
"airplane_type": type
}
)
return fls | 2269ab4116e0fe0ba14a9b08185de0c8d7bff1ec | 657,707 |
from typing import Optional
from typing import List
import re
import itertools
def get_expanded_article_pages(page_ref: Optional[str]) -> List[int]:
"""['p. D-D', 'p. D', 'p. D, D ', 'p. D, D-D ', 'p.D-D', 'p.D',
'p. D-D, D ', 'page D', 'p., D-D', 'p. D-D, D-D ']"""
if page_ref is None:
return []... | 8c412dd8785aec2e4d8e7d3b574c07e0eec374db | 657,708 |
def get_core_path(self) -> str:
"""
Gets the coredump location for the program
:return: the absolute path to the expected coredump
"""
return self._parser.get_core_path(self._name) | 88a63bedc2bf0149cc717c3f8c0a8c2707f7e2a8 | 657,709 |
def norm_grid_description(grid_desc):
"""Normalize a grid description into a canonical form.
Examples
--------
>>> from landlab.grid.create import norm_grid_description
>>> grid_desc = [
... (3, 4), {"xy_spacing": 4.0, "xy_of_lower_left": (1.0, 2.0)}
... ]
>>> normed_items = list(n... | bfc4c72dd09467d9a638aa0ab50b1c6f13a6b8a5 | 657,710 |
def train_test_split(data, pct_test):
"""Splits data into a training and testing sections
Args:
data: a numpy array of rows of features
n_test: the amount of data to be tested on (selected from the end of the
dataset)
var_name: the name of the variable to be train test ... | 9b165ad9ac31a76a58b24d9c6b84529b22589ebe | 657,711 |
def string_to_bytes(data_string):
""" Converts a series of characters into bytes. """
sb = ''.join([chr(x) for x in data_string])
return sb | 53ec880b37ab315c8db48b40de5af49c267f1db8 | 657,712 |
def path_Cleanup(path):
"""
:type path: str
:rtype: unicode
"""
# 처음에 시작하는게 혹시 // 이런거라면 True
unc = path.startswith("//") or path.startswith("\\\\")
path = path.replace("//", "/")
path = path.replace("\\", "/")
# 경로 끝이 /로 끝나는애라면
if path.endswith("/") and not path.endswith(":/"):
... | f2599940633e5a8d34debadb95e6c41e6e13d812 | 657,713 |
def remove_label(sentence):
"""
Input: A sentence picked out from the dataset with the label at the end.
Output: A tuple (sentence, label)
"""
return (sentence.strip()[: -1].strip(), sentence.strip()[-1]) | e0c67e417298d7b07f64485aab7f7401c1b0196e | 657,714 |
import argparse
def get_cmd_args():
"""Helper function for analyzing arguments"""
parser = argparse.ArgumentParser(description='Reuters Search')
parser.add_argument(
'-s',
action="store",
dest="search_term",
help='The search term you want to find in the documents. Add quot... | df8252d3ed5e4eead95bc031ff876e93872f6aa4 | 657,715 |
import logging
import random
def load_apprentice_persona_list(personas_fpath: str, shuffle: bool):
"""
Reads a list of curated apprentice personas.
"""
logging.info('Loading personas.')
with open(personas_fpath, 'r') as pf:
personas = [p.strip() for p in pf if p.strip()]
logging.info(f... | 08a4eeaa897838eb46cd8ded1f8364392ca5f59e | 657,716 |
def compute_route(start_road, start_pos, exit):
"""
start_road: object for the start road
start_pos: position on the start road
exit: name for the exit road (string)
"""
# The exit must be of str type
assert isinstance(exit, str)
# A map from (in_road, out_road) to (shortest_dist, pos, l... | a2d6973474959c44b29df24d99dd255e0c4f1e61 | 657,718 |
def layout_one(title):
"""Formating layout for plotly visualization graph containing multiple variables of one company
Args:
title of graph
Returns:
layout configuration
"""
layout = dict(title = title,
legend = dict(
orientation = 'h',
x = -0.01,
... | 4eb7a73bfc808d27b385e9c65a63d0e22332056d | 657,719 |
import ast
def replace_fields(node, **kwds):
"""
Return a node with several of its fields replaced by the given values.
"""
new_kwds = dict(ast.iter_fields(node))
for key, value in kwds.items():
if value is not new_kwds[key]:
break
else:
return node
new_kwds.upd... | bc37c0a6b24ffc1d2a2bcbd055efe26234909466 | 657,720 |
def return_this(anything: dict):
"""
returns the value in the "This" key.
:param anything:
:return:
"""
return anything["This"] | a24a2366b73932f38cdc999d5bf747415d4171d5 | 657,721 |
def get_vasp_gga(raw_data):
"""
Return the KPOINTS data in format of a VASP input for LDA or GGA functional
"""
lines = []
lines.append("Special k-points for band structure")
lines.append("<...> ! intersections ")
lines.append("line-mode")
lines.append("reciprocal")
for s in raw_dat... | afe021fefed728afc53392216338f45a07a1227d | 657,722 |
import fnmatch
import os
def get_unique_file_name(filedir, filename):
"""
Get a unique filename by appending filename with .x, where x
is the next untaken number
"""
# Get the number of conflicting log files
fnames = os.listdir(filedir)
conflicts = fnmatch.filter(fnames, "%s*" % filen... | d7e72d7ce8f106367321311cabce2551222ccc3f | 657,723 |
def lookup(obj, *path):
"""Lookups repeatedly the items in the list `path` of the object `obj`. In
case any `IndexError` or `KeyError` is thrown, `None` is returned. For
example the call `safe_lookup(obj, "a", 0, "b")` returns
`obj["a"][0]["b"]` when it exists and `None` otherwise."""
try:
r... | 464f1950517285af2f23031a57ab5ae96fdba11d | 657,724 |
def geojson_to_tuples_betydb(bounding_box):
"""Convert GeoJSON from BETYdb to
( lat (y) min, lat (y) max,
long (x) min, long (x) max) for geotiff creation"""
min_x, min_y, max_x, max_y = None, None, None, None
if isinstance(bounding_box, dict):
bounding_box = bounding_box["coordi... | cb547c499242235cfd5b2e9db109ef965bea319d | 657,725 |
def replace_multiple(base_word: str, all_replacements: dict) -> list:
"""replaces characters in str:base_word with dict:all_replacements
replace_multiple replaces all at once instead of one at a time
i.e. password -> p@ssw0rd instead of password -> p@ssword -> p@ssw0rd
:param base_word: original string... | c1a6b83ec7bb4deb8c8d97e955b4fceed3dbf9c2 | 657,726 |
def stripnl(s):
"""remove newlines from a string (and remove extra whitespace)"""
s = str(s).replace("\n", " ")
return ' '.join(s.split()) | 7fd7a169c5a067178c7a5866383b2789d71aee79 | 657,727 |
def mod_12(any_int):
"""
Returns the value of the input modulo 12
Params:
* any_int (int): any integer
Returns:
* the integer modulo 12
"""
return any_int % 12 | 766b89e71083a624d457b875db1879e4103a58b5 | 657,728 |
def handle_status_code(response):
"""
Handles status codes for HTTP requests
There's probably a better way to do this... but I'm new
:param response:
:return:
"""
if response.status_code == 400:
val = 'Bad Request'
elif response.status_code == 401:
val = 'Unauthorized'
... | 85583683481051e7de75cf620a23663e4e7efff1 | 657,729 |
def retrieveHost():
"""
Retrieve the 3d host application where the script is running.
@rtype: string
@return: the name of the host, ie blender, maya or c4d
"""
global host
host = ""
try:
host = "dejavu"
except Exception as e:
print("host not supported", e)
r... | 65f8051ad991a8effafe86f7991fa8d69b6cbf2f | 657,730 |
def map_color(text, key='fontcolor'):
"""Map the text to a color.
The text is mapped to a color.
:param text: string of text to be mapped to a color. 'error' and
'fail' in the text will map to 'red'.
:param key: in returned dictionary, the key to use that corresponds to
... | d60e27d128123fbef833b85021420c9e95409ec2 | 657,731 |
def compute_cumulants(moments):
"""
Compute the cumulants from the moments up to order 4
"""
assert len(moments) >= 4, "You must have moments at least up to order 4."
kappas = [0] * 4
kappas[0] = moments[0]
kappas[1] = moments[1] - moments[0] ** 2
kappas[2] = moments[2] - 3 * moments[1]... | 4d81f65b8016204a890437042c1dcbcae90f529f | 657,732 |
import numpy
import math
import itertools
def tformat(array,
name=None,
d=None,
filter=lambda x: abs(x) > 1e-8, # pylint:disable=redefined-builtin
format='%s', # pylint:disable=redefined-builtin
nmax=numpy.inf,
ncols=120):
"""Formats a numpy-... | f154f8f61a3efa8b6ec6567282f429e859126b1e | 657,733 |
def find_smallest(seq):
"""Функция находит минимум в последовательности"""
smallest = seq[0]
smallest_index = 0
for i, v in enumerate(seq):
if v < smallest:
smallest = v
smallest_index = i
return smallest_index | 6d1447d9f94b8e562d4884a50de957cd7df9a21d | 657,734 |
import math
def tor_network_sim_num_sites(ms,scale_tor_network=1):
"""Answers: "how many new websites are visited over Tor in x ms?.
This is based on 140M websites/24h by Mani et al.., the upper bound if a
95% confidence interval for inferred website visits in early 2018 for the
entire Tor network.
... | 6e30312856b155c85bae2c043778e7359bd4f58d | 657,735 |
from typing import Optional
import sys
def pytest_report_header(config: Config) -> Optional[str]: # type: ignore
"""Adds header to pytest runner.
Args:
config (Config): configuration option
"""
if config.getoption("emoji_out"):
return (
f"Running on {sys.platform} platfor... | c9dd9c6e1abd0ddbcb2be4b1c8c892a4760504f2 | 657,736 |
def _bbox(pts):
"""Find the AABB bounding box for a set of points"""
x, y = pts[0]
ax, ay, bx, by = x, y, x, y
for i in range(1, len(pts)):
x, y = pts[i]
ax = x if x < ax else ax
ay = y if y < ay else ay
bx = x if x > bx else bx
by = y if y > by else by
return... | 95802ea790153020fcd6c20193536e1b19ca6102 | 657,737 |
def parse_ndenovo_exac(info, clinSig):
"""Rm benign variants greater than 1% bc these were used to train mpc"""
if clinSig == 'Benign':
if 'ANN=' in info:
if 'af_exac_all' in info:
exac = info.split('af_exac_all=')[1].split(';')[0]
if float(exac) > 0.01:
... | 2de33203d60ccbf6141e6cd87f1bffae910677d6 | 657,738 |
import math
def rnd(x):
"""
Round a number so that the output SVG doesn't have unneeded precision
"""
digits = 6
if x == 0 or not math.isfinite(x):
return x
digits -= math.ceil(math.log10(abs(x)))
return round(x, digits) | bcb40d726a31716c73886fe9e8c5ecc00f1d32b5 | 657,739 |
import requests
def store_document(url, document):
"""
Stores a document in the database
:param url: the base url of the REST server
:param document: document string
:returns response.text: document_id is returned if successful
"""
url += "/documents"
headers = {"Content-Type": "appli... | 0e2dc9ad1ec2f0da2c3006ae1d3df1d830c893fe | 657,740 |
def check_for_fields_to_keep(term, dbterm):
""" see if any of the fields that are not added from the owl
are present and also check for only other fields that have
changed
"""
patches = {'uuid': term.get('uuid')}
if 'is_slim_for' in dbterm:
patches['is_slim_for'] = dbterm['is_sli... | 9e14608881fcb24398a8c024f48da16a87c68b9b | 657,741 |
def is_positive(example):
"""
Check if the example is positive.
:param example: the example
:type example: Atom
:return: `True` if the example is positive; otherwise, `False`
:rtype: bool
"""
return example.weight > 0.0 | 55a754a961459c28ac341e5e06cacb0c9ccff393 | 657,743 |
def extract_file_name(file):
"""
Assume last backslash is start of the file name
"""
assert(file is not None)
name_start = file.rfind("/")
return file[name_start+1:] | 6d9ae06c04bc3eff99e8da38d82e2de808192023 | 657,744 |
def basic_crop(data):
"""
Just display the cropped frame.
Parameters
----------
data : dict
The input data.
Returns
-------
crop : numpy.ndarray
The cropped frame.
"""
return data['crop']; | aa8d5023ee87fce25bc303290f737f3f52b5e7d3 | 657,745 |
def process_argument(argv, key, description, errors, default_value=None):
"""Retrieves argument value or writes error message"""
argument_value = None
for i, v in enumerate(argv):
if v.startswith(key + '='):
argument_value = v[v.index('=') + 1:]
elif v == key and i < len(argv) - ... | 6f7af768cbd94a466bffce2817fb67fa97378f8e | 657,746 |
import random
def odds(poweroftwo):
""" Return True with odds 2**-poweroftwo , else False
For example, odds(2) will be True roughly 1/4 of the time,
odds(3) will be True about 1/8 of the time, and so on.
"""
#
# To test this look at for example this count of the errors
# >> (a,b)... | 8dc283c88fe735eab01be228aa7fe2ac1f86cd2e | 657,747 |
import os
def estimate_genome_size(fasta: str) -> int:
"""
Guesses genome size from fasta file size, assumes 1 byte ~= 1 base
:param: fasta str -- a fasta file
:return: int -- approximate genome size in nucleotides
"""
return (os.path.getsize(fasta)) | a2911f8114936e3b09b89717fdf1c8c1e961ad17 | 657,748 |
from typing import Union
from typing import Any
import ipaddress
def check_ip(val: Union[str, Any]) -> Any:
"""
Function to check whether a value is valid ip address
"""
try:
return bool(ipaddress.ip_address(val))
except ValueError:
return False | 9a1e125552a6aa3e6fcb767227682aa1397b1fbc | 657,749 |
def split_fold(arguments, cores):
"""
Cores is the number of subprocesses you intend to spawn
arguments is the list whose elements are the values you want to compute over.
"""
assert type(arguments) == list, 'Your first positional argument is not a list. Please pass in a list.'
result = []
i... | b1164ed69767e3959526f356ef10309bfbaab919 | 657,750 |
import re
def decode(line: str, track_qty: bool = False) -> tuple:
"""
Decode file line
:param line: line string
:param track_qty: duplicate bags depending on quantity
:return: luggage properties
"""
line = re.sub(r' bags?', '', line.strip().replace('.', ''))
m = re.match(r'(?P<bag>.... | 6641c6b07bd1ad7e7c7e89c60cf9d7cc20a71e86 | 657,751 |
import math
def entropy(probabilities):
""" Calcola entropia della distribuzione di probabilità
:param probabilities: lista contenente una distribuzione di probabilità
:return: valore dell'entropia relativa alla distribuzione in input
"""
entropy = 0.0
for i in range(len(probabilities)):
entropy += probabil... | 81b7f4b4b95664804a2ed17086c12a43125ac6b6 | 657,752 |
import re
def PreCompiledRegexSecret():
"""
This function will create list of precompiled regex object to find secret (high entropy strings) within the content.
Returns
--------
list
a list of precompiled regex objects.
"""
seclst = ['secret', 'secret_key', 'token', 'secret_token... | 4ce72a594e08c2aa87d0ef4cc9ddd0a017a61846 | 657,753 |
import sys
def __format_doc__(string, extra_indent=0, line_start=0, line_end=-1):
"""
Remove significant leading space from all lines and return the resulting
string.
"""
if not string:
return ''
# Convert tabs to spaces and split into a list of lines:
lines = string.expandtabs(4)... | a87081c47a93224dc61e4289e38a494d2b94b7b5 | 657,754 |
def TENSOR_AXIS_IN_RANGE_APPLY_FILTER(arg_values):
"""Ensures the axis is less than the rank of the tensor."""
tensor, axis = arg_values
return axis.value < len(tensor.shape) | 8908b38192ec3d11e681c7304fd62a96220315d1 | 657,755 |
import re
def has_ancillary_files(source_type: str) -> bool:
"""Check source type for indication of ancillary files."""
if not source_type:
return False
return re.search('A', source_type, re.IGNORECASE) is not None | ced6e6bf339cd7e01577ea69cd97dc658948ef85 | 657,756 |
def safefloat(value):
"""safely converts value to float or none"""
try:
return float(value)
except ValueError:
return None | 59c3f08b0b2df2f1d66fbf6892d659cd93f86da3 | 657,757 |
def prepareImageSignal(button, label, type_, col, row,
x, y, xPixel, yPixel):
"""See Plot documentation for content of events"""
return {'event': 'imageClicked',
'button': button,
'label': label,
'type': type_,
'col': col,
'row':... | 62b0a0398103e4e815e2cac781ef1d95177cd5a4 | 657,758 |
import json
import os
import shutil
def clean(json_makefile, all):
"""Remove build artifacts."""
with open(json_makefile) as fobj:
makefile = json.load(fobj)
if os.path.exists(makefile['dst_path']):
shutil.rmtree(makefile['dst_path'], True)
if all:
if os.path.exists(makefile[... | 7dfb778af9c8a69059fc201ad0b9578714955e37 | 657,759 |
def get_bit(number, position):
"""Returns the bit at the given position of the given number. The position
is counted starting from the left in the binary representation (from the most
significant to the least significant bit).
"""
if position < 0 or position > 31:
return 0
return (number... | 426fb4822eedd4b5b1fbc559b549bce7d1488c1f | 657,760 |
def hgvs_justify_dup(chrom, offset, ref, alt, genome):
"""
Determines if allele is a duplication and justifies.
chrom: Chromosome name.
offset: 1-index genomic coordinate.
ref: Reference allele (no padding).
alt: Alternate allele (no padding).
genome: pygr compatible genome object.
Ret... | 2ba7dc7383086f21fd9d9b9ac6c5d92b6bf04144 | 657,761 |
from typing import List
import os
def get_immediate_subdirectories(full_path: str, ignore: List=[], absolute_path=True) -> List:
"""
Get all immediate sub-directories for a certain full path.
Args:
full_path (str): Full path to folder to get immediate sub-directories for.
ignore (List): L... | 81621f8ab6ce9bf86c3516895e2e5b0b110462f6 | 657,762 |
def reverse(t):
"""Return a tuple with reversed order"""
return tuple([t[i] for i in range(len(t)-1, 0, -1)]) | bef4b8ecc48a2fc1e90a1cb99bdcb0706d3768c3 | 657,763 |
import glob
def number_of_netcdf_files(source_dir):
"""
Counts the number of netcdf files in the given directory
:param source_dir:
:return:
"""
netcdf_pattern = source_dir + "/*.nc"
netcdf_list=sorted(glob.glob(netcdf_pattern))
return len(netcdf_list) | 2963c842eb9e55200c6bff894ef575f054ba8a67 | 657,764 |
def parse_access_variable(v):
"""
Parses the accessibility arguments from a variable anme.
Should be structued as <variable_name>_<dir>_within<travel_time>_mode.
For example: `sb_jobs_sector92_to_within20_OpAuto`:
- variable: sb_jobs_sector92
- direction: travel towards the zone
... | 83ac0d8bfda29a18f6785a5bea5dfa7a4fdb004e | 657,765 |
import struct
def _encode_int64(value: int) -> bytes:
"""Encodes an int64 in big-endian stripping leading zeros."""
return struct.pack(">Q", value).lstrip(b"\x00") | 30a372c6f6e19272457415b4f0512ea8fce681d7 | 657,766 |
from typing import Optional
def _serialize_identifier(prefix: str, identifier: Optional[str]) -> str: # pylint: disable=unsubscriptable-object
"""Serialize an identifier, which is never quoted."""
return "%s%s" % (prefix, identifier) if identifier else "" | 602e34f0704186f15ec364f2141fca26a6f36cdb | 657,767 |
def sgf_files():
"""
Fixtures that contain examples of games in sgf-format
and label of winner
"""
sgf_texts = [
"""
PW[amybot-beginner]
BR[31k]
WR[21k]
TM[86400]OT[14400 fischer]
RE[B+16]
SZ[9]
""",
"""
WR[10级] KM[0]... | b3423bb15638c6fd276008cdbcc2eb6ab8088fa9 | 657,768 |
import sys
def get_python_version():
"""
Get Python version.
:return: Python version
:rtype: str or unicode
"""
return sys.version.split("\n")[0] | 6378486e71148806503d09077d12d24f4cebe311 | 657,769 |
def piece_wise_add(list_a, list_b):
"""Add each element of list a to list b.
After trying to get numpy to work with decimals for about 10 minuts
it was raising cryptic errors. Enough of that nonsense.
"""
return [x+y for x, y in zip(list_a, list_b)] | faf9c6b9b4768278e68cb9f871520d8b4da2873f | 657,770 |
from pathlib import Path
import subprocess
def pdf_to_text(pdf_file, text_file, output_layout='table'):
"""
Convert pdf file to text and save it to disk
Requirement: Xpdf tools
This unction requires 'pdftotxt.exe' binary file from https://www.xpdfreader.com/
Download Xpdf tools from https://www.x... | 028dbf0f5cfdc6367b518467d14b0031544f293a | 657,771 |
import copy
def filter_event_in_instance(instances, required_event_types):
"""Filter events in the instance, keep event mentions with `required_event_types`
过滤实例中的事件,只保留需要的事件类别的事件标注
"""
new_instances = list()
for instance in instances:
new_instance = copy.deepcopy(instance)
new_ins... | ca412599ee584a43ff172afd20328af5c497dc35 | 657,772 |
def intersect(a, b):
"""Find intersection of two lists, sequences, etc.
Returns a list that includes repetitions if they occur in the inputs."""
return [e for e in a if e in b] | 987d3bcecfcac90dc7eecb44ff32282164d807c6 | 657,773 |
def get_internal_body(target_name, target_type, intermediate_repr):
"""
Get the internal body from our IR
:param target_name: name of target. If both `target_name` and `target_type` match internal body extract, then emit
:type target_name: ```str```
:param target_type: Type of target, static is st... | a9d40bd26ea69275222dd59680b9e4c739c0834c | 657,774 |
def mask_deltar_first(backend, objs1, mask1, objs2, mask2, drcut):
"""Masks objects in the first collection that are closer than drcut to
objects in the second collection according to dR=sqrt(dEta^2 + dPhi^2)
Args:
backend (library): either hepaccelerate.backend_cpu or hepaccelerate.backend_cud... | d110ae6510163fc210b971076a545d0682e96824 | 657,775 |
def running_paren_sums(program):
"""
Map the lines in the list *program* to a list whose entries contain
a running sum of the per-line difference between the number of '('
and the number of ')'.
"""
count_open_parens = lambda line: line.count('(') - line.count(')')
paren_counts = map(count_o... | 16b9e502f0df98c47b55eb57d04f944468bc6ce7 | 657,776 |
def pretty_str_time(dt):
"""Get a pretty string for the given datetime object.
Parameters
----------
dt : :obj:`datetime`
A datetime object to format.
Returns
-------
:obj:`str`
The `datetime` formatted as {year}_{month}_{day}_{hour}_{minute}.
"""
return "{0... | 388e1b81b10d67193b2f7834f72a69a2c3716c7f | 657,778 |
import re
import logging
import os
import uuid
def cleanup_one_entry(dups, trash_dir):
"""Handles one set of duplicates."""
regexp = re.compile('\(\d+\)')
remove = filter(regexp.search, dups)
for d in remove:
logging.info('Moving %r to trash...' % d)
if os.path.exists(d):
try:
os.rename... | 94370df0f3aa0a828586624d62749cdf9ac1610b | 657,779 |
def define_op_expr(left_expr, opr, right_expr):
"""Returns op expression"""
obj = {
"left": left_expr,
"op": {"name": opr},
"right": right_expr,
}
return obj | a69f932e8f70b77eccc8e2efa84981519f929ce0 | 657,780 |
import torch
def get_outputs(image, model, threshold):
""" Performs inference phase and thresholds the outputs.
:param image: image as ndarray
:param model: model which performs the inference
:param threshold: detection threshold
:return: lists of masks, boxes, classes and final scores
"""
... | 52131c1268c41831f8ec4d6ab0d7f66617b1b9dc | 657,781 |
import json
def getNodeGroups(session, url, details=False):
"""
Return a list of node group objects (by the index endpoint).
Passing details=True will get all information for each node group.
"""
groups = []
page = 1
per_page = 100
done = False
while not done:
new_node_gr... | d865f1e99cee94410b68bee5c4384bbcd4d4a52f | 657,782 |
import threading
def synchronized(func):
"""synchronized decorator function
This method allows the ability to add @synchronized decorator to any method.
This method will wrap the decorated function around a call to threading.Lock
ensuring only a single execution of the decorated method/line of co... | 6ac02e42816c920ce98e35507833f24dcb2349db | 657,783 |
import os
def jinja2_filepath_basename(env, filepath):
"""Returns the base name, i.e. the filename w/o path and extension, of
'filepath'. Note the semantics of this filter differ from
python's os.path.basename!.
"""
return os.path.splitext(os.path.basename(filepath))[0] | 882df5fed754df3744c027b520ac6672a818e2e3 | 657,784 |
def what_betais(fc, last_symbol, beta1, beta2, beta3, beta4):
"""
This function is a fix to correct the consisent wrong output of the beta array order.
If fc is between 6623 and 7968 each bit needs to be flipped
Likewise if the last bit decoded is a certain bit
Input
fc ... | e7c0acfc9835881ec2f4d4e58139e4f9c12c1325 | 657,785 |
def input_keywords(scf_in):
"""Extract all keywords from a quantum espresso input file
Args:
scf_in (str): path to input file
Return:
dict: a dictionary of inputs
"""
keywords = dict()
with open(scf_in, 'r') as f:
for line in f:
if '=' in line:
key, val = line.split('=')
k... | f64345e07d6db4e24815b0c6fce7b1055fb58619 | 657,786 |
def url_exists(url):
"""Checks whether a URL exists."""
return True
validator = URLValidator(True)
try:
validator(url)
return True
except ValidationError:
return False | 6d3f10c2550bca6d6b55c9c9c97d1b8e9b04d4ee | 657,787 |
def strip_definition_from_video(vid_id):
"""Strip any sort of HD tag from the video"""
hd = ['[HD]', '[FHD]', '[SD]', '(SD)', '(HD)', '(FHD)']
for item in hd:
vid_id = vid_id.replace(item, '')
return vid_id | 996a37309e5c4de6d5bd5110a16f4dcdf6760bab | 657,788 |
import random
def generate_hash_str():
"""
generate random hash. Letter A at the end is important to preserver Order in JS
:return: hash code (str)
"""
return f"{random.getrandbits(32):x}A".strip() | b7b7122f9cef9f459b74f902ccd1c0836cd25e98 | 657,790 |
import os
def get_img_paths(FILE_PATH):
"""
When provided a path to a file of images, returns the path to each image inside.
"""
img_paths = []
valid_images = [".jpg", ".gif", ".png", ".tga"]
for f in os.listdir(FILE_PATH):
ext = os.path.splitext(f)[1]
if ext.lower() not in val... | 1af5b3ffd2ccd3470c8b51945316104fa415bde3 | 657,792 |
def skipHeader(infile):
"""
skip the lines beginning with a '!'
"""
## find where the header ends
counter = 0
while infile.readline().startswith("!"):
counter += 1
## reposition the file iterator
infile.seek(0)
for i in range(0, counter):
infile.readline()
return infile | 5f9a785fb0f5c3b019b70d293eeec240d53ae30e | 657,793 |
from typing import Optional
def moins_lettre(m : str, c : str) -> Optional[str]:
"""
Précondition : len(m) > 1
Précondition : len(c) == 1
"""
# première occurrence vue ou non
premiere_trouvee : bool = False
# résultat
res : str = ''
d : str # caractère coura... | 87abc171f67e1393ef4c440d6516b3cd5ed90658 | 657,795 |
def check_if_exact_result(result, iterable, iterable_key, message):
""" Check if the result of other function is a single value of exact result index
or two values of the nearest ones. """
choice = ''
choice_msg = ''
if type(result) == list:
if result[0] == -1:
first = 0
... | fa068f146c53d108d6dda3ac1a32bdb5a754ed5d | 657,796 |
def sexpr_print_sexpr(sexpr):
"""Prints a python S-expression as a string S-expression."""
if isinstance(sexpr, str):
return sexpr
elif isinstance(sexpr, int):
return str(sexpr)
elif isinstance(sexpr, tuple):
assert len(sexpr) > 1, sexpr
parts = map(sexpr_print_sexpr, sex... | 5099c127b4daccd7c6a48940bfeeaab81445a860 | 657,797 |
def find_pivot(input_list):
"""Find the pivot point of the sorted yet "shifted" list.
A simple divide and conquer strategy to find the pivot point of the list.
Time complexity O(log n)
:param input_list: a sorted and pivoted list (i.e. "shifted")
:type input_list: list
:return: an index of th... | b790a1f0828373f036e034535e4c294d815298eb | 657,798 |
import os
def _pretty_hdrprotection(opt):
"""
Return the name of a C header protection (e.g. CRC_IMPLEMENTATION_H).
"""
if opt.output_file is None:
filename = 'pycrc_stdout'
else:
filename = os.path.basename(opt.output_file)
out_str = ''.join([s.upper() if s.isalnum() else '_' ... | 5b5ec9c092940dadc08b739d8e5632d00d9f8d64 | 657,799 |
import numpy
def generate_notes(model, network_input, pitchnames, n_vocab):
""" Generate notes from the neural network based on a sequence of notes """
# pick a random sequence from the input as a starting point for the prediction
start = numpy.random.randint(0, len(network_input)-1)
int_to_note = di... | 55dfec6f01cb1e9050722a7ddab29bddfa611d1d | 657,800 |
import sympy
def jacobian(expr, symbols):
"""
Derive a symbolic expr w.r.t. each symbol in symbols. This returns a symbolic jacobian vector.
:param expr: A sympy Expr.
:param symbols: The symbols w.r.t. which to derive.
"""
jac = []
for symbol in symbols:
# Differentiate to every ... | 613057e249dd79bef748f155b695344bd3abbd3a | 657,801 |
import requests
def get_track_info(url):
"""
Get the track info of the passed URL.
"""
_client_ID = "LvWovRaJZlWCHql0bISuum8Bd2KX79mb"
api = "http://api.soundcloud.com/resolve.json?url={}&client_id={}"
URL = api.format(url, _client_ID)
r = requests.get(URL).json()
title = r["title"]
... | 2a12aed19b6fdffa4d32faf2f7023c58da448717 | 657,802 |
def bmi(W, H):
"""
Body Mass Index Calculator
Calculates the BMI
Algorithm: https://www.cdc.gov/healthyweight/assessing/bmi/childrens_bmi/childrens_bmi_formula.html
:return: The BMI in kg/m^2
:rtype: float
"""
res = 703.0*W/(H*H)
return res | 2d158735b3ed77d5b847fac45ece22fb597faf38 | 657,803 |
def parse_morphs(morph):
"""Parses the strings representing morphological
tags into a series of dictionaries, e.g.
[
gender=NEUTER|case=NOMINATIVE|number=SINGULAR|degree=POSITIVE,
number=SINGULAR|person=PERSON_3|mood=INDICATIVE|voice=ACTIVE|tense=PRESENT,
_,
gender=MA... | 08ab36edcfc72cb4003ccb6c8360cf09ef069c51 | 657,804 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.