content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def merge_sort(nsl: list) -> list:
"""
function sorts an array by a merge method.
:param nsl: type list: non sorted list
:return: type list: list after merge sort
"""
sl = nsl[:]
n = len(nsl)
if n < 2:
return sl
else:
left_arr = merge_sort(nsl=nsl[:n//2])
rig... | bc6aacda515ac1b8509e1db29974a003b7739903 | 679,472 |
from enum import Enum
def create_enum(name, members):
"""creates an enum class with the given name and given members"""
cls = type(name, (Enum,), dict(_BY_VALUE = {}))
cls._idl_type = name
for n, v in members.items():
em = cls(n, v)
setattr(cls, n, em)
cls._BY_VALUE[v] = em
... | 1f2014eff6f206dc23abf3aacdbdee18983bb391 | 679,473 |
from typing import List
import os
def get_middleware_services() -> List[str]:
"""Get a list of current middleware services"""
return (
[os.environ["MIDDLEWARE_SERVICE"]]
if os.environ.get("MIDDLEWARE_SERVICE", None)
else ["middleware:8887"]
) | b468ab03a41d5369a78b011481d7c0b1edc1315e | 679,474 |
import json
def read_json(filename):
"""
Deserializes json formatted string from filename (text file) as a dictionary.
:param filename: string
"""
with open(filename) as f:
return json.load(f) | baec461293e45613126fa29648f4c8a83b49e719 | 679,475 |
def redshift2dist(z, cosmology):
""" Convert redshift to comoving distance in units Mpc/h.
Parameters
----------
z : float array like
cosmology : astropy.cosmology instance
Returns
-------
float array like of comoving distances
"""
return cosmology.comoving_distance(z).to('Mpc'... | 105f665ac6046692c3ec4652201bce63246dd6a9 | 679,476 |
import platform
def get_correct_os():
"""
Returns the Os name:
get_os -> bool
Linux: linux
Mac: darwin
Windows: windows
"""
os = platform.system().lower()
return os == "linux" | e4242d88105485873272831ce4358bf96e8966a0 | 679,477 |
def _CheckExclusivePvs(pvi_list):
"""Check that PVs are not shared among LVs
@type pvi_list: list of L{objects.LvmPvInfo} objects
@param pvi_list: information about the PVs
@rtype: list of tuples (string, list of strings)
@return: offending volumes, as tuples: (pv_name, [lv1_name, lv2_name...])
"""
res... | 66cfcfbe723a258242b97a60c220290c89d58c2e | 679,478 |
def first_half(dayinput):
"""
first half solver:
Starting with a frequency of zero, what is the resulting
frequency after all of the changes in frequency have been applied?
"""
lines = dayinput.split('\n')
result = 0
for freq in lines:
result += int(freq)
return result | 3ae205a8347086e9d411acdf8b72a1ce0b390655 | 679,479 |
def treat_pdb_id(pdb_id):
"""
:param file upload:
:return: pdbid or the first part of upload file.
"""
return pdb_id.replace(".pdb", "").replace(".ent", "") | 9db8c6c308f1b0c8a67ab49899b3b898bf51201d | 679,480 |
def reorder(x, indexList=[], indexDict={}):
"""
Reorder a list based upon a list of positional indices and/or a dictionary of fromIndex:toIndex.
>>> l = ['zero', 'one', 'two', 'three', 'four', 'five', 'six']
>>> reorder( l, [1, 4] ) # based on positional indices: 0-->1, 1-->4
['one', 'f... | 9649c5392657fe6ab329fbb1b829ffc3bae19543 | 679,481 |
import platform
def get_architecture():
"""
Get the cpu architecture of the user's pc
Returns:
architecture(str): The architecture of the user's pc
"""
if platform.machine().endswith('64'):
return 'x64'
if platform.machine().endswith('86'):
return 'x32'
return... | 1c3739d032685512757e726e7547c32eef11e611 | 679,482 |
def textarea_to_list(text: str):
"""Converts a textarea into a list of strings, assuming each line is an
item. This is meant to be the inverse of `list_to_textarea`.
"""
res = [x.strip() for x in text.split("\n")]
res = [x for x in res if len(x) > 0]
return res | be2c1e7bb7c506b197804f7bfd6e78fff324e9ef | 679,483 |
from pathlib import Path
def iterdir(path):
"""Return directory listing as generator"""
return Path(path).iterdir() | 54e370f7a9a99f267b5a91a85219ce90f1e6dafd | 679,484 |
import re
def rename_implicit(v):
"""
Usage of inline comprehensions generates a implicit ".0" variable that
trips up guard generation. This renames these variables in guards.
"""
m = re.match(r"^[.](\d+)$", v)
if m:
assert v == ".0", f"currently only .0 supported: {v}"
# to s... | 77d75e6d89c476ed7b1210cd41df8cb834fbf3ae | 679,485 |
import requests
import json
def get_instance_region():
""" Retrieve the region from the instance-data url for instance this
method is called from.
Returns
-------
aws region of current instance
"""
id_request = requests.get(
'http://instance-data/latest/dynamic/instance-identity/d... | 3280fd65bc6537966162341c69320c5e69476cc1 | 679,486 |
import numpy
def distancesFromArrays(xData, yData):
"""Returns distances between each points
:param numpy.ndarray xData: X coordinate of points
:param numpy.ndarray yData: Y coordinate of points
:rtype: numpy.ndarray
"""
# Split array into sub-shapes at not finite points
splits = numpy.no... | 22f3dc620a42c0ee58cacc7c64aa40efc779364f | 679,487 |
import multiprocessing
import os
def default_test_processes():
"""Default number of test processes when using the --parallel option."""
# The current implementation of the parallel test runner requires
# multiprocessing to start subprocesses with fork().
if multiprocessing.get_start_method() != 'fork'... | 27caf9058145d54ebf21a970f9e1a93e14d51d0d | 679,488 |
import re
def count_ops_in_hlo_proto(hlo_proto,
ops_regex):
"""Counts specific ops in hlo proto, whose names match the provided pattern.
Args:
hlo_proto: an HloModuleProto object.
ops_regex: a string regex to filter ops with matching names.
Returns:
Count of matching ops... | 0e1a933a85e738e505f1b229625023f88e4c2d33 | 679,489 |
import time
def get_date(temps=None):
"""Retourne la date et l'heure sous la forme :
le mardi 1 janvier 1970 à 00:00:00
Si le paramètre n'est pas précisé, retourne la date et l'heure
actuelle.
Sinon, le temps peut être :
- un timestamp
- une structime
"""
... | 06f195690bfef2a750b4663398d3f8d311387c0e | 679,490 |
import os
def prepare_path(path, loc):
""" change directory to starting path, return chemkin path
"""
return os.path.join(path, loc) | d1ed397dba6a63fd4d1c32c43a6b77c232d8045b | 679,491 |
def create_time_callback(data):
"""Creates callback to return distance between points."""
times = data["times"]
# returns the distance between two nodes
def time_callback(from_node, to_node):
"""Returns the manhattan distance between the two nodes"""
return times[from_node][to_node]
return time_callbac... | 9f8fd06725b9ce4036a42e04696a6812034bedc8 | 679,493 |
def list_diff(l1: list, l2: list):
""" Return a list of elements that are present in l1
or in l2 but not in both l1 & l2.
IE: list_diff([1, 2, 3, 4], [2,4]) => [1, 3]
"""
return [i for i in l1 + l2 if i not in l1 or i not in l2] | dd5c2ebecddec8b3a95cde30dae28cac6b996c51 | 679,494 |
def get_list_sig_variants(file_name):
"""
Parses through the significant variants file
and creates a dictionary of variants and their
information for later parsing
: Param file_name: Name of file being parsed
: Return sig_variants_dict: A dictionary of significant results
"""
... | 3b9551d512295f73e74c8a2ccc391ac93ff0664c | 679,495 |
def attack_successful(prediction, target, targeted):
"""
See whether the underlying attack is successful.
"""
if targeted:
return prediction == target
else:
return prediction != target | 6cd17a7852268d97243bbc8c68938eb4a68727ac | 679,496 |
def merge(elements):
"""Merge Sort algorithm
Uses merge sort recursively to sort a list of elements
Parameters
elements: List of elements to be sorted
Returns
list of sorted elements
"""
def list_merge(a, b):
"""Actual "merge" of two lists
Compares every member of a l... | 3b896f5b3b1c88064d64dbaef9dc656448fecb78 | 679,497 |
def map_structure(func, structure, args=(), kwargs={}):
"""apply func to each element in structure
Args:
func (callable): The function
structure (dict, tuple, list): the structure to be mapped.
Kwargs:
args (tuple,list): The args to the function.
kwargs (dict): The kwargs t... | 46d13e18c14940c6f0d59c754ad10cdd6d27d913 | 679,498 |
import os
def resolve_dataset_variable(path):
"""
Resolves a dataset plus variable path into a dataset path and
variable name.
example: "/tmp/foo.nc:bar" -> ("/tmp/foo.nc", "bar")
Parameters
----------
path: string, a compound path of dataset:variable
Returns
-------
tuple o... | 97fa6f04f8aa40f8ac779d0cf2683a3d099d3f2b | 679,499 |
def is_a_monitoring_request(request):
"""Returns True it the input request is for monitoring or health check
purposes
"""
# does the request begin with /health?
return request.get_full_path()[:7] == '/health' | ce475eadeaacf67cadca1a3a254a5b5632d59fd5 | 679,500 |
def num2songrandom(num: str) -> int:
"""
将用户输入的随机歌曲范围参数转为发送给 API 的数字
Algorithm: (ratingNumber * 2) + (ratingPlus ? 1 : 0)
Example: '9+' -> 19
"""
return int(num.rstrip('+')) * 2 + (1 if num.endswith('+') else 0) | ec1a21cacc08c57340d0796b8ddf2e2144e4638b | 679,501 |
def pad(size, padding):
"""Apply padding to width and height.
:param size: two-tuple of width and height
:param padding: padding to apply to width and height
:returns: two-tuple of width and height with padding applied
"""
width = size[0] + padding.left + padding.right
height = size[1] + p... | 9e1021ec6dac2598e58779db440eae853418cbc4 | 679,502 |
def _parse_input_list(input_list: str) -> list[str]:
"""
Converts a CSV list of assets IDs into a list of parsed IDs (but not Asset objects)
"""
return [fqn_id for fqn_id in input_list.split(",") if fqn_id != "" and fqn_id != ":"] | 280bb0e110be0f1230533acfa0f8ae4f3f2ac7af | 679,503 |
def count_where(predicate, iterable):
"""
Count the number of items in iterable that satisfy
the predicate
"""
return sum(1 for x in iterable if predicate(x)) | 460e9fe3b515eb568bb3587947d3cef99b500be1 | 679,504 |
def add_default_value_to(description, default_value):
"""Adds the given default value to the given option description."""
# All descriptions end with a period, so do not add another period.
return '{} Default: {}.'.format(description,
default_value if default_value else '... | e33c1a6212cea712b826701cc77f2a1cf46abea6 | 679,505 |
def highlight_file():
""" Syntax highlighting of a file"""
return NotImplementedError() | b6a52923a8c750d03bc98256b2d416b4fe22fd65 | 679,506 |
def _get_voxdim(hdr):
"""Get the size of a voxel from some image header format."""
return hdr.get_zooms()[:-1] | 9cbcc84c337896f92a4531a8768802ad8ee2aee7 | 679,507 |
def nearest_words_from_iter(model, word, from_folder, top=20, display=False, it=1):
"""
Get top nearest words from some iteration of optimization method.
"""
C, W = model.load_CW(from_folder=from_folder, iteration=it)
model.W = W.copy()
model.C = C.copy()
nearest_sum = model.nearest_words(... | affd5358516ff3c0e6d4d5f7c4d4285ee4c0d0cc | 679,508 |
def derive_order_id(user_uid: str, cl_order_id: str, ts: int, order_src='a') -> str:
"""
Server order generator based on user info and input.
:param user_uid: user uid
:param cl_order_id: user random digital and number id
:param ts: order timestamp in milliseconds
:param order_src: 'a' for rest ... | 662199714e303ccd4a438e1aac97c92bbd266d96 | 679,509 |
def get_edge(source, target, interaction):
"""
Get the edge information in JSON format.
:param source: the id or name of source node.
:param target: the id or name of target node.
:param interaction: the interaction of edge.
:return : the JSON value about edge.
"""
if interaction is No... | d1018257fa7a1007369a482fc58713c18c44d4d0 | 679,510 |
def find_the_duplicate(nums):
"""Find duplicate number in nums.
Given a list of nums with, at most, one duplicate, return the duplicate.
If there is no duplicate, return None
>>> find_the_duplicate([1, 2, 1, 4, 3, 12])
1
>>> find_the_duplicate([6, 1, 9, 5, 3, 4, 9])
9
... | 66fd5fbce24dc818542ff60271e2330e1b2b96c0 | 679,512 |
def is_invocation(event):
"""Return whether the event is an invocation."""
attachments = event.get("attachments")
if attachments is None or len(attachments) < 1:
return False
footer = attachments[0].get("footer", "")
if footer.startswith("Posted using /giphy"):
return True
retu... | 8c8af01611526376ae44f12fbdf521552e4cca56 | 679,513 |
def expand_kz(k, kxc, kyc):
"""Expand z component of wavenumber to second order.
Args:
k: Wavenumber.
kxc: Expansion kx coordinate.
kyc: Expansion ky coordinate.
Returns:
kz: Zeroth order term.
gxkz: First derivative w.r.t x.
gykz: First derivative w.r.t y.
... | 97e87b08a2c1e263d99739569c0d81554b54cab8 | 679,515 |
import sys
def _find_venv_bin(basedir, exec_base):
"""Determine the venv executable in different platforms."""
if sys.platform == "win32":
return basedir / "Scripts" / f"{exec_base}.exe"
return basedir / "bin" / exec_base | c0e420f9459f0f19db7d12e9eab9fee95d1e883a | 679,516 |
def calc_prof(ability, profs, prof_bonus):
"""
Determine if proficiency modifier needs to be applied.
If character has expertise in selected skill, double the proficiency bonus.
If character has proficiency in selected skill/ability/save,
prof_mod = prof_bonus (multiply by 1).
If character h... | 56a6cb2df4ce1e023641bea9b6b400787d6c0607 | 679,517 |
from sys import intern
def intern_string(string):
"""Takes a (potentially) unicode string and interns it if it's ascii"""
if string is None:
return None
try:
return intern(string)
except UnicodeEncodeError:
return string | 3b89d0a45e77809b454cff0c27ba94a27445d4be | 679,518 |
def inexact(pa, pb, pc, pd):
"""Tests whether pd is in circle defined by the 3 points pa, pb and pc
"""
adx = pa[0] - pd[0]
bdx = pb[0] - pd[0]
cdx = pc[0] - pd[0]
ady = pa[1] - pd[1]
bdy = pb[1] - pd[1]
cdy = pc[1] - pd[1]
bdxcdy = bdx * cdy
cdxbdy = cdx * bdy
alift = adx * ... | 3e4e72147a97942ed6f392cd8559d5f6c3dd708b | 679,519 |
def oef_port() -> int:
"""Port of the connection to the OEF Node to use during the tests."""
return 10000 | 62fbd90a3745abba1fdfe01327e5399c5fd7bc98 | 679,520 |
def get_input(filename):
"""returns list of inputs from data file. File should have integer values,
one per line.
Args:
filename: the name of the file with the input data.
Returns:
a list of integers read from the file
"""
text_file = open(filename, "r")
input_strs = text_... | 1b39d031e8928ee7ec75ba7b05e6093b4c9000e9 | 679,521 |
def tuple_for_testing(model, val, replace_i):
"""this function creates a tuple by changing only one parameter from a list
Positionnal arguments :
model -- a list of valid arguments to pass to the object to test
val -- the value you want to put in the list
replace_i -- the index of t... | bc42ab1538d81f22777b8bf724c4754262155247 | 679,522 |
import json
def config_update_date(is_all=False):
"""获取配置文件中上次更新日期"""
with open('config.json',mode='rb') as f:
json_str = json.load(f)
if is_all:
update_date = json_str['update_date_all']
else:
update_date = json_str['update_date']
if update_date == "No... | ba8ea2bb2a6615964031f80b3d182cc271eef1db | 679,524 |
import re
def is_unique_str(txt):
"""
Checks if given string is unique.
A string is unique if it contains letters (upper & lower case), numbers, spaces and special characters.
Args:
txt (str): given project name or work package subject.
Returns:
bool: True if given string is uniq... | a0275b6edb3991f77a67c844aec1cacb734e894a | 679,525 |
import random
def make_bit_generators():
"""Create a list of bit generators."""
value_third = -1
def third_true():
nonlocal value_third
value_third += 1
return value_third == 3
value_fifth = -1
# note: false comes first
def every_fifth_false():
nonlocal value_... | 540a91b3425cce302916f5f69712518c952de4c9 | 679,526 |
def all_entities_on_same_layout(entities):
""" Check if all entities are on the same layout (model space or any paper layout but not block).
"""
owners = set(entity.dxf.owner for entity in entities)
return len(owners) < 2 | e49b797800ce12bb9f5eabe6d2f2af7fa61f0ac6 | 679,527 |
from datetime import datetime
def now():
""" Return formatted now time. Example: Sun/17.09.2017/09:00:22
"""
return datetime.now().strftime("%a/%d.%m.%Y/%H:%M:%S") | 8596550eb8bfe62254c9de2c50b608fd0bd537b5 | 679,529 |
def merge_dicts(dicts_a, dicts_b):
"""Merges two lists of dictionaries by key attribute.
Example:
da = [{'key': 'a', 'value': 1}, {'key': 'b', 'value': 2}]
db = [{'key': 'b', 'value': 3, 'color':'pink'}, {'key': 'c', 'value': 4}]
merge_dicts(da, db) = [{'key': 'a', 'value': 1}, {'key': ... | cd1bf5611c414cf5e728baa3bb74cc1ceb477823 | 679,530 |
def parenthesize(s):
"""
>>> parenthesize('1')
'1'
>>> parenthesize('1 + 2')
'(1 + 2)'
"""
if ' ' in s:
return '(%s)' % s
else:
return s | d1463e5e366d818c6fd86b39024549075e356a62 | 679,531 |
def play_game(board, players, verbose=False):
"""Plays a game, given a board with biddings and initialized players.
Parameters
----------
board: GameBoard
a board, with biddings already performed, but no action
players: list
a list of 4 initialized players, with 8 cards each and giv... | de5d90b39e11c6ca88deec77dbb3869ed571c63b | 679,532 |
def _is_def_line(line):
"""def/cdef/cpdef, but not `cdef class`"""
return (line.endswith(':') and not 'class' in line.split() and
(line.startswith('def ') or
line.startswith('cdef ') or
line.startswith('cpdef ') or
' def ' in line or ' cdef ' in line or ' cpdef... | d891dbbebea004fe63526a70196d493b636dbcb1 | 679,533 |
def is_element_in_viewport(session, element):
"""Check if element is outside of the viewport"""
return session.execute_script("""
let el = arguments[0];
let rect = el.getBoundingClientRect();
let viewport = {
height: window.innerHeight || document.documentElement.clientHeight,... | 0f34565e7359c8c62a409feed0dd4191528db8be | 679,534 |
import math
def rotate(a, angle) -> tuple:
"""Rotates the point."""
rad = math.radians(angle)
cos = math.cos(rad)
sin = math.sin(rad)
x = cos * a[0] - sin * a[1]
y = sin * a[0] + cos * a[1]
return x, y | d5f58be0cad524b5ba1401af6ab845ace2a7b6e2 | 679,536 |
def _PiecewiseConcat(*args):
"""Concatenates strings inside lists, elementwise.
Given ['a', 's'] and ['d', 'f'], returns ['ad', 'sf']
"""
return map(''.join, zip(*args)) | d279e4140e28aadd3cac3c40a24055ba9e703d0d | 679,537 |
def brute_force(s: str) -> int:
"""
Finds the length of the longest substring in s without repeating characters.
Parameters
----------
s : str
Given string.
Returns:
int
Length of the longest substring in s without repeating characters.
Speed Analysis: O(n), no ma... | 62f9d18266b7dc335b5c9a896d5bb5b7528fc070 | 679,538 |
def _add_exdate(vevent, instance):
"""remove a recurrence instance from a VEVENT's RRDATE list
:type vevent: icalendar.cal.Event
:type instance: datetime.datetime
"""
def dates_from_exdate(vdddlist):
return [dts.dt for dts in vevent['EXDATE'].dts]
if 'EXDATE' not in vevent:
ve... | 7ece85b3f5d8715f78c04426349388e8e0f1132b | 679,539 |
from datetime import datetime
import os
def write_timestamp(trg_dir):
"""another little helper file, write a timestamp out to a text file so
that we know when everything was last backed up.
Arguments:
- `trg_dir`: where should we write the timestamp file?
"""
now = datetime.now()
fname ... | 56fb12b7348e4b06a367e01cc8c9ef2764a12eb6 | 679,540 |
def get_box(mol, padding=1.0):
"""
Given a molecule, find a minimum orthorhombic box containing it.
Size is calculated using min and max x, y, and z values.
For best results, call oriented_molecule first.
Args:
mol: a pymatgen Molecule object
padding: the extra space to be added... | 896505ad0f776a3d7fe0ea4103b1c8ac517bf8d0 | 679,541 |
import logging
def get_most_frequent_response(input_statement, response_list):
"""
:param input_statement: A statement, that closely matches an input to the chat bot.
:type input_statement: Statement
:param response_list: A list of statement options to choose a response from.
:type response_list:... | 3e1d9235955f8f6b3155c7f3e38f2f87a971aabf | 679,542 |
def get_score(path):
"""
In a windows os some common folders are placed in the user home dir.
This function detects how many common folders there are in path.
"""
common_folders = ['Desktop', 'Downloads', 'Dropbox', 'Music',
'Documents', 'Videos', 'Links', 'Favorites', 'Pictur... | a1dfbbb7a2d239622f30f5135b27187df7eef167 | 679,543 |
from typing import Dict
from typing import Any
from typing import Sequence
def _get_keyword_ids_per_class(config: Dict[str, Any],
vocab: Sequence[str]) -> Sequence[Sequence[int]]:
"""Gets keyword ids for each class in the PSL constraint model."""
vocab_mapping = {word: word_id for w... | d5eb39273d18b61e87bc79070b48826cde4441d2 | 679,544 |
import time
import requests
def prenesi_eno_stran(url):
"""Argument funkcije je niz, ki predstavlja url spletne strani. Funkcija
vrne niz z vsebino spletne strani, razen če pride do napake. Takrat vrne None.
"""
time.sleep(10)
try:
vsebina_strani = requests.get(url, headers={"User-Agent": ... | b2272a7428058249cfa527165c2671d97080a004 | 679,546 |
from pathlib import Path
def _is_already_configured(configuration_details):
"""Returns `True` when alias already in shell config."""
path = Path(configuration_details.path).expanduser()
with path.open('r') as shell_config:
return configuration_details.content in shell_config.read() | 0c4cb3cda41fbb7d64ad784d73937fd5a3a0ccca | 679,547 |
def is_maximum_local(index, relative_angles, radius):
"""
Determine if a point at index is a maximum local in radius range of relative_angles function
:param index: index of the point to check in relative_angles list
:param relative_angles: list of angles
:param radius: radius used ... | c5f108889a3da9aaacbde5e50549fcef7a89147a | 679,548 |
def get_clean_name(name, char='-'):
"""
Return a string that is lowercase and all whitespaces are replaced
by a specified character.
Args:
name: The string to be cleaned up.
char: The character to replace all whitespaces. The default
character is "-" (hyphen).
Returns:
... | 0f825b0a3e29d432c71f44ea685238d06ab9600c | 679,549 |
def decrement(field):
"""
Decrement a given field in the element.
"""
def transform(element):
element[field] -= 1
return transform | 2e392e7ed3f18dfce176b698de25c81e9081b333 | 679,551 |
def read_list_of_filepaths(list_filepath):
"""
Reads a .txt file of line seperated filepaths and returns them as a list.
"""
return [line.rstrip() for line in open(list_filepath, 'r')] | f6bc0219b1d1c7ea9b1df87d70a0cae5be94d8f9 | 679,553 |
def gatherKeys(data):
"""Gather all the possible keys in a list of dicts.
(Note that voids in a particular row aren't too bad.)
>>> from shared.tools.examples import complexListDict
>>> gatherKeys(complexListDict)
['date', 'double', 'int', 'string']
"""
keys = set()
for row in data:
keys.update(row)
return... | 3d49f0a9b5e8315b2af99d10ff0d383a45a0d210 | 679,556 |
def test_config(request, wooqi):
"""
Test config
"""
return request.config.getoption("--seq-config") | e5b4420d42546ed48fa1b9bb2774216fa9408676 | 679,558 |
def user_id() -> int:
""" Here is where you would do some sort of look up
"""
return 1 | 5f5d0003883fb43773ef150e80c7eac295722398 | 679,559 |
def read_file(path):
"""Reads file"""
with open(path) as file:
return file.readlines() | e4759b5dce7ad4a332b4554229073e5f32973d04 | 679,560 |
def process_marker_fonts(prompt):
"""
Replace <s> with sharpie font sections
"""
prompt = prompt.replace('<s>', '<font name="PermanentMarker" color="#B1BDC3">')
prompt = prompt.replace('</s>', '</font>')
if '<font' in prompt and '</font>' not in prompt:
prompt = prompt + '</font>'
re... | 7d97e8b6871d2bf7552331a9c647c7cd80d18b25 | 679,561 |
import torch
def sigmoid(z):
"""Applies sigmoid to z."""
return 1/(1 + torch.exp(-z)) | 572c4fc234401d05b05108ee477540399824f7d8 | 679,562 |
def delete_species_json(ibs, species_uuid_list):
"""
REST:
Method: DELETE
URL: /api/species/json/
Args:
species_uuid_list (list of str) : list of species UUIDs to be delete from IBEIS
"""
species_rowid_list = ibs.get_species_rowids_from_uuids(species_uuid_list)
ibs.delet... | f1de6a82b5ab361de1be2722216f9b8520c7e401 | 679,563 |
import base64
def decode64(string):
""" Decode a string from base64 """
return base64.b64decode(string) | 116da563b2d4e97672322e44f0732b988352dcb3 | 679,564 |
import logging
import os
def link(file_path, target_path):
"""Link file to the target name.
Ensure that the target directory exists. If target file already exists,
log warning and return False.
"""
if target_path.exists():
logging.warning('link target {} exists'.format(str(target_pa... | 374c353bfa19a39f25954338ed5298a03115a51c | 679,565 |
def return_all_valid_modes_string():
"""
return_all_valid_modes_string:
Args: -
Returns: request_modes [str]
This is hard coded to include only
dlr, tram, tube, overgound, tflrail.
"""
request_modes = (f'tube,tram,overground,dlr,tflrail')
return(request_modes) | 9dd0cfcc51c077213f7a087b8be0283583fc2cfe | 679,566 |
import threading
import time
def rate_limited(num_calls=1, every=1.0):
"""Rate limit a function on how often it can be called
Source: https://github.com/tomasbasham/ratelimit/tree/0ca5a616fa6d184fa180b9ad0b6fd0cf54c46936 # noqa E501
Args:
num_calls (float, optional): Maximum method invocations w... | 1783ac412d7b7dcb0cc8adb3af4f94ae02808a6a | 679,567 |
import os
def dirfilenames(name1,name2,name3,name4):
"""Convert arguments to directories and names for copy() and move()"""
dir1 = ""
dir2 = ""
if os.path.isdir(name1):
dir1 = name1
name1 = name2
if name4 is not None:
dir2 = name3
name2 = name4
e... | 1cd7ad064072ea2917142aa2ff041b680214ede7 | 679,568 |
def throttling_mod_func(d, e):
"""Perform the modular function from the throttling array functions.
In the javascript, the modular operation is as follows:
e = (e % d.length + d.length) % d.length
We simply translate this to python here.
"""
return (e % len(d) + len(d)) % len(d) | 60e0bc5902623b02cb9d8faf969ccbc094f968f8 | 679,569 |
import math
def dimension_of_bounding_square(number):
"""Find the smallest binding square, e.g.
1x1, 3x3, 5x5
Approach is to assume that the number is the largest
that the bounding square can contain.
Hence taking the square root will find the length of the
side of the bounding square.
The... | 58d4acf078c33df69904ffba855f7c41656fd66c | 679,570 |
def key_has_granted_prefix(key, prefixes):
"""
Check that the requested s3 key starts with
one of the granted file prefixes
"""
granted = False
for prefix in prefixes:
if key.startswith(prefix):
granted = True
return granted | 80720ef8e1160d73aa8701653781fb3b30334e63 | 679,571 |
import json
def load_metadata(datapath):
"""Extract class experiment metadata """
with open(datapath + '/experiment_metadata.json', 'r') as f:
args_dict = json.load(f)
return args_dict | cc37f6ece6dd4e9a42d6e93e86e52b3eba46e4d3 | 679,572 |
def add_key(rec, idx):
"""Add a key value to the character records."""
rec["_key"] = idx
return rec | 0270ba0084b2c513a7b30a51ec57ebf31c8e7a7d | 679,573 |
import os
def build(filename):
"""
Given a Makefile name, run "make all". Return True if successful,
False otherwise.
"""
if not os.path.exists(filename):
raise OSError("File '%s' does not exist" % filename)
status = os.system("make -f %s all" % filename)
return True if stat... | e723b7498e66c5d05be10d2ba6f6415d29bd65a8 | 679,574 |
def normalize_table(table):
""" Normalizes you a table by dividing each entry in a column
by the sum of that column """
sums = [0]*len(table.values()[0])
for k in table:
for i in range(len(table[k])):
sums[i] += table[k][i]
for k in table:
for i in range(len(table[k])):
... | a58824ade79233c262a361838ad64cec477fca1a | 679,575 |
def unpack_twist_msg(msg, stamped=False):
""" Get linear and angular velocity from a Twist(Stamped) message. """
if stamped:
v = msg.twist.linear
w = msg.twist.angular
else:
v = msg.linear
w = msg.angular
return (v.x, v.y, v.z), (w.x, w.y, w.z) | 1182a9c5c9aff25cb2df261a32409d0b7df8d08d | 679,576 |
from typing import List
import math
def log_add(args: List[int]) -> float:
"""
Stable log add
"""
if all(a == -float('inf') for a in args):
return -float('inf')
a_max = max(args)
lsp = math.log(sum(math.exp(a - a_max) for a in args))
return a_max + lsp | 8472533aaca83ae287c5ea1b8b975663409878a5 | 679,577 |
def calc_altdiff(resp, st_ind, end_ind):
"""calcs altitude difference"""
assert resp['altitude'] is not None, "altitude data not in json response"
return resp['altitude']['data'][end_ind] - resp['altitude']['data'][st_ind] | 726c4b8238dbeba12cf30a85fc702eab4cadbea6 | 679,578 |
import requests
from bs4 import BeautifulSoup
def get_soup(url):
"""Gets soup object for given URL."""
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
return soup | 6bb402dac489a7e1a49af6cc55f1dc823ac389bf | 679,579 |
import itertools
def group_words(words):
"""If words appear multiple times, group all occurrences."""
# First, split any cases where multiple meanings are grouped already
split_words = []
for w in words:
for meaning in w[0].split(', '):
split_words.append((meaning, w[1]))
# T... | 1fd7578f43ada1a6fbd69223d9143e7761254a37 | 679,580 |
def generate_fake_ping_data(random_state, size):
"""
Generate random ping values (in milliseconds) between 5 and 20,
some of them will be assigned randomly to a low latency between 100 and 200
with direct close values between 40 and 80
"""
values = random_state.random_integers(low=5, high=20, si... | 991b180f76f13e3c5107fc6a578a5259297c1b57 | 679,581 |
def split_cols_with_dot(column: str) -> str:
"""Split column name in data frame columns whenever there is a dot between 2 words.
E.g. price.availableSupply -> priceAvailableSupply.
Parameters
----------
column: str
Pandas dataframe column value
Returns
-------
str:
Valu... | 7cb82a2e15afa41f58fabcd019739731af00c214 | 679,582 |
def parse_stat(stat):
"""Parses the stat html text to get rank, code, and count"""
stat_clean = stat.replace('\n', ' ').replace('.', '').strip()
stat_list = stat_clean.split(' ')
rank = stat_list[0]
code = code_orig = ' '.join(stat_list[1:-1])
# remove xx and dd from the end of the code so we c... | a9dea9b642dc34dcc4717d1f5458952274bfae93 | 679,584 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.