content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_timepoint( data, tp=0 ):
"""Returns the timepoint (3D data volume, lowest is 0) from 4D input.
You can save memory by using [1]:
nifti.dataobj[..., tp]
instead: see get_nifti_timepoint()
Works with loop_and_save().
Call directly, or with niftify().
Ref:
[1]: http:/... | f5a718e5d9f60d1b389839fc0c637bee32b500bf | 4,079 |
def method_from_name(klass, method_name: str):
"""
Given an imported class, return the given method pointer.
:param klass: An imported class containing the method.
:param method_name: The method name to find.
:return: The method pointer
"""
try:
return getattr(klass, method_name)
... | 97274754bd89ede62ee5940fca6c4763efdbb95c | 4,080 |
import re
def parse_value(string: str) -> str:
"""Check if value is a normal string or an arrow function
Args:
string (str): Value
Returns:
str: Value if it's normal string else Function Content
"""
content, success = re.subn(r'^\(\s*\)\s*=>\s*{(.*)}$', r'\1', string)
if not ... | ead42d7f300c68b6978699473de8506794bb1ab4 | 4,081 |
import os
def file_exists(fpath: str):
"""Checks if file exists by the given path
:param str fpath:
A path to validate for being a file
:returns:
True, if fpath is a file
False, if fpath doesn't exists or isn't a file
"""
return os.path.isfile(fpath) | 7bc85a461d6928acddd15b3be1fa8fca028b015b | 4,082 |
def convert(origDict, initialSpecies):
"""
Convert the original dictionary with species labels as keys
into a new dictionary with species objects as keys,
using the given dictionary of species.
"""
new_dict = {}
for label, value in origDict.items():
new_dict[initialSpecies[label]] =... | 5143f31acd1efdf1790e68bade3a1f8d8977bcde | 4,083 |
def createGrid(nx, ny):
"""
Create a grid position array.
"""
direction = 0
positions = []
if (nx > 1) or (ny > 1):
half_x = int(nx/2)
half_y = int(ny/2)
for i in range(-half_y, half_y+1):
for j in range(-half_x, half_x+1):
if not ((i==0) and (... | fe74af508e1bc7185d21f9c86b4eab64a66a52f5 | 4,084 |
def command_ltc(bot, user, channel, args):
"""Display current LRC exchange rates from BTC-E"""
r = bot.get_url("https://btc-e.com/api/2/ltc_usd/ticker")
j = r.json()['ticker']
return bot.say(channel, "BTC-E: avg:$%s last:$%s low:$%s high:$%s vol:%s" % (j['avg'], j['last'], j['low'], j['high'], j['vol']... | 7aa411b6708e54b09cf2b9aef9c8b01899b95298 | 4,085 |
def union_exprs(La, Lb):
"""
Union two lists of Exprs.
"""
b_strs = set([node.unique_str() for node in Lb])
a_extra_nodes = [node for node in La if node.unique_str() not in b_strs]
return a_extra_nodes + Lb | 2bd634a22b27314f6d03c8e52c0b09f7f4b692db | 4,087 |
import re
import itertools
def compile_read_regex(read_tags, file_extension):
"""Generate regular expressions to disern direction in paired-end reads."""
read_regex = [re.compile(r'{}\.{}$'.format(x, y))\
for x, y in itertools.product(read_tags, [file_extension])]
return read_regex | e677b8ff622eb31ea5f77bc662845ba0aef91770 | 4,088 |
from typing import List
def get_bank_sizes(num_constraints: int,
beam_size: int,
candidate_counts: List[int]) -> List[int]:
"""
Evenly distributes the beam across the banks, where each bank is a portion of the beam devoted
to hypotheses having met the same number of c... | 7a515b1e7762d01b7f7a1405a943f03babe26520 | 4,091 |
import ast
def parse_data(data):
"""Takes a string from a repr(WSGIRequest) and transliterates it
This is incredibly gross "parsing" code that takes the WSGIRequest
string from an error email and turns it into something that
vaguely resembles the original WSGIRequest so that we can send
it throug... | 63470f1a935ef6218c239f99228eaf7919b9f09c | 4,092 |
def _is_ref_path(path_elements):
"""
Determine whether the given object path, expressed as an element list
(see _element_list_to_object_path()), ends with a reference and is
therefore eligible for continuation through the reference. The given
object path is assumed to be "completed" down to a singl... | da8bc8eb7611ce7b5361209873e871f2a4656a03 | 4,093 |
def is_leap(year):
"""
Simply returns true or false depending on if it's leap or not.
"""
return not year%400 or not (year%4 and year%100) | 5cb40664b2e8aa9aea647a356b63708f00891a2c | 4,095 |
def knapsack_fractional(weights,values,capacity):
""" takes weights and values of items and capacity of knapsack as input
and returns the maximum profit possible for the given capacity of knapsack
using the fractional knapsack algorithm"""
#initialisaing the value of max_profit variable
max_profit=... | 8cb05c199baf65c24512fa97882085e7bb66a98d | 4,096 |
import os
from os.path import dirname, abspath, realpath
from platform import system
def get_libpath():
"""
Get the library path of the the distributed SSA library.
"""
root = dirname(abspath(realpath(__file__)))
if system() == 'Linux':
library = 'Linux-SSA.so'
elif system() == 'D... | 0b23429796f00c56cba081e4f86420de7267135b | 4,097 |
def coord(row, col):
""" returns coordinate values of specific cell within Sudoku Puzzle"""
return row*9+col | 14cda1489215a2b36d61ac6eac56c14981290b16 | 4,098 |
def post_authn_parse(request, client_id, endpoint_context, **kwargs):
"""
:param request:
:param client_id:
:param endpoint_context:
:param kwargs:
:return:
"""
if endpoint_context.args["pkce"]["essential"] is True:
if not "code_challenge" in request:
raise ValueErro... | 6e9e00a5d073a57cf0245b2506abfd822b5f6ff5 | 4,099 |
def constructed(function):
"""A decorator function for calling when a class is constructed."""
def store_constructed(class_reference):
"""Store the key map."""
setattr(class_reference, "__deserialize_constructed__", function)
return class_reference
return store_constructed | 29101fe6deb1112b5e69291377a3d8ab12082268 | 4,101 |
def datetime_to_hours(dt):
"""Converts datetime.timedelta to hours
Parameters:
-----------
dt: datetime.timedelta
Returns:
--------
float
"""
return dt.days * 24 + dt.seconds / 3600 | e7373cbb49e21340fef1590a655059fd39c6ce88 | 4,104 |
def adjust_learning_rate(optimizer, step):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
if step == 500000:
for param_group in optimizer.param_groups:
param_group['lr'] = 0.0005
elif step == 1000000:
for param_group in optimizer.param_groups:
... | 729c6650eb9b88102b68ba5e8d356e1cfa8b6632 | 4,105 |
import os
def find_file(path, include_str='t1', exclude_str='lesion'):
"""finds all the files in the given path which include include_str in their
name and do not include exclude_str
----------
path: path to the directory
path where the files are stored
include_str: string
strin... | 32f3e373268f3cf310eebceb339c0c6cb9e34cb8 | 4,106 |
def remove_suffix(input_string, suffix):
"""From the python docs, earlier versions of python does not have this."""
if suffix and input_string.endswith(suffix):
return input_string[: -len(suffix)]
return input_string | af4af2442f42121540de00dfaece13831a27cc57 | 4,107 |
import requests
def get_bga_game_list():
"""Gets a geeklist containing all games currently on Board Game Arena."""
result = requests.get("https://www.boardgamegeek.com/xmlapi2/geeklist/252354")
return result.text | 61418d5c0e0ad12c3f7af8a7831d02f94153ac84 | 4,108 |
import http
def build_status(code: int) -> str:
"""
Builds a string with HTTP status code and reason for given code.
:param code: integer HTTP code
:return: string with code and reason
"""
status = http.HTTPStatus(code)
def _process_word(_word: str) -> str:
if _word == "OK":
... | 9730abf472ddc3d5e852181c9d60f8c42fee687d | 4,109 |
import time
def retry(func_name, max_retry, *args):
"""Retry a function if the output of the function is false
:param func_name: name of the function to retry
:type func_name: Object
:param max_retry: Maximum number of times to be retried
:type max_retry: Integer
:param args: Arguments passed... | 29051605dbad65823c1ca99afb3237679a37a08c | 4,110 |
def benedict_bornder_constants(g, critical=False):
""" Computes the g,h constants for a Benedict-Bordner filter, which
minimizes transient errors for a g-h filter.
Returns the values g,h for a specified g. Strictly speaking, only h
is computed, g is returned unchanged.
The default formula for the ... | ca40941b4843b3d71030549da2810c9241ebdf72 | 4,111 |
def get_mode(elements):
"""The element(s) that occur most frequently in a data set."""
dictionary = {}
elements.sort()
for element in elements:
if element in dictionary:
dictionary[element] += 1
else:
dictionary[element] = 1
# Get the max value
max_value ... | bc792ffe58ffb3b9368559fe45ec623fe8accff6 | 4,112 |
import re
def remove_special_message(section_content):
"""
Remove special message - "medicinal product no longer authorised"
e.g.
'me di cin al p ro du ct n o lo ng er a ut ho ris ed'
'me dic ina l p rod uc t n o l on ge r a uth ori se d'
:param section_content: content of a section
:ret... | 37d9cbd697a98891b3f19848c90cb17dafcd6345 | 4,114 |
def apply_function_elementwise_series(ser, func):
"""Apply a function on a row/column basis of a DataFrame.
Args:
ser (pd.Series): Series.
func (function): The function to apply.
Returns:
pd.Series: Series with the applied function.
Examples:
>>> df = pd.Da... | d2af0a9c7817c602b4621603a8f06283f34ae81a | 4,115 |
def BitWidth(n: int):
""" compute the minimum bitwidth needed to represent and integer """
if n == 0:
return 0
if n > 0:
return n.bit_length()
if n < 0:
# two's-complement WITHOUT sign
return (n + 1).bit_length() | 46dcdfb0987268133d606e609d39c641b9e6faab | 4,116 |
def fetch_last_posts(conn) -> list:
"""Fetch tooted posts from db"""
cur = conn.cursor()
cur.execute("select postid from posts")
last_posts = cur.fetchall()
return [e[0] for e in last_posts] | dd5addd1ba19ec2663a84617904f6754fe7fc1fc | 4,118 |
import socket
def tcp_port_open_locally(port):
"""
Returns True if the given TCP port is open on the local machine
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(("127.0.0.1", port))
return result == 0 | f5c801a5016085eedbed953089742e184f514db5 | 4,120 |
def wrap(text, width=80):
"""
Wraps a string at a fixed width.
Arguments
---------
text : str
Text to be wrapped
width : int
Line width
Returns
-------
str
Wrapped string
"""
return "\n".join(
[text[i:i + width] for i in range(0, len(text), w... | 793840a1cae51397de15dd16051c5dfffc211768 | 4,121 |
import socket
def get_ephemeral_port(sock_family=socket.AF_INET, sock_type=socket.SOCK_STREAM):
"""Return an ostensibly available ephemeral port number."""
# We expect that the operating system is polite enough to not hand out the
# same ephemeral port before we can explicitly bind it a second time.
s... | 37287b70e35b8aa7fbdb01ced1882fb3bbf38543 | 4,123 |
def lastmsg(self):
"""
Return last logged message if **_lastmsg** attribute is available.
Returns:
last massage or empty str
"""
return getattr(self, '_last_message', '') | ad080c05caadbb644914344145460db0164f017c | 4,124 |
def _callback_on_all_dict_keys(dt, callback_fn):
"""
Callback callback_fn on all dictionary keys recursively
"""
result = {}
for (key, val) in dt.items():
if type(val) == dict:
val = _callback_on_all_dict_keys(val, callback_fn)
result[callback_fn(key)] = val
return re... | 3cab018413a7ba8a0e5bbae8574025253a2ea885 | 4,125 |
import os
def running_on_kaggle() -> bool:
"""Detect if the current environment is running on Kaggle.
Returns:
bool:
True if the current environment is on Kaggle, False
otherwise.
"""
return os.environ.get("KAGGLE_KERNEL_RUN_TYPE") == "Interactive" | ac1432666ccc8ca8e9d1d73938c5a1212f4fc429 | 4,126 |
def getCountdown(c):
"""
Parse into a Friendly Readable format for Humans
"""
days = c.days
c = c.total_seconds()
hours = round(c//3600)
minutes = round(c // 60 - hours * 60)
seconds = round(c - hours * 3600 - minutes * 60)
return days, hours, minutes, seconds | f49225ae2680192340720c8958aa19b9e9369f5f | 4,128 |
def get_list_channels(sc):
"""Get list of channels."""
# https://api.slack.com/methods/channels.list
response = sc.api_call(
"channels.list",
)
return response['channels'] | d31271bcc065b4a212e298c6283c4d658e5547da | 4,129 |
def construct_sru_query(keyword, keyword_type=None, mat_type=None, cat_source=None):
"""
Creates readable SRU/CQL query, does not encode white spaces or parenthesis -
this is handled by the session obj.
"""
query_elems = []
if keyword is None:
raise TypeError("query argument cannot be N... | fbe28156beca73339fa88d200777e25172796864 | 4,130 |
import json
def json2dict(astr: str) -> dict:
"""将json字符串转为dict类型的数据对象
Args:
astr: json字符串转为dict类型的数据对象
Returns:
返回dict类型数据对象
"""
return json.loads(astr) | f13b698dcf7dda253fd872bb464594901280f03b | 4,132 |
import os
def add_service_context(_logger, _method, event_dict):
"""
Function intended as a processor for structlog. It adds information
about the service environment and reasonable defaults when not running in Lambda.
"""
event_dict['region'] = os.environ.get('REGION', os.uname().nodename)
ev... | f5ea74b09ddd7024a04bc4f42bbd339b82adc9e3 | 4,133 |
import os
def get_drives():
"""A list of accessible drives"""
if os.name == "nt":
return _get_win_drives()
else:
return [] | f370697170d27600322d6b1eae1c6028e73dc5a6 | 4,134 |
def fibonacci(length=10):
"""Get fibonacci sequence given it length.
Parameters
----------
length : int
The length of the desired sequence.
Returns
-------
sequence : list of int
The desired Fibonacci sequence
"""
if length < 1:
raise ValueError("Sequence le... | afa3ef63a663b4e89e5c4a694315083debdbab59 | 4,135 |
def lowercase_words(words):
"""
Lowercases a list of words
Parameters
-----------
words: list of words to process
Returns
-------
Processed list of words where words are now all lowercase
"""
return [word.lower() for word in words] | b6e8658f35743f6729a9f8df229b382797b770f6 | 4,137 |
def _standardize_df(data_frame):
"""
Helper function which divides df by std and extracts mean.
:param data_frame: (pd.DataFrame): to standardize
:return: (pd.DataFrame): standardized data frame
"""
return data_frame.sub(data_frame.mean(), axis=1).div(data_frame.std(), axis=1) | cbe0e1f5c507181a63193a4e08f4ed8139d9e129 | 4,138 |
def isempty(s):
"""
return if input object(string) is empty
"""
if s in (None, "", "-", []):
return True
return False | 9c3ffd6ab818e803c1c0129588c345361c58807f | 4,139 |
def clamp(val, min_, max_):
"""clamp val to between min_ and max_ inclusive"""
if val < min_:
return min_
if val > max_:
return max_
return val | 31f2441ba03cf765138a7ba9b41acbfe21b7bda7 | 4,140 |
def get_ip(request):
"""Determines user IP address
Args:
request: resquest object
Return:
ip_address: requesting machine's ip address (PUBLIC)
"""
ip_address = request.remote_addr
return ip_address | 84e1540bc8b79fd2043a8fb6f107f7bcd8d7cc8c | 4,141 |
def _is_valid_new_style_arxiv_id(identifier):
"""Determine if the given identifier is a valid new style arXiv ID."""
split_identifier = identifier.split('v')
if len(split_identifier) > 2:
return False
elif len(split_identifier) == 2:
identifier, version = split_identifier
if not... | 71171984ad1497fa45e109b9657352c20bfe7682 | 4,142 |
def count_vowels(s):
"""Used to count the vowels in the sequence"""
s = s.lower()
counter=0
for x in s:
if(x in ['a','e','i','o','u']):
counter+=1
return counter | 236500c76b22510e6f0d97a4200865e2a18b47c3 | 4,144 |
def get_start_block(block):
"""
Gets the deepest block to use as the starting block.
"""
if not block.get('children'):
return block
first_child = block['children'][0]
return get_start_block(first_child) | e658954bb69f88f10c2f328c605d6da094ba065d | 4,146 |
def parse_worker_string(miner, worker):
"""
Parses a worker string and returns the coin address and worker ID
Returns:
String, String
"""
worker_part_count = worker.count(".") + 1
if worker_part_count > 1:
if worker_part_count == 2:
coin_address, worker = worker.s... | 3492716fc9f5290a161de0b46e7af87afbe6b348 | 4,147 |
def str_view(request):
"""
A simple test view that returns a string.
"""
return '<Response><Message>Hi!</Message></Response>' | fd9d150afdf0589cdb4036bcb31243b2e22ef1e2 | 4,149 |
def get_mnsp_offer_index(data) -> list:
"""Get MNSP offer index"""
interconnectors = (data.get('NEMSPDCaseFile').get('NemSpdInputs')
.get('PeriodCollection').get('Period')
.get('InterconnectorPeriodCollection')
.get('InterconnectorPeriod'))
... | 46211e9a29f1fd1fd3148deaaaa064b6d6b05ca7 | 4,150 |
from typing import Generator
import pkg_resources
def get_pip_package_list(path: str) -> Generator[pkg_resources.Distribution, None, None]:
"""Get the Pip package list of a Python virtual environment.
Must be a path like: /project/venv/lib/python3.9/site-packages
"""
packages = pkg_resources.find_dis... | 9e73e27c2b50186dedeedd1240c28ef4f4d50e03 | 4,151 |
def _get_reverse_complement(seq):
"""
Get the reverse compliment of a DNA sequence.
Parameters:
-----------
seq
Returns:
--------
reverse_complement_seq
Notes:
------
(1) No dependencies required. Pure python.
"""
complement_seq = ""
for i in seq... | 31408767c628ab7b0e6e63867e37f11eb6e19560 | 4,152 |
def check_table(conn, table, interconnect):
"""
searches if Interconnect exists in table in database
:param conn: connect instance for database
:param table: name of table you want to check
:param interconnect: name of the Interconnect you are looking for
:return: results of SQL query searching... | 0888146d5dfe20e7bdfbfe078c58e86fda43d6a5 | 4,153 |
def xml_escape(x):
"""Paranoid XML escaping suitable for content and attributes."""
res = ''
for i in x:
o = ord(i)
if ((o >= ord('a')) and (o <= ord('z'))) or \
((o >= ord('A')) and (o <= ord('Z'))) or \
((o >= ord('0')) and (o <= ord('9'))) or \
... | 018dc7d1ca050641b4dd7198e17911b8d17ce5fc | 4,154 |
def read_tab(filename):
"""Read information from a TAB file and return a list.
Parameters
----------
filename : str
Full path and name for the tab file.
Returns
-------
list
"""
with open(filename) as my_file:
lines = my_file.readlines()
return lines | 8a6a6b0ec693130da7f036f4673c89f786dfb230 | 4,155 |
def int2(c):
""" Parse a string as a binary number """
return int(c, 2) | dd1fb1f4c194e159b227c77c4246136863646707 | 4,156 |
def properties(classes):
"""get all property (p-*, u-*, e-*, dt-*) classnames
"""
return [c.partition("-")[2] for c in classes if c.startswith("p-")
or c.startswith("u-") or c.startswith("e-") or c.startswith("dt-")] | 417562d19043f4b98068ec38cc010061b612fef3 | 4,157 |
def _setter_name(getter_name):
""" Convert a getter name to a setter name.
"""
return 'set' + getter_name[0].upper() + getter_name[1:] | d4b55afc10c6d79a1432d2a8f3077eb308ab0f76 | 4,158 |
def thumbnail(img, size = (1000,1000)):
"""Converts Pillow images to a different size without modifying the original image
"""
img_thumbnail = img.copy()
img_thumbnail.thumbnail(size)
return img_thumbnail | 4eb49869a53d9ddd42ca8c184a12f0fedb8586a5 | 4,161 |
import os
def get_unique_dir(log_dir='', max_num=100, keep_original=False):
"""Get a unique dir name based on log_dir.
If keep_original is True, it checks the list
{log_dir, log_dir-0, log_dir-1, ..., log_dir-[max_num-1]}
and returns the first non-existing dir name. If keep_original is False
then... | 0cc517f67929fd29e1a38d0dc0aae73e3e4c9252 | 4,163 |
def create_contrasts(task):
"""
Create a contrasts list
"""
contrasts = []
contrasts += [('Go', 'T', ['GO'], [1])]
contrasts += [('GoRT', 'T', ['GO_rt'], [1])]
contrasts += [('StopSuccess', 'T', ['STOP_SUCCESS'], [1])]
contrasts += [('StopUnsuccess', 'T', ['STOP_UNSUCCESS'], [1])]
c... | 221b1b1ebcc6c8d0e2fcb32d004794d1b0a47522 | 4,167 |
from typing import List
import logging
def sort_by_fullname(data: List[dict]) -> List[dict]:
""" sort data by full name
:param data:
:return:
"""
logging.info("Sorting data by fullname...")
try:
data.sort(key=lambda info: info["FULL_NAME"], reverse=False)
except Exception as excep... | 0b4ecf53893bda7d226b3c26fe51b9abc073294b | 4,168 |
def check_position(position):
"""Determines if the transform is valid. That is, not off-keypad."""
if position == (0, -3) or position == (4, -3):
return False
if (-1 < position[0] < 5) and (-4 < position[1] < 1):
return True
else:
return False | f95ab22ce8da386284040626ac90c908a17b53fa | 4,169 |
def split_kp(kp_joined, detach=False):
"""
Split the given keypoints into two sets(one for driving video frames, and the other for source image)
"""
if detach:
kp_video = {k: v[:, 1:].detach() for k, v in kp_joined.items()}
kp_appearance = {k: v[:, :1].detach() for k, v in kp_joined.item... | 0396003a17172a75b121ddb43c9b9cf14ee3e458 | 4,170 |
def extract_timestamp(line):
"""Extract timestamp and convert to a form that gives the
expected result in a comparison
"""
# return unixtime value
return line.split('\t')[6] | 84618f02e4116c70d9f6a1518aafb0691a29ef07 | 4,171 |
def plot_histogram(ax,values,bins,colors='r',log=False,xminmax=None):
"""
plot 1 histogram
"""
#print (type(values))
ax.hist(values, histtype="bar", bins=bins,color=colors,log=log,
alpha=0.8, density=False, range=xminmax)
# Add a small annotation.
# ax.annotate('Annotation', ... | d11e89c005275a176fd00d0e2ac5173ee8f490b1 | 4,172 |
from operator import and_
def get_repository_metadata_by_changeset_revision( trans, id, changeset_revision ):
"""Get metadata for a specified repository change set from the database."""
# Make sure there are no duplicate records, and return the single unique record for the changeset_revision. Duplicate recor... | 33f5da869f8fde08e2f83d7a60a708e4848664a1 | 4,175 |
def repetitions(seq: str) -> int:
"""
[Easy] https://cses.fi/problemset/task/1069/
[Solution] https://cses.fi/paste/659d805082c50ec1219667/
You are given a DNA sequence: a string consisting of characters A, C, G,
and T. Your task is to find the longest repetition in the sequence. This is
a ma... | 4dde2ec4a6cd6b13a54c2eafe4e8db0d87381faa | 4,177 |
def parse_headers(headers, data):
"""
Given a header structure and some data, parse the data as headers.
"""
return {k: f(v) for (k, (f, _), _), v in zip(headers, data)} | 456c2ab2d2f7832076a7263be8815b9abeec56dd | 4,178 |
def dataset_parser(value, A):
"""Parse an ImageNet record from a serialized string Tensor."""
# return value[:A.shape[0]], value[A.shape[0]:]
return value[:A.shape[0]], value | 0b07b6eec9e3e23f470970c489ad83c416d650e7 | 4,179 |
def check_rule(body, obj, obj_string, rule, only_body):
"""
Compare the argument with a rule.
"""
if only_body: # Compare only the body of the rule to the argument
retval = (body == rule[2:])
else:
retval = ((body == rule[2:]) and (obj == obj_string))
return retval | 9237da310ebcc30f623211e659ac2247efb36f69 | 4,181 |
def get_lines(filename):
"""
Returns a list of lines of a file.
Parameters
filename : str, name of control file
"""
with open(filename, "r") as f:
lines = f.readlines()
return lines | 1307b169733b50517b26ecbf0414ca3396475360 | 4,182 |
def normalize_type(type: str) -> str:
"""Normalize DataTransfer's type strings.
https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransfer-getdata
'text' -> 'text/plain'
'url' -> 'text/uri-list'
"""
if type == 'text':
return 'text/plain'
elif type == 'url':
return 'tex... | 887c532218a7775ea55c6a39953ec244183af455 | 4,183 |
def filterLinesByCommentStr(lines, comment_str='#'):
"""
Filter all lines from a file.readlines output which begins with one of the
symbols in the comment_str.
"""
comment_line_idx = []
for i, line in enumerate(lines):
if line[0] in comment_str:
comment_line_idx.append(i)
... | 8a6ce56187afc2368ec81d11c38fe7af2eacb14f | 4,184 |
def search_trie(result, trie):
""" trie search """
if result.is_null():
return []
# output
ret_vals = []
for token_str in result:
ret_vals += trie.find(token_str)
if result.has_memory():
ret_vals = [
one_string for one_string in ret_vals
if resu... | 75ad08db7962b47ea6402e866cf4a7a9861037c9 | 4,185 |
def GetFlagFromDest(dest):
"""Returns a conventional flag name given a dest name."""
return '--' + dest.replace('_', '-') | 021ab8bca05afbb2325d865a299a2af7c3b939c9 | 4,187 |
def ganache_url(host='127.0.0.1', port='7445'):
"""Return URL for Ganache test server."""
return f"http://{host}:{port}" | 9de6e2c26c0e1235a14c8dd28040fcdfb8a36a7f | 4,188 |
def unwrap(func):
"""
Returns the object wrapped by decorators.
"""
def _is_wrapped(f):
return hasattr(f, '__wrapped__')
unwrapped_f = func
while (_is_wrapped(unwrapped_f)):
unwrapped_f = unwrapped_f.__wrapped__
return unwrapped_f | 17aa0c8cc91578fd1187784ad0396ed91c5ec9b8 | 4,189 |
from typing import Dict
def missing_keys_4(data: Dict, lprint=print, eprint=print):
""" Add keys: _max_eval_all_epoch, _max_seen_train, _max_seen_eval, _finished_experiment """
if "_finished_experiment" not in data:
lprint(f"Add keys _finished_experiment ...")
max_eval = -1
for k1, v... | ad8d3f7c19dd4eefa0db465dd52b5e8dc8f0bd1e | 4,190 |
def tlam(func, tup):
"""Split tuple into arguments
"""
return func(*tup) | 0e3a9b93b36795e6c11631f8c8852aba59724f88 | 4,191 |
def priority(floors, elevator):
"""Priority for a State."""
priority = 3 - elevator
for i, floor in enumerate(floors):
priority += (3 - i) * len(floor)
return priority | b65abac24fb85f50425f2adfd4d98786b41c9a2d | 4,192 |
import re
def modify_list(result, guess, answer):
"""
Print all the key in dict.
Arguments:
result -- a list of the show pattern word.
guess -- the letter of user's guess.
answer -- the answer of word
Returns:
result -- the list of word after modified.
"""
guess ... | 9384ecd09659c55808a859dd613641ccac46c760 | 4,194 |
def get_N_intransit(tdur, cadence):
"""Estimates number of in-transit points for transits in a light curve.
Parameters
----------
tdur: float
Full transit duration
cadence: float
Cadence/integration time for light curve
Returns
-------
n_intransit: int
Number of... | d126b5590a8997b8695c1a86360421f2bf4b8357 | 4,195 |
def extract_keys(keys, dic, drop=True):
"""
Extract keys from dictionary and return a dictionary with the extracted
values.
If key is not included in the dictionary, it will also be absent from the
output.
"""
out = {}
for k in keys:
try:
if drop:
ou... | 15a66fff5207df18d8ece4959e485068f1bd3c9c | 4,196 |
import sqlite3
def getStations(options, type):
"""Query stations by specific type ('GHCND', 'ASOS', 'COOP', 'USAF-WBAN')
"""
conn = sqlite3.connect(options.database)
c = conn.cursor()
if type == "ALL":
c.execute("select rowid, id, name, lat, lon from stations")
else:
c.execute(... | 59d45a79542e68cd691cf848f3d4fe250389732c | 4,197 |
import textwrap
def inputwrap(x, ARG_indented: bool=False, ARG_end_with: str=" "):
"""Textwrapping for regular 'input' commands.
Parameters
----------
x
The text to be wrapped.
ARG_indented : bool (default is 'False')
Whether or not the textwrapped string should be indented.
A... | af0ab3b69205965b40d3e03bdcfe3148889f7080 | 4,199 |
import random
import string
def random_string_fx() -> str:
"""
Creates a 16 digit alphanumeric string. For use
with logging tests.
Returns:
16 digit alphanumeric string.
"""
result = "".join(random.sample(string.ascii_letters, 16))
return result | 835c2dc2716c6ef0ad37f5ae03cfc9dbe2e16725 | 4,200 |
def parse_date(td):
"""helper function to parse time"""
resYear = float(td.days)/364.0 # get the number of years including the the numbers after the dot
resMonth = int((resYear - int(resYear))*364/30) # get the number of months, by multiply the number after the dot by 364 and divide by 30... | bda78b0968b59c13f763e51f5f15340a377eeb35 | 4,202 |
def report_cots_cv2x_bsm(bsm: dict) -> str:
"""A function to report the BSM information contained in an SPDU from a COTS C-V2X device
:param bsm: a dictionary containing BSM fields from a C-V2X SPDU
:type bsm: dict
:return: a string representation of the BSM fields
:rtype: str
"""
report =... | df0aa5ae4b50980088fe69cb0b776abbf0b0998d | 4,203 |
def perdict_raw(model, *args, **kwargs):
"""
Tries to call model.predict(*args, **kwargs, prediction_type="RawFormulaVal"). If that fail,
calls model.predict(*args, **kwargs)
"""
try:
return model.predict(*args, **kwargs, prediction_type="RawFormulaVal")
except TypeError:
return ... | 2ab7790c0cd48cc9b26f6e7888dd61436cb728b4 | 4,204 |
import random
def random_function(*args):
"""Picks one of its arguments uniformly at random, calls it, and returns the result.
Example usage:
>>> random_function(lambda: numpy.uniform(-2, -1), lambda: numpy.uniform(1, 2))
"""
choice = random.randint(0, len(args) - 1)
return args[choi... | 3f8d11becc52fde5752671e3045a9c64ddfeec97 | 4,205 |
def biweekly_test_data():
""" Provides test data for the full system test when using "biweekly" time_scale."""
time_scale = "biweekly"
time_per_task = {
"Free" : 480 * 9 * 2,
"Work" : 480 * 5 * 2,
"Sleep" : 480 * 7 * 2
}
min_task_time = 60
preferences = {
"Free" :... | b5f354a17819133c3c29e7652f6b1132599e89b6 | 4,207 |
def is_rescue_entry(boot_entry):
"""
Determines whether the given boot entry is rescue.
:param BootEntry boot_entry: Boot entry to assess
:return: True is the entry is rescue
:rtype: bool
"""
return 'rescue' in boot_entry.kernel_image.lower() | ba456c2724c3ad4e35bef110ed8c4cc08147b42c | 4,208 |
import math
def rad_to_gon(angle: float) -> float:
"""Converts from radiant to gon (grad).
Args:
angle: Angle in rad.
Returns:
Converted angle in gon.
"""
return angle * 200 / math.pi | cbf7070a9c3a9796dfe4bffe39fdf2421f7279ed | 4,210 |
def detected(numbers, mode):
"""
Returns a Boolean result indicating whether the last member in a numeric array is the max or
min, depending on the setting.
Arguments
- numbers: an array of numbers
- mode: 'max' or 'min'
"""
call_dict = {'min': min, 'max': max}
if mode not in ca... | b0a5b19e7d97db99769f28c4b8ce998dbe318c5b | 4,211 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.