content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import os
import requests
import logging
import subprocess
def run_wdl_md5sum(wdl_input):
"""Pass a local md5sum wdl to the wes-service server, and return the path of the output file that was created."""
endpoint = 'http://localhost:8080/ga4gh/wes/v1/workflows'
params = '{"ga4ghMd5.inputFile": "' + os.pat... | 7e8d89de84148b1060bac509ba90136cc4027e4a | 682,500 |
def getFirstMatching(values, matches):
"""
Return the first element in :py:obj:`values` that is also in
:py:obj:`matches`.
Return None if values is None, empty or no element in values is also in
matches.
:type values: collections.abc.Iterable
:param values: list of items to look through, c... | 7b11d769ba9a95bfd586fdac67db6b6e9a0cebc1 | 682,501 |
def generateBlockStatement(amount, sender, date, receiver, message)->str:
"""_summary_
Args:
amount (Decimal): _description_
sender (String): _description_
date (DateTime): _description_
receiver (_type_): _description_
message (_type_): _description_
Returns:
... | fe085397e06d2071f64b83c13de799f4314e5f30 | 682,502 |
from typing import Tuple
from typing import List
def compute_padding(kernel_size: Tuple[int, int]) -> List[int]:
"""Computes padding tuple."""
# 4 ints: (padding_left, padding_right,padding_top,padding_bottom)
# https://pytorch.org/docs/stable/nn.html#torch.nn.functional.pad
assert len(kernel_size) =... | a0e50ac4d2eb77f99bae117f9357cc6cefeb78c9 | 682,503 |
def look_at_nearest_cells(data,i,j,simbol):
"""
Смотрим на ближайшие ячейки и считаем количество
заполненных элементов указанным символом
"""
#Внутри
if ((0<i<len(data)-1) and (0<j<len(data[i])-1)):
count=0
if data[i-1][j-1]==simbol: #Левый верхний
count+=1
if... | 9a3ae093629e7a1bf9a5ff6011180484a27b90dd | 682,504 |
def normalize_sphere(pc, radius=1.0):
"""
Args:
pc: A batch of point clouds, (B, N, 3).
"""
## Center
p_max = pc.max(dim=-2, keepdim=True)[0]
p_min = pc.min(dim=-2, keepdim=True)[0]
center = (p_max + p_min) / 2 # (B, 1, 3)
pc = pc - center
## Scale
scale = (pc ** 2).su... | 51396454e887532b7a3ecde4d3b7d46688301041 | 682,505 |
def _calculate_temperature(c, h):
""" Compute the temperature give a speed of sound ``c`` and humidity ``h`` """
return (c - 331.4 - 0.0124 * h) / 0.6 | 08555185c563bc5d67c4408e15253994b71ad703 | 682,506 |
import itertools
def combinations_comparison(ids_dict_fixed, align_df):
"""
"""
combination_ids_proportions = []
# list of tuples, where each tuple has: (id1, id2)
result_list = list(itertools.combinations(ids_dict_fixed.keys(), 2))
for ind,i in enumerate(result_list):
combination_i... | 0d1a99c0a8651823f045a28c708e751f24ba59d2 | 682,507 |
def get_region(df, region):
""" Extract a single region from regional dataset. """
return df[df.denominazione_regione == region] | 08a78778bc9b2e3e4eabeb846ea88ee7a67f67a8 | 682,508 |
def get_installed_tool_shed_repository( trans, id ):
"""Get a tool shed repository record from the Galaxy database defined by the id."""
return trans.sa_session.query( trans.model.ToolShedRepository ).get( trans.security.decode_id( id ) ) | aeda7ad13a0c2dc490a93b5240bd4dd3c6aa283a | 682,511 |
def _label_group(key, pattern):
"""
Build the right pattern for matching with
named entities.
>>> _label_group('key', '[0-9]{4}')
'(?P<key>[0-9]{4})'
"""
return '(?P<%s>%s)' % (key, pattern) | db244f37d968e8cda5d2525b1ba56a009766fb03 | 682,513 |
def _to_set(loc):
"""Convert an array of locations into a set of tuple locations."""
return set(map(tuple, loc)) | 57623e0063df65eb51b46a3dbb01915528e60090 | 682,514 |
def is_valid_port(entry, allow_zero = False):
"""
Checks if a string or int is a valid port number.
:param list,str,int entry: string, integer or list to be checked
:param bool allow_zero: accept port number of zero (reserved by definition)
:returns: **True** if input is an integer and within the valid port... | 4a267120f639fd91d1554f9038b323fa028201c0 | 682,515 |
from typing import Any
def hide_if_not_none(secret: Any):
""" Hide a secret unless it is None, which means that the user didn't set it.
:param secret: the secret.
:return: None or 'hidden'
"""
value = None
if secret is not None:
value = 'hidden'
return value | a2d242e764066916a9427609ab0c949a9237e06a | 682,516 |
def percentIncrease(old, new):
"""
Calculates the percent increase between two numbers.
Parameters
----------
old : numeric
The old number.
new : numeric
The new number.
Returns
-------
numeric
The percent increase (as a decimal).
"""
return (new - ... | 1b0636fa52ef6691c2f7066db6df5f40cf52dc64 | 682,517 |
import dill
def load_optimiser(file_name):
"""
:rtype: BayesOptimiser
"""
with open(file_name, 'rb') as file:
optimiser = dill.load(file)
return optimiser | 05a41417723dfc56f2cca6764f8fa47b2f7797d6 | 682,518 |
from typing import OrderedDict
def create_model(api, name, fields):
"""Helper for creating api models with ordered fields
:param flask_restx.Api api: Flask-RESTX Api object
:param str name: Model name
:param list fields: List of tuples containing ['field name', <type>]
"""
d = OrderedDict()
... | 9119e43e07ba3c7baeb176b0f7ba285f64c8c8da | 682,519 |
def B(A: int, D: int) -> int:
"""Function that should become part of the graph - B"""
return A * A + D | 99496c169638ff256a4e4be7d5cd7cf099e565c1 | 682,520 |
import torch
def rgb_to_srgb(image):
"""Applies gamma correction to rgb to get sRGB. Assumes input is in range [0,1]
Works for batched images too.
:param image: A pytorch tensor of shape (3, n_pixels_x, n_pixels_y) in which the channels are linearized R, G, B
:return: A pytorch tensor of shape (3, n_... | 60d4e199152fba9829076722816f6e8efa3c659d | 682,521 |
def confirmed_password_valid(password, confirmation):
"""
Tell if a password was confirmed properly
Args:
password the password to check.
confirmation the confirmation of the password.
Returns:
True if the password and confirmation are the same (no typos)
"""
return password == confirmation | 2404ee5b1d0c75cc9ddab4155fd10efad7ab0b70 | 682,522 |
def contains(element):
"""
Check to see if an argument contains a specified element.
:param element: The element to check against.
:return: A predicate to check if the argument is equal to the element.
"""
def predicate(argument):
try:
return element in argument
exce... | 901785df69b8ee3f07c01cc1d3a1ce1c31d204b2 | 682,523 |
from decimal import Decimal
def get_load_avg(parent, host, port, community):
""" This is a plugin to be loaded by Ecks3
return an array of tuples containing (name, value) for each measured interval (normally 1, 5 and 15 minutes)
name is the description of the interval returned by the host
... | 109fff413205f0745129e52b256683f243192bf0 | 682,524 |
from typing import List
import shlex
import os
import re
def get_cmake_args() -> List[str]:
"""Return the list of extra CMake arguments from the environment."""
cmake_args = shlex.split(os.environ.get("CMAKE_ARGS", ""))
if "CONDA_BUILD" in os.environ:
install_re = re.compile(r"-D\s*CMAKE_INSTALL.*... | 5551e00d81cec309f1f44fdc13ec5791983b8435 | 682,525 |
def split_bbox(bbox):
"""Split a bounding box into its parts.
:param bbox: String describing a bbox e.g. '106.78674459457397,
-6.141301491467023,106.80691480636597,-6.133834354201348'
:type bbox: str
:returns: A dict with keys: 'southwest_lng, southwest_lat, northeast_lng,
northeas... | 7ee3a466eac84235d1897bc2996afcbe243f64d9 | 682,526 |
def compare_rgb_colors_tolerance(first_rgb_color, second_rgb_color, tolerance):
"""
Compares to RGB colors taking into account the given tolerance (margin for error)
:param first_rgb_color: tuple(float, float, float), first color to compare
:param second_rgb_color: tuple(float, float, float), second col... | c1c912eaabe52fbb581ca6c3c6d0769b55a7e470 | 682,528 |
from pathlib import Path
def GetRendererLabelFromFilename(file_path: str) -> str:
"""Gets the renderer label from the given file name by removing the '_renderer.py' suffix."""
file_name = Path(file_path).stem
return file_name.rstrip("_renderer.py") | 11e97b9712046840103b7bb5910f2b82109f0545 | 682,529 |
def _sample_generator(*data_buffers):
"""
Takes a list of many mono audio data buffers and makes a sample generator
of interleaved audio samples, one sample from each channel. The resulting
generator can be used to build a multichannel audio buffer.
>>> gen = _sample_generator("abcd", "ABCD")
>>... | 4688d9abd62d88e08563625a5f53c5088e4c9bcd | 682,530 |
def get_novel_smiles(new_unique_smiles, reference_unique_smiles):
"""Get novel smiles which do not appear in the reference set.
Parameters
----------
new_unique_smiles : list of str
List of SMILES from which we want to identify novel ones
reference_unique_smiles : list of str
List o... | 2316e4c4bc41a8f68a2c2ff636f6a99222154e98 | 682,531 |
def error(message, code=400):
"""Generate an error message.
"""
return {"error": message}, code | 11214c1cfa7052aefa91ae532b15548331d153cb | 682,532 |
import os
def make_output_filename(input_name, new_extension):
"""
Return an output filename based on an input filename; using basename and
splitext
"""
return os.path.splitext(os.path.basename(input_name))[0] + new_extension | 6a76beb968771f8bbbbfe3cb00b1b73570acff15 | 682,533 |
import warnings
def _validate_buckets(categorical, k, scheme):
"""
This method validates that the hue parameter is correctly specified. Valid inputs are:
1. Both k and scheme are specified. In that case the user wants us to handle binning the data into k buckets
ourselves, using the stated... | 2953c08d85705728d8f269db67772e420ee85f87 | 682,534 |
def colon_concepts2labels(report_concepts):
"""
Convert the concepts extracted from colon reports to the set of pre-defined labels used for classification
Params:
report_concepts (dict(list)): the dict containing for each colon report the extracted concepts
Returns: a dict containing for each colon report the s... | e8fbeb767648e1f1c53e5f02f102ffe40f21a652 | 682,535 |
import yaml
def creds():
""" read and yield eos configuration """
with open("../ansible/group_vars/lab/secrets.yml") as stream:
creds = yaml.safe_load(stream)
return creds | 85c0bb139616509c29232a31d1cc384c436c1358 | 682,536 |
import json
def save_json(f, cfg):
""" Save JSON-formatted file """
try:
with open(f, 'w') as configfile:
json.dump(cfg, configfile)
except:
return False
return True | 75c232000962a4edbad5131b11f2701157f32d76 | 682,537 |
import math
def parallelepiped_magnet(
length=0.01, width=0.006, thickness=0.001, density=7500
):
"""
Function to get the masse, volume and inertial moment of a parallelepiped
magnet. International system units.
The hole for the axis is ignored.
"""
V = length * width * thickness
m = V... | 56ddf74e437e3cc60a9eb11e291fe93ccaa58fd2 | 682,538 |
def max_cw(l):
"""Return max value of a list."""
a = sorted(l)
return a[-1] | 21b079b5c3dd4cb7aba55588d38ba57a058bbb97 | 682,539 |
import os
def getImageSetDirectories(data_dir):
"""
Returns a list of paths to directories, one for every imageset in `data_dir`.
Args:
data_dir: str, path/dir of the dataset
Returns:
imageset_dirs: list of str, imageset directories
"""
imageset_dirs = []
for channel_d... | 58ba7d4d47d91d2fe7c49c550487509dd494ab97 | 682,541 |
import numpy
def CombineChunks(float_array_input):
"""Converts a sliced array back into one long one. Use this if you want to write to .wav
Parameters
----------
float_array_input : float
The array, which you want to slice.
Returns
-------
numpy array
The sliced arrays.
... | 9d2ac778009b51fb5659fca8a2c3c50e7bf1227e | 682,542 |
def eia_mer_url_helper(build_url, config, args):
"""Build URL's for EIA_MER dataset. Critical parameter is 'tbl', representing a table from the dataset."""
urls = []
for tbl in config['tbls']:
url = build_url.replace("__tbl__", tbl)
urls.append(url)
return urls | 6d753c6c191ce27e52749407b575203452183d4c | 682,543 |
def context_feature_columns():
"""Returns context feature columns."""
return {} | 6bb7c55f40445dff3f974c8485bc1fe9ecaeef73 | 682,544 |
import torch
def cg(Avp_f, b, x0=None, nsteps=None, rdotr_tol=1e-10):
"""
:param Avp_f: function handler f(x) that calculates A @ x on given x
:param b: see description above, same shape with x
:param x0: initial point of solver, default is 0
:param nsteps: maximum try steps, default equals to dim... | aa1c8f7d9d89ee6028a1ad164863146b3bb56fab | 682,545 |
def safe_index(l, e):
"""Gets the index of e in l, providing an index of len(l) if not found"""
try:
return l.index(e)
except:
return len(l) | 223d89964888293586726f29978e195549c8c134 | 682,546 |
import codecs
import json
def load_json(path_to_json: str) -> dict:
"""Load json with information about train and test sets."""
with codecs.open(path_to_json, encoding='utf-8') as train_test_info:
return json.loads(train_test_info.read()) | 729cbfb714594e00d6d8ceb786ea8f55e094905b | 682,547 |
def template_pattern(name, disambiguator = ''):
"""
Returns regex matching the specified template.
Assumes no nested templates.
"""
disambiguator = str(disambiguator) # used to prevent duplicate group names
z = ''.join(x for x in name if x.isalpha())[:20] + str(len(name)) + disambiguator
t =... | aacd997271efe064155ddcae18fe3e6d99d45c5b | 682,548 |
import base64
import os
def get_binary_file_downloader_html(bin_file, file_label='File'):
"""From:https://blog.jcharistech.com/2020/11/08/working-with-file-uploads-in-streamlit-python/"""
with open(bin_file, 'rb') as f:
data = f.read()
bin_str = base64.b64encode(data).decode()
href = f'<a href... | cbdf7acff41ba6f577b4afd64f60e95e96707008 | 682,549 |
def _and(arg1, arg2):
"""Boolean and"""
return arg1 and arg2 | 3456e68c2d06dc212ddff43869bb760b85245729 | 682,550 |
def caesar_cipher_encryptor(input_s, key):
"""
@brief Given non-empty string of lowercase letters and non-negative integer
representing a key, return new string obtained by shifting every letter in
input string by k positions in the alphabet, where k is the key.
"""
lower_case_alphabet = "abcdef... | 617373b020010eba94f36971f69bf4be2bf27005 | 682,552 |
def string_is_hex(color_str):
"""
Returns whether or not given string is a valid hexadecimal string
:param color_str: str
:return: bool
"""
if color_str.startswith('#'):
return len(color_str) in (4, 7, 9)
else:
return len(color_str) in (3, 6, 8) | 05253e83a065afde590246dc402aeda39dfe01e8 | 682,553 |
def reformat_companies(data):
"""
Reformats the mca.gov.in data to global standard by renaming and restructuring. Also removes some unneeded columns
:param data: unformatted data
:return: Formatted data
"""
rename = [
['Paid up Capital(Rs)', 'Paid up capital'],
['Date of last AG... | 9bddd32fded1f2e58f1288dc0c35a8312e0f8f8d | 682,554 |
def get_repositories(reviewboard):
"""Return list of registered mercurial repositories"""
repos = reviewboard.repositories()
return [r for r in repos if r.tool == 'Mercurial'] | 520235347e3cb32bcb190d69f5038feaa966753f | 682,555 |
import importlib
import sys
def __get_test_function(test_module_name):
"""
Load the test module and return the test function
"""
print("QGIS Test Runner - Trying to import %s" % test_module_name)
try:
test_module = importlib.import_module(test_module_name)
function_name = 'run_all'... | 9e1af5115333c69154ed96a7ebd9797dba18ba89 | 682,556 |
import grp
def check_gid(gid):
""" Get numerical GID of a group.
Raises:
KeyError: Unknown group name.
"""
try:
return 0 + gid # already numerical?
except TypeError:
if gid.isdigit():
return int(gid)
else:
return grp.getgrnam(gid).g... | 5d3151754da1eaf83507288bb2ecdde25e2f27ad | 682,557 |
def bin_to_str(val):
""" Converts binary integer to string of 1s and 0s """
return str(bin(val))[2:] | f3043dfb8ca6f8c9cc4b3d7405ed47b96e886f33 | 682,558 |
def is_pot(n):
"""\
Check if n is the power of 2. It can also be done by using logical right
shift operator in O(n) time, where n is the bits of n's type.
"""
return n == n & -n | 12345d9520e521d1d26df25bf69baec709f8fe73 | 682,559 |
def get_parse_context(i, deps, data):
"""
get the two elements from data at position 'i' linked through deps [left|right] (to last added edges)
"""
if i == -1 or not len(deps):
return '', ''
deps = deps[i]
valency = len(deps)
if valency == 1:
return data[deps[-1]], ''
els... | de278c1904410e7890cd735f75b262190b27a4db | 682,560 |
import signal
def register_signal_handler(sig, handler):
"""Registers a signal handler."""
return signal.signal(sig, handler) | 1a845312b958f70dc6efd2fdcb491bb37ac2cae7 | 682,562 |
import math
def norm2(point_1, point_2):
"""
Using least squares to get a straight line distance.
You could use easting,northing points for these calculations
:param point_1:
:param point_2:
:return:
"""
x_1, y_1 = point_1
x_2, y_2 = point_2
return math.sqrt((x_1 - x_2) ** 2 + ... | 20dd0a7e68dad41eef1de43e33ed10cac5385326 | 682,563 |
import sys
def chooseMultipleItem(msg, *elem):
"""
Convenience function to allow the user to select multiple items from a
list.
"""
n = len(elem)
if n > 0:
sys.stdout.write(msg + "\n")
for i in range(n):
sys.stdout.write(" %d - %s\n" % (i + 1, elem[i]))
s... | dbffc23030e9a821f89b80229183acf06ae949d5 | 682,564 |
import re
def wiki_to_md(text):
"""Convert wiki formatting to markdown formatting.
:param text: string of text to process
:return: processed string
"""
fn = []
new_text = []
fn_n = 1 # Counter for footnotes
for line in str(text).split('\n'):
# Replace wiki headers with markd... | fd55f23a222d807dcc789145c1a58d1f9709e3c4 | 682,565 |
def compute_distances_graph(nodes, edges):
""" Run message passing to compute minimum distances.
Takes a list of nodes with nodeids and edges (expressed using those nodeids)
Returns a dictionary mapping from nodeid u to a dictionary that maps from a nodeid v
to an integer that is the minimum... | d256e77dda40e4b5b213c575ace9545796b465d5 | 682,566 |
def AfterTaxIncome(combined, expanded_income, aftertax_income,
Business_tax_expinc, corp_taxliab):
"""
Calculates after-tax expanded income.
Parameters
----------
combined: combined tax liability
expanded_income: expanded income
corp_taxliab: imputed corporate tax liabili... | 6c8f570169356d81c40cfd358df1d036ab15b4b3 | 682,567 |
import os
def walk_dir(search_dir,ext=".shp",white_list=None):
"""
預設是找到目錄內有的 .shp 檔案的 pathname 回傳
如果有提供 white_list, 則只會找到那些檔案。用在新增幾個檔案要匯入的情況
"""
pathnames = []
for dirpath, dirnames, filenames in os.walk(search_dir):
#print("dirpath=%s\ndirnames=%s\nfilenames=%s" %(dirpath, dirnames, ... | 04c2c8fb3e77e1843f2d8abef21b585afdfe5cf6 | 682,568 |
def IsUnderAlphabet(s, alphabet):
"""
#################################################################
Judge the string is within the scope of the alphabet or not.
:param s: The string.
:param alphabet: alphabet.
Return True or the error character.
########################################... | f2db8362373b9fe07133e8b40369dd7f0516b6ca | 682,569 |
from pathlib import Path
from typing import List
import os
def directory_remove_file(
path: Path,
file_names: List[str]
) -> List[str]:
"""
Parameters
----------
path : Path
The path of the file to remove.
file_names : List[str]
The list of files from which to remove the pa... | 63ee675b3c033846696361b9cb532a61d3ef39cd | 682,570 |
def _find_tbl_starts(section_index, lines):
"""
next three tables are the hill, channel, outlet
find the table header lines
:param section_index: integer starting index of section e.g.
"ANNUAL SUMMARY FOR WATERSHED IN YEAR"
:param lines: loss_pw0.txt as a list of strings
... | a64feb7ccf444c8ec57928ce4a6756143ed2a11d | 682,572 |
import functools
def custom_sum(*args):
"""This function can sum any objects which have __add___"""
return functools.reduce(lambda x, y: x + y, args) | 6946b90859ce6595dfcb409772db270c7677b3fb | 682,573 |
import numpy
def create_circle(R=0.5, center=(0.0, 0.0), ds=0.01):
"""
Generate coordinates of circle.
Parameters
----------
R: float, optional
radius;
default: 0.5.
center: 2-tuple of floats, optional
center's coordinates;
default: (0.0, 0.0).
ds: float, optional
me... | 89fa5250f6e7d66402a8c7f06e709fd851e01a01 | 682,574 |
def decode_list_index(list_index: bytes) -> int:
"""Decode an index for lists in a key path from bytes."""
return int.from_bytes(list_index, byteorder='big') | 3e7616fe04bf60e69772ead027617d75ba75988a | 682,575 |
import glob
import os
def find_files(d, k=""):
"""
Name: find_files
Inputs: - str, file path (d)
- str, keyword(s) in the file to search (k)
Outputs: List
Features: Searches the given directory for word files
"""
my_files = glob.glob(os.path.join(d, k))
return sort... | 5ff80155fee232a0e6ae19efab8543ae9b76835c | 682,576 |
def mode_decomposition(plant):
"""Returns a list of single mode transfer functions
Parameters
----------
plant : TransferFunction
The transfer function with at list one pair of complex poles.
Returns
-------
wn : array
Frequencies (rad/s).
q : array
Q factors.
... | e2520a0e0f860b16127a9a16081f1b9c33c792fd | 682,577 |
def index():
"""Default handler for the test bench."""
return "OK" | 961fcbd19f5eb90e32cae02d280f20e2a8006b82 | 682,578 |
def assign_province_road_conditions(x):
"""Assign road conditions as paved or unpaved to Province roads
Parameters
x - Pandas DataFrame of values
- code - Numeric code for type of asset
- level - Numeric code for level of asset
Returns
String value as paved or unpav... | 81fe01661bf184dd52795f4b8b0ecf3c04e4f917 | 682,579 |
import ast
def guess_type(string):
"""
Guess the type of a value given as string and return it accordingly.
Parameters
----------
string : str
given string containing the value
"""
string = str(string)
try:
value = ast.literal_eval(string)
except Exception: # Synt... | 8436957a6c1ef8eb35812ff75b6091af9ccb6eed | 682,580 |
def description(language='en', value=''):
"""Create and return a description (dict)"""
return {language: {'language': language, 'value': value}} | c5f1533caf4a263804d307905ca4580d33f4816b | 682,581 |
from typing import List
def split_high_level(s: str,
c: str,
open_chars: List[str],
close_chars: List[str]
) -> List[str]:
"""Splits input string by delimiter c.
Splits input string by delimiter c excluding occurences
of ... | a9b3db6b43ae62fc18feecaee43cc56689e02546 | 682,582 |
import os
def _get_file_name(nii_file):
"""Construct the raw confound file name from processed functional data."""
if isinstance(nii_file, list): # catch gifti
nii_file = nii_file[0]
suffix = "_space-" + nii_file.split("space-")[1]
# fmriprep has changed the file suffix between v20.1.1 and v2... | 4963146b15d4a9652f323019ec78fd76298f2c84 | 682,583 |
def semicolon_separated_strings(value):
"""Turn lists into semicolon separated strings"""
if isinstance(value, list):
return ';'.join(semicolon_separated_strings(v) for v in value)
return str(value) | cbf73944e18def47be8c7c10ab8a1fa9a9b466ce | 682,584 |
import re
def fix_N_not_V(input_line):
""" Fix cases where the PSpice netlist used N() rather than V(). """
n_line = input_line
n_line = re.sub(r"( N)(\([^\n]+\))",
repl=r" V\2",
string=n_line,
flags=re.IGNORECASE)
return n_line | 3793f6a7655bf0a469297d029becdce8dfe011bc | 682,585 |
def tonumpy(img):
"""
Convert torch image map to numpy image map
Note the range is not change
:param img: tensor, shape (C, H, W), (H, W)
:return: numpy, shape (H, W, C), (H, W)
"""
if len(img.size()) == 2:
return img.cpu().detach().numpy()
return img.permute(1, 2, 0).c... | 2e045b817be6d88f463315222a26dbc13389319a | 682,586 |
import re
def substitute_query_params(query, params):
"""
Substitutes the placeholders of the format ${n} (where n is a non-negative integer) in the query. Example, ${0}.
${n} is substituted with params[n] to generate the final query.
"""
placeholders = re.findall("((\${)(\d+)(}))", query)
for... | 89bbc525a549e8484fa1e2a8b4da3d0083b37aa8 | 682,587 |
def human_readable(kb):
"""
Returns an input value in KB in the smallest unit with a value larger than one as a
human readable string with the chosen unit.
"""
format = "%3.2f %s"
for x in ['KiB','MiB','GiB']:
if kb < 1024.0 and kb > -1024.0:
return format % (kb, x)
... | 362c7290fe352859d2ea00235bc8333dc9c11b70 | 682,589 |
import argparse
def parse_command_line():
"""Parse the command line arguments."""
parser = argparse.ArgumentParser(prog="check_abi")
parser.add_argument("-d", "--work_path", default="/var/tmp", nargs="?",
help="The work path to put rpm2cpio files and results"
... | 82dd9d47c8dd0ac8e6faa01b816d67db69dda8ae | 682,590 |
import re
def get_mapbender_config_value(base_dir, variable):
""" Returns the requested mapbender.conf value
Args:
base_dir: File path
variable: Requested variable name
Returns:
The variable value
"""
define_pattern = re.compile(r"""\bdefine\(\s*('|")(.*)\1\s*,\s*('|")(.*... | f8c338bf093eba998f8950509a57d0e7f3512476 | 682,591 |
def get_layer_by_name(model, layer_name):
"""
Helper function to get layer reference given layer name
:param model : model (nn.Module)
:param layer_name : layer_name
:return:
"""
for name, module in model.named_modules():
if name == layer_name:
return module
... | 643573831d8fca2a7a154efb78040e21849c802a | 682,592 |
import time
import select
import struct
def recv_ping(icmp_socket, dest_addr, id, timeout):
"""Receive a single ICMP packet"""
while True:
start_time = time.time()
ready = select.select([icmp_socket], [], [], timeout)
time_in_select = (time.time() - start_time)
if ready[0] == ... | d017b3b1102bbedf99fe2e7faee59dfd70c8bda7 | 682,593 |
def group_text(text, n=5):
"""Groups the given text into n-letter groups separated by spaces."""
return ' '.join(''.join(text[i:i+n]) for i in range(0, len(text), n)) | 0918cda00b4ac0e1692bde3c939207eb4fa8896e | 682,594 |
def p_length_unit(units):
"""Returns length units string as expected by pagoda weights and measures module."""
# NB: other length units are supported by resqml
if units.lower() in ['m', 'metre', 'metres']: return 'metres'
if units.lower() in ['ft', 'foot', 'feet', 'ft[us]']: return 'feet'
assert(False) | 31d5c355231a23f3e71dd35328862d1522ef91e2 | 682,595 |
def GetTablesInQuery(columns, values):
"""Returns a set of table names that are joined in a query."""
q_tables = set()
for col, val in zip(columns, values):
if col.name.startswith('__in_') and val == [1]:
q_tables.add(col.name[len('__in_'):])
return q_tables | f214733e0df1507285fc8653c06e561b2e65aa9a | 682,596 |
def stdin(sys_stdin):
"""
Imports standard input.
"""
inputs = [x.strip("[]\n").split(",") for x in sys_stdin]
return [int(x) for x in inputs[0]] | 2dcab519dc25461c68e92b8682f2a08ce4a9155d | 682,597 |
from typing import Callable
def fname(func: Callable) -> str:
"""Return fully-qualified function name."""
return "{}.{}".format(func.__module__, func.__name__) | e7c6f6b0d2eb955066a4bc68c6184e263b5352a1 | 682,598 |
def get_object_typename(o):
"""We determine types based on type names so we don't have to import
(and therefore depend on) PyTorch, TensorFlow, etc.
"""
instance_name = o.__class__.__module__ + "." + o.__class__.__name__
if instance_name in ["builtins.module", "__builtin__.module"]:
return o... | e206ca99fa013e9b12ef38f21f2bd032724681b7 | 682,599 |
def Calc_SAVI(Reflect,L):
"""
This function calculates and returns the Surface albedo, NDVI, and SAVI by using the refectance from the landsat image.
"""
# Computation of Soil Adjusted Vegetation Index (SAVI)
SAVI = (1 + L) * ((Reflect[:, :, 3] - Reflect[:, :, 2]) /
(L + Refle... | 2130dfd69977569ca799134c8c11d9e146e6e2f1 | 682,600 |
def loaded_graph_(graph):
"""
:type graph: qmxgraph.widget.qmxgraph
:rtype: qmxgraph.widget.qmxgraph
"""
graph.load_and_wait()
return graph | 3ab62a2bb06361babcb5cb4cc2fc9cd0fd5630ae | 682,602 |
import inspect
import functools
def get_function_doc(func):
"""获取函数的doc注释
如果函数被functools.partial包装,则返回内部原始函数的文档,可以通过设置新函数的 func.__doc__ 属性来更新doc注释
"""
partial_doc = inspect.getdoc(functools.partial)
if isinstance(func, functools.partial) and inspect.getdoc(func) == partial_doc:
while isin... | 0e9390757dcc3b8e2a50d1f10dd778461eaefa7e | 682,604 |
def dot4(a,b):
""" 4 vect dot product"""
return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3] | 283a37c22d6d9d02a938de72dfb193d389ef3f53 | 682,605 |
import click
def purge_queue():
"""Purge indexing queue."""
def action(queue):
queue.purge()
click.secho('Harvester queue has been purged.', fg='green')
return queue
return action | 610ad0ae75934ad2f7af097992dea8e8bd4712c7 | 682,606 |
def func2(a, b):
"""
this is func2
"""
return a, b | b836c7472e7376e238e74071cfd8ac2db59ae3cd | 682,607 |
def is_palindrome(s):
"""
is_palindrome
-------------
Takes in a string as an input
Outputs a boolean of True or False
Depending on the outcome of the question
- is this strong a plaindrome
"""
# normalise our string to have all lower case letters
lower_s... | 0a779e7bf2adf58a05099f9798189f8ff82e0e8e | 682,608 |
def swap_namedtuple_dict(d):
"""
Turn {a:namedtuple(b,c)}
to namedtuple({a:b},{a:c})
"""
if not isinstance(d, dict):
return d
keys = list(d.keys())
for k, v in d.items():
assert v._fields == d[keys[0]]._fields
fields = d[keys[0]]._fields
t = []
for i in range(len(... | c0d9a33682664db14a5e795736cf0d02fcb1cd91 | 682,609 |
def getNrOfDictElements(thisdict):
"""
Will get the total number of entries in a given dictionary
Argument: the source dictionary
Output : an integer
"""
total = 0
for dicttype in thisdict:
for dictval in thisdict[dicttype]:
total += 1
return total | 4721f023d2059924697622edd9a3786ac28f08cb | 682,610 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.