content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def blend(alpha, base=(255, 255, 255), color=(0, 0, 0)):
"""
:param color should be a 3-element iterable, elements in [0,255]
:param alpha should be a float in [0,1]
:param base should be a 3-element iterable, elements in [0,255] (defaults to white)
:return: rgb, example: (255, 255, 255)
"""
return tuple(int(... | 19587df9f6f0ede7938f7b5a15c348b066656909 | 651,405 |
import time
def time_function(f, *args):
"""
Call a function f with args and return the time
(in seconds) that it took to execute.
"""
tic = time.time()
f(*args)
toc = time.time()
return toc - tic | 066a9504d2074a9d59e7f55282e3080244348026 | 651,407 |
def parse_rank_specification(s):
"""
Parses info about rank specification, used to filter games by player's ranks.
Returns None (all ranks allowed),
or a set of possible values
(None as a possible value in the set means that we should include games without rank info)
# returns None, all ranks ... | ff7ce2b9940b6cd55bf0fab7bd2f633637fd7cc8 | 651,409 |
from typing import Sequence
from pathlib import Path
def real_words() -> Sequence[str]:
"""Loads a list of real words to search."""
with (Path(__file__).parent / 'words.txt').open() as path:
return tuple(map(str.strip, path.readlines()))[:5] | 230d3d625d112114d9ed088c1743a65b7bb84a7f | 651,411 |
def list_(client, file_=None, name=None, value=None, get_expanded=None, select=False):
"""Get a list of notes from one or more models.
Values will automatically be returned Base64-encoded if they are strings
which contain Creo Symbols or other non-ASCII data.
Args:
client (obj):
cr... | 712f43114e260c3eaff0b601d622fdd2f9723743 | 651,413 |
def ordinary_annuity(p: float, i: float, n: float) -> float:
"""
Calculates the annuity payment given loan principal, interest rate and number of payments
:param p: loan principal value
:param i: monthly nominal interest rate
:param n: number of payments
:return: annuity payment
"""
nume... | 7627c245d21c8bac38d574919b790a1c3e205598 | 651,414 |
from typing import List
def _join(iterable: List, and_or: str) -> str:
"""Join iterables grammatically."""
return ', '.join(iterable[:-2] + [f' {and_or} '.join(iterable[-2:])]) | cef0c515b5b9af926d4a6612f244569ff5f26fbc | 651,421 |
def downToLocal(poetryList, path):
"""ไธ่ฝฝ่ฏ่ฏไฟๅญๅฐๆฌๅฐtxt
Args:
poetryList (List): ่ฏ่ฏๅ่กจ
path (String): ไฟๅญ่ทฏๅพ
Returns:
None
"""
for content in poetryList:
with open(f'{path}' f'{content[0]}.txt', 'w', encoding='utf-8') as file:
file.writelines('\n'.join(content))... | b530e0d3af6975b42276ea9963ca34ceee877568 | 651,423 |
def Julian_centuries_since_2000(jd):
"""
Julian centuries from Jan 1, 2000.
@param jd : Julian date
@type jd : float
@return: float
"""
t = (jd-2451545.)/36525.
return t | 2ff9c9b0be59b60a8bbb3f0f3861449b6896d09d | 651,425 |
def services_type(loader):
""" Returns a function which validates that services string contains only a combination of blob, queue, table,
and file. Their shorthand representations are b, q, t, and f. """
def impl(string):
t_services = loader.get_models('common.models#Services')
if set(strin... | e3d6c34e4c0e3b42369199aac5c0b5817b202634 | 651,430 |
def dump_queue(queue):
"""
Empties all pending items in a queue and returns them in a list.
"""
result = []
queue.put("STOP")
for i in iter(queue.get, 'STOP'):
result.append(i)
return result | 806db0443d671bc7b4bfe8054d903c46ba10eaa9 | 651,432 |
def iterable(arg):
""" Simple list typecast
"""
if not isinstance(arg, (list, tuple)):
return [arg]
else:
return arg | 6502eb92507e30fcc5bf54c3d40937b4236573ab | 651,434 |
def complement(predicate):
"""Generates a complementary predicate function for the given predicate
function.
:param predicate:
Predicate function.
:returns:
Complementary predicate function.
"""
def _negate(*args, **kwargs):
"""Negation."""
return not predicate(*args, **kwargs)
retu... | f8538057044a95a40133110c801459545c2d3776 | 651,436 |
def mytask(data, *args, **kwargs):
"""Simple task which returns reverse string
"""
return data[0][::-1] | cfc26959910d1e8cbc638e6426fd0b519d752295 | 651,443 |
def unpack_point_msg(msg, stamped=False):
""" Get coordinates from a Point(Stamped) message. """
if stamped:
p = msg.point
else:
p = msg
return p.x, p.y, p.z | 9c73105be73cbcdc55cef0f268851567dcbcd822 | 651,445 |
import uuid
def uuid_from_string(idstr):
"""Convert an uuid into an array of integers"""
if not idstr:
return None
hexstr = uuid.UUID(idstr).hex
return [int(hexstr[i:i+2], 16) for i in range(32) if i % 2 == 0] | 4a2bb28068b86394ebae213951eb4bf6a3875fb7 | 651,447 |
import string
import random
def random_string_generator(size=6, chars=string.ascii_uppercase + string.digits):
"""
Generate random string
Args:
size: length of the string
chars: sequence of chars to use
Returns: random string of length "size"
"""
return ''.join(random.choice(c... | 4b9e9ef10664c57b6839f549f6ca9aac9fa78fdc | 651,449 |
import math
def compute_colors(n, cols):
"""Interpolate a list of colors cols to a list of n colors."""
m = len(cols)
lst = []
for i in range(n):
j = math.floor (i * (m - 1.0) / (n - 1.0))
k = math.ceil (i * (m - 1.0) / (n - 1.0))
t = (i * (m - 1.0) / (n - 1.0)) - j
(r0... | 121f2080faa3ca9d574572a47c231fc525ee74fe | 651,450 |
def issubstring(s1, s2, *args, **kwargs):
"""Is s1 a substring of s2"""
return s2.count(s1) > 0 | 9a3aad1e3f46677457d78e9169c241577102200e | 651,451 |
def common_characters(w1, w2):
"""
Parameters:
----------
w1: str
w2: str
Returns:
--------
int:
Number of characters common between two strings
"""
ws1 = set(w1)
ws2 = set(w2)
return len(ws1.intersection(ws2)) | dcb3aa3f06bf2057532527be52cf545e1affb9f6 | 651,452 |
def topic_filename(topic: str) -> str:
"""
Returns the filename that should be used for the topic (without extension).
"""
# Remove commas and replace spaces with '-'.
return topic.replace(",", "").replace(" ", "-") | 4d8c20d4ee82fdd33238b90f1021e50f8e16817c | 651,453 |
def get_published_file_entity_type(tk):
"""
Return the entity type that this toolkit uses for its Publishes.
.. note:: This is for backwards compatibility situations only.
Code targeting new installations can assume that
the published file type in Shotgun is always ``PublishedFi... | 864ce47673991a9cac15b52b0edf2c11148cc08e | 651,460 |
def tokenize(chars):
"""
Convert a string of characters into a list of tokens.
"""
return chars.replace('(', ' ( ').replace(')', ' ) ').split() | daf16f256d2b322c4d12cc0d32161f1394b28b88 | 651,461 |
import json
def set_config(config_name):
"""
Config parse
:param config_name: config file name
:type config_name: str
:return: parsed config
:rtype: dict
"""
try:
return json.load(open(config_name, 'r'))
except FileNotFoundError:
print('%s %s' % (config_name, 'no... | eb4e53018efb6b3f0db4a0cfa587493fdf80bf52 | 651,462 |
def hsv_to_rgb(h, s, v):
"""Convert HSV values RGB.
See https://stackoverflow.com/a/26856771.
:param h: Hue component of the color to convert.
:param s: Saturation component of the color to convert.
:param v: Value component of the color to convert.
:rtype: tuple
""... | 0b74f5ccbff722a139bea316c41f644aa2d7a36d | 651,468 |
def next_byte(server_socket):
"""
This method reads in one byte.
:param server_socket: the socket to read one byte from
:return: a byte object of the single byte read in
"""
return server_socket.recv(1) | ee04743e53c6893a2c4627e5c28d2ea88617668c | 651,469 |
def cleanupQuotes(text):
"""
Removes quotes if text starts and ends with them
Args:
text (str): Text to cleanup
Returns:
Text with quotes removed from start and end (if they existed) or original string (if not)
"""
if text.startswith('"') and text.endswith('"'):
return text[1:-1]
else:
return text | 6079cd9491e248f20d645ebc1fb9c99d073e18ac | 651,470 |
def max3(a,b,c):
"""a,b,c์ ์ต๋๊ฐ์ ๊ตฌํ์ฌ ๋ฐํ""" #์๋ง ํจ์๋ฅผ ์
๋ ฅํ ๋ ์ถ๊ฐ๋ก ์ค๋ช
๊ฐ์ ๋์ด ๋ค์ด๊ฐ๋๊ฒ ๊ฐ๋ค.
maximum=a
if b>maximum: maximum=b
if c>maximum: maximum=c
return maximum | 190f0fd8f13d40ae53c43ef0b56591975a967a27 | 651,471 |
def truncate_to_fit(text, len):
"""
Truncate text to specified length.
"""
return text[:len] | f93dc690075cf1417ff64a15a3b2ec9a26b117b3 | 651,473 |
def add_headers(response):
"""
This function adds headers to outbound requests to increase the security posture in the browser
"""
response.headers["Cache-Control"] = "public, max-age=31536000"
response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
response.hea... | 48173a4660d0c24903ae203dc49949193436f645 | 651,475 |
def _abberation_correction(R):
"""Calculate the abberation correction (delta_tau, in degrees) given the Earth Heliocentric Radius (in AU)"""
return -20.4898/(3600*R) | 7fea54c0bc6fffc9e8ab40057b011da327fe0bd7 | 651,479 |
def get_photo_rel_url(album_name, filename):
"""
Gets path of source photo relative to photos basedir
:param album_name:
:param filename:
:return:
"""
return "%s/%s" % (album_name, filename) | 0e3fbb3bf58c7fddabffc995eaa10d9b86cb8fb0 | 651,480 |
def iconset_from_class(value):
"""
extracts the iconset from a class definition
"fa-flask" -> "fa"
:param value:
:return:
"""
if '-' in value:
return value.split('-')[0]
return '' | b03e0642a2e6e4fa784b71a4d65bfdbfd509ba5e | 651,481 |
def make_vertical_bar(percentage, width=1):
"""
Draws a vertical bar made of unicode characters.
:param value: A value between 0 and 100
:param width: How many characters wide the bar should be.
:returns: Bar as a String
"""
bar = ' _โโโโโ
โโโ'
percentage //= 10
if percentage < 0:
... | d6001a5af2ad298f95ca4b32a45cef36c3587c09 | 651,488 |
import torch
def images_to_levels(target, num_level_grids):
"""Convert targets by image to targets by feature level.
[target_img0, target_img1] -> [target_level0, target_level1, ...]
"""
target = torch.stack(target, 0)
level_targets = []
start = 0
for n in num_level_grids:
end = s... | fca57e9b3f3e41a58139daf1d94e731d1c36cda3 | 651,494 |
def is_shared_library(f):
"""Check if the given File is a shared library.
Args:
f: The File to check.
Returns:
Bool: True if the given file `f` is a shared library, False otherwise.
"""
return f.extension in ["so", "dylib"] or f.basename.find(".so.") != -1 | 8045a89fd19f3c1bdc9054fd824df6c1d6be302a | 651,504 |
def generate_trail(wire_directions):
"""Given a list of wire directions, generate a set of coordinate pairs for the wire's path"""
trail = set()
current_location = (0, 0)
for direction in wire_directions:
heading = direction[0]
distance = int(direction[1:])
while distance > 0:
... | 151faa19b9898449dbd6b51528d0a7674b204773 | 651,507 |
def song_decoder(song):
"""
Removes 'WUB' from a string to find the true message of the song.
:param song: The input consists of a single non-empty string, consisting only of uppercase English letters, the string's length doesn't exceed 200 characters
:return: the words of the initial song that Polycarp... | 7dd1ffed422f7fcab6efe00cabe84a8a5493b7e7 | 651,508 |
def str_starts_with_any_in_list(string_a, string_list):
"""
Check if string_a starts with any string the provided list of strings
"""
for string_b in string_list:
if string_a.startswith(string_b):
return True
return False | c687ea09f9ce011cf3301d98a13bb23378e9acbc | 651,509 |
def check_monotonic(a):
"""
Parameters
----------
a
input array
Returns
-1 -- for monotonic, non-increasing
0 -- for non-monotonic
1 -- for monotonic, non-decreasing
-------
>>> check_monotonic([1,2,3])
1
>>> check_monotonic([3,2,1])
-1
>>... | 260b174bf610b12f061be64d4715e0de03f14548 | 651,511 |
def format_report(count, new_inst, del_inst, svc_info):
"""
Given a service's new, deleted inst, return a string representation for email
"""
needed = False
body = ''
if new_inst is not None and len(new_inst) > 0:
needed = True
body += '\n\n New Instances: '
for inst in ... | af4228c354393164d8bf48698479262c5470afcd | 651,514 |
import math
def p_to_q(p):
""" Turn error probability into Phred-scaled integer """
return int(round(-10.0 * math.log10(p))) | d60ee7bb434a599d641ca61156361779955e09bd | 651,516 |
def _make_credentials_property(name):
"""Helper method which generates properties.
Used to access and set values on credentials property as if they were native
attributes on the current object.
Args:
name: A string corresponding to the attribute being accessed on the
credentials attrib... | 17692cb4cf0ea072d4345d60106bb04c0ad030bd | 651,517 |
import pytz
def to_utc(dt):
"""This converts a naive datetime object that represents UTC into
an aware datetime object.
:type dt: datetime.datetime
:return: datetime object, or None if `dt` was None.
"""
if dt is None:
return None
if dt.tzinfo is None:
return dt.replace(tz... | bb06d553a02453f6701f175eb6d15d63134776cb | 651,518 |
import torch
def qlog_t(q):
"""
Applies the log map to a quaternion
:param q: N x 4
:return: N x 3
"""
n = torch.norm(q[:, 1:], p=2, dim=1, keepdim=True)
n = torch.clamp(n, min=1e-8)
q = q[:, 1:] * torch.acos(torch.clamp(q[:, :1], min=-1.0, max=1.0))
q = q / n
return q | fbb7b3d7956b3e96921fc8c36647f3f695e539a1 | 651,522 |
import pathlib
def quandl_apikey_set(apikey, filename=None):
"""Store the Quandl Token in $HOME/.updoon_quandl
Parameters:
-----------
apikey : str
The API Key from the Quandl Website.
See https://www.quandl.com/account/api
filename : str
Absolute path to the text where t... | e3f9ecee89f51e8107f482e7b175a0220d2f2fb7 | 651,524 |
import torch
def compute_argmax(ten):
"""Compute argmax for 2D grid for tensors of shape (batch_size, size_y, size_x)
Args:
ten (torch.[cuda].FloatTensor): (batch_size, size_y, size_x)
Returns:
indices (torch.[cuda].LongTensor): (batch_size, 2) index order: (y, x)
"""
batch_size ... | d69c6ae13dfa2aef27a7e6ed621e928c146c0554 | 651,526 |
def get_cbmc_info(n_insert, n_dihed, cutoffs):
"""Get the CBMC_Info section of the input file
Parameters
----------
n_insert : int
number of insertion sites to attempt for CBMC
n_dihed : int
number of dihedral angles to attempt for CBMC
cutoffs : list
list containing CBM... | 769640657d46b1862dedd952f15b97dba80420b4 | 651,529 |
def has_active_balance_differential(spec, state):
"""
Ensure there is a difference between the total balance of
all _active_ validators and _all_ validators.
"""
active_balance = spec.get_total_active_balance(state)
total_balance = spec.get_total_balance(state, set(range(len(state.validators))))... | 24b0f4d4289e2b683d96c446010a32b50dad1b33 | 651,530 |
from typing import Union
def to_boolean(envvar: Union[str, bool]) -> bool:
"""
Coerce the input to a boolean.
>>> to_boolean("True")
True
>>> to_boolean("FALSE")
False
NOTE: An empty string is interpreted as False:
>>> to_boolean("")
False
Booleans are returned as-is:
... | c373dae669127f6e0a823b21eef8311e76de0493 | 651,534 |
import zipfile
def _ExtractZipEntries(path):
"""Returns a list of (path, CRC32) of all files within |path|."""
entries = []
with zipfile.ZipFile(path) as zip_file:
for zip_info in zip_file.infolist():
# Skip directories and empty files.
if zip_info.CRC:
entries.append(
(zip_i... | 4ba4742964f553c75e7d97e07e15119efd6c96cb | 651,537 |
def get_icon(icon: str) -> str:
"""
Get icon unicode from dictionary.
Parameters:
icon (str): icon code from API response.
Returns:
(str): icon unicode.
"""
icons = {"01": ":sun:",
"02": ":sun_behind_cloud:",
"03": ":cloud:",
"04": ":cloud:",
"09": ":cloud_with_rain:",
"10": ":sun_behind_r... | 2964c7573086ec86d6d22df6ea3fb35380bbd950 | 651,542 |
def get_start_timestamp_mapping(file_path):
"""Get mapping of video name id to star timestamp."""
mapping = {}
with open(file_path) as f_in:
for line in f_in.readlines():
if line.strip() == '':
continue
video_name, time_txt = line.strip().split(',')
... | 15a9ea922c60d018ffde0e407db097027c034057 | 651,544 |
import re
def add_datepart(df, fieldname):
"""
Adds date related features to dataframe df inplace
df: dataframe
fieldname: name of the date field in df
"""
new_df = df.copy()
field = df[fieldname]
target_prefix = re.sub('[Dd]atetime$', '', fieldname)
date_features = (
... | 7774056dd856553501f288c9c97dbc04d359ae59 | 651,549 |
def _apply_signed_threshold(value, min_thr=None, max_thr=None):
"""
Apply threshold on signed value.
usage examples :
>>> _apply_signed_threshold(0.678, min_thr=0.5)
0.5
>>> _apply_signed_threshold(-0.678, min_thr=0.5)
-0.5
>>> _apply_signed_threshold(0.678, max_thr=2.0)
0.678
>>> _apply_signed_thres... | 098a37ec49930634475868c12ffe8bf28b252a48 | 651,550 |
def list_sorted(words):
""" Check if a Tuple of words are Anagrams using Sorted
:param words: Tuple
:return: bool
"""
word_one, word_two = words
return sorted(word_one) == sorted(word_two) | e6449769d51571a8faaab0cbcf51aa7800d766e8 | 651,551 |
def select_hannover_from_metadata(metadata):
"""Select entries from Hannover"""
return metadata.query('doi == "10.6084/m9.figshare.12275009"') | 0400073dcd9a752df4352f4d3e1195fe23fae6d5 | 651,552 |
import hashlib
def get_fd_hash(fd):
"""
Compute the sha256 hash of the bytes in a file-like
"""
BLOCKSIZE = 1 << 16
hasher = hashlib.sha256()
old_pos = fd.tell()
fd.seek(0)
buf = fd.read(BLOCKSIZE)
while buf:
hasher.update(buf)
buf = fd.read(BLOCKSIZE)
fd.seek(o... | 2607d44feeeabe38e3ea240f800e8e42add3ff7a | 651,553 |
def crop(img, left=None, right=None, top=None, bottom=None):
"""Crop image.
Automatically limits the crop if bounds are outside the image.
:param numpy.ndarray img: Input image.
:param int left: Left crop.
:param int right: Right crop.
:param int top: Top crop.
:param int bottom: Bottom cr... | e4d18b959c9f0f55f9c6d24a41658922e34b53c0 | 651,556 |
import yaml
def open_yaml(path):
"""Open yaml file and return as a dictionary"""
data = {}
with open(path) as open_file:
data = yaml.safe_load(open_file)
return data | 81cc6a046566ec4a9d365ed14d26036e5b6c1005 | 651,557 |
import logging
def getLogger(name):
"""
Returns a logger. Wrapper of logging.getLogger
"""
logger = logging.getLogger(name)
return logger | 85ea7245ff87a26d127b54a20b5e852d6d09d7d6 | 651,558 |
def find_missing_keywords(keywords, text):
"""
Return the subset of keywords which are missing from the given text
"""
found = set()
for key in keywords:
if key in text:
found.add(key)
return list(set(keywords) - found) | 4612511654aae93104c6a1edc98b1b4927619539 | 651,561 |
def samplesheet_headers_to_dict(samplesheet_headers: list) -> dict:
"""
Given a list of headers extracted with extract_samplesheet_header_fields, will parse them into a dictionary
:param samplesheet_headers: List of header lines
:return: Dictionary containing data that can be fed directly into the RunSa... | 2df9d99d0971ce182e8e62453c5b7006918806d0 | 651,569 |
from typing import Dict
from typing import Any
from typing import List
import yaml
def insert_worker(worker: Dict[str, Any], workers: List[Dict[str,
Any]]) -> None:
"""Inserts client or server into a list, without inserting duplicates."""
def dump(... | 35d9e908dbc2f706034ab70ca78e890ea79736e7 | 651,571 |
def solve_5bd6f4ac(x):
"""
- Problem : 5bd6f4ac \n
*General Description* (Problem and solving it visually - intuition):
I get the zoomed in grid, only containing the top right third of the original input grid.\n
*Algorithm* (to guide understandiing of the code)
- Fi... | 07e9de65e2284fa3a3c6a6dc5165af44440cda17 | 651,576 |
def set_windows_slashes(directory):
"""
Set all the slashes in a name so they use Windows slashes (\)
:param directory: str
:return: str
"""
return directory.replace('/', '\\').replace('//', '\\') | dcca256d71133d1d394df30177bd151ae059a065 | 651,578 |
def to_str(s):
"""Parse a string and strip the extra characters."""
return str(s).strip() | 1e978481b926e82e1f72c16ca15c3bf2a6db1b53 | 651,580 |
def remove_prefix(text: str, prefix: str) -> str:
"""
Removes the prefix if it is present, otherwise returns the original string.
"""
if text.startswith(prefix):
return text[len(prefix):]
return text | acd31410ef982adba2eb69d2553a0eaa0df9b5f9 | 651,581 |
def classesByCredits (theDictionary, credits):
"""Lists the courses worth a specific credit value.
:param dict[str, int] theDictionary: The student's class information
with the class as the key and the number or credits as the value
:param int credits: The credit value by which classes are queried
... | 1169d8d52977d808d73993b135beef2daa64e89b | 651,582 |
import base64
def _decode_string(text):
"""Decode value of the given string.
:param text: Encoded string
:return: Decoded value
"""
base64_bytes = text.encode('ascii')
message_bytes = base64.b64decode(base64_bytes)
return message_bytes.decode('ascii') | b7ab66e032ac9560a6b0c55add022f26840e2a18 | 651,587 |
def create_occurence_dict(text):
"""Create the occurence dict of characters for a given text.
:text: str, ascii text
:returns: Dict[char:int], occurence dict
"""
result = {}
for c in text:
if c in result:
result[c] += 1
else:
result[c] = 1
return resu... | 827edad4ea226ddebdab1e8ec4a72895fef8497d | 651,592 |
import torch
def gaussian_smearing(distances, offset, widths, centered=False):
"""
Perform gaussian smearing on interatomic distances.
Args:
distances (torch.Tensor): Variable holding the interatomic distances (B x N_at x N_nbh)
offset (torch.Tensor): torch tensor of offsets
cente... | 5efd0093bd9705ea6752517a06de5392db6f7476 | 651,595 |
def search_roles_by_name(api, configuration, api_version, api_exception, role_name):
""" Searches for a role by name and returns the ID.
:param api: The Deep Security API modules.
:param configuration: Configuration object to pass to the api client.
:param api_version: The version of the API to use.
... | e5ea95316f56a3fe742a5c71b50428c58bcf459c | 651,596 |
def get_relevant_features(features,
diff_threshold = 0.05,
active_threshold = 0.1,
inactive_threshold = 0.1):
"""
-- DESCRIPTION --
Extract "relevant" features from a set of given features. Relevant in this
case means that th... | 2ae3a49786f8d4e5e80c158add6fb2fdc85f412e | 651,598 |
def group_weights(weights):
"""
Group each layer weights together, initially all weights are dict of 'layer_name/layer_var': np.array
Example:
input: {
...: ...
'conv2d/kernel': <np.array>,
'conv2d/bias': <np.array>,
.... | 357b9eacda4fad058ffb5b1bec96ed4f030486b1 | 651,599 |
from typing import Dict
from typing import List
def dict2args(data: Dict) -> List[str]:
"""Convert a dictionary of options to command like arguments."""
result = []
# keep sorting in order to achieve a predictable behavior
for k, v in sorted(data.items()):
if v is not False:
prefix... | ef2d30a1ceeb95929b5a8e5ed2ef2af750aaaa44 | 651,604 |
import hashlib
def _hash(example_with_id) -> str:
"""Hashes a single example."""
key = example_with_id[0], example_with_id[1]["text"]
key_bytes = str(key).encode("utf8")
return hashlib.sha256(key_bytes).hexdigest() | 112736cec9566633cabd6cfe74b8fe4780b5c861 | 651,606 |
import pickle
def reference(infile):
"""
Load the given reference profile file.
:params infile: The input filename or file object
:returns: The reference list
"""
# If the input is a string then open and read from that file
if isinstance(infile, str):
with open(infile, "rb") as i... | 550a8fdc1295e249c23a0ae3c21fb2e9c7570573 | 651,607 |
from typing import Optional
def _text_compare(t1: Optional[str], t2: Optional[str]) -> bool:
"""Compare two text strings, ignoring wrapping whitespaces.
Args:
t1:
First text.
t2:
Second text.
Returns:
True if they are equal, False otherwise.
"""
... | 965c61e565aa2608742bcd291fcdf04b26d3ff38 | 651,610 |
def invert_y_and_z_axis(input_matrix_or_vector):
"""
This Function inverts the y and the z coordinates in the corresponding matrix and vector entries
(invert y and z axis <==> rotation by 180 degree around the x axis)
For the matrix multiplication holds:
|m11 m12 m13| |x| |m11 x + m12 y + ... | 76e71af3c4ed8bae98c69ccf8fd52d383ddb0ce3 | 651,612 |
import ast
def binop(x, op, y, lineno=None, col=None):
"""Creates the AST node for a binary operation."""
lineno = x.lineno if lineno is None else lineno
col = x.col_offset if col is None else col
return ast.BinOp(left=x, op=op, right=y, lineno=lineno, col_offset=col) | cf8f0320b71ffee0f3e4916c73e7feccf8ec0160 | 651,613 |
def strtobool(value):
"""
This method convert string to bool.
Return False for values of the keywords "false" "f" "no" "n" "off" "0" or 0.
Or, return True for values of the keywords "true" "t" "yes" "y" "on" "1" or 1.
Or, othres return None.
Args:
value : string value
Return:
Return False for va... | a56d1317aa7b5767875841499c88f498f5dd7989 | 651,620 |
def toStringVer(version):
"""Converts a semantic version string to a string with leading zeros"""
split = version.split(".")
fullversion = ""
for i, v in enumerate(split, start=0):
fullversion += v.rjust(2, "0")
return fullversion | 5e5b4b395cc0d9539f066c0ec68fb257572576af | 651,628 |
def ranges_overlap(x1, x2, y1, y2):
"""Returns true if the ranges `[x1, x2]` and `[y1, y2]` overlap,
where `x1 <= x2` and `y1 <= y2`.
Raises:
AssertionError : If `x1 > x2` or `y1 > y2`.
"""
assert x1 <= x2
assert y1 <= y2
return x1 <= y2 and y1 <= x2 | b83699379e9036f5e7981bf2c541cf3931a54638 | 651,629 |
import re
def initialize_record(fields, shape_record):
"""Initializes a dictionary that stores a shapefile record.
Args:
fields: List that stores the shapefile record names
shape_record: Object that contains a shapefile record
and associated shape
Returns:
... | 4343c4622069afdac34a3939e90bb089d322cf00 | 651,636 |
from pathlib import Path
def collect_filepaths(main_path, format="png"):
"""
Collect a set of files using a determined location on disk and a known list
of file formats. This is useful to get the full path of files encountered
on a disk folder.
Parameters
----------
main_path : str
... | 171cffe20611924acf3c6879433550a97f10622e | 651,640 |
import re
def natural_sort(values, case_sensitive=False):
"""
Returns a human readable list with integers accounted for in the sort.
items = ['xyz.1001.exr', 'xyz.1000.exr', 'abc11.txt', 'xyz.0999.exr', 'abc10.txt', 'abc9.txt']
natural_sort(items) = ['abc9.txt', 'abc10.txt', 'abc11.txt', 'xyz.0999.exr... | 9ed1ef665912e0b820f9cb001909bd95fd23ee26 | 651,643 |
def python_name(cmd_name):
"""Convert ``-`` to ``_`` in command name, to make a valid identifier."""
return cmd_name.replace("-", "_") | f79dfec66310b19d667f0799a0fc3eedbe771152 | 651,644 |
def name(name):
"""Give a command a alternate name."""
def _decorator(func):
func.__dict__['_cmd_name'] = name
return func
return _decorator | f03f80f1022b87380ba2a15b2ff783885b722556 | 651,646 |
import inspect
def params(func):
"""Shorthand to get the parameter spec for a function."""
return list(inspect.signature(func).parameters.values()) | f1666b0d5cc27fb9d0612bb84b0f18e449a6a836 | 651,650 |
import random
def random_class_ids(lower, upper):
"""
Get two random integers that are not equal.
Note: In some cases (such as there being only one sample of a class) there may be an endless loop here. This
will only happen on fairly exotic datasets though. May have to address in future.
:param lo... | dcb351efbf772f2408213b362b9a5af4bfabc8cb | 651,651 |
import torch
def blur_with_zeros(image, blur):
"""Blur an image ignoring zeros.
"""
# Create binary weight image with 1s where valid data exists.
mask = torch.ones(image.shape, device=image.device)
mask[image <= 0] = 0
# Compute blurred image that ignores zeros using ratio of blurred images.
... | d747f5bf8c8b53f37d735963990b935a02604535 | 651,652 |
import re
def cleanhtml(raw_html):
"""
This function is for creating filenames from the HTML returned from the API call.
It takes in a string containing HTML tags as an argument, and returns a string without HTML tags or any
characters that can't be used in a filename.
"""
# Created a regular... | 51a0bd1ce37e3bc59d0b457b398acbcd518b2fdd | 651,653 |
def endfSENDLineNumber( ) :
"""Indicates the end of an ENDF data section for one (MF, MT) pair."""
return( 99999 ) | bd910343d6800bbb608774cdf6a62585d32dc54f | 651,655 |
def partition_at_level(dendrogram, level) :
"""Return the partition of the nodes at the given level
A dendrogram is a tree and each level is a partition of the graph nodes.
Level 0 is the first partition, which contains the smallest communities, and the best is len(dendrogram) - 1.
The higher the level... | fd8e12fd60e2f8c399a87aaf62d24864e5380f9c | 651,656 |
def _extract_data(spark, input_fname, app_config):
"""
Read the input data in the form of csv file.
:param spark : Active spark session
:param input_fname : Input filename as in the storage directory
:param app_config : loaded json object with app configuration
:returns : spark dataframe of inp... | 1103bdcad1fa9d8b5b018882cc43b9c5917b3937 | 651,657 |
import re
def parse_details_page_notes(details_page_notes):
"""
Clean up a details page notes section.
The purpose of this function is to attempt to extract the sentences about
the crash with some level of fidelity, but does not always return
a perfectly parsed sentence as the HTML syntax varies ... | bbe7041668974d3fa3b27828966d39b78f1775a3 | 651,663 |
def get_prob_current(psi, psi_diff):
"""
Calculates the probability current Im{psi d/dx psi^*}.
"""
print("Calculating probability current")
curr = psi*psi_diff
return -curr.imag | 5573a437cc4bea28612f8f6224979558bf7e173a | 651,668 |
def get_urls(info):
"""Return list of SLC URLs with preference for S3 URLs."""
urls = list()
for id in info:
h = info[id]
fields = h['_source']
prod_url = fields['urls'][0]
if len(fields['urls']) > 1:
for u in fields['urls']:
if u.startswith('s3:/... | 891ca10d95963447c3498091ea114322d8262934 | 651,669 |
def get_provider(ns, type, backend):
"""
Returns SSSD provider for given backend.
:type type: string
:param type: Type of the provider (= value of its LMI_SSSDProvider.Type
property).
:type backend: LMIInstance of LMI_SSSDBackend
:param backed: SSSD backend to inspect.
:rtype: strin... | 1c8ac89c27aa8b600073adf47be0e64eaf13b950 | 651,671 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.