content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_index(list_wid):
"""
Returns first number of currently selected
text in supplied list widget, eg from
3 [ascsdf] sdf sdf
would return the integer 3
"""
try:
str_index = str(list_wid.item(list_wid.currentIndex().row()).text())
return int(str_index.split()[0])
excep... | 501d5b19801101a4e26d740f87a41cc36424c3f3 | 632,064 |
import torch
def correct(output, target, tokens):
"""Computes the number of correct predictions.
Args:
output (torch.tensor): output of the model
target (torch.tensor): masked labels
tokens (int): vocabulary size
Returns:
int: number of correct predictions
"""
wit... | 48dc9021720212048d7903c81229a529a122d9e1 | 632,065 |
def parse_event_description(in_event):
"""Find and make nice the gig description from a single event from bar 303 website
Args:
in_event (scrapy.http.response.html.HtmlResponse): The html response for the single event from bar 303 website
Returns:
str: Event Description, maybe an e... | 3a15bc3a3aa272c8ff6e06c8dec09f02bfcfcb87 | 632,066 |
def expected_ic_m_ndp_values():
"""Values for m_ndp."""
return {
"accuracy_0.175": 1.0,
"precision_0.175": 1.0,
"recall_0.175": 1.0,
"f1_score_0.175": 1.0,
"TP_0.175": 2013,
"FP_0.175": 0,
"TN_0.175": 547,
"FN_0.175": 0,
"accuracy_0.225": 1... | 25616dfb6b82cc3e2c8f508cc67e6b6f0630719d | 632,067 |
import random
def random_order(ugraph):
"""
returns a list of random node order
"""
nodes = ugraph.keys()
random.shuffle(nodes)
return nodes | 781ac99331ad2f76292ccaeb5017bd859719ca52 | 632,068 |
import torch
def is_autocast_enabled() -> bool:
"""Similar to torch.is_autocast_enabled, but compatible with torch 1.5.1"""
if hasattr(torch, "is_autocast_enabled"):
return torch.is_autocast_enabled()
return False | a998dbf371840ea3cce00536d309ea32620344a2 | 632,069 |
def _split_input_slice(input_shape, num_split):
"""Get input slice from the input shape.
Parameters
----------
input_shape : tuple
The input shape of the net.
num_split : int
The number of split we want to have.
Returns
-------
slices : list of slice
The split ... | 60e72838a6cc2c4d0701a4c106997e81c41a8028 | 632,071 |
import subprocess
def check_quota_usage(account_name):
"""
Use doveadm to get the current quota usage of the account with given name.
:param account_name: The name (email address) of the account to check
:type account_name: str
:return: The quota usage in MiB or None if it could not be found
... | dcec0f25af466473ef65f61012081d3910ba7449 | 632,072 |
def get_DIB_data(Dataset):
"""Function that modifies a pytorch dataset so that the target contains the example index."""
class DIBData(Dataset):
def __getitem__(self, index):
img, target = super().__getitem__(index)
return img, (target, index) # append the index
return DIB... | 6b094f88cf2233cf669c4fa4156994132d6b2394 | 632,073 |
def mln_title(title_parts):
"""Convert title_parts to the way Minuteman represents books in series."""
if title_parts["series"]:
return "{} : {} Series, Book {}".format(title_parts["title"],
title_parts["series"],
title_part... | 1e47bbf8237564c65439ba540e0840b7ecb5019d | 632,074 |
from datetime import datetime
def datetime_to_iso(timestamp):
"""Parse a datatime string and returns a datetime in iso format.
@param timestamp: timestamp string
@return: ISO datetime
"""
return datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S").isoformat() | dee6c931605250033e12f406109b4fbf3b65acf6 | 632,075 |
def is_good_response(response):
"""Helper method to check if boto3 call was a success."""
code = response["ResponseMetadata"]['HTTPStatusCode']
# get response code 201 on EFS creation
return 200 <= code < 300 | 4501439f140fed4576dff8f84fcf038aa552f781 | 632,076 |
def coco2bdd(labels):
"""Map PyTorch Tensor of MS COCO
labels to corresponding BDD100K class.
Parameters
----------
labels : Tensor
A list of labels for predicted bboxes.
Returns
-------
Tensor
"""
person_mask = labels == 1
labels[person_mask] = 5
return labels | 92c1dd9d1da8e6c56cbf07d7428572796a4317c3 | 632,077 |
def next_temperature(prev_temp, prev_next_temp, prev_to_prev_temp, lamb):
"""
Calculator of the next temperature
to be computed with the explicit
method
"""
return prev_temp + lamb * (prev_next_temp - 2*prev_temp + prev_to_prev_temp) | ea08bde8f74fc8a79de35c50d65413eb08d610d0 | 632,078 |
def vips_image_new_from_array(cls, array, scale = 1, offset = 0):
"""Create a new image from an array.
The array argument can be a 1D array to create a height == 1 image, or a 2D
array to make a 2D image. Use scale and offset to set the scale factor,
handy for integer convolutions.
"""
# we ac... | 6c9b74e4d899b9b488d7f5ea331e0b6ec26aa409 | 632,079 |
def svc_ids(svc):
"""
Returns the account ID and service ID of a given service.
"""
return svc['accountId'], svc['id'] | 80fc584a69279187b76c4a3366b36f70289636e0 | 632,080 |
def delete(lst, **kwargs):
"""Delete an element from a list that matches the search criteria in ``**kwargs``
Parameters
----------
lst: list
List to be searched.
"""
for (idx, element) in enumerate(lst):
for attr, val in kwargs.items():
res = getattr(element, attr)
... | 23dd298375515efa9345f79a4528f077422a6260 | 632,081 |
import logging
def time_format(t):
"""
对于年月日进行排序输出,传入参数必须为str类型
:param t:
:return:
"""
if isinstance(t, str):
time_format_part = t.split()
time_format = time_format_part[-2] + "年 " + time_format_part[0] + " " + time_format_part[1] + "日 " + time_format_part[2]
return tim... | 060e358743a859e55c24fbcfd13a0649583b45fe | 632,082 |
import time
def get_offset():
""" Returns 0 if local time after 6AM and before 6PM, 1 otherwise."""
hour = time.localtime().tm_hour
if hour > 6 and hour < 18:
return 0
else:
return 1 | 9c03916014096ddbe3408dd4497c17135a4aef84 | 632,083 |
def get_odds_for_hom(total_hom, total_het, total_homalt):
"""
This class will return the odds of generating an image each time we see a hom case
:param total_hom: Total hom cases present
:param total_het: Total het cases present
:param total_homalt: Total homalt cases present
:return:
"""
... | aebf72bbc7b2cc865f362027ef6566a24ab078c4 | 632,084 |
def split_train_test_val(X, y, threshold=0.1): # Tested [N]
"""
Creates and compiles a fully-connected feed forward neural network model using Keras
Args:
X (DataFrame):
y (ndarray): Labels
threshold (float): The proportion to split the data
Returns:
Xval (Dat... | 1a12592a54ba62dbd3bd0b1478bf9dc79dd20284 | 632,085 |
import requests
def gather_data(playlist_id_, api_key_, page_token_=None):
"""Receive playlist data from YouTube's API"""
url = "https://www.googleapis.com/youtube/v3/playlistItems"
max_results = 50 # 50 is YouTube's max for a request
parameters = {
"key": api_key_,
"maxResults": ma... | 64c2a91ecf22176e9748310521306fe3b439c1b4 | 632,086 |
def vector_function_column(table, function, index):
"""
This function carries out a given function on a given table column
It is necessary to refer to the column index and the function as a function pointer
"""
for j in range(len(table)):
try:
table[j][index] = function(table[j][... | 17a42681c8114bac7113e956c3752a51228253cd | 632,087 |
import torch
def soft_step(x, temperature):
"""Differentiable relaxation of the Heaviside step function."""
return torch.sigmoid(x / temperature) | 672db4208cc50474e225e0dcc7d53393af4fc47a | 632,088 |
def retrieve_prop_from_edge(edge_info, prop):
"""Retrieve property info from the edge data."""
if prop == 'api':
data = edge_info['info'].get('$api')
if data:
if not isinstance(data, list):
data = [data]
return ','.join(data)
elif prop == 'source':
... | f8713c9f0559b190538e1453f765d8167cd43c7b | 632,089 |
def pmul(p, n):
"""Return the multiple of the given probabilty."""
return 1.0 - (1.0 - p) ** n | a8424efe5476e900a56d2aa6cc9fc510e3e29030 | 632,090 |
def is_medium_truck(df):
"""Return if vehicle is a medium truck, per NHTSA convention."""
yr = df['YEAR']
body = df['BODY_TYP']
return ((yr.between(1975, 1981) & body.isin([53, 54, 56])) |
(yr.between(1982, 1990) & body.isin([70, 71, 75, 78])) |
((1991 <= yr) & body.isin([60, 61... | 64c08fe1774846a94a31d77d2aa1ced87b96b4c5 | 632,091 |
def crossProd(a,b):
"""Pretty self-explanatory, this function bakes cookies"""
normal_vect = [
a[1]*b[2] - a[2]*b[1],
a[2]*b[0] - a[0]*b[2],
a[0]*b[1] - a[1]*b[0]]
return normal_vect | bae64138b21ea5cac6ea066a6b74c0b9f63ff0d3 | 632,092 |
import sys
def _sub():
"""Implementation of __SUB__ in perl"""
try:
frame = sys._getframe(1)
name = frame.f_code.co_name
return frame.f_globals[name]
except Exception:
return None | 9ab14c7ca0b3972406da004db4127d6f0b471e82 | 632,093 |
from typing import Optional
from typing import Any
def make_create_json(
summary: str,
project_key: str,
type_name: str,
description: Optional[str],
assignee: Optional[str],
priority_name: Optional[str],
labels: Optional[str],
due_date: Optional[str],
) -> Any:
"""Makes a JSON stri... | 6071e90f6d18de8766d492abd72723bc91aa61a3 | 632,094 |
import posixpath
import os
def _NormalizeFileList(file_list):
"""Removes non-empty directory entries and sorts resulting list."""
parent_directories = set([])
directories = set([])
files = set([])
for f in file_list:
# Drops any trailing /.
norm_file_path = posixpath.normpath(f)
if f.endswith('/... | ffb01d9f07402d909847c4085ea9dabccf07d7c4 | 632,095 |
def normalize_pixel_values(pixels):
""" Normalize pixel values to be in the range [0, 1] """
pixels = pixels.astype("float32")
pixels /= 255.0
return pixels | e8d4a621e6c411251e41eeac2cfc82989895affd | 632,096 |
def clean_meta_data(meta_data_frame):
"""
Clean the meta data we have. Remove an unnamed column, rename some other columns, drop some columns
:param meta_data_frame: pd dataframe
:return: cleaned pd dataframe
"""
meta = meta_data_frame.loc[:, ~meta_data_frame.columns.str.contains("^Unnamed")]
... | fb61391e99067b02471310fb6c629204fd436739 | 632,097 |
def get_results(iso3, strategies, results, all_settlements,
regional_lookup):
"""
"""
output = []
regions_lut = set()
for region in results:
modeling_region = region['modeling_region'].replace("'", "")
regions_lut.add(modeling_region)
for strategy in strategies:
... | 057d662034ad1ce9cecbbaa510eceb1a79946126 | 632,098 |
from typing import Any
def _is_not_empty(attribute: Any, value: Any) -> bool:
"""Filter out empty Lists and Dictionaries"""
if value == dict():
return False
elif value == list():
return False
else:
return True | 786d332c25b5b13ea97f2d6c6ac6bd667e8d675a | 632,099 |
import re
def load_version():
"""Open and parse out the version number from the _version.py module.
Inspired by http://stackoverflow.com/a/7071358
"""
version_file = "baya/_version.py"
version_line = open(version_file).read().rstrip()
vre = re.compile(r'__version__ = "([^"]+)"')
matches =... | 0356f7884e763801c4fa0d4b1fd56736549fa12c | 632,100 |
def to_iamc_layout(df):
"""Transform *df* to a standard IAMC layout.
The returned object has:
- Any (Multi)Index levels reset as columns.
- Lower-case column names 'region', 'variable', 'subannual', and 'unit'.
- If not present in *df*, the value 'Year' in the 'subannual' column.
Parameters
... | aaa64e3b3f4139881955675a88e9f93af02453ea | 632,101 |
def multi_match_aware_interval(k, delta, i, s, pi, li):
"""
Function returning the interval of relevant substrings to lookup using the
multi-match-aware substring selection scheme described in the paper.
Args:
k (int): Levenshtein distance threshold.
delta (int): Signed length differenc... | 096b3650df7c7f73e8d5644395c66ff36b40072e | 632,103 |
def delete_files_template(get_s3_client_func, get_bucket_func, delete_keys_func, key_list, s3_bucket):
"""
Curried template function for deleting files from an S3 bucket
:param get_s3_client_func: A function that returns an S3 client
:param get_bucket_func: A function that returns an object representi... | d766fd1fb12b044f3436da0846f3802a6ad521c1 | 632,104 |
def find_srl_role_of_span(span, srl):
"""If span is involved as one of the arguments of the given srl, return the srl role. Else return None
The SRL eventargument must completely cover the given span. Since SRL arguments do not overlap, there is only max
1 SRL role to return
:type span: nlplingo.text.t... | eb011358b68b69be3da70d388af341ea1e634e38 | 632,105 |
def hashable(raw):
"""If `raw` contains nested lists, convert them to tuples
>>> hashable(('a', 'b', 'c'))
('a', 'b', 'c')
>>> hashable(('a', ['b', 'c'], 'd'))
('a', ('b', 'c'), 'd')
"""
result = tuple(hashable(itm) if isinstance(itm, list) else itm
for itm in raw)
r... | 9d66280ccc739d16fbae3a07c61b51cff19439ea | 632,108 |
import torch
def get_float_encoding(
token: str, embedding_size: int, vmax: float = 1.0
) -> torch.Tensor:
"""Convert a token representing a float into a _fixed_ embedding vector.
NOTE: This can be used for *any* range of numbers > 0.
Args:
token (str): A token representing a float. NOTE: Nee... | 0bc9414ba80663d5d05c3a55077cae78a25d21eb | 632,109 |
def cross_sub_array(arr, low, mid, high):
"""
:param mid: lsum is left sum
"""
lsum = -10000
sum = 0
maxl = mid
maxr = mid + 1
for i in range(mid, low - 1, -1):
sum = sum + arr[i]
if sum > lsum:
lsum = sum
maxl = i
# rsum is right sum
rsum... | 45e73a97c6c4dccf9356161bbbfd1e46c6820092 | 632,110 |
def latex_cmidrule(num_chunks:list, separate=1, offset=1):
"""compute and return the c-mid rule.
"""
cstart = offset + separate + 1
l = ''
for c in num_chunks:
l += '\cmidrule{' + '{}-{}'.format(cstart, cstart + c-1) + '}'
cstart += c + separate
return l | 9143d61f75ca0c5b982881671f55881325562b23 | 632,111 |
def catch_erroneous_destination(destination):
"""
Catch instructions that are not valid and throw an error.
"""
error_msg = "Available instructions are: 'any', or '#', where '#' "\
"is an integer."
if destination not in ["any"]:
try:
integer_destination = int(destination)... | acd76e5487dfab294b70a0f2ead8266ca2130e52 | 632,112 |
def uclu_sayisi():
"""
Kullanicidan kac tane uclu kullanmak isticegini geri dondurur.
@return int : Kullanıcıdan aldıgı cevap
"""
kullanici_girdi = int(input("Kac tane üclü kullanmak istediginizi giriniz:"))
return kullanici_girdi | a490f4a0e327e35e188ac4a516dd57bf6c296dc7 | 632,114 |
def __missing__(self, key):
"""
Called by XOutput.__getitem__() to implement self[key]
for dict subclasses when key is not in the dictionary.
"""
return self.xoutput_dict.__missing__(key) | 63c9b3bd2240fa80b05c1226c234a0e2f620de75 | 632,116 |
from typing import Union
from pathlib import Path
from typing import List
import os
def get_files(directory: Union[str, Path], extension: str) -> List[Path]:
"""Find all files in directory with extension.
Args:
directory : Directory to recursively find the files
extension : File extension to ... | bbabebb78a3f6f776f5d28a6ff1ccff3e7f719f5 | 632,117 |
from typing import Tuple
def default_pruning_sparsities_perf() -> Tuple[float, ...]:
"""
:return: the sparsities to check for effects on the loss
"""
return 0.0, 0.4, 0.6, 0.7, 0.8, 0.85, 0.9, 0.95, 0.975, 0.99 | fe7c44efdda1579fc894d834684e2ee607bb771b | 632,118 |
from pathlib import Path
def get_input_data(input_file: Path) -> list[str]:
"""Get the input data from the file"""
if not input_file.exists():
raise FileNotFoundError(f"Input file {input_file} not found!")
with open(input_file, "r") as f:
return f.readlines() | 2f79ff023544ec7077c7cba120ad6a9dc6a0f0e2 | 632,119 |
def spin_words(sentence):
"""
Write a function that takes in a string of one or more words, and returns the same string, but with all five or more
letter words reversed (Just like the name of this Kata). Strings passed in will consist of only letters and spaces.
Spaces will be included only when more th... | 8f3a13b6ae7505608b962d0d74c0daca34a52514 | 632,121 |
def measurement_process_equality(mp1, mp2):
"""Helper function to check for equality between two MeasurementProcess objects."""
same_return_type = mp1.return_type == mp2.return_type
same_obs = mp1.obs == mp2.obs
same_wires = mp1._wires == mp2._wires
same_eigs = mp1._eigvals == mp2._eigvals
same_... | e0e414928f7c29e8977effd9e9f9bb2a262f94c7 | 632,122 |
def pos_num_check(input_value, warning_box):
"""Checks if input is a positive number."""
try:
pos_num_value = float(input_value)
if pos_num_value > 0:
warning_box.config(text="")
return True
else:
warning_box.config(text="Please type a positive number.")
return False
except ValueError:
warning_bo... | e9a5fc761b492fb775ac16df170ef2700eea231a | 632,123 |
def paragraphs(linelist):
"""
Break a list of lines at blank lines into a list of line-lists.
"""
plist = []
newlinelist = []
for line in linelist:
line = line.strip()
if line:
newlinelist.append(line)
elif newlinelist:
plist.append(newlinelist)
... | 681633b1e03c0adb1619d919c47f30108d5684a8 | 632,125 |
def friendly_number(number, base=1000, decimals=0, suffix='',
powers=['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']):
"""
Format a number as friendly text, using common suffixes.
>>> friendly_number(102)
'102'
>>> friendly_number(10240)
'10k'
>>> friendly_number(12341234, ... | b29797dc747791853001fb32a387c184b3b9a138 | 632,126 |
import os
import re
def get_star_name(data_file):
""" Find star name (usually works for approx. standard filenames) """
bn = os.path.basename(data_file)
try:
pattern = '|'.join([
'HD\d+', 'HIP\d+', 'HR\d+', 'BD-\d+', 'CD-\d+', 'NGC\d+No\d+',
'GJ\d+', 'Gl\d+'
])
... | 3a5e2974906a195fbf03d217ba3660292b080310 | 632,127 |
from typing import List
def list_truncated_nums(n: int) -> List[int]:
"""
Returns a list of all left and right truncated numbers of n
>>> list_truncated_nums(927628)
[927628, 27628, 92762, 7628, 9276, 628, 927, 28, 92, 8, 9]
>>> list_truncated_nums(467)
[467, 67, 46, 7, 4]
>>> list_truncat... | ec349e55e60e3164373702d2d020a9cd791ec039 | 632,128 |
import csv
def get_arp_table():
"""
Get ARP table from /proc/net/arp
"""
with open('/proc/net/arp') as arpt:
names = [
'IP address', 'HW type', 'Flags', 'HW address',
'Mask', 'Device'
] # arp 1.88, net-tools 1.60
reader = csv.DictReader(
... | 9db978fcf7fa47aa825208957b54ed64b7941363 | 632,129 |
def to_device(data_tuple, device):
"""
Move data to device
"""
device_tuple = [x.to(device) for x in data_tuple[:-2]]
if data_tuple[-2] is not None:
device_tuple.append(data_tuple[-2].to(device))
else:
device_tuple.append(None)
if data_tuple[-1] is not None:
device_tu... | 95d35792728092562732457f1f49fa9f0e6f5d06 | 632,130 |
import os
import sys
def path_locations(home_dir):
"""Return the path locations for the environment (where libraries are,
where scripts go, etc)"""
home_dir = os.path.abspath(home_dir)
abiflags = getattr(sys, 'abiflags', '')
py_version = 'python%s.%s' % (sys.version_info[0], sys.version_info[1])
... | c39361f3380d7f78187e6b5a3f5c3bd2b2fc5f9d | 632,133 |
def judge_checksum(content: bytes) -> bool:
"""
Judge if the checksum is right or not.
:param content: the content of segment
:return: A bool
"""
even_sum = 0x0
odd_sum = 0x0
for i in range(len(content)):
b = content[i]
if i % 2:
odd_sum += b
odd... | aec6fc15a213639de432b58ae9ac2e7abb5d92ee | 632,134 |
import yaml
def check_release_version_from_config(pre_commit_config_yaml):
"""checks the pre-commit-config.yaml in the current directory and returns the release tag detailed there"""
with open(pre_commit_config_yaml, "r") as file:
config = yaml.safe_load(file)
res = filter(lambda x: "pii-secre... | ffdd877b496beb35dd6cd06a5ae62150cc7672bb | 632,135 |
def request_update_translation():
"""
Call /update/ view to push a translation/suggestion etc.
"""
def func(client, **args):
update_params = {
"translation": "approved translation",
"plural_form": "-1",
"ignore_check": "true",
}
update_params.... | 1b745292aaf8e885ef3a851b4804f68490a44910 | 632,136 |
import random
def rand_char():
"""
随机产生验证码的字符
:return: 字母
"""
char_list = 'ABCDEFGHJKMNPQRSTUVWXY3456789'
index = random.randint(0, len(char_list)-1)
return char_list[index] | 90673ffc5a4fd4b6463d668805ad95d410b52f7e | 632,139 |
import random
def getRandomColor():
"""Return a string of a random color."""
return random.choice(('black', 'red', 'green', 'yellow', 'blue',
'purple', 'cyan', 'white')) | 1220c63857d917721998f14f1470a3660a4210db | 632,140 |
from functools import reduce
def factors(n, ordered=True):
"""Get factors of a number in a list.
Parameters:
n (int): The number that you want to get the factors of.
ordered (bool): Whether you want the output to be ordered from smallest to largest. Setting this value to false will marginally increas... | 5927699ae291cbbea3aad20aba9fd423a17e245c | 632,141 |
import re
def regex_password(password):
"""
Regex
Password includes at least one digit, one uppercase letter, one lowercase letter, and one special character.
"""
# The {8,} means "at least 8".
# print(re.match(r"^(?=.*[\d])(?=.*[A-Z])(?=.*[a-z])(?=.*[@#$%^&*?!+-_=])[\w\d@#$]{8,}", password))
... | b7593fcaa5b75d8ed154e0930cdfc0b4d09b7247 | 632,142 |
import os
def _is_readable(path):
"""
Tests whether path exists and is readable.
>>> from extended_pathlib import Path
>>> Path('/usr/bin/python').is_readable()
True
"""
return os.access(str(path), os.R_OK) | 8630f74cbb7a6e0fe6c16788c8fbcfdf8f4c9727 | 632,143 |
def px2hc(xpx, ypx, dx, dy, xc, yc, sz):
"""
Given positions in pixel coordinates (x = [0->nx-1]; y = [0->ny-1]),
determine the HC x and y coordinates in arcseconds.
- xpx, ypx = pixel coordinates of AR positions
- dx, dy = arcsec/px
- xc, yc = FOV center in arcsec from solar disk center
- x... | 0ef0cea5e31757069cdc5a4af9b93778ef881efd | 632,144 |
import os
import glob
def Dir_Parser(test_path):
"""
Input:
@ test_path: a string containing the path of the directory
Return:
@ file_map: a dictionary with the one min files
key is the bnYearMonthDate-HourMin
item is a list containing the file names in that min
... | 419c6229752e51da3cc4e99603df8c3739daecbe | 632,145 |
def get_hyperparams(tree_type, dataset):
"""
Input
tree_type: str, Tree-ensemble type.
dataset: str, dataset.
Return
- Dict of selected hyperparameters for the inputs.
"""
lgb = {}
lgb['adult'] = {'n_estimators': 100, 'num_leaves': 31, 'max_depth': -1}
lgb['bank_mark... | dc311006f33a18089681f4f835d62fadd388444f | 632,146 |
from typing import AsyncGenerator
import os
import asyncio
async def scantree(path: str) -> AsyncGenerator[os.DirEntry, None]:
"""Recursively yield DirEntry objects for given directory."""
def is_dir(entry: os.DirEntry) -> bool:
return entry.is_dir(follow_symlinks=False)
loop = asyncio.get_runni... | 927123279061a37c9a06be92bd5f3e404afa5e17 | 632,147 |
import logging
def get_birthday(soup):
"""
Utility function to get the Birthday of an actor from his wikipedia page.
:param soup: Beautiful Soup object
:return: String containing the actor's birth date in yyyy-mm-dd format.
"""
logging.info("getBirthday called.")
# Isolate the info box ta... | 22c0efbfcbea85dabbdfae619b6f7ac28e46fe82 | 632,148 |
def fix_text(text):
"""Fix the text and return it.
@param text : a string of text or rich-text
@return: the fixed text
@rtype: str
You can add other other fixes and tweaks here.
"""
try:
fixed = text.decode('utf-8')
except UnicodeDecodeError:
fixed = text.decode('latin-... | 06725371f2fa8f4866c8d6147291d2fd0a427b72 | 632,150 |
import re
def clean_string(instring):
"""
:param instring:
:return:
"""
outstring = re.sub(r'[^\x00-\x7f]', r'', instring)
outstring = outstring.replace('_', ' ')
if len(instring) > 3:
outstring = outstring.title()
else:
outstring = outstring.upper()
return outstr... | f60bb3d02f653f715adfbfbea3d32e9cffb45d20 | 632,151 |
import math
def _2d_rotate(position, angle_degrees):
"""rotate a 2d vector around an angle (in degrees)"""
radians = math.radians(angle_degrees)
# take the negative of the angle because the orientation circle works clockwise in this world
cos = math.cos(-radians)
sin = math.sin(-radians)
x, y ... | cd031deef2ed1be59ffa03214055ede3277d7912 | 632,154 |
import itertools
def product_no_consecutives(iterables, repeat=2):
""" Returns Cartesian product of input iterable excluding those contaning
equal consecutives elements.
See: `itertools.product`
"""
def has_no_equal_consecutives(sequence):
it, it_shifted = itertools.tee(sequence)
next... | e8fa05f8dfff07ccc9abc708ba6cd625a516bb68 | 632,155 |
def true_or_false(value):
"""Replace Yes/No with True/False"""
if value in {'0', 'Yes'}:
return True
if value in {'1', 'No'}:
return False
raise ValueError('{} is neither True nor False'.format(value)) | a548a3393cea6f39de93426ca8bb42022a6fb175 | 632,156 |
def crop_window(window, cropper_window):
"""Returns a version of window cropped against cropper_window.
Also returns a tuple containing two bools: (cropped_rows, cropped_cols)"""
(changed_rows, changed_cols) = (False, False)
((row_start,row_end),(col_start, col_end)) = window
if row_start < cropper... | a37ebc1b35c04cf45feb660760138f3314d180ea | 632,157 |
def argmaxIndex(l, f = lambda x: x):
"""
@param l: C{List} of items
@param f: C{Procedure} that maps an item into a numeric score
@returns: the index of C{l} that has the highest score
"""
best = 0; bestScore = f(l[best])
for i in range(len(l)):
xScore = f(l[i])
if xScore > b... | d6351600278f5451f2aa9d463e791e9c61387588 | 632,158 |
import os
def exists(directory: str, filename: str) -> bool:
"""Check if the given file exists in the given directory.
It's synchronous, but it's probably fine for a test.
"""
return os.path.exists(os.path.join(directory, filename)) | 1ce8c43f44d4dd45fdf4272809ada637b598a701 | 632,159 |
import re
def _mask_back(article, index):
"""From index move back to the previous word"""
word_back = re.compile(r'^(\w+)\W')
m = word_back.match(article[:index])
if m:
return index - len(m.group(1))
else:
return index | 715881998ac172ede351651d6ba7d708af16d1aa | 632,160 |
def is_scoped_package(name):
"""
Return True if name contains a namespace.
For example::
>>> is_scoped_package('@angular')
True
>>> is_scoped_package('some@angular')
False
>>> is_scoped_package('linq')
False
>>> is_scoped_package('%40angular')
True
"""
return name.st... | 22d54aaf967f8556686a023f296f70d38a864496 | 632,161 |
def quotify(text: str) -> str:
"""
Turn a string into a discord quote.
:param text: Text to put into quote
:return: Discord quote
"""
return "> " + text.replace("\n", "\n> ") | afb856ad81190ac15279dbffb1d1b24413645366 | 632,162 |
def AddRepositoryTags(prefix='', rid=True, date=True, revision=True,
wrap=False):
"""Add repository tagging into the output.
Args:
prefix: comment delimiter, if needed, to appear before tags
rid: bool; True includes the revision Id: repository tag.
date: bool; True includes the Da... | 59057ebaad1f2807bb186c0010fbc8f5828988f2 | 632,163 |
import json
def load_json(filename):
""" load external json file """
with open(filename) as data_file:
json_data = json.load(data_file)
return json_data | 9557ed533588606a4e66a1fc110a09e728cb4d4b | 632,164 |
def _report_settings():
"""Return settings to be used for all reports."""
# Set the font description for saving out text with matplotlib
font = {'family': 'monospace',
'weight': 'normal',
'size': 16}
return font | 25e8287aa7daa66975107beeb38a334fc5e08981 | 632,165 |
def poem_fragments(poem_series, split_into):
"""
Gets wordlend of a poem,
if larger than SPLIT_INTO partions into next paragraph
return author, title and poem broken in this way
"""
poem = poem_series
poem_author = poem.author
poem_title = poem.title
poem_content = poem.content
... | f2eb4fd3f866cbcfa123fcbbb2a7818a737177fd | 632,167 |
import math
def euclid(onsets, pulses):
"""returns a list of ones and zeros for a give euclidean rhythm
>>> euclid(3,8)
[1, 0, 0, 1, 0, 0, 1, 0]
"""
slope = float(onsets) / float(pulses)
result = []
previous = None
for i in range(pulses):
current = int(math.floor(float(i) * sl... | ac06108bc86f57c8a0b381f813fa03aecf3ea752 | 632,168 |
def class_to_dict(inst, ignore_list=[], attr_prefix=''):
""" Writes state of class instance as a dict
Includes both attributes and properties (i.e. those methods labeled with @property)
Note: because this capture properties, it should be viewed as a snapshot of instance state
:param inst: insta... | 1c3e1f752028240f67188d47499a0557b0351a82 | 632,169 |
def generate_id(text):
"""Deterministically generates an ID from a given text.
NOT guaranteed to be unique, but the alternative was to
either drop some data for not having IDs, or
generating uniquely on the fly: which is hard to do on
a batch system.
A negative integer is returned to avoid... | cec5c398dbc3fc3ee12fb9d2d8af6081bd91165f | 632,170 |
import os
import random
def getPasswords():
"""
Returns an array of strings to be used as the password and the decoys
"""
groups = []
# script file / password file location
__location__ = os.path.realpath(os.path.join(os.getcwd(),
os.path.dirna... | 33e61c6e00dc631c8b1cc53275325bbcdf096787 | 632,171 |
def getTemperature(
U_code,
helium_mass_fraction=None,
ElectronAbundance=None,
mu = None):
"""U_code = snapdict['InternalEnergy'] INTERNAL ENERGY_code = VELOCITY_code^2 = (params.txt default = (km/s)^2)
helium_mass_fraction = snapdict['Metallicity'][:,1]
ElectronAbundance= snapdict['Electron... | 68ccc44c89298d060d8e6d8a1837d9190a6a9b51 | 632,172 |
import re
def hasMainFunc( filename ):
"""
Returns True if file contains something that looks like a main() or
main( int argc, char argv ) function.
"""
main_regex = re.compile('.*main(.*argc.*argv).*')
f = open(filename)
for line in f.readlines():
if main_regex.search( line ):
... | 0c80895b7fbaadfc772a724c687f2f5e68b22677 | 632,173 |
import requests
import time
def get_from_bgg(api_url, parameters):
"""Successively attempts to get data from BGG given an API"""
response = requests.get(api_url, params=parameters)
# Retry if return codes indicate "too many requests"
while response.status_code == 202 or response.status_code == 429:
... | 361c4e29aecfd8a70da7ec75924400b44a519b04 | 632,174 |
import re
import itertools
def extract_param_list(params, prefix=''):
"""Extract a list-of-dicts based on parameters containing AWS style list.
MetricData.member.1.MetricName=buffers
MetricData.member.1.Unit=Bytes
MetricData.member.1.Value=231434333
MetricData.member.2.MetricName=buffers2
Met... | f84a4db4592c9609074996df7b1bd33adbf5e1e1 | 632,175 |
def is_palindrome(num):
""" Returns true if a number is a palindrome """
reverse, forward = 0, num
while (num > 0):
reverse = reverse*10 + num%10
num /= 10
return forward == reverse | e1e3eb23a3bd83d8978c68468b633dc2daca370c | 632,176 |
def privilege_check(user, *required_privileges):
"""Tests if the user has one of the required_privileges to view the
requested component.
"""
for perm in required_privileges:
if user.has_property(perm):
return True
return False | 18fe8837a9152991b2ef8974c19303677349ee8c | 632,177 |
def pages_endash(record):
""" Convert pages to use an html en dash
"""
try:
# Convert to list of page numbers
pages = [p.strip() for p in record['pages'].split('-')
if p.strip()]
record['pages'] = '–'.join(pages)
except KeyError:
pass
return reco... | 873efb473df3f2222b94d1ed51c830125226e879 | 632,178 |
from pathlib import Path
import json
def save_shards_metadata(shard_dir: Path, **kwargs) -> Path:
"""Save metadata file into tar-shards directory
"""
if not shard_dir.exists() or not shard_dir.is_dir():
raise ValueError(f'Invalid shard_dir: {shard_dir}')
metadata_file = shard_dir / 'metadata.j... | 5042ffbd15fd237ae3a5a9c86841acc77781f885 | 632,179 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.