content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import random
def chooseWords(wordList):
"""
Mengembalikan sebuah kata random yang diambil dari wordlist
"""
return random.choice(wordList) | 9739588a00985981eb01f285c504b30766076718 | 669,802 |
from datetime import datetime
def past_date(date_string):
"""checks whether date given is a past date
:returns True for past date, False otherwise."""
try:
str_to_date = datetime.strptime(date_string, "%Y-%m-%d %H:%M").date()
if str_to_date > datetime.now().date():
return False... | b71ed70d63cfb5710649294f51933bcf41de22a1 | 669,803 |
def time_to_str(delta_t, mode="min"):
"""Convert elapsed time to string representation
Parameters
--------
delta_t: time difference
Elapsed time
mode: str
Time representation manner, by "minitues" or "seconds".
Returns
--------
delta_str: str
Elapsed time string... | f1cba8a07fd75e82a0a9009739ab6e9e23c371ac | 669,804 |
def find_squeezenet_layer(arch, target_layer_name):
"""Find squeezenet layer to calculate GradCAM and GradCAM++
Args:
arch: default torchvision densenet models
target_layer_name (str): the name of layer with its hierarchical information. please refer to usages below.
target_layer_na... | 0294e443804fc28ee69e9cfae9280e101151d08a | 669,805 |
import torch
def VariableRecurrent(inner):
""" Copied from torch.nn._functions.rnn without any modification """
def forward(input, hidden, weight, batch_sizes):
output = []
input_offset = 0
last_batch_size = batch_sizes[0]
hiddens = []
flat_hidden = not isinstance(hidde... | 2941fa49aabbe6824b8d3e5dfb73e22a41ff4332 | 669,806 |
def is_in_bijection(a, b):
"""
Test if a bijection exists between the elements of :attr:`a` and the elements of :attr:`b`.
Given two numpy arrays :attr:`a` and :attr:`b` returns ``True`` if
- :attr:`a` and :attr:`b` have same size
- there exists a bijective function :math:`f` such that, fo... | e227d33e820238cc1b5895274cadd94dfb9c80a7 | 669,807 |
def commit_query(include_pr: bool, include_author: bool) -> str:
"""Helper function to build a graphql query for github.
The output of this function is meant to go inside the repository
field.
"""
author = '''
author {
name
email
user {
login
}
... | b9045db2a335b991ba8043f2546353077d9714d7 | 669,808 |
def is_word_guessed(secret_word, letters_guessed):
"""
secret_word: string, the word the user is guessing; assumes all letters are
lowercase
letters_guessed: list (of letters), which letters have been guessed so far;
assumes that all letters are lowercase
returns: boolean, True if all the le... | 14377e1638e271b8d24207dcb56871a6a336d492 | 669,809 |
import math
def sinh(x):
"""Get sinh(x)"""
return math.sinh(x) | 8adf2afd4858ed6e0e73cd4237bec5197b7393ad | 669,810 |
def norm_to_max(vals):
"""Normalizes items in vals relative to max val: returns copy."""
best = max(vals)
return [i/best for i in vals] | 874b54fde9386a197d80b80e8632f0826796eb90 | 669,811 |
def predistortion_enabled(session, Type='Boolean', RepCap='', AttrID=1150005, buffsize=0, action=['Get', '']):
"""[Predistortion Enabled <?>]
Sets/Gets the Predistortion Enabled attribute.
If true (the default), any waveforms that are created are pre-distorted to compensate for amplitude and phase variatio... | b8808df07784c69cb2a55a1c38cdd93ab7e82259 | 669,813 |
def build_between_sentence_data(data):
"""
extract the inter-sentential level parsing
return a list
each element in the list is a list of root EDUs of each sentences in a
discourse
"""
between_sentence_data = []
for edus in data:
between_sentence_data.append([])
for edu ... | 7cb03f0975e1aff2298af1ab1d13198e7fac7e84 | 669,814 |
import os
def _tile_from_img(img):
"""
Turns an img into the appropriate x, y, z tile based on its filename.
Imgs have a filename attribute which is something
like "lib/cartopy/data/wmts/aerial/z_0/x_0_y0.png"
"""
_, z = os.path.basename(os.path.dirname(img.filename)).split('_')
xy, _ = ... | 4dd0b975d18e9e172f3de454e4c50268e2db3ed2 | 669,815 |
def prefix_string() -> str:
"""Use string as prefix."""
return "test" | 6e3d89079b67f8d7cb4eaac28cfdebaead01d733 | 669,816 |
import argparse
def cmdLineParse():
"""Command line parse."""
parser = argparse.ArgumentParser(
description="plots coherence matrix of a neighborhood"
)
parser.add_argument(
"-i", dest="inputDS", type=str, required=True, help="Input Stack VRT"
)
parser.add_argument(
"-w... | 2c626a2fc81a5b2a1d6d5055013d62c0e2210eea | 669,817 |
def _abs(arg):
"""Returns the absolute value."""
return abs(arg) | d42359d5307701df2593c4b605f478fc9b4f516b | 669,818 |
import os
def handle_user_opts(variables, defaults):
""" Some variables are dependent upon default values
We do the probably hacky thing of going through
and updating them accordingly
We make the assumption / decision that only
the first basedir value supplied should
be ap... | 038e41fccc493fcee8940b39d4b75c52683e74ff | 669,819 |
def verletDerivCalc(function:float,y1stDerivHalf:float,h:float) -> tuple:
"""2nd part of algorithm - demands f(x+h,y(m+1),y'(m+1/2))"""
y2ndDeriv = function # simple assignment
y1stDeriv = y1stDerivHalf + 0.5*h*y2ndDeriv
return (y1stDeriv,y2ndDeriv) | c9ea8361d9ccea3a3261a4d7bab48b55fe4d05d5 | 669,822 |
def sort_two_list(list1, list2, reverse=False):
"""
排序两个列表
:param list1: 列表1
:param list2: 列表2
:param reverse: 逆序
:return: 排序后的两个列表
"""
list1, list2 = (list(t) for t in zip(*sorted(zip(list1, list2), reverse=reverse)))
return list1, list2 | a87ead7e0cd4a40d0fd07d2c1af87b5ab03d03db | 669,823 |
def get_utility_command_output_filename(name, selector=None):
"""
Return the filename to the output of the utility command.
:param name: utility name (string).
:param selector: optional special conditions flag (boolean).
:return: filename (string).
"""
return "" | e03d25380ef97bac7b7df6739b3b1e5a6d17b11c | 669,824 |
from typing import List
from typing import Any
def node_values_for_tests() -> List[Any]:
"""[summary]
Returns:
List[Any]: list of potential node values
"""
return [1, 2, 3, 4, 5, 6, 7, "spam", "sausage"] | b77fd6d0e5788737d2e1935ceb076d1a8afafdbb | 669,825 |
def add_chars() -> bytes:
"""Returns list of all possible bytes for testing bad characters"""
# bad_chars: \x00
chars = b""
chars += b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f"
chars += b"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"
chars += b"\x20\x21\x2... | cce8008085e6480642dad23b8e3a11728912d9ae | 669,826 |
import subprocess
import shlex
def _call(cmd, **kwargs):
"""A wrapper over subprocess.call that splits cmd with shlex.split"""
return subprocess.call(shlex.split(cmd), **kwargs) | d0f2bf11d7b844853d0d3b8d96a13720a4354af1 | 669,828 |
def _flatten(tree, u, to_lang, **kw):
"""Recursively flatten C{tree}.
@rtype: C{str}
"""
s = tree.succ[u]
if not s:
return to_lang(u, **kw)
elif len(s) == 2:
l, r = s
if 1 in s[l]:
l, r = r, l
l = _flatten(tree, l, to_lang, **kw)
r = _flatten(... | 2aaeb4000ec9db5b63dd478c1e4cd6f0ff0225b2 | 669,829 |
def convert_to_binary(x: int) -> str:
"""Convert a base-ten integer into its binary equivalent."""
# divide x by 2
# the remainder is the last binary digit
# divide the quotient of x // 2 by 2
# the remainder is the second-to-last binary digit
# repeat until quotient == 0
def inner(x):
... | 32e65fe325871fa53ff181a19301f1043f367951 | 669,830 |
import math
def xy_yaw_from_quaternion(quat):
"""Calculate the yaw angle in the xy plane from a rotation quaternion.
:param quat: A unit quaternion representing the
:type quat: Any container that has numerical values in index 0, 1, 2 and 3
:return: The yaw angle in radians projected on the xy plane
... | 255225c80bba64f0d347871584db8a4138c199b8 | 669,832 |
import os
def collect_new_sosreports(server, username):
"""
A function to generate sosreports.
Args:
server: hostname/IP server from which sosreport
has to be collected.
username: User to be used to login.
Returns:
bool: True if successful else false.
"""
comm... | 41234f40d5e7e4b273b0fa531f34cfbdfc7f6aa7 | 669,833 |
def get_wandb_project_dict_trainval(project_name):
"""Return wandb project dictionary
Args:
project_name (str): wandb project name
Returns:
dict: dictionary containing best models run_id split_name and dataset_name
"""
res = None
if project_name == "lastfm_dat":
res = {... | cc2d63ccfc374096e8b67020dad1e8a899529354 | 669,834 |
import sys
import functools
import warnings
def for_testing_only(func, _testing_check=lambda: 'pytest' in sys.modules):
"""
A decorator that marks a function as available for testing purposes only.
If the decorated function is called outside of testing, a warning is raised.
Testing this decorator lea... | 31d3aa4305dd175d241aeb2b19f9a0504ec1a257 | 669,835 |
import json
def discrete(cats, name="discrete"):
"""Return a class category that shows the encoding"""
ks = list(cats)
for key in ks:
if isinstance(key, bytes):
cats[key.decode("utf-8")] = cats.pop(key)
return "discrete(" + json.dumps([cats, name]) + ")" | 621b64e4cf2203036614973a7463ec5bd04a64cf | 669,836 |
def get_prefix(prefix: str, session, fqdn) -> dict:
"""Get a prefix object from the API."""
url = "{}/ipam/prefixes/?prefix={}".format(
f"http://{ fqdn }/api", prefix.replace("/", "%2F")
)
result = session.get(url)
return result.json()["results"][0] | 8f91a87ee6809118bbf03b454925dbb5b3ecb18c | 669,837 |
def bubble_sort(input_list):
"""Bubble sort."""
if not isinstance(input_list, (list, tuple)):
raise ValueError('input takes list/tuple only')
if isinstance(input_list, (tuple)):
input_list = list(input_list)
if not all(isinstance(val, (int, float)) for val in input_list):
raise... | f0b55393734923f82581d0999a387b4804678438 | 669,838 |
from typing import Any
def option_selected(variable: Any, testvalue: Any) -> str:
"""
Returns ``' selected="selected"'`` if ``variable == testvalue`` else
``''``; for use with HTML select options.
"""
return ' selected="selected"' if variable == testvalue else '' | aedf22cbf5b5078835cd32656e4d0b789c48e54f | 669,839 |
def get_ordinary_word(ord_path):
"""常用词词典"""
ord_dic = []
with open(ord_path, 'r', encoding='utf8') as fr:
for line in fr.readlines():
ord_dic.append(line.split()[0])
return ord_dic | 3b2c847b2561211494cf899be0eaf72623e5dd79 | 669,842 |
def handle_args(pwb_py, *args):
"""Handle args and get filename.
@return: filename, script args, local args for pwb.py
@rtype: tuple
"""
fname = None
index = 0
for arg in args:
if arg.startswith('-'):
index += 1
else:
fname = arg
if not fn... | acd7ec2d05e719a73f329469a0c3569312ea9781 | 669,843 |
def loss_rate(loss_q, win_start_idx, pkt_loss_cur, recv_time_cur_us,
recv_time_prev_us, win_size_us, pkt_idx):
""" Calculates the loss rate over a window. """
# If there were packet losses since the last received packet, then
# add them to the loss queue.
if pkt_loss_cur > 0 and pkt_idx > ... | 27f6e560d0cf63b240965b3fc8a1bf813464c885 | 669,844 |
from typing import Dict
def is_active_user(user: Dict) -> bool:
"""
Returns true if the user is active and not the bot
:param user: the user to check
:return: boolean if user is active
"""
return (user is not None
and not user['deleted']
and not user['is_restricted']
... | 0ce709a32eef92dd12493c7e8877b7ebed643437 | 669,845 |
import os
def to_unix_path(file_path):
"""Utility function to turn a Windows-style path into Unix-style. Windows
can handle the latter, so we use this representation internally. Python can
handle this in any case. We also replace Windows' ";" for path separation by
os.pathsep to make sure this runs on... | 3f3f808a6c6bc6d41b10c0edf4b451e49dd77dcf | 669,847 |
import sys
import os
import gettext
import inspect
def find_localedir(localedir):
"""
Custom function to find the locales message catalog in a multi-platform
application.
"""
if localedir is None:
if sys.platform.startswith('linux'):
return gettext.bindtextdomain('messages')
... | eb99db6db82f7d586e849a925f5158007f29f760 | 669,848 |
from typing import Union
import os
def readme_location(filename: Union[str, str] = "README.md") -> str:
"""Path to the README file"""
current_dir = os.getcwd()
readme_file = os.path.join(current_dir, filename)
return readme_file | e740818f9c4da0eb1a52e8f2c00c3e2e45ee0145 | 669,849 |
import types
def copy_func(f, name=None):
"""
Return a function with same code, globals, closure, and name (or provided name).
"""
fn = types.FunctionType(f.__code__, f.__globals__, name or f.__name__,
f.__defaults__, f.__closure__)
# If f has been given attributes
fn.__dict__.upda... | 65be84ec7e46c7f6726248fa627bfd9b800a24af | 669,850 |
def __eq__(self, other):
"""Common `__eq__` implementation for classes which has `__slots__`."""
if self.__class__ is not other.__class__:
return False
return all(getattr(self, attr) == getattr(other, attr)
for attr in self.__slots__) | bcc9f70e3b27b0a19fe7ed99858a616cac05ffac | 669,851 |
def compute_delta(num_levels):
"""Computes the delta value from number of levels
Arguments
---------
num_levels : int
The number of levels
Returns
-------
float
"""
return num_levels / (2.0 * (num_levels - 1)) | ad97e2041453863e82fc259780f1a125b9e81776 | 669,852 |
def label_wrapper(func):
"""Adds a label function argument to func and returns unchanged label."""
def wrapper(images, label, *args, **kwargs):
return func(images, *args, **kwargs), label
return wrapper | a1f3632c863adc2ba2453b66e4b481c67d2a425e | 669,853 |
def _replace_slash(s, replace_with="__"):
"""Conda doesn't suppport slashes. Hence we have
to replace it with another character.
"""
return s.replace("/", replace_with) | 277a03faf4a87294fdd702082de68ef20d6fe895 | 669,854 |
import torch
def true_divide(x, y):
"""Divides x / y elementwise (using Python 3 division operator semantics).
NOTE: Prefer using the Tensor operator or divide which obey Python
division operator semantics.
This function forces Python 3 division operator semantics where all integer
arguments are... | b4ba1137ba4eade861c8eb9b87bf2207030d531f | 669,855 |
def _set_object_from_model(obj, model, **extra):
"""Update a DesignateObject with the values from a SQLA Model"""
for fieldname in obj.FIELDS:
if hasattr(model, fieldname):
if fieldname in extra.keys():
obj[fieldname] = extra[fieldname]
else:
obj[... | 7920a759a40a67c04ca4a8712aa77d83c8f85ae5 | 669,856 |
def str_to_class(cls_name: str) -> type:
"""
Converts a string into the class that it represents
NB: Code based on https://stackoverflow.com/questions/452969/does-python
-have-an-equivalent-to-java-class-forname
:param cls_name: The string representation of the desired class
:return: A pointer ... | 5fe2b06697fed364c3cd6c1a4574e27e44a00a40 | 669,857 |
def rescol(rescol):
""" Comfirms that a give value is a valid results column and returns
the corresponding units column and results column.
"""
if rescol.lower() == 'concentration':
unitscol = 'units'
elif rescol.lower() == 'load_outflow':
unitscol = 'load_units'
else:
ra... | 8d007227b2a19b071d32776d37b43774a6e83134 | 669,858 |
import glob
import os
def get_cog_files():
"""
Returns a list of cog files within the program's known directories.
"""
cogs = [os.path.basename(f) for f in glob.glob("cogs/*.py", recursive=True)]
return [f[:len(f)-3] for f in cogs] | fa4445931264210da1cd56f56f28a680bc43280b | 669,859 |
import re
def natural_keys(text):
"""Sort strings naturally.
Sort a list of strings in the natural sorting order.
Args:
text (str): Input text to be sorted
Returns:
(list): list of naturally sorted objects
"""
def atoi(text):
return int(text) if text.isdigit() else ... | d7c7b807b2c5c6540853c450ba482462de80e4db | 669,860 |
def remove_first_line(text):
"""Remove the first line from a text block.
source: string of newline-separated lines
returns: string of newline-separated lines
"""
_, _, rest = text.partition('\n')
return rest | 48d6449fba3c75e4e120676b5acf8ff92a5d6918 | 669,861 |
def ContentTypeTranslation(content_type):
"""Translate content type from gcloud format to API format.
Args:
content_type: the gcloud format of content_type
Returns:
cloudasset API format of content_type.
"""
if content_type == 'resource':
return 'RESOURCE'
if content_type == 'iam-policy':
... | 3676261db84286e5e410a5cceb7423bfdec47dce | 669,862 |
def get_fk_model(model, fieldname):
"""returns None if not foreignkey, otherswise the relevant model"""
field_object, model, direct, m2m = model._meta.get_field_by_name(fieldname)
if direct and field_object.get_internal_type() in [
"ForeignKey",
"OneToOneField",
"ManyToManyField",
... | 2bed2f0f8018ada2416573bcfbd00f3d5e23c115 | 669,863 |
def valida_produto(numero_produto, estoque):
"""
Funcao para verificar se o numero produto passado eh valido
:param numero_produto: string dada como input pelo usuario contendo o numero do produto
:param estoque: lista de estoque atualizado
:return: produto_valido (bool), numero_produto (int)
""... | e45ead1ce3df1cfd46b3da406cacd8d6992fe225 | 669,864 |
def join_and_wash(split, data_list):
"""
join and wash
:param split:
:param data_list:
:return:
"""
return split.join(data_list).replace("\r", "").replace("\t", "").replace("\n", "").strip() | 4d73a99f059ab86439486c6ae82403a5c386f4e2 | 669,865 |
import json
def load_circuit_ordering(file):
"""Loads a circuit ordering (e.g. mapping from spin-orbitals to qubits) to a file.
Args:
file (str or file-like object): the name of the file, or a file-like object.
Returns:
ordering (list)
"""
if isinstance(file, str):
wi... | 05977ce119db9f5a737a455dfc04c25c6f154828 | 669,866 |
import time
def gen_time_str():
""" tool function """
return time.strftime("%Y%m%d_%H%M%S", time.gmtime()) | 810200a585f334b42344ac0e42a0926c8959335f | 669,867 |
def when_did_it_die(P0, days):
"""
Given a P0 and an array of days in which it was alive, censored or dead,
figure out its lifespan and the number of days it was alive'
Note, the lifespan is considered to last up to the last observation.
I.e., a worm that was observed to live 3 days, and died o... | 1f7a92ed04a69f006753777eaa2c56d17aa209e3 | 669,868 |
def op_to_dunder_unary(op: str) -> str:
"""Return the dunder method name corresponding to unary op."""
if op == '-':
return '__neg__'
elif op == '+':
return '__pos__'
elif op == '~':
return '__invert__'
else:
return op | f0606c7d29a5295fe30f055b0dc0b324d58c6528 | 669,869 |
from typing import List
def int_version(name: str, version: str) -> List[int]:
"""splits the version into a tuple of integers"""
sversion = version.split('-')[0].split('+')[0].split('a')[0].split('b')[0].split('rc')[0]
#numpy
#scipy
#matplotlib
#qtpy
#vtk
#cpylog
#pyNastran
# '... | a9b0bd338526486b465379e131ebd0bfdacd306a | 669,870 |
def is_natural_number(*arr):
"""Check if the numbers are natural number (includes zero).
:param arr: number array
:return: True if are natural number, or False if not
"""
for n in arr:
if n < 0:
return False
return True | 4a5f11a5249c60df37638f63b416c252d2841603 | 669,872 |
from typing import FrozenSet
def _overlap(set_a: FrozenSet, set_b: FrozenSet) -> bool:
"""Return True if there are overlapping items in set_a and set_b, otherwise return False.
# Passes as both sets have element 'b'
>>> _overlap(frozenset({'a', 'b'}), frozenset({'b', 'c'}))
True
# Fails as there... | 876ca5939750a6e50b9f5532a5d501f211cebde0 | 669,873 |
def _allows_downcast_fallback(super_class):
"""Get the whether downcast can fallback to a dict or not"""
return getattr(super_class, "__deserialize_downcast_allow_fallback__", False) | 335b212ee54a0e3e4935b0b88edd8a94f4cf2ece | 669,875 |
async def read_root():
"""Displays greeting message in homepage
Returns:
dict: a dictionary with greeting message
"""
return {"message": "✌"} | 0acf629d948ec362865d5db099aad4d7a80999bb | 669,876 |
from typing import List
def full_minutes(nums: List[float]) -> List[int]:
"""
Get a series of natural numbers from the smallest to the highest
supplied number for fetching weather data by coordinates.
Weather data is saved in objects by full lat-lng coordinates.
Each object contains again data fo... | 33233571da73799babb3f18a666a294e717c8dea | 669,878 |
def prefix(text: str): # NOTE: PEP 616 solved this in python version 3.9+
"""
Takes the first word off the text, strips excess spaces and makes sure to always return
a list containing a prefix, remainder pair of strings.
"""
segmented = text.split(' ', 1)
# ensure a list of 2 elements unpacked i... | b451af96350aff60da4ef5c3c25b2df2592f75cb | 669,879 |
import os
def get_relative_path(relative_dir):
"""."""
cur_path = os.path.dirname(os.path.realpath(__file__))
dir_path = os.path.normpath(os.path.join(cur_path, relative_dir))
return dir_path | d34ac52552d7ab0653f1cfb3ce5009c2330eb5d5 | 669,882 |
import os
def get_common_parent(paths):
"""Get the common parent directory of multiple absolute file paths."""
common_path = os.path.commonprefix(paths)
return os.path.dirname(common_path) | 475b205e50504e697bb901829947b626ad8f3e90 | 669,883 |
def greeting_dynamic(name):
"""Dynamically typed function."""
return "Hello " + name | f3182a62e7bd6992dd8b866252a738338d3b91e1 | 669,884 |
def application(environ, start_response):
"""A simple application function"""
resp_body = b'Hello, world!\n'
status = '200 OK'
resp_headers = [
('Content-Type', 'text/plain'),
('Content-Length', str(len(resp_body)))
]
start_response(status, resp_headers)
return [resp_body] ... | 1be7f9e4ee20cf90803bd70186bbabd4778a774f | 669,885 |
def ifexists(total_pages, page_no):
"""
This function checks whether the given page number is in the specified range
of total pages.
:param total_pages:
:param page_no:
:return: True or False
"""
if page_no <= total_pages:
return False
return True | 5f1c9022b89e38488dce74138e8d8341a9f09f9d | 669,886 |
import torch
def evaluate(model, loader):
"""Compute average of scores on each batch (unweighted by batch size)"""
return torch.mean(torch.tensor([model.score(batch) for batch in loader]), dim=0) | 916967ed89857b10f3fb54b4a6535c3d6b92f7ec | 669,887 |
def get_min_word_length():
"""Get user-inputted minimum word length for the game."""
while True:
min_word_length = input(
'What minimum word length do you want? [4-16] ')
try:
min_word_length = int(min_word_length)
if 4 <= min_word_length <= 16:
... | 5167b8b1d9f6a8bdb29098c8d3d702a332adc29f | 669,888 |
import time
import os
def file_age(fn):
"""Get the age of a file in seconds"""
return time.time() - os.stat(fn).st_mtime | e2ee63c3ba4b5fe6a7217eb5518d176045fc421e | 669,889 |
def NoShifter(*args, **kwargs):
"""
Dummy function to create an object that returns None
Args:
*args: will be ignored
*kwargs: will be ignored
Returns:
None
"""
return None | 87c18ef0b4c0b4a17005c707ad17cd193ccd97b7 | 669,890 |
import os
def logical_abspath(p):
"""Same as os.path.abspath,
but use the logical current working to expand relative paths.
"""
if os.path.isabs(p):
return os.path.normpath(p)
cwd = os.getenv('PWD')
if cwd and os.path.isabs(cwd) and os.path.samefile(cwd, '.'):
return os.path.no... | 25f4cee018a08ef2cc654c4acd4ce818e0b57dc7 | 669,891 |
def combine_labels(labels):
"""
Combine wt, tc, et into WT; tc, et into TC; et into ET
:param labels: torch.Tensor of size (bs, 3, ?,?,?); ? is the crop size
:return:
"""
whole_tumor = labels[:, :3, :, :, :].sum(1) # could have 2 or 3
tumor_core = labels[:, 1:3, :, :, :].sum(1)
enhanced... | bf60e83395dc09878632b1e5cafb2f1497ccaec3 | 669,892 |
import collections
import operator
def get_hg_root(hg):
"""
Choose the haplogroup based on the highest count and branch depth (E.x. J2a21 = J)
"""
list_hg = []
init_hg = "NA"
for i in hg:
list_hg.append(i)
collections_hg = collections.Counter(list_hg)
try:
h... | faf56a987fe55d84f5a5b0ac4bd781391762569c | 669,893 |
import inspect
from warnings import filters
def get_filters():
"""
Loads filters by inspecting members of the 'filters' package.
"""
filter_classes = []
for _, member in inspect.getmembers(filters):
if inspect.isclass(member):
filter_classes.append(member)
return filter_cl... | 05d97bfe61fd2ffd9552b000a33d10cc466ff0b9 | 669,894 |
def hpa_to_mmhg(pressure: int) -> int:
"""
Converts pressure in hpa to mmhg
Args:
pressure: pressure to convert
Returns: pressure in mmhg
"""
return int(pressure * 0.75006156130264) | b8431e4f141cb1609b9ffceffd17ab4369439cd1 | 669,895 |
def find_max_nr_doc(data):
"""
finds the maximum nr of documents returned over all queries
:param data:
:param queries:
:return:
"""
queries = list(set(data[:, 1].astype(int)))
max_nr = 0
for query in queries:
n_max = data[data[:,1] == query].shape[0]
if n_max > max_n... | d1625ad12b0e5f617e16b4cc1ccd8e66a5e0c639 | 669,896 |
def unemployment_rate(earning, earning_new, unemployment):
"""
Args:
earning: how much money the player earned last round
earning_new: how much money the player earned this round
unemployment: unemployment rate of the player had last round
Returns: unemplo... | 25f671212bc9b428a8c52f88a575ea36e1fc0178 | 669,897 |
import csv
def read_pages(dirname):
"""Read the pages table."""
filename = "%s/pages.csv" % dirname
climbers = []
gaps = []
with open(filename, newline="") as fp:
reader = iter(csv.reader(fp))
assert next(reader) == ["climber", "gap"]
for line in reader:
climbe... | 2217922d3a399d98e4c750138141845bcdcb7cab | 669,898 |
def getPrintTagLenght():
"""
Method to return the length of the strings used for Screen output
@ In, None,
@ Out, tagLenght, int, the default tag length
"""
tagLenght = 25
return tagLenght | 47232b0367b835e9ae07e931fc92ba337f685f14 | 669,899 |
from typing import Any
def verify_assign_and_read(obj: Any, attr: str, value: Any) -> Any:
"""
Assign value to attribute, read and return result.
Assert that values can be mutated and read before and after mutation.
"""
try:
setattr(obj, attr, value)
except AttributeError:
rai... | b7ae561c3cee9d9f379a6c0883a6f3bdb5861768 | 669,900 |
import tqdm
def find_stable_phases(all_compounds, criteria):
"""
find all compounds with e_above_hull within given range of zero
args:
all_compounds - returned from load_compounds (list of dicts)
criteria - criteria for a stable phase in meV
output:
list of dicts of stable phas... | 6ac9815b0b175536add3aba8ab43f592a3c21de3 | 669,901 |
def parse_channal_response(channel=dict()):
"""
Parse channel dict to extract key metadata, including:
id, title, description, viewCount, videoCount, subscriberCount
:param channel: a dictionary containing all metadata of a channel
:return:
"""
result = {}
result['id'] = channel['id']
... | 595c0fd592707eeee873c68ec5a5fa31c26816f3 | 669,902 |
import json
def split_dataset(bq_row, num_partitions, ratio):
"""Returns a partition number for a given bq_row."""
assert num_partitions == len(ratio)
bucket = sum(map(ord, json.dumps(bq_row))) % sum(ratio)
total = 0
for i, part in enumerate(ratio):
total += part
if bucket < total... | f8603bb5fb2ff90f931e55209c64918bdb05eb4f | 669,903 |
import torch
def azimuthal_average(image, center=None):
# modified to tensor inputs from https://www.astrobetter.com/blog/2010/03/03/fourier-transforms-of-images-in-python/
"""
Calculate the azimuthally averaged radial profile.
Requires low frequencies to be at the center of the image.
Args:
... | a40754537a58f07cf99f6b207be8a7f95d258c9f | 669,904 |
def list_comments_response_keys():
"""
ListCommentsResponse definition
Optional key: "next"
"""
return ["items"] | 6c23d6b8d3b7a4d863dbb277ec875b9638873ac0 | 669,905 |
def has_diff_value(dict_obj, key, value):
"""Returns True if dict_obj contains key, and its value is something other than value."""
return key in dict_obj and dict_obj[key] != value | d42a1dcde846ed0e615a0ad312355900cf3a0841 | 669,906 |
import re
def isolate_punctuation(text):
""" Isolate punctuation in a sentence.
>>> split_punctuation('Hi there!')
'Hi there !'
Args:
text (str): Input sentence
Returns:
str: Output sentence with isolated punctuation
"""
text = re.sub('([.,!?()])', r' \1 ', text)
tex... | 381d2785f6f01a29afb4406c2240afd06a3b3ef9 | 669,908 |
def integral(shift, op, elements, accumulator):
""" Inverse of derivative.
Scans a list of elements using an accumulator. Returns the integral of the elements and the final state of the accumulator.
----------
shift : Shift of -1 is an exclusive scan and a shift of 1 is an inclusive scan.
op : Opera... | 67acc6fd66f5f2b6b3992dba999f485f05aeb4f3 | 669,909 |
import operator
def bin(x):
"""Return the binary representation of an integer."""
value = operator.index(x)
return value.__format__("#b") | 92c24f0a828197f48656af5b7031e79b0e663b4c | 669,910 |
def get_scaled(x, y, radius, image):
"""Scales x y and raius whose values are from 0 to 1 to int values."""
scaled_x = int(x*image.shape[1])
scaled_y = int(y*image.shape[0])
scaled_radius = int(radius*max(image.shape[1], image.shape[0]))
return (scaled_x, scaled_y, scaled_radius) | a22776399beebb279ef07956f4ab6f318a81495b | 669,911 |
import os
def _clearObstacle(path):
"""检查路径是否存在并尝试删除文件或空文件夹"""
if os.path.exists(path):
if os.path.isfile(path):
try:
os.remove(path)
except Exception:
print("已存在同名文件且无法删除,生成中断。")
return False
else:
try:
... | c445640b1c686cfb994a90a6c0f8efbd7920fe82 | 669,912 |
def does_database_have_data(instance, db):
"""
Run a script on the host to see if the database import finished.
"""
return instance.query(
'database_looks_finished.sh',
db_pass=db.password,
db_host=db.host,
db_port=db.port,
db_name=db.dbname,
db_user=db.u... | db2940124fd4597672ad7861c778c72d2fb8d6f2 | 669,913 |
import os
def is_interactive():
""" check if gdb runs in interactive mode
returns: True if gdb runs in interactive mode
"""
stdout = os.readlink('/proc/%d/fd/1' % os.getpid())
return True if stdout.startswith("/dev/pts/") else False | 8753efdc99ac393384e91461a32b9eae02d30d39 | 669,915 |
import torch
def equal(input, other):
"""
In ``treetensor``, you can get the equality of the two tree tensors.
Examples::
>>> import torch
>>> import treetensor.torch as ttorch
>>> ttorch.equal(
... torch.tensor([1, 2, 3]),
... torch.tensor([1, 2, 3]),
... | e60c1f032a8fc81f14ae869452eafecbc5b182cc | 669,916 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.