content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def read_world_file(filename):
""" Loads world from file, returns world_state as 2D list """
f = open(filename, 'r')
graph = f.readline()
height = f.readline()[7:]
width = f.readline()[6:]
type = f.readline()
world = []
for i in range(int(height)):
row = f.readline()
worl... | 7b94b1dc05fb7e15b5ef77af3f4c0f5a59824815 | 678,905 |
import math
def geometric_progression(a, r, n):
"""Returns a list [a, ar, ar^2, ar^3, ... , ar^(n-1)]"""
comp = []
for num in range(n):
comp.append(a*math.pow(r, num))
return(comp) | d7be789f516c4fcc138075ef2782ae8232c05add | 678,906 |
def lifetime_high(m):
"""Compute the lifetime of a high mass star (M > 6.6 Msun)
Args:
m (array): stellar mass.
Returns:
array: stellar lifetimes.
"""
return (1.2 * m**(-1.85) + 0.003) * 1000. | a7990108f50befd2c73ba4099c4005b827dded94 | 678,907 |
def replace_subset(lo, hi, arr, new_values, unique_resort=False):
"""
Replace a subset of a sorted arr with new_values. Can also ensure the resulting outcome is unique and sorted
with the unique_resort option.
:param lo:
:param hi:
:param arr:
:param new_values:
:param unique_resort:
... | 7c85fd36b9b08037d798dc79abd3fdce3f2a879f | 678,908 |
def get_ls_number(soup):
"""
:param soup:
:return: (list)
"""
numbers = soup.find(
"select", attrs={
"id": "ContentPlaceHolder1_ddlLoksabha"}).find_all("option")
return [ls.text for ls in numbers] | 404829ba80c67ac4e9f2239da1494f992a3fb3cb | 678,909 |
def change_contrast(img, level):
"""
Change contrast, that eventually can return the negative at high enough values
:param img: PIL image object
:param level: Adjust brightness (int)
:return: PIL image object
"""
factor = (259 * (level + 255)) // (255 * (259 - level))
def contrast(c):
... | ad451f27504cb24ab3fa17feaf71b8f08fcd25eb | 678,911 |
import sys
def loadDictionary(file):
"""Open a text file and load as lower case strings"""
try:
with open(file) as in_file:
loaded_text = in_file.read().strip().split('\n') # processes text file: whitespace, separate lines, added to list
loaded_text = [x.lower() for x in loa... | 430c715c0eae3998c201bf3cdebd291f45304511 | 678,913 |
import re
def get_emails(soupcontent):
"""
soupcontent: expected to be a bs4 object
Description: This functions gets emails from bs4 object and returns a list
"""
emaillist = []
soupere = soupcontent.find_all(
text=re.compile(
r"\S[a-zA-Z0-9._%+-].*?[a-zA-Z0-9_%... | 6660eebb11887b35c4d68cf3bae946546b2064e3 | 678,914 |
def reduce(whole, reduce_to=1000):
"""reduce number of entries in list by skipping"""
reducer = int(len(whole) / reduce_to)
reduced = whole[::reducer]
return reduced | 8a4268493848c494b91e2e13a8f24ab9177710cc | 678,915 |
def remove_comment(command):
"""
Return the contents of *command* appearing before #.
"""
return command.split('#')[0].strip() | 20a6246bffb11a07f77b49197c6f0a8b436e05d9 | 678,916 |
def oridam_generate_patterns(word_in, cm, ed=1, level=0, pos=0, candidates=None):
""" ed = 1 by default, pos - internal variable for algorithm """
alternates = cm.get(word_in[pos], [])
if not candidates:
candidates = []
assert ed <= len(
word_in
), "edit distance has to be comparable... | 1a6aa2b8b81e707e2d3de336ae565e285958f62f | 678,917 |
import os
import platform
def paths_from_iddname(iddname):
"""Get the EnergyPlus install directory and executable path.
Parameters
----------
iddname : str, optional
File path to the IDD.
Returns
-------
eplus_exe : str
Full path to the EnergyPlus executable.
eplus_ho... | 42227abe11fd452ac84fb97bcb68297dd4fed717 | 678,918 |
import os
def read_hosts_file(hosts_file):
"""
Reads a hosts file where host are listed line by line
Args:
hosts_file: Path to the hosts file
Returns:
list(str): A list hosts
"""
if not os.path.isfile(hosts_file):
message = "{:s} is not a valid file".format(hosts_file)
... | 14e20670af7792e2d500012c87709f8801e32b42 | 678,919 |
def latex_table_template():
"""
Return latex table template, can be changed for different latex table
definitions
"""
return "" | 65d598bc80fec7b38d2c47202754ef3bcbb90bbe | 678,920 |
def getdefaultencoding(space):
"""Return the current default string encoding used by the Unicode
implementation."""
return space.newtext(space.sys.defaultencoding) | 7ee385e18b59b1c4fa0070d1d3205d2f53a933ab | 678,921 |
import string
def get_letter_counts_by_position(filename):
"""Return a dictionary with letter -> count pairs from a wordlist."""
counts = []
for i in range(0, 5):
counts.append(dict.fromkeys(string.ascii_lowercase, 0))
with open(filename) as file:
for line in file:
for i, c... | 96e0a6a07cde19cd779472533ecefe6e3b202c8d | 678,922 |
def seconds_to_str(value):
"""Convert seconds to a simple simple string describing the amount of time."""
if value < 60:
return "%s seconds" % round(value, 2)
elif value < 3600:
return "%s minutes" % round(value / 60, 2)
else:
return "%s hours and %s minutes" % (round(value / 360... | 0416caace4420bd69a245309e2e8f447267655c1 | 678,923 |
def blank_reference_input(tokenized_input, blank_token_id): #b_encoding is the output of HFace tokenizer
"""
makes a tuple of blank (input_ids, token_type_ids, attention_mask)
right now token_types_ids, position_ids, and attention_mask simply point to tokenized_input
"""
#1) let us leave token_... | 165ec03106327688a91f8949de2dbe5b47f31695 | 678,924 |
def get_mask(k: int, c: int) -> int:
"""Returns the mask value to copy bits inside a single byte.
:param k: The start bit index in the byte.
:param c: The number of bits to copy.
Examples of returned mask:
Returns Arguments
00001111 k=0, c=4
011111... | 055945afb8ed2c3d1c57f00726f43a38d5fe98ba | 678,925 |
def get_user_country(soup):
"""
Returns the location of the user via the scraper.
"""
follow = soup.find("li", itemprop="homeLocation")
if not follow:
country = "N/A"
else:
country = (follow.get_text())
return str((country.strip())) | 41932c6d8b9bd948ac14c5001df51bc35c4a065b | 678,927 |
def transform_yaw(batch):
"""Used in pred_mode='single' or 'multi', predict only single agent. This is baseline."""
return batch["image"], batch["yaw"] | 0eb62f9f0accf4c01ae49503f3f1ea6323d12204 | 678,928 |
def v1_pT(p, T):
"""
*2.1 Functions for region 1
Release on the IAPWS Industrial formulation 1997 for the
Thermodynamic Properties of Water and Steam, September 1997
5 Equations for Region 1, Section. 5.1 Basic Equation
Eqution 7, Table 3, Page 6
"""
I1 = [0, 0, 0, 0, 0... | fc8cf5fd026b39c45236c44448ff2999899fadf8 | 678,929 |
def calc_intersection(actual_position, calculated_position):
"""
Calculates the Coordinates of the intersection Area.
"""
x_actual = actual_position.get("x", None)
y_actual = actual_position.get("y", None)
w_actual = actual_position.get("width", None)
h_actual = actual_position.get("height",... | eb91223f5afaa98ef8052388c8802129f52ef08f | 678,930 |
import re
def matchTuples(mapping,key,value):
""" mapping is a (regexp,[regexp]) tuple list where it is verified that value matches any from the matched key """
for k,regexps in mapping:
if re.match(k,key):
if any(re.match(e,value) for e in regexps):
return True
... | 8fc966f7f4216cb2e40f70c9051097df2806fd24 | 678,931 |
def organization_link_to_issue_doc_template_values(url_root):
"""
Show documentation about organizationLinkToIssue
"""
optional_query_parameter_list = [
{
'name': 'organization_we_vote_id',
'value': 'string', # boolean, integer, long, string
'description': 'T... | b9be9771bbfc5579b7fbe46c5074fc83ee1f3494 | 678,932 |
def _hoist_track_info(track):
"""Mutates track with artist and album info at top level."""
track['album_name'] = track['album']['name']
artist = track['artists'][0]
track['artist_name'] = artist['name']
return track | 27c1a2729adceea06cb13618120703fc2a1d95d3 | 678,933 |
import os
import importlib
def handle_parsers(shell, args):
"""
Handle parsers.
:param shell: Shell
:param args: Arguments
:rtype: Exit code (int)
"""
# Exit code
exit_code = 0
# Absolute path
args.project = os.path.abspath(args.project)
module = importlib.import_mo... | 86f10c5277d0248be11bec7c858efa1951620b17 | 678,934 |
def checksum(input_str, offset=1):
"""Sum of all digits which match the next digit"""
length = len(input_str)
return sum(
int(i) for index, i in enumerate(input_str)
if input_str[(index + offset) % length] == i
) | 1eae535d82fe8b84c735b04a1cc5f9ccc93f4fdc | 678,935 |
def match_subroutine_def(names):
"""
"""
if len(names) < 2: return ""
if names[0]=="SUBROUTINE":
return names[1]
return "" | 70d782029dabccc29a7f84ef5a06a02f5bf3a9d8 | 678,938 |
import time
def isDSTTime(timestamp):
"""Helper function for determining whether the local time currently uses daylight saving time."""
local_time = time.localtime(timestamp)
return time.daylight > 0 and local_time.tm_isdst > 0 | 48537d699cf973c05170c7eeced35d72e173a2d0 | 678,939 |
def get_endpoints(astute_config):
"""Returns services endpoints
:returns: dict where key is the a name of endpoint
value is dict with host, port and authentication
information
"""
master_ip = astute_config['ADMIN_NETWORK']['ipaddress']
# Set default user/password becaus... | 8aeb6cc6c83216026a94908e3cd5355e878fbf39 | 678,941 |
def drop_columns(df, what_to_drop):
""" drop columns. what_to_drop : list """
if what_to_drop != None:
what_to_drop = [what_to_drop]
print("dropping " + str(what_to_drop))
for d in what_to_drop:
df = df.drop(columns=[d], axis=1)
return df | afefdb28930231772c27ab1fc85b1271aad2b957 | 678,942 |
from typing import Union
from typing import Iterable
from typing import Sequence
def flatten(
nested_seq: Union[Iterable, Sequence]
) -> list:
"""Returns unidimensional list from nested list using list comprehension.
----------
Parameters
----------
nestedlst: list containing other lists e... | 786ed6c2009cc290d3186dc41332b3aa20929a53 | 678,943 |
def single_child(node):
""" The single child node or None. """
result = None
if node.nodes is not None and len(node.nodes) == 1:
result = node.nodes[0]
return result | 42bf0be4c202677e05fb5d589620233e6a13b645 | 678,944 |
import argparse
def collect_args():
"""Returns a minimal default argument parser instance for all prepare scripts.
"""
parser = argparse.ArgumentParser(
description="Prepare fauna FASTA for analysis",
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument('-v... | df5822fde34033df527e4b7b58369e30f02636e6 | 678,946 |
import argparse
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Train a Fast R-CNN network')
parser.add_argument('--cfg', dest='cfg',
help='config file path',
default='configs/pascal_voc/faster_rcnn_r50_... | 0f3973a6316021ae201d9d2a0b23ab1065d8071c | 678,947 |
def get_candidates_from_unimod(mass_shift, tolerance, unimod_df):
"""
Find modifications for `mass_shift` in Unimod.org database with a given `tolerance`.
Paramenters
-----------
mass_shift : float
Modification mass in Da.
tolerance : float
Tolerance for the search in Unimod db... | 05b1929b52fc9ad902f96028334407e34eaa2132 | 678,948 |
import os
def create_workspace(workspace_location: str) -> bool:
"""
Creates a temporary workspace
"""
os.mkdir(workspace_location)
return True | fdf05892c35ae8ca28fb2171f00a3898d2f88b74 | 678,950 |
def count_paras(paras):
"""Count the trainable parameters of the model.
"""
return sum(p.numel() for p in paras if p.requires_grad) | ad4d2748a1c301c63e2b6389efff425cae2664ed | 678,951 |
import re
def is_arn_match(resource_type, arn_format, resource):
"""
Match the arn_format specified in the docs, with the resource
given in the IAM policy. These can each be strings with globbing. For example, we
want to match the following two strings:
- arn:*:s3:::*/*
- arn:aws:s3:::*person... | edd82b19d143c6ca394400dfdf42eea74c0de66d | 678,952 |
import re
def _has_no_hashtag(href):
"""
Remove sub chapters
:Param href: tags with the `href` attribute
:Return: True if `href` exists and does not contain a hashtag
else return False
"""
return href and not re.compile("#").search(href) | ef84c7db899a711421d1f1c5a42cfc7b7a91b22d | 678,953 |
def orm_query_keys(query):
"""Given a SQLAlchemy ORM query, extract the list of column keys expected
in the result."""
return [c["name"] for c in query.column_descriptions] | cf9dbe457d369e6da3f83c4cdf74595ad8dcbc83 | 678,954 |
def ParsePrimitiveArgs(args, arg_name, current_value_thunk):
"""Parse the modification to the given repeated field.
To be used in combination with AddPrimitiveArgs; see module docstring.
Args:
args: argparse.Namespace of parsed arguments
arg_name: string, the (plural) suffix of the argument (snake_case)... | bfc456f5e6a0c4110a144e2cb38cf01a5e59bfc4 | 678,955 |
import argparse
def time_average_argparser():
"""
Define an argument parser for time averaging data.
Parameters
----------
None
Returns
-------
ap : ArgumentParser object
An instance of an `ArgumentParser` that has the relevant options defined.
"""
ap = argparse.Argum... | a0440d3686a60aa3c4673e5dbd51914c4aba64ab | 678,956 |
def parse(atom_types_filename):
"""
Parse ``atom_types`` file
"""
d = {}
with open(atom_types_filename) as f:
for line in f:
line = line.strip()
if not line or line.startswith('#'):
continue
fields = line.split('#', 1)[0].split()
... | 6207debaa0dcd6d4a109a95e712e2b27eaa0ca71 | 678,957 |
import os
def get_version_from_iso_fname(log, fname):
"""
Get Coral version from ISO file name
"""
fname = os.path.basename(fname)
suffix = ".iso"
if not fname.endswith(suffix):
log.cl_error("unexpected ISO fname [%s] without %s suffix",
fname, suffix)
retu... | 2c09320d30de63e91bd47a70a7f5bd9cc52b1a74 | 678,959 |
def select_text_color(r, g, b):
"""
Choose a suitable color for the inverse text style.
:param r: The amount of red (an integer between 0 and 255).
:param g: The amount of green (an integer between 0 and 255).
:param b: The amount of blue (an integer between 0 and 255).
:returns: A CSS color in... | a8663b261c0d6ae087d08e8ecb67a77d51935b10 | 678,960 |
def point_to_geojson(lat, lng):
"""
Converts a single x-y point to a GeoJSON dictionary object of coordinates
:param lat: latitude of point
:param lng: longitude of point
:return: dictionary appropriate for conversion to JSON
"""
feature = {
'type': 'Feature',
'geometry': {
... | 7ff10caab2ea92bd64d1532cac819205806e9e74 | 678,961 |
import argparse
from pathlib import Path
def create_parser() -> argparse.ArgumentParser:
"""Create argument parser."""
parser: argparse.ArgumentParser = argparse.ArgumentParser(
description="ONAP data provider"
)
parser.add_argument(
"-f",
"--filename",
type=Path,
... | 801b933a103212d665b53c77a9ea9ddbf6cd5068 | 678,962 |
import collections
import json
def to_json(sids):
"""prepare to send to zabbix"""
_l = []
for sid, file in sids:
_e = collections.OrderedDict()
_e = {"{#INSTANCE_NAME}": sid, "{#ALERTLOG}": file}
_l.append(_e)
return '{\"data\":'+json.dumps(_l)+'}' | 63ec572279f161c88e5b68340de683fb05620d99 | 678,963 |
import torch
def seq_to_mask(seq_len, max_len):
"""[get attention mask with sequence length]
Args:
seq_len ([torch.tensor]): [shape: bsz, each sequence length in a batch]
"""
max_len = int(max_len) if max_len else seq_len.max().long()
cast_seq = torch.arange(max_len).expand(seq_len.size(0... | 54e95d544ba44882fb4067547e4185d1ef104922 | 678,965 |
import re
def parse_article(context: str) -> str:
"""
article 부분에 대한 변환
:param context:
:return:
"""
# parmalink_article : 게시글 보기 일 때에 해당하는 사항에 대한 변환.
# contents = contents.replace("<s_permalink_article_rep>", "{% if article_rep['type'] == 'permalink' %}")
# contents = contents.repla... | 7a8f1d5476f4dac12abb7b21876c22d448a31e9f | 678,966 |
def _cfg_time_limit(value):
"""Sets timeout in seconds"""
v = int(value)
assert v > 0
return v | 1ef0e166d7d692325a532464dee5edb3b2fe2622 | 678,968 |
import webbrowser
def _SF_Session__OpenURLInBrowser(url: str): # Used by SF_Session.OpenURLInBrowser() Basic method
"""
Display url using the default browser
"""
try:
webbrowser.open(url, new = 2)
finally:
return None | af04276ecf2562f701dd0d183803c65e89de8fb9 | 678,969 |
import yaml
def load_settings():
"""Loads settings.yaml and sets default variables on necessary RAPIDS_LIBS entries"""
with open("settings.yaml") as settings_file:
settings = yaml.load(settings_file, Loader=yaml.FullLoader)
# Set default RAPIDS_LIBS values
for lib in settings["RAPIDS_LIBS"]:
... | 0d81b5d5ddcab0c67f701d6535067bc3c396948a | 678,970 |
from typing import Mapping
def nop(string: str, _: Mapping[str, str]) -> str:
"""No operation parser, returns given string unchanged.
This exists primarily as a default for when no parser is given as the use
of `lift(str)` is recommended when the parsed value is supposed to be a
string.
:param s... | aae2cf22a40a43ff22c3230c1df84f376b1ef245 | 678,971 |
import socket
def authenticate(port, password):
"""
Authentication function used in all testcases to authenticate with server
"""
s = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
s.sendto(b"AUTH %s" % password, ("127.0.0.1", port))
msg, addr = s.recvfrom(1024)
return (s, ms... | 6507f295fd047ce87eb96569edb09dd9f7e777df | 678,972 |
import grp
def groupmembers(name):
"""Return the list of members of the group with the given
name, KeyError if the group does not exist.
"""
return list(grp.getgrnam(name).gr_mem) | 17ee78b80a6c2b6801c4223931cee223d1e42f70 | 678,973 |
import math
def rotate_point(angle, point, origin):
"""
Rotates a point about the origin.
Used from http://stackoverflow.com/q/8948001/1817465 mramazingguy asked Jan 20 '12 at 21:20
:param angle: cw from E, in degrees
:param point: [x, y]
:param origin: [x0, y0]
:return: The point, rotat... | 37b8ff9c2ca6f2dc87125ff1ddd14e58eb09f324 | 678,974 |
def fit_size(size, target_size):
"""
fit (width, height) to (trg_width, trg_height), keep aspect.
"""
width, height = size
aspect = width / float(height)
target_width, target_height = target_size
target_aspect = target_width / float(target_height)
return (target_height * aspect, target... | abc515b5268f967381bc95b5077d528eeed8a092 | 678,975 |
def did_to_dirname(did: str):
"""
Takes a Rucio dataset DID and returns a dirname like used by
strax.FileSystemBackend
"""
# make sure it's a DATASET did, not e.g. a FILE
if len(did.split('-')) != 2:
raise RuntimeError(f"The DID {did} does not seem to be a dataset DID. "
... | 6d37bdc2eda19af6f2791fad7084b64bdc688278 | 678,976 |
def get_fields_with_model(cls):
"""
Replace deprecated function of the same name in Model._meta.
This replaces deprecated function (as of Django 1.10) in Model._meta as
prescrived in the Django docs.
https://docs.djangoproject.com/en/1.11/ref/models/meta/#migrating-from-the-old-api
"""
retu... | 7e0da079cfcc6e55341d9a11a53684690f628338 | 678,978 |
def parse_genome_size(txt_file):
"""Pull out the genome size used for analysis."""
with open(txt_file, 'rt') as txt_fh:
return txt_fh.readline().rstrip() | f386898478393596e28e6e6d47a7da372a8f6b98 | 678,979 |
async def present(
hub,
ctx,
name,
lock_level,
resource_group=None,
notes=None,
owners=None,
connection_auth=None,
**kwargs,
):
"""
.. versionadded:: 2.0.0
.. versionchanged:: 4.0.0
Ensure a management lock exists. By default this module ensures that the management ... | 531f849dc50c4b521e7c1b707e0737b05005bb0f | 678,980 |
def sort_set_by_list(s, l, keep_duplicates=True):
"""
Convert the set `s` into a list ordered by a list `l`.
Elements in `s` which are not in `l` are omitted.
If ``keep_duplicates==True``, keep duplicate occurrences in `l` in the result; otherwise, only keep the first occurrence.
"""
if kee... | 0b43367f178e6f69b40c62bc67af760c82ef9206 | 678,981 |
import json
def merge_tweets(path):
""" Takes a directory (path object) and joins the files into single json
"""
tweet_files = [e for e in path.iterdir() if e.is_file()]
all_tweets = []
for file_path in tweet_files:
with open(str(file_path)) as f:
day_of_tweets = json.load(f)
... | 62faf3b62d4e48ca753d57d3132e714ba49b1d6e | 678,982 |
import os
def find_tests(theme):
"""Find all of the test files in the assets directory."""
test_files = []
for dirpath, dirnames, filenames in os.walk("/home/codio/workspace/assets/{}/" .format(theme)):
for filename in filenames:
if filename.endswith('.xml'):
test_file... | 2ec39e2e1963cfe1a5e225f5a0cedbb20f832637 | 678,984 |
def flex_portable_tensorflow_deps():
"""Returns dependencies for building portable tensorflow in Flex delegate."""
return [
"//third_party/fft2d:fft2d_headers",
"//third_party/eigen3",
"@com_google_absl//absl/types:optional",
"@com_google_absl//absl/strings:str_format",
... | 4962fcbea67dba0ea093051210acfa06f12f0157 | 678,986 |
def _process_get_set_NSCProperty(code, reply):
"""Process reply for functions zGetNSCProperty and zSETNSCProperty"""
rs = reply.rstrip()
if rs == 'BAD COMMAND':
nscPropData = -1
else:
if code in (0,1,4,5,6,11,12,14,18,19,27,28,84,86,92,117,123):
nscPropData = str(rs)
... | 6043361e832a6f10aeb8e5cd395cb0b96ff90f7b | 678,987 |
def get_leq_quantile(df, col, q):
"""
Returns values less than or equal to passed quantile
"""
return df[(df[col] <= df[col].quantile(q=q))].to_frame() | 3d696275fd0910f0b9ffb1983ed736cac7c4518e | 678,988 |
import pytz
def IsValidTimezone(timezone):
"""
Checks the validity of a timezone string value:
- checks whether the timezone is in the pytz common_timezones list
- assumes the timezone to be valid if the pytz module is not available
"""
try:
return timezone in pytz.common_timezones
ex... | 9e2d8855b710f0d087d04a12a936f6979bc7c5d7 | 678,989 |
def remove_dbl_un(string):
"""remove a __ from the beginning of a string"""
if string.startswith("__"):
return string.replace("__", "", 1)
return string | 72ffb546c5bf089deffa20eff0138bc6fdd6a0a4 | 678,990 |
def confirm_logging_buffer_size(ssh_conn):
"""confirm the buffer size"""
cmd = 'show run | i logging'
ssh_conn.sendline(cmd)
ssh_conn.expect('#')
prompt = ssh_conn.before + ssh_conn.after
return prompt.strip(cmd) | 0d26d32c0f2971e9815563c9718631cd8c452c9d | 678,991 |
def get_conferences_organized_by_cluster(researcher_list, testing=False):
""" Conferences organized by cluster of researchers
Researchers are looking in some ways.
Args:
Example:
Scientific Committee of 4S anual meeting at http://www.4sonline.org/meeting
"""
researcher_li... | 2de9a75dd223c48380b5f56a6347c8a093b5ffa8 | 678,993 |
def xp_to_level(level: int):
"""Returns the amount of EXP needed for a level.
Parameters
----------
level: int
The level to find the amount of EXP needed for.
Returns
-------
int:
The amount of EXP required for the level.
"""
return (level ** 3) // 2 | 764f6854788dda44277d76e0850c71999a433510 | 678,994 |
def add_default_values(message_dict, consume_schema_types):
"""
Method add default values for all properties in given message
to correspond given json schema.
See default value in schema or it would be None
:param message_dict: properties with its values as dict
:param consume_schema_types: jso... | 22b1587078acdd0be9e1a4157f02c8d8dd77d6a8 | 678,995 |
import re
def data_size(node, ks, cf):
"""
Return the size in bytes for given table in a node.
This gets the size from nodetool cfstats output.
This might brake if the format of nodetool cfstats change
as it is looking for specific text "Space used (total)" in output.
@param node: Node in whic... | a04a3deb105cdb9c1f3d6bc3d7003909fb779789 | 678,996 |
def gpu_size(wildcards, attempt):
"""Return model size in gb based on {prot} and {model}"""
prot = wildcards.get('prot', 'V3')
model = wildcards.get('model', 'protbert')
if 'bert' not in model:
return 0
if prot == 'V3':
return 9*attempt
return 12*attempt | 02ac56ebf661a1ff6e7e6c024ce6c491d5c8ae42 | 678,997 |
import os
def checkpoint_log_paths(env_name):
"""
create the checkpoint and log dirs and return them
"""
log_dir = "PPO_logs"
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_dir = log_dir + '/' + env_name + '/'
if not os.path.exists(log_dir):
os.makedirs(log_dir)
... | 7e306af6e880d358e1f5b222e9dff55c399afbf9 | 678,998 |
from typing import List
def write_segment(segmented: List[List[str]], fout, out_format: str, criteria: str):
""" actual writing process depending on format. """
written = 0
if out_format == "sent":
for sent in segmented:
if criteria == "bomm" and (len(sent) < 7 or len(sent) > 75):
... | 54327268af8490a1884e3393a107c8e8ed07f322 | 678,999 |
def is_prime(P):
"""
Method to check if a number is prime or composite.
Parameters:
P (int): number to be checked, must be greater than 1
Returns:
bool: True if prime, False if composite
"""
for i in range(2, P):
j = P % i
if j == 0:
... | 674c39005e62ce7c8d53497b8c0f7aafade730a0 | 679,000 |
import torch
def get_embeddings(indexes, sin_pattern, weights_norm=None, return_emb_values=False):
"""
Calculates the ground truth embeddings for given ground truth batch
:param indexes: ground truth label of instances [BSxWxH]
:param sin_pattern: tensor with sins patterns [NxWxH]
:param weights_n... | 972ef5a80d82ecbf4f06cbb1e46d5acaedcfbb7f | 679,001 |
def h(number):
"""
convert a number to a hex representation, with no leading '0x'.
Example::
assert h(16) == '10'
assert hex(16) == '0x10'
"""
return "%02x" % number | 60a5221f2b8dea8f5fdb9573cb4f9e5eb83c238f | 679,002 |
def add_feature_transaction_completed_ratio(profile_updated_df):
"""
Create feature transcation count to offer completed ratio
to avoid np.inf as a result of division, a 0.1 number was added to the denominator
"""
profile_updated = profile_updated_df.copy()
profile_updated['transaction_complet... | 88bfc6bf35050dfe0b114a55342137fd16af9af5 | 679,003 |
import pipes
def readlines_no_carrige_return(filename):
"""This is a wrapper for reading file content from a file. It reads the file
associated with given file name, through a pipe that deletes all carrige
return (\\r) symbols. It returns the result of readlines()."""
# Pipe input through 'tr' to dele... | c83129be86e2f95d457ece2e44bae408a1d3ee2a | 679,005 |
from typing import Sequence
def max_len(
row: Sequence) \
-> int:
"""
Max `len` of 1d array.
"""
return max(len(str(x)) for x in row) | 4ad559b67422480360be0c58a374cec96ef6fcbc | 679,006 |
def calculate_air_density(pressure, temperature):
"""
Calculates air density from ideal gas law.
:param pressure: Air pressure in Pascals
:param temp: Air temperature in Kelvins
:return density: Air density in kg/m^2
"""
R = 286.9 # specific gas constant for air [J/(kg*K)]
density... | dbc861eff42847ddf63b27e38f5250cd3a1f8fa0 | 679,007 |
import pprint
def api_message_to_javadoc(api_message):
""" Converts vpe.api message description to javadoc """
str = pprint.pformat(api_message, indent=4, width=120, depth=None)
return " * " + str.replace("\n", "\n * ") | ca5d862f216ff52f12db8365a520fee8e40b515b | 679,008 |
def _pick_best(gene_string):
"""
Example
-------
>>> _pick_best('TRAV12-2*01,TRAV12D-1*01')
TRAV12-2*01
>>>_pick_best('TRAV12-2*01'
'TRAV12-2*01'
"""
return gene_string.split(",")[0] | fc437769037ab4d5cdccf42a40a0c7a79338df2f | 679,009 |
def get_singles(trade_stats):
"""
Get singles.
"""
singles = {'monitor': {}, 'backtest': {}}
for mode in trade_stats:
singles[mode] = trade_stats[mode]['single']
return singles | 26a0da22028b6db19932b5a6bc2f9c39055bfa69 | 679,010 |
def set_ranks(taxonomy):
"""Set ranks for species/subspecies creation."""
default_ranks = [
"genus",
"family",
"order",
"class",
"subphylum",
"phylum",
]
taxon_rank = None
if "subspecies" in taxonomy:
ranks = ["species"] + default_ranks
... | 00a13aa72773efa3928a0cf67d161aeb98a64ad2 | 679,011 |
import os
def curate_files(input_directory, output_directory, bit_8):
"""Generates name lists for input and output images
Inputs:
input_directory: string, path to the input image directory
output_directory: string, path to the output image directory
bit_8: boolean, if true outputs 8 bi... | 776dfa9021371ce5ca37ba23879324c8f22c42c5 | 679,012 |
def read_xyz(filepath):
"""
Reads coordinates from an xyz file.
Parameters
----------
filepath : str
The path to the xyz file to be processed.
Returns
-------
atomic_coordinates : list
A two dimensional list containing atomic coordinates
"""
with ... | d699c0d7ef084fca4f9d37d5de39ff4fd9e43adc | 679,013 |
def get_adaptive_eval_interval(cur_dev_size, thres_dev_size, base_interval):
""" Adjust the evaluation interval adaptively.
If cur_dev_size <= thres_dev_size, return base_interval;
else, linearly increase the interval (round to integer times of base interval).
"""
if cur_dev_size <= thres_dev_size:
... | 8ddb8d0fb850eccc37936bfb7dc3e3581b9e95e7 | 679,014 |
def merge_specializations(data, duplicated_courses, id):
"""
Merges specializations for the same course
"""
specializations = []
for course in data["courses"]:
if course["id"] == id:
for specialization in course["specializations"]:
specializations.append(specializ... | f6e86e9bfce7083b8d2e684726ca0d8493e38ef3 | 679,015 |
def convert88to256(n):
""" 88 (4x4x4) color cube to 256 (6x6x6) color cube values
"""
if n < 16:
return n
elif n > 79:
return 234 + (3 * (n - 80))
else:
def m(n):
"0->0, 1->1, 2->3, 3->5"
return n and n + n-1 or n
b = n - 16
x = b % 4
... | 5725c77c40020504a71f6eea5127b2895e475db2 | 679,016 |
from datetime import datetime
def get_timestamp():
"""
returns a formatted string for a timestamp when called
:return:
"""
raw_time = datetime.now()
string_time = raw_time.strftime('%H:%M %m/%d/%Y')
return string_time | ac7afa3c4506f847018d598d773c985714856602 | 679,017 |
def standard(X):
"""
standard : This function makes data ragbe between 0 and 1.
Arguments:
X (numoy array) : input data.
--------
Returns:
standard data.
"""
xmin = X.min()
X = X-xmin
xmax = X.max()
X = X/xmax
return X | 3559b6ec7be4bfd6729b827cdf671b20c5361939 | 679,018 |
def list_to_sql_in_list(l):
"""Convert a python list into a string that can be used in an SQL query with operator "in" """
return '(' + ','.join(f"'{e}'" for e in l) + ')' | 01d773406923e77d5d2e5343243f4411e55fd038 | 679,019 |
import glob
import os
def get_filenames(source_dir):
"""Get all filenames to be searched for images."""
return glob.glob(os.path.join(source_dir, '*.md')) | 2bfbb1519e64a3bc5da7b5d5c1b2c31b1b046dde | 679,020 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.