content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import re
def is_message_overwatch_time_basic(cleaned_message_content: str) -> bool:
"""
Returns True/False if the message's content looks like it's for Overwatch
:param cleaned_message_content: The messages cleaned content (can be gotten from utils.get_clean_message_content)
:return: bool: True/False... | 6e3b9c40264c7b8594eaa1c84f0f39a71b5ad482 | 659,944 |
def tochar(v):
"""Check and convert value to a character"""
if isinstance(v, str) and len(v) == 1:
return v
else:
raise ValueError('Expected a character, but found %s' % v) | e406db33807ca0f25e5b348924226b58fcf04da3 | 659,945 |
def _isArray(val):
"""
Actually array is list in Python,
for now we do not treat tuple as an array type.
"""
return isinstance(val, list) | 2f1709ee735605dd7df16f5c975e8bc263dec21d | 659,946 |
import glob
import os
def explode_glob_path(path):
"""Take a glob and hand back the full recursive expansion,
ignoring links.
"""
result = []
includes = glob.glob(path)
for item in includes:
if os.path.isdir(item) and not os.path.islink(item):
result.extend(explode_glob_pa... | d0b5496a54e697332284d37c8d84e18ec9d219b8 | 659,947 |
def get_iorient(orient):
"""Converts x, y, z, u and a, b, c, u to 0, 1, 2, 3.
This is a helper function for bound methods in class diffusivitiy
and for determining thickness from raypath for wholeblocks"""
if orient == 'x' or orient == 'a':
iorient = 0
elif orient == 'y' or orient == 'b':
... | 4e69d089ac10acfc584ba275ba84b9cd77a5ce73 | 659,948 |
from datetime import datetime
def end_of_day(dt: datetime, tz):
"""
将时间设置为当日结束(23:59:59)
"""
return dt.replace(hour=23, minute=59, second=59, microsecond=0, tzinfo=tz) | 88320a7c77838d629f78469548c4c879a046a19c | 659,949 |
def convert_list_to_sql_tuple(filter_list):
""" This function takes a list and formats it into a SQL list that can be used
to filter on in the WHERE clause. For example, ['a', 'b'] becomes ('a', 'b') and
can be applied as: SELECT * FROM table WHERE column IN ('a', 'b').
Note that any pre-formatting on... | 0571fbc5e79169acd48c5983bda92e8a084a20a5 | 659,953 |
def remove_classifiers(config_dict, remove_nb=False, remove_trees=False, remove_svms=False, remove_other=True):
"""Gets TPOT configuration, returns it without models from selected families."""
nbs = []
svms = []
trees = []
other_classifiers = []
preprocessing = []
for key in config_dict:
... | c40ce3c81f13c3c8c6132fa31015cbfc6f183f03 | 659,954 |
def transform_keyword(keywords):
"""
Transform each keyword into a query string compatible string
"""
keywordlist = []
for keyword in keywords:
keywordlist.append(keyword.lower().replace(" ", "+"))
return keywordlist | 64d2e47bfab5575a5174861d8636c127bb20510e | 659,956 |
def dups(lst):
"""
>>> dups([1, 2, 1, 3, 2, 5])
[1, 2]
"""
return list(set(filter(lambda x: lst.count(x) != 1, lst))) | 54d356f5187110c82e6bdc6b71ee565a43bc9938 | 659,957 |
import argparse
def get_args():
"""Parse command line arguments."""
parser = argparse.ArgumentParser(
description="Generate reconstructions via retrieve and deform."
)
parser.add_argument(
"--input_path_1",
type=str,
default="source.ply",
# default="/media/andy... | c5292ccdb25b1316323d6c552bb2fc9512c50430 | 659,958 |
def average_daily_peak_demand(peak_usage: float, peak_hrs: float = 6.5) -> float:
""" Calculate the average daily peak demand in kW
:param peak_usage: Usage during peak window in kWh
:param peak_hrs: Length of peak window in hours
"""
return peak_usage / peak_hrs | e3793bfb7c22af9876bdb99ab75ed475f4901b25 | 659,960 |
def is_page_fan(request):
""" checks if the user likes the page, the tab is in. """
try:
is_fan = request.fb_session.signed_request['page']['liked']
except (AttributeError, KeyError, TypeError):
is_fan = False
return {'is_fan' : is_fan, 'signed_request': request.fb_session.signed_req... | 5bd37bbdc5fca3cdce6356921f859cfac3ba551b | 659,961 |
import re
def herbarium(image_file):
"""Map the image file name to a herbarium."""
image_file = str(image_file)
if image_file == 'nan':
return ''
image_file = image_file.upper()
parts = re.split(r'[_-]', image_file)
return parts[1] if parts[0] == 'TINGSHUANG' else parts[0] | ce496261b5a79ee4e1ec3fc5743530b65cdbbaaf | 659,962 |
def vsi_piksli(širina, višina):
"""Naredi matriko v velikosti zaslona"""
piksli = []
for j in range(višina):
vrstica = []
for i in range(širina):
vrstica.append(None)
piksli.append(vrstica)
return piksli | f6be1ce43a42d218ab27aa8905ddb7e3ab8e54b6 | 659,963 |
def time_check(time1, time2):
"""
此程序用于检测time1是否大于、小于或等于time2。
两个参数必须均为一个由 年、月、日、小时、分钟、秒、毫秒 组成的元组。
:param time1:
:param time2:
:return: 一个列表。第0项元素为time1小于time2,第1项为大于,第2项为一样
"""
if len(time1) != len(time2):
return 1
less = [True, False, False]
great = [False, True, False... | 6618d7cf6c6b492f9b5ad77c7a557abe52d09808 | 659,964 |
def range_addition(n, updates):
"""
LeetCode 370: Range Addition
Assume you have a list `[0] * n` and are given k update operations.
Each operation is represented as a triplet `[start_index, end_index, increment]`,
which adds increment to each element of subarray A[start_index ... end_index] (start... | 906971c1cf768d2893dd2ca093cf9cca58ba23c2 | 659,966 |
import os
def type_f(path):
"""Find the extention of the file."""
extension = os.path.splitext(path)[1]
return extension | 1abb29735e649efec5ed5f61affbf8023f7e3ffe | 659,967 |
import sys
def get_command_without_error_checking(name):
"""
Returns a command module
"""
__import__('ebs_deploy.commands.' + name + '_command')
return sys.modules['ebs_deploy.commands.' + name + '_command'] | beea90c9bb7af80ee6a45e1b6d8766d466d16ad7 | 659,968 |
def run_function(ptr):
"""Given a pointer to a function, run function and return output"""
return ptr | 7bef6bc0d159f0a55da9dd956cd8019299c30c77 | 659,969 |
async def get_message(ctx, message:int):
"""
Returns a previous message for a given channel and location (relative to context).
Parameters:
ctx (context): Passthrough for context from command.
message (int): Location of message relative to sent command.
Returns:
Message: The me... | 9ceb5499fd8afb9ec25ae010c7645b4bda9f4c17 | 659,970 |
def parse_event_data(event):
"""Parses Event Data for S3 Object"""
s3_records = event.get('Records')[0].get('s3')
bucket = s3_records.get('bucket').get('name')
key = s3_records.get('object').get('key')
data = {"Bucket": bucket, "Key": key}
return data | 26bcce3dbaa3ce64c906d137261b3ef9458f59b6 | 659,971 |
import gc
import inspect
def is_property(code):
"""
Using some CPython gc magics, check if a code object is a property
gc idea taken from trace.py from stdlib
"""
# use of gc.get_referrers() was suggested by Michael Hudson
# all functions which refer to this code object
gc.collect()
c... | cc5e77f9fc4a0b73401059918864c422813bdd75 | 659,972 |
def _remove_trailing_zeros_in_headers(d):
"""Remove the suffix '.0' from keys."""
d1 = {}
for key, value in d.items():
if isinstance(value, dict) and key.endswith('.0'):
d1[key[:-2]] = value
else:
d1[key] = value
return d1 | 92b72b78510e00a7e1e5572877148d449232641f | 659,973 |
def choose_actions(actions, money, max_money):
"""Pick actions"""
actions_len = len(actions)
cursor = 0
chosen_actions = []
while money > 0 and cursor < (actions_len - 1):
curr_action = actions[cursor]
# Check if enough money to buy this action
action_cost = curr_action[1]... | e07cfa9f676563fbc686657062de6718aa58a13a | 659,974 |
def _check_symmetry(matrix):
"""
Checks whether a matrix M is symmetric, i.e. M = M^T.
By @t-kimber.
Parameters
----------
matrix : np.array
The matrix for which the condition should be checked.
Returns
-------
bool :
True if the condition is met, False otherwise.
... | e12ae8abb821d12fa83950c0fb61c6d89410fe4c | 659,975 |
from typing import Tuple
import math
def calc_differential_steering_angle_x_y(wheel_space: int, left_displacement: float,
right_displacement: float, orientation: float) -> Tuple[float, float, float]:
"""
Calculate the next orientation, x and y values of a two-wheel
... | 1669b5082bf9c6f1f2cbf0fb68c7e142c55b9988 | 659,976 |
def calc_surface_pressure_0(wrf_xr, units='hPa'):
"""
"""
pres = wrf_xr['PSFC']
if units == 'hPa':
pres = pres * 0.01
elif units == 'kPa':
pres = pres * 0.001
elif units != 'Pa':
raise ValueError('units must be kPa, hPa, or Pa.')
return pres | 366b2c25ec6efcf27fa57e7cc9bed967b7a06734 | 659,977 |
import numpy
def _line_segment_distance(line_coord, coord):
"""
Get the (2-d) distance from the point given by coord from the line segment defined by line_coord.
Parameters
----------
line_coord : numpy.ndarray
This is implicitly assumed to be shape (2, 2).
coord : numpy.ndarray
... | 269b7ee0c50eef55d93ab8629757b78b92267ce6 | 659,978 |
def get_stream_to_download(video_streams):
"""Gets the stream to download from the provided video streams.
arguments:
video_streams: a video streams object provided by a video object from
pytube.
"""
mp4_streams = video_streams.filter(file_extension="mp4")
stream = mp4_streams... | fb8ec285ad473634152d31913c3ecc0b84a83fd5 | 659,979 |
from typing import OrderedDict
def __dict_to_list(obj):
"""
Converts a dictionary to a list recursively
{'0':'value0', '1':'value1'}
will be
['value0', 'value1']
Args:
obj - dictionary object to be converted
Returns:
list if conversion was possible
"""
... | f302ec89a59a8c48d628dcfdc70e772025fd54cf | 659,982 |
import os
def getenv(e, *args):
"""
Workaround Django's braindead import error silencing, by emitting
an error when an environment variable missing would cause an exception
"""
have_default = len(args) > 0
try:
return os.environ[e]
except:
if have_default:
retur... | 298827d479b78eba80ae94c4eb4016fdc451b9cb | 659,983 |
from typing import Callable
import json
import yaml
import argparse
def format_type(value) -> Callable:
"""
Date Dumper one of (json, yaml)
"""
dumpers = {"json": lambda data: json.dumps(data, sort_keys=True, indent=4)}
if yaml is not None:
dumpers["yaml"] = yaml.dump
try:
ret... | f4b1d1111226306a1463ed143d11320fe2ab8a75 | 659,984 |
import itertools
def concat(*iterables):
"""
:param iterables: the iterables to concatenate
:return: the concatenated list
:rtype: list
"""
return list(itertools.chain(*iterables)) | 82feab920d93fbb744e507e1d499358df31e1c33 | 659,985 |
from pathlib import Path
import os
def get_cert_pw():
"""
Get keystore password from local container
Returns:
Certificate password
"""
hadoop_user_name = "HADOOP_USER_NAME"
crypto_material_password = "material_passwd"
material_directory = "MATERIAL_DIRECTORY"
password_suffix =... | e94d89a1487466e8c2f86bd1e9b89380c75e9bbe | 659,986 |
def _localized_name(val, klass):
"""If no language is defined 'en' is the default"""
try:
(text, lang) = val
return klass(text=text, lang=lang)
except ValueError:
return klass(text=val, lang="en") | 72ef67aa32ed0a1c7948b9cff8dc610d966c458f | 659,987 |
import time
import calendar
def format_time(time_str, format):
"""
This will take a time from Jira and format it into the specified string. The time will
also be converted from UTC to local time.
Jira time format is assumed to be, "YYYY-MM-DDTHH:MM:SS.ssss+0000". Where "T" is the
literal charact... | 4c8126f3348cef9b9311e48f9564529945bd2aaf | 659,988 |
def transform_data(df, params):
""" transform data here. """
return df | 833b81cb9a2eda58a0b71f5536b8fc96f02731e4 | 659,989 |
def determine_fan_in_profile(profile, database):
"""Determine the fan-in profile."""
for func in database.ents("function,method,procedure"):
function_metrics = func.metric(["CountLineCode", "CountInput"])
function_size = function_metrics["CountLineCode"]
function_fan_in = function_metri... | bd36126820871b72891c679cb89c41eeb4d72bf1 | 659,990 |
def _get_row_partition_type_tensor_pairs_tail(partition):
"""Gets a row partition type tensor pair for the tail.
If value_rowid is defined, then it is used. Otherwise, row_splits
are used.
Args:
partition: a RowPartition.
Returns:
A list of (row_partition_type, row_partition_tensor) pairs.
"""
... | ef72da5b236c967a388c5da524e417f830aec738 | 659,991 |
import math
def compute_perfect_tree(total):
"""
Determine # of ways complete tree would be constructed from 2^k - 1 values.
This is a really subtle problem to solve. One hopes for a recursive solution,
because it is binary trees, and the surprisingly simple equation results
from the fact that it ... | 648840b7c1fb562fa98cc9eaabb0775013d0019e | 659,992 |
import subprocess
def exec_cmd_with_output(command):
"""
Utility function to execute a command and capture output and return code
:param command: type list. [0] is the command, [1] and on are params for
: : the command. i.e. [ "find", ".", "-print"]
:returns first: the return code from executing the ... | a7eddd7c46cde1f901889e7c67db5e8fa981df0d | 659,994 |
def identify_correct_partition_idx(array, begin_idx, end_idx):
"""
This function looks at the element of array[end_idx] and then it identifies its correct position index in a sorted array such that everything to left is smaller or equal, and everything to right is larger.
Reference:
https://www.you... | 1ca390175dd920eee470b22ace4210bee1153656 | 659,995 |
def get_choices(query):
"""Get a list of selection choices from a query object."""
return [(str(item.id), item.name) for item in query] | 677938799a1b42d13fb73b578370546c92b47a5d | 659,996 |
def preprocess_features(rap_lyrics_dataframe):
"""Prepares input features from rap lyrics dataset.
Args:
rap_lyrics_dataframe: A Pandas DataFrame expected to contain data
from the rap_lyrics data set.
Returns:
A DataFrame that contains the features to be used for the model, including
syntheti... | 23cf46807141437c5b46548a7d435f1c2480e106 | 659,997 |
def mu_std(x):
"""
Obtiene las medias y las desviaciones estandar atributo a atributo.
Parámetros
----------
x: un ndarray de shape (M, n) con los datos
Devuelve
---------
mu, de ndarrays de shape (n,) con las medias y las desviaciones estandar respectivamente.
"""
ret... | 5388b831df5a07331a0f62ec0635c7129e203bd9 | 659,998 |
def get_Q_max_H_FC(Theta_SW, q_max_FC):
"""ファンコンベクターの最大暖房出力 (3a)
Args:
Theta_SW(ndarray): 往き温水温度 (℃)
q_max_FC(ndarray): ファンコンベクターの最大能力(W)
Returns:
ndarray: ファンコンベクターの最大暖房出力 (3a)
"""
return q_max_FC * (Theta_SW - 20) / (60 - 20) * 3600 * 10 ** (-6) | a515bc91ad4ac3fa214a9485fd6c91278de427b7 | 659,999 |
import math
def power_sum( pdb_lst ):
""" take a list of powers in dBm, add them
in the linear domain and return the sum
in log
"""
sum_lin = 0
for pdb in pdb_lst:
sum_lin += 10**(float(pdb)/10)*1e-3
return 10*math.log10(sum_lin/1e-3) | 03cc41a7520f78e5608e3dff4e5989f0f704bd7e | 660,000 |
def interval_intersection(interval1, interval2):
"""Compute the intersection of two open intervals.
Intervals are pairs of comparable values, one or both may be None to
denote (negative) infinity.
Returns the intersection if it is not empty.
>>> interval_intersection((1, 3), (2, 4))
(2, 3)
... | 56ed1fa4e8f800512f242a1a2bf66cf1f0c2c3ec | 660,001 |
from typing import Union
def is_true(val: Union[str, int]) -> bool:
"""Decide if `val` is true.
Arguments:
val: Value to check.
Returns:
True or False.
"""
value = str(val).strip().upper()
if value in ("1", "TRUE", "T", "Y", "YES"):
return True
return False | 0f6fd71222d343ca0cc614e6a71c7ca2907a0f1b | 660,002 |
def humanize_bytes(
num: float, suffix: str = "B", si_prefix: bool = False, round_digits: int = 2
) -> str:
"""Return a human friendly byte representation.
Modified from: https://stackoverflow.com/questions/1094841/1094933#1094933
Args:
num: Raw bytes
suffix: String to append
s... | ccbbf472a8e6bb5f5c065532a96702698e11b55d | 660,004 |
def api_root():
""" Root """
return 'simple Web API with Python & Flask' | e0d257312b3c9bc503c702a5adef545ac6c44f5e | 660,005 |
import math
def boiling_point(altitude):
"""
Get the boiling point at a specific altitude
https://www.omnicalculator.com/chemistry/boiling-point-altitude
:param float altitude: Altitude in feet (ft)
:return: The boiling point in degF
:rtype: float
"""
pressure = 29.921 * pow((1 - 0.... | 08cdb56482571d69acdaf25f10e39f2845590821 | 660,006 |
def macroName(o):
""" Return the macro name of the given object """
if o.macroName is None:
if type(o) is type:
return o.__name__
return type(o).__name__
return o.macroName | 151fb46017c89c9bca4d2219d19eeaf812d74bfe | 660,007 |
from typing import Sequence
from typing import Iterable
def _merge_dashes(elements: Sequence[float]) -> Iterable[float]:
""" Merge multiple consecutive lines, gaps or points into a single element. """
def sign(v):
if v < 0:
return -1
elif v > 0:
return +1
retur... | c64e7fb4eb4a71c1d3f1062b498a2468af202596 | 660,008 |
import numpy
def _calc_f_sharp(N, nclasses, features):
"""_calc_f_sharp(N, nclasses, features) -> matrix of f sharp values."""
# f#(x, y) = SUM_i feature(x, y)
f_sharp = numpy.zeros((N, nclasses))
for feature in features:
for (i, j), f in feature.iteritems():
f_sharp[i][j] += f
... | 83a622223dbab21062fe48265979a712817fe4cc | 660,009 |
def get_usa_veh_id(acc_id, vehicle_index):
"""
Returns global vehicle id for USA, year and index of accident.
The id is constructed as <Acc_id><Vehicle_index>
where Vehicle_index is three digits max.
"""
veh_id = acc_id * 1000
veh_id += vehicle_index
return veh_id | e89875d5f9f48293e3069a7fe468ee9455d24147 | 660,010 |
def decode( string, dtype='U' ):
""" short wrapper to decode byte-strings read from FRBcat """
if 'f' in dtype:
if 'null' in string:
return float('NaN')
return float(string)
return string | 586ebeb66b288f3863f09d89508696c2823bdc3d | 660,011 |
import re
def is_correct_uri(uri):
"""
:param uri:
:return:
"""
uri = uri if not uri.startswith('0x') else uri.replace('0x', '')
return re.match(r"[0-9|a-f|A-F]{40}@\d+\.\d+\.\d+\.\d+:\d+", uri.strip()) is not None | 1bef5bf801bd7cf1134aba6b4c6e09e3fdea6b86 | 660,012 |
import os
from datetime import datetime
def get_log_path(dirname):
"""
Creates a path to a new log file that is in the right directory and does
not clash with existing paths.
"""
assert os.path.isdir(dirname)
timestamp = datetime.strftime(datetime.now(), '%y-%m-%d-%H%M%S')
log_num = 0
... | 1183420eef33e8cdc26fdce47d6126801e8f42b0 | 660,013 |
def get_image_ids(metadata, proxy=False):
"""
image_ids.txt has the structure
<path>
path/to/image1.jpg
path/to/image2.jpg
path/to/image3.jpg
...
"""
image_ids = []
suffix = '_proxy' if proxy else ''
with open(metadata['image_ids' + suffix]) as f:
for line in f.readl... | 061e107e4287ff8cf0cfc43595248c3bfd2033ac | 660,014 |
import calendar
def to_unix_timestamp(timestamp):
"""
Convert datetime object to unix timestamp. Input is local time, result is an
UTC timestamp.
"""
if timestamp is not None:
return calendar.timegm(timestamp.utctimetuple()) | 95481b7c9d1a3a63e6a428f28e8a2fd87e49c623 | 660,015 |
import platform
def is_platform_arm() -> bool:
"""
Checking if the running platform use ARM architecture.
Returns
-------
bool
True if the running platform uses ARM architecture.
"""
return platform.machine() in ("arm64", "aarch64") or platform.machine().startswith(
"armv"... | 5e487a5d8a6e3423f9752c1e7b520afd8a2d5f08 | 660,016 |
def get_content(html_soup):
"""
Extracts text content of the article from content
Input : Content in BeautifulSoup format
Output : Text content of the article
"""
html_soup.find('figure').extract()
content = html_soup.find('div', attrs = {"class" : "entry-content"}).get_text()
return con... | 88e02d03616a25b27b53d02a2888cc6d4088cad1 | 660,017 |
import yaml
def read_radial_build(file_):
"""
Loads the radial build YAML file as a Python dictionary
Parameters
----------
file_ : str
The radial build file path
Returns
-------
radial_build : list
A Python dictionary storing the tokamak radial build data
"""
... | c3560cf582941bbc9bdec99d5692983cffee98f7 | 660,018 |
def strip_module_names(testcase_names):
"""Examine all given test case names and strip them the minimal
names needed to distinguish each. This prevents cases where test
cases housed in different files but with the same names cause clashes."""
result = list(testcase_names)
for i, testcase in enumerat... | 40f63942d27b7d2fe06f4ad96ea2faad6937eab1 | 660,019 |
import torch
def relax(FpFmZ, T1, T2, EE, RR):
""" Propagate EPG states through a period of relaxation over
an interval T.
torch
INPUT:
FpFmZ = 3xN vector of F+, F- and Z states.
T1, T2 = Relaxation times (same as T)
T = Time interval (same as T1,T2)
OUTPUT:
FpFmZ ... | f09332dc7ad0df93545c3e990b25c87bc3bedbdb | 660,022 |
def scientific(number):
"""returns a string in scientific number format"""
return "{:.2e}".format(number) | 2668cd5aceff3d60447647572ead45edca989589 | 660,023 |
def text_to_lowercase(text):
"""Set all letters to lowercase"""
return text.lower() | 69809b8e02ae468067a55cfdf2b56b020e3f9883 | 660,024 |
def print_solution(data, manager, routing, solution,num):
"""Prints solution on console."""
total_distance = 0
total_load = 0
count_car = 0
for vehicle_id in range(data['num_vehicles']):
index = routing.Start(vehicle_id)
plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)
... | 5daf03c2bbba2f6e06369df2c79756eeeefb6e78 | 660,025 |
def safe_compare(val1, val2):
"""
Compares two strings to each other.
The time taken is independent of the number of characters that match.
:param val1: First string for comparison.
:type val1: :class:`str`
:param val2: Second string for comparison.
:type val2: :class:`str`
:returns: ... | a3ed9bff7516add1b062e45d58c508fa0ea7f35e | 660,026 |
import os
def getJobName(programPath=None):
"""
generate a job name for task array
"""
if programPath is None:
return "Bat_%d" % os.getpid()
else:
return "Bat_%s" % (os.path.split(programPath)[1]) | f3959fd8fc3b5057243f2c7c3bba6ce0e67ff48e | 660,027 |
def loess_abstract(estimator, threshold, param, length, migration_time, utilization):
""" The abstract Loess algorithm.
:param estimator: A parameter estimation function.
:type estimator: function
:param threshold: The CPU utilization threshold.
:type threshold: float
:param param: The safe... | 34908b76d135cd0b087943cea59ec480844bc082 | 660,028 |
import subprocess
def call_command_line(string, **kwargs):
"""Executes string as a command line prompt. stdout and stderr are keyword args."""
return subprocess.run(string.split(" "), **kwargs) | ca2c979e77ad93ec49ac9a33bcca5d81a48a7b04 | 660,029 |
def map_headers(reader):
"""Read the map header file (MAPHEAD).
The file format is as such:
magic : uint16le
level pointers : int32le (100 of them).
"""
magic = int.from_bytes(reader.read(
2), byteorder='little', signed=False)
uses_rlew_compression = magic == 0xABCD
lev... | d0ad37f5cf3f371e7ca4f0f784784f1a337c7530 | 660,030 |
def capitalize_haiku(haiku_array):
"""Capitalize appropriate words in haiku"""
period = '.'
# Always capitalize the first word.
haiku_array[0] = haiku_array[0].capitalize()
for i in range(1, len(haiku_array)):
if haiku_array[i] == period and i+2 < len(haiku_array):
# If the curre... | a6c80adf9bff350604de9333aa51ee91ea0a12ac | 660,031 |
def construct_backwards_adjacency_list(adjacency_list):
"""
Create an adjacency list for traversing a graph
backwards
The resulting adjacency dictionary maps
vertices to each vertex with an edge
pointing to them
"""
backwards_adjacency_list = {}
for u in adjacency_list:
for v in adjacency_list[u... | ecb2c4eefe3e1c7fa67a66f8aa9701d7c443cb12 | 660,032 |
import sys
import importlib
def import_or_reload(modulename):
"""
Behaves like 'import modulename' would, excepts forces the imported
script to be rerun
"""
# see if the proposed module is already loaded
# if so, we will need to re-run the code contained in it
if modulename in sys.modules... | 533d3a06d93451ebe9206abfae55877fec65083c | 660,033 |
from functools import reduce
def _rebuild_xarray_from_pixels(pixels):
"""Combines pixel sized ccd-products into a larger xarray object.
Used to combine single pixels with latitude, longitude, time back into a single xArray dataset instance
Args:
pixels: iterable of xArray datasets that can be co... | 653f0f97d4326b7a392fcc7ba886130c2eb02aee | 660,034 |
import math
def law_of_cosines(a, b, angle):
"""
Return the side of a triangle given its sides a, b and the angle between them (Law of cosines)
"""
return math.sqrt(
a**2 +
b**2 -
2*a*b*math.cos(math.radians(angle))
) | 743748d8eff369e9cd01367569b38c90fcac1f09 | 660,035 |
def remove_author_username(list_of_contributors):
"""Remove the username of the author from the list of contributors
:param list_of_contributors: A list, the list of contributors
"""
authors_username = 'EragonJ'
authors_username_transifex = 'eragonj'
if authors_username in list_of_contributor... | d1a408f1c884d1bbbbfdd91ebeadd38f36b333f2 | 660,038 |
def get_default_num_stump_evaluations():
"""
returns default r (number of splits) to try at a tree node
----
Returns
----
result : int
default number of splits to examine
"""
return 5 | 48d04bd5b4d103a46053ae5542e98486d4e8f84e | 660,039 |
def normalize_confusion_matrix(confusion_matrix_dict: dict, normalize_index: int = 0) -> dict:
"""
normalize a confusion matrix;
:param confusion_matrix_dict: dict, a confusion matrix, e.g.,
{('a', 'a'): 1, ('a', 'b'): 2, ('b', 'a'): 3, ('b', 'b'): 4};
:param normalize_index: int, [0, 1], the p... | 2241226671139ee816c104de80bc865aca2f12ae | 660,040 |
def compute_resize_params_2(image_dims, min_resize_dim, max_resize_dim):
"""
:param image_dims: as tuple of (width, height)
:param min_resize_dim:
:param max_resize_dim:
:return:
"""
lower_size = float(min(image_dims))
higher_size = float(max(image_dims))
scale_factor = min_resize_d... | 667ad1a61e31e39fa04d3a16063edec71c3890d6 | 660,041 |
def is_nested_list(l):
"""
Check if list is nested
:param l: list
:return: boolean
"""
return any(isinstance(i, list) for i in l) | 229f244de536edc1f9496851ef1991ebdb343bdf | 660,042 |
def get_db_collections(db):
"""
db.collection_names()
DeprecationWarning: collection_names is deprecated.
Use list_collection_names instead.
"""
# return db.collection_names()
return db.list_collection_names() | d27d1c4cae4cab70a039a96cc594fd3302cee775 | 660,043 |
import re
def check_if_border(feature, operon_borders):
"""Return start/end coordinate of the SeqFeature if its accession is the first/last in the given tuple.
Parameters
----------
feature : SeqFeature
Directory with input genbank files.
operon_borders : str
Directory to store th... | 4cb9cdbfd9f72427b783c848a782cb2f70d98a32 | 660,044 |
def getfilename(data, *args, **kwargs):
"""Return dataname
"""
return args[0] | 0b08b670de9e45c28b9a21240bed91400d7e78f3 | 660,045 |
import os
def get_complete_filename(module_path: str, filename: str):
""" Get the full path of a filename, given it's module path """
dirname = os.path.dirname(os.path.realpath(module_path))
return os.path.join(dirname, filename) | 33ba3e226f1eafacdf25a82ca8cfa13a2a16acc4 | 660,046 |
import random
def random_color_from_string(str):
""" Given a string, return an RGB color string.
The same string will always give the same result but otherwise is random. """
rng = random.Random(str)
cs = ['#d98668', '#d97400', '#bfab5c', '#aee66e', '#9bf2be', '#1b9ca6', '#0088ff', '#0000a6', ... | 19b94272ab9617ac70a7b1b447a57c2d5c1f05c6 | 660,047 |
async def is_friendly(config, ctx, profile: str):
"""Checks if user set themselves to accept friend requests"""
if ctx.guild:
server = str(ctx.guild.id)
else:
return False
member = ctx.guild.get_member_named(profile)
if member:
try:
friendme = await config.get_ra... | 25257e3d5372ab5b2abd1e65c3d474d138089056 | 660,048 |
def find_variable(frame, varname):
"""Find variable named varname in the scope of a frame.
Raise a KeyError when the varname cannot be found.
"""
try:
return frame.f_locals[varname]
except KeyError:
return frame.f_globals[varname] | f97bbcd5d60faf7cecce12d08f53eb144a766bd0 | 660,049 |
def xml_output_document(request):
"""XML document generated by XSLT transform."""
document = request.param
return document | de6bb2b3d6b9da15a03727948efac1e5d7ae6005 | 660,050 |
def join_ints(ints):
"""Joins list of intergers into the ordered comma-separated text.
"""
return ','.join(map(str, sorted(ints))) | 1e263fe00c01fd81252df0e824f5300126374cbd | 660,051 |
def are_equal(drive_list, partition_infos):
"""Checks whether partitions in a drive fit to the expected partition infos.
"""
if len(drive_list) == len(partition_infos):
for drive_info, partition_info in zip(drive_list, partition_infos):
if drive_info[0] != partition_info[0]:
... | 66521eaa59975d058e2875f99dc465a51810d624 | 660,052 |
import pathlib
def tmp_archive_path(tmp_path_factory) -> pathlib.Path:
"""Make variable 'tmp_archive_path' available from throughout this test module."""
return tmp_path_factory.mktemp("archive") | 26064441c94efc3e4e69bff289344fb796c11867 | 660,053 |
import random
def cubic_root(x):
"""
Calculate Cubic Residue
Args:
x: The Target
Returns:
A Cubic Residue of x
"""
F = x.field
p = F.p
m = F.degree()
rho = 1
pm = p**m
r = (pm - 1) // 3
rho = 1
while rho ** r == 1:
rho = F(random.randint(1, p - 1), random.randint(1, p - 1))
t =... | 212fa16cf06ad3012dff2cd2f270d90e4da98013 | 660,054 |
import re
def get_version(galaxy_file):
"""
Get the version from the collection manifest file (galaxy.yml).
In order to avoid the dependency to a yaml package, this is done by
parsing the file with a regular expression.
"""
with open(galaxy_file, 'r') as fp:
ftext = fp.read()
m = ... | eed57ff44af9139a0ef80cc596e2f5ee2a6027d5 | 660,055 |
import os
def _get_dataset_dir(dataset_name, data_dir=None, folder=None,
create_dir=True):
""" Create if necessary and returns data directory of given dataset.
Parameters
----------
dataset_name: string
The unique name of the dataset.
data_dir: string, optional
... | 65ea8406d5840a3e4c2d3238b9cd5d5c2aa929f5 | 660,056 |
from typing import List
def simulate_car() -> List[float]:
"""Simulate a car for one second"""
x0 = 0
dt = 0.25 # 4 Hz, typical GPS
v = 144 * 1000 / 3600 # 144 km/hour = 90mph, pretty fast
x = [x0 + v * dt * i for i in range(5)]
return x | 22ef9ffda9597fb452d9da225e97023ddb9dc682 | 660,057 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.