content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import contextvars
def RunInNewContextMiddleware(app, wsgi_env, start_response):
"""Runs the app in a copy of the current context.
Start every request by calling contextvars.copy_context() and running the
rest of the request in the newly copied context. This ensures that
each request has its own context that... | cfa96f2011610beb4f2af030ce39e4c62f0f7931 | 645,846 |
def strip_comments(content):
"""Manual striping of comments from file content.
Many localized content pages contain original English content in comments.
These comments have to be stripped out before analyzing the links.
Doing this using regular expression is difficult. Even the grep tool is
not su... | 3fdad45d48e0e14a1ef3eeef0520b1b154c9ca52 | 645,847 |
def hsl_to_str(hue, sat, light):
""" Convert an HSL color value into a string.
Args:
hue (int): value between 0-360
sat (int): value between 0-100
light (int): value between 0-100
Returns:
str: string representation of the HSL tuple. Note that
the hue is an integer... | ed0bd6ce344fe1f8333155e68b7dd0ac2de15c73 | 645,851 |
def mean(values, empty=0):
""" calculates mean of generator or iterator.
Returns `empty` in case of an empty sequence """
n, mean = 0, 0
for value in values:
n += 1
mean += (value - mean) / n
return mean if n > 0 else empty | b697a34a0cf311daea06f5d5fbe0a5ba58e6aec0 | 645,853 |
def sum_payout(cost_matrix, confusion_matrix):
"""
Calculate the profit from cost and confusion matrices.
"""
return (confusion_matrix * cost_matrix).sum() | 8b1b0fe44a283582625ad2cdee91411b59cfb105 | 645,854 |
import torch
def batch_matmul(input: torch.Tensor, weight: torch.Tensor) -> torch.Tensor:
"""
Batch matrix multiply different batch elements of the input with different weights.
If weights are 3D, Input batch is divided in N groups, and each group element is matrix multiplied by a different
filter. I... | 2b2865bb7af23fbb6801a733a99787ed8d520e7a | 645,857 |
def spawn(awaitable):
"""Start running a coroutine asynchronously. Returns the associated task."""
return (yield ("create_task", awaitable)) | 9cecbb28a953d844e48c352163886738b3edcca4 | 645,859 |
def get_iso_time(date_time):
"""
Converts the provided datetime object to an ISO-format time-tag.
Parameters
----------
date_time : datetime.datetime
Datetime object to convert to ISO format.
Returns
-------
time_in_iso : str
Provided time in ISO format: YYYY-MM-DDTHH:M... | 8d819a00c43850fb75a48135b3bd413efff60107 | 645,864 |
def is_any_in_txt(txt_list, within_txt):
"""
Within (txt_list), is there one item contained in within_txt ?
Example: (['a', 'b'], 'ab') --> Yes, a is contained in ab
"""
for x in txt_list:
if x in within_txt:
return True
return False | 24b72856e2febce9bdc4dabc857ef1842c19317b | 645,866 |
import math
def format_count(number, maxlen=3):
"""
Returns a formatted count number,
e.g. "1.3K" if number is longer than allowed maximum.
"""
result = str(number)
if len(result) > maxlen:
UNITS = "KMGTPEZY"
log = min(len(UNITS) - 1, math.floor(math.log(number, 1000)))
... | a14ce97025dae2eb47ebc0a571ec059b9a29d17f | 645,868 |
def redcap_default_ship_to_vbr_location() -> str:
"""Returns the VBR Location ID shipment location for UCSD"""
# Response is a location_id mapped to these locations
# See src/scripts/data/location.csv
return "1" | 992e103d5ea9d43b88967adae9cf582abe2c353e | 645,873 |
import re
def process(s):
"""Process the file name as input string s to ensure that it adheres to
Windows file naming requirements. """
if len(s) > 240: s = s[0, 240]
return ''.join(re.split(r"[\\\:\*\?\"\<\>\|]", s.strip())) | 88481e7121f2a33d7ea5e7a5b108adcd78350105 | 645,874 |
def ignore_filename(fn, include_dotdirs=False):
"""
Ignores particular file name patterns output by TSK. Detecting new
and renamed files becomes difficult if there are 3+ names for an
inode (i.e. "dir", "dir/.", and "dir/child/..").
"""
return (not include_dotdirs and (fn.endswith("/.") or fn.e... | c3bf8c2f4c2674e2d4ea98eb5794a558446ce68f | 645,875 |
def find_neighbor(x,y):
"""if y is within +-10bp of x"""
# print (x,y)
chr_x = x[:-1].split(":")[0]
start_x = int(x[:-1].split(":")[-1].split("-")[0])
chr_y = y[:-1].split(":")[0]
start_y = int(y[:-1].split(":")[-1].split("-")[0])
# print (chr_x,chr_y,start_x,start_y)
if chr_x != chr_y:
return False
if abs... | 590d917bf71e7dd357a9b24e16f22a4cea597787 | 645,876 |
def mask_sequence(seq, maskchar, fpos, tpos):
"""Given a sequence, mask it with maskchar starting at fpos (including) and
ending at tpos (excluding)
"""
if len(maskchar) > 1:
raise RuntimeError("Internal error: more than one character given to mask_sequence")
if fpos < 0:
fpos = 0
... | 8e6dfca2c1575da4f31fd1c9c07fd20a8eb78271 | 645,881 |
def fibonacci(n):
"""
this function has one parameter (n).
this function should return the nth value
in the fibonacci series.
the function is implemented using recursion.
each number in the fibonacci sequence
is the sum of the two numbers that precede it.
the sequence goes:
0, 1, 1, 2, 3, 5, 8... | f307fae836c5e9c45b032cf8fe63786d35ac3ab9 | 645,882 |
def clear(df,col,val):
""" Check distribution of variable
This function accepts a dataframe,column(feature) and value which returns count of the value,
containing the value counts of a variable(value_counts)
Keyword arguments:
df - Pandas dataframe
col - Feature of the datagrame
va... | 80f756d5d23f8bfa8c0eb4b2182ec1db158d0581 | 645,885 |
def gen_backend_tfvars_files(environment, region):
"""Generate possible Terraform backend tfvars filenames."""
return [
"backend-%s-%s.tfvars" % (environment, region),
"backend-%s.tfvars" % environment,
"backend-%s.tfvars" % region,
"backend.tfvars"
] | 7c05061d2fed80e81900b529d5849959ba06dff2 | 645,886 |
def get_prot_res_seq_cif(CifDict, EntNum):
"""
Gives sequence as taken from mmCIF file, entity poly pdbx seq section
Takes the canonical sequence.
Parameters
----------
CifDict: dict
EntNum: int
Returns
-------
canonseq: str
"""
# canon_seqlist = CifDict["_entity_poly.p... | 8a078ee039cc4439806448c77d512a3bea807afa | 645,891 |
def get_direct_deps(graph, top_node):
"""Gets the direct dependencies of given top_node.
@param graph The graph to read for dependencies.
@param top_node The node, which dependencies are wanted.
@return The dependencies in a set.
"""
deps = set()
for i in range(len(graph.body)):
if ... | 9392b31a9ecf6081f86454455fdfa32c501fa20b | 645,893 |
import math
def applyDeadZone(val, deadZone):
"""
Apply a dead zone to an input with no other smoothing. Values outsize the dead zone are correctly scaled for 0 to 1.0
:return:
The float value of the adjusted intput
"""
sign = 1.0
if val < 0.0:
sign = -1.0
val = math.fabs(val)... | 42937474a10065efe793ce09f1b4625676c7d733 | 645,897 |
import torch
def xyxy2xywh(box: torch.Tensor) -> torch.Tensor:
"""
Returns the xywh format of the input bounding box tensor
Arguments:
box (torch.Tensor): Bounding box tensor in xyxy format
Output:
output (torch.Tensor): Bounding box tensor in xywh format
"""
... | d119f7b436cfbaadcb940b335fe6cda39d145fb1 | 645,899 |
def parse_email_remediation_key(key):
"""Returns the tuple (message_id, recipient) for the key created using create_email_remediation_key."""
return key.split(':', 1) | 495eff306e89ada4430bc4995d96fb88e0c4f032 | 645,900 |
def read_text(file_name):
"""
Parameters
----------
file_name : string, name of file to read
Returns
-------
line : string of the file contents
"""
inFile = open(file_name,'r') # Python function to open a file via name
line = inFile.read() # Function to read contents into ... | 51dbcd5bb28a78980201906a4a7f5dbef50cef8f | 645,903 |
def bezier2(t, ps):
""" evaluate quadratic bezier curve at t given three points in list ps """
umt = 1 - t
return umt * umt * ps[0] + 2 * umt * t * ps[1] + t * t * ps[2] | 71b6873d823cef7854bc8b56a874815c52362545 | 645,911 |
def is_valid_filename_extension(ext: str) -> bool:
"""
By convention extensions are the initial `.`.
E.g., "tgz" is valid, but not ".tgz".
"""
valid = not ext.startswith(".")
return valid | 21cf0eae149567d34d24a3066727076b98dc6f20 | 645,914 |
def beautify_url(url):
"""
Remove the URL protocol and if it is only a hostname also the final '/'
"""
try:
ix = url.index('://')
except ValueError:
pass
else:
url = url[ix+3:]
if url.endswith('/') and url.index('/') == len(url)-1:
url = url[:-1]
return ur... | 5c0ba43534758eb5d90ade1531881006ef58e8a8 | 645,915 |
import json
def story(request):
"""
Provides a detailed HPACK story to test with.
"""
path = request.param
with open(path, 'r', encoding='utf-8') as f:
details = json.loads(f.read())
return details | aecf93441c62aa1671bb343275d96ab5b8f68614 | 645,917 |
def parse_model_cfg(path):
"""Parses the yolo-v3 layer configuration file and returns module definitions"""
file = open(path, 'r')
lines = file.read().split('\n')
lines = [x for x in lines if x and not x.startswith('#')]
lines = [x.rstrip().lstrip() for x in lines] # get rid of fringe whitespaces
... | f3eed138eeeb446b31ad75b11253b1649f69c49a | 645,921 |
def make_str_content(content):
"""
In python3+ requests.Response.content returns bytes instead of ol'good str.
:param content: requests.Response.content
:return: str representation of the requests.Response.content data
"""
if not isinstance(content, str):
content = str(content.decode())
... | c8ccdf34a4e3375ebd09c15c94651e74f6af4f2b | 645,922 |
def beta(R0, gamma):
"""
R0 from model parameters.
"""
return R0 * gamma | 1c21be0be39e0b2ab6e1807e110adf892e13f15a | 645,923 |
import re
def get_build_number_from_body(body):
"""Extracts the build number from the given body.
Arguments:
body {dict} -- The body as extracted by `extract_body()`
Returns:
str -- The build number if given. If there's an error extracting this
or if the build numb... | 0132f9bd41b4b4f4f2018c29f5a314ee9d2bf9db | 645,925 |
def format_time(decisecond):
"""
Convert time in tenths of seconds
into formatted string m:ss.t
:param decisecond: int >= 0
:return: str
"""
assert isinstance(decisecond, int)
assert decisecond >= 0
decisecond, tenths = decisecond//10, decisecond % 10
minutes, seconds = decise... | 006489e1849642a5d63db32e08f535d8a6182fba | 645,926 |
def make_iterator(args, lock, queue):
"""
Makes an iterator over args and passes the lock an queue to each element.
"""
return ((arg, lock, queue) for arg in args) | 2eb2aefda8f29dd5dc776dd5b646f9f1ff4ba7a9 | 645,928 |
import pickle
def pickle_save(obj, fp, verbose=1):
"""Save an object as a pickle file."""
try:
with open(fp, 'wb') as f:
pickle.dump(obj, f)
except Exception as err:
if verbose: print("Saving object failed. Error:", err)
return False
else:
if verbose: print(... | eb536e4eacff6daae371b8b68b839c14f42a0366 | 645,929 |
import socket
def is_valid_ip_address(ip_addr):
"""This method checks if string provided is a valid IP address
Args:
ip_addr (str): IP Address String
Returns:
(boolean): True/False
"""
try:
socket.inet_aton(ip_addr)
return True
except (socket.error, TypeError):
... | 9ff7cec7eaaa77ece911baaf11b0391d5c5c150b | 645,930 |
def sync_batch_request(func, params, get_data=lambda x: x["info"], limit=500):
"""
同步请求接口
:param func: 请求方法
:param params: 请求参数
:param get_data: 获取数据函数
:param limit: 一次请求数量
:return: 请求结果
"""
# 如果该接口没有返回count参数,只能同步请求
data = []
start = 0
# 根据请求总数并发请求
while True:
... | 59d9dfe6c4503f3b7e11937091f33b8106746429 | 645,938 |
import torch
def batch_torch_denormalize_box_params(box_params, scale=3):
""" Denormalize the box parameters utilizing the accumulated dateaset statistics
:param box_params: float tensor of shape [N, 6] containing the 6 box parameters, where N is the number of boxes
:param scale: float scalar that scales... | 28846d5e8e09542bb873d7cb2e57e67099a1da4d | 645,939 |
def read_voca(path):
"""
open file from path and read each line to return the word list
"""
with open(path, 'r') as f:
return [word.strip() for word in f.readlines()] | 2ae35bc9918217c30dbfb7d3cc6e168424854d06 | 645,940 |
import locale
def get_day_name(day):
"""
Get the short day name in the currently activated locale.
:param day:
:return:
day 0 = Sunday
"""
# Locale keys are 1=Sun, 2=Mon, ...
locale_key = "ABDAY_%d" % (1 + day)
option = getattr(locale, locale_key)
day_name = locale.nl_langinfo(... | b3326f4a1cab553fdd92a033002e70f4f69765c2 | 645,943 |
def color_to_str(C):
"""Convert color value to hex string."""
# Scale from [0-1] to [0-255]
V = [int(round(c * 255)) for c in C]
# Clamp values to [0-255]
for i in range(len(V)):
V[i] = max(min(V[i], 255), 0)
return '#{:02X}{:02X}{:02X}'.format(V[0], V[1], V[2]) | 6b93f2484fabb237f1d9cf2c505c986043648a95 | 645,947 |
import struct
def decode_ga(ga: int) -> str:
""" Decodes a group address into human readable string representation
>>> decode_ga(270)
'0/1/14'
"""
if not isinstance(ga, int):
ga = struct.unpack('>H', ga)[0]
return '{}/{}/{}'.format((ga >> 11) & 0x1f, (ga >> 8) & 0x07, (ga) & 0xff) | c65d2f1808077bf0a34d1054bf7409f0c1c854af | 645,950 |
def ccw(a, b, c):
"""
1: c is left of the line a->b
-1: c is on the right of line a->b
0: c is on the line a->b
>>> ccw(Vector(0, 0), Vector(3, 4), Vector(6, 8))
0
>>> ccw(Vector(0, 0), Vector(3, 4), Vector(6, 9))
1
>>> ccw(Vector(0, 0), Vector(3, 4), Vector(6, 7))
-1
"""
... | c445d11d2fe82236ae4aa42c2e21dfc33942bda2 | 645,954 |
import ast
def get_literal_tuple(param_type):
"""
get literal option from annotation string and return result in tuple.
"""
s_index: int = str(param_type).index('[')
e_index: int = str(param_type).index(']')
str_list = str(param_type)[s_index + 1:e_index]
res = ast.literal_eval(str_list)
... | 8ee28a06fa10bc5ed8ac524c15bbd0bef0d2e1df | 645,955 |
from pathlib import Path
from typing import List
def get_all_files_in_directory(path: Path) -> List[Path]:
"""
Returns all the files in a directory structure.
For example, given a directory structure like::
dir_a: dir_b, file_a, file_b
dir_b: file_c
and you provide the path to ``dir... | 339bade149a145336e68e3958b437937a89c720e | 645,956 |
import copy
def get_object_state(obj, ignore_attributes=()):
"""Returns a dictionary with the state of the attributes of an object.
Note that this is not general. For example, it will throw an error for classes
that define a __slots__ field (like namedtuples).
Args:
obj: a Python object
ignore_attri... | 42377b5ae20bd4ceaa4f58cec3681b6ddc655eb6 | 645,959 |
def remove_trailings(input_string):
"""
Remove duplicated spaces.
"""
output_string = " ".join(input_string.split())
return output_string | f53cd6f55b1a5a43225223b3695d542b8c4876b6 | 645,960 |
def scaleFromRedshift(redshift):
"""
Converts a redshift to a scale factor.
:param redshift: redshift of the object
:type redshift: float or ndarray
:return: scale factor
:rtype: float or ndarray
"""
return 1. / (redshift + 1.) | 99501af0f5a2005ed952e8d01ad7533d02bfdf22 | 645,961 |
def calc_f_number(aperture_diameter,
focal_length):
"""
Calculate the f-number N (or f#) of an optical system.
https://en.wikipedia.org/wiki/F-number
Returns
-------
double : no units
"""
return focal_length / aperture_diameter | 93f8050ee7baa1d20f0431514f86412cca953af9 | 645,971 |
def timezone_format(value):
""" Check the value of the timezeone offset and, if postive, add a plus sign"""
try:
if int(value) > 0:
value = '+' + str(value)
except:
value = ''
return value | e6abafec8c66b3891bba33a5f1110a4a406e9777 | 645,975 |
import click
def prompt_for_dsn(dsn):
"""
Prompt interactively for postgres database connection details.
:return: dictionary with the keys: host, port, database, user, password
"""
click.echo('Please provide PostgreSQL connection info:')
# Note: Using '' as the prompt default is necessary to... | bf3f0ef3f5f9358d875e1747bc652b02cd48577f | 645,979 |
def fastFib(n, memo = {}):
"""
Assumes n is an int >= 0, memo used only by recursive calls
Returns Fibonacci of n
"""
if n == 0 or n == 1:
return 1
try:
return memo[n]
except KeyError:
result = fastFib(n-1, memo) + fastFib(n-2, memo)
memo[n] = result
... | 7b3cb2aa2b6f8eccde043ce9b800f2580ded6305 | 645,980 |
def escape_for_query(query_part: str) -> str:
"""Escapes all characters reserved by jriver in a natural string.
Do not put a complete query in here - this method is used to escape
reserved characters in a natural string that will be used as a query fragment.
This is usually the content of a field (e.g.... | 13635b9091fe11c335867893422da23844116160 | 645,983 |
def create_firmware_update_payload(device_info: dict, compliance_data_list: list) -> list:
"""
Creates the payload to send to OME to execute the firmware update
Args:
device_info: A dictionary of dictionaries containing the type information for each device
compliance_data_list: A list of di... | 7040361cba99f608a82b59a9de2396fb6621ecac | 645,991 |
from typing import OrderedDict
def mapProfiles(settings):
"""Profile ID mapped to index in the list in an OrderedDict"""
profileMap = OrderedDict()
i = 0
print(settings)
while i < len(settings):
if "profileID" in settings[i]:
index = settings[i]["profileID"]
profil... | 7c0f8af6a2de877cb649ac53e14b80bc1e13c252 | 646,005 |
def test_datasource_connection(connection, body, error_msg=None):
"""Test a datasource connection. Either provide a connection id, or the
connection parameters within connection object.
Args:
connection: MicroStrategy REST API connection object.
body: Datasource Connection info.
err... | 96b1f08e7313583c12cb10d1b76bf3bdc17b2ab8 | 646,006 |
def _noto_relative_path(filepath):
"""Return relative path from some noto root, or None"""
x = filepath.find('noto-fonts')
if x == -1:
x = filepath.find('noto-cjk')
if x == -1:
x = filepath.find('noto-emoji')
if x == -1:
return None
return filepath[x:] | ac2e9aa968bf65629072053ca2c3c3a09d426a7d | 646,009 |
import jinja2
def load_template(in_template):
""" Returns a jinja2 template from file.
Parameters
---------
in_template: str
path and name of jinja2 template
Returns
-------
output_template: jinja template object
"""
with open(in_template, 'r') as default:
output_... | a5af11fd55fcf93dfc37e7330dcfc9d6e4a23c1e | 646,011 |
def parse_ptimes(ln):
"""
Mini function for getting the time (in a string) from a line of an errlog file.
"""
timestring = ln.split(" ")[3]
return timestring | 4f2b80386fa78845e85d0c4c39efc5b30b70eb2a | 646,016 |
def wrap(x, low, high):
"""Wraps data between low and high boundaries."""
diff = high - low
while x > high:
x -= diff
while x < low:
x += diff
return x | 3a7ac9c9f63dbc61304322c7827774ce81ca3752 | 646,017 |
def _get_chunks(text, length=200, overlap=50):
"""Splits text into chunks
Args:
text (str): Text
length (int, optional): Chunk length. Defaults to 200
overlap (int, optional): Chunk overlap. Defaults to 50
Return:
list: Text chunks
"""
l_total = []
l_partial = ... | 61d312114b3e1ee50fb2f43f8f288c7597ca2f0e | 646,019 |
def _get_header(soup):
"""Extract the column names from the "list-row-headings" class.
Parameters
----------
soup: bs4.BeautifulSoup
The html web page.
Returns
-------
list
Each element is a string with a column name.
"""
column_heading_class = "list-row-headings"
... | 43161030c6365c7b9de115ea1373697de0074f11 | 646,020 |
def getDistance (origin, point):
"""
Returns the distance between two points.
"""
dist = ((origin[0]-point[0])**2 + (origin[1]-point[1])**2)**0.5
return dist | aa945f7cbf9b1e06fdf999f1f2bd1bf75a0f4acd | 646,021 |
def cart_count(a) -> int:
"""
Count the number of items in the cart.
:param a: List of products. Untyped as I'm unsure how 'dict_items' type truly works.
:return: Int of the number of items in the cart.
"""
count = 0
# a is of type 'dict_items'
for i, this_tuple in enumerate(a):
... | e9c31fceab86ceed6b7099e835b0a17210b42218 | 646,024 |
import re
def confirm(prompt, default='y'):
"""Confirmation prompt."""
default = default.lower()
if default not in ['y', 'n']:
default = 'y'
choicebox = '[Y/n]' if default == 'y' else '[y/N]'
prompt = prompt + ' ' + choicebox + ' '
while True:
some_input = input(prompt).strip(... | fce0b96825b5e22d7ea9f76e693a5a4753e14720 | 646,027 |
def check_if_number_even(n):
"""
checks if int n is an even number
"""
if (n % 2) == 0:
return True
else:
return False | 3a46dadeb4a0afcd20cc4d2e693e680ba61f6805 | 646,032 |
def is_close(first, second, rel_tol=1e-09, abs_tol=0.0):
"""
Almost equality for float numbers
:param first
:param second
:param rel_tol: relative tolerance, it is multiplied
by the greater of the magnitudes of the two arguments;
as the values get larger, so does the allowed difference
... | e341ea0fe01a90ae48145e9338c59f9da01f070f | 646,036 |
def user_id(uid):
"""Google user unique id to feedly ``:user_id`` format
:param uid: Google unique account UUID
:type uid: :class:`basestring`
:returns:
:rtype: :class:`basestring`
>>> user_id('00000000-0000-0000-0000-000000000000')
'user/00000000-0000-0000-0000-000000000000'
... | 1b65efb5848af6f4a90442d4de4506d62c6bd1fd | 646,037 |
def timedelta_to_seconds(delta):
"""
Take a timedelta object and return the total number of seconds.
"""
return delta.seconds + (delta.days * 86400) | 23bc2b9e36f58db68e39625e41dd4f0728d25457 | 646,039 |
def fetch_all_table_names(schema, eng):
"""
Finds all tables within a given schema.
"""
tables = eng.execute(
f"SELECT table_name FROM information_schema.tables WHERE table_schema = '{schema}';"
)
return [table[0] for table in tables] | afcabfb33a084e98b494aac8287c7c4e97ccde7d | 646,040 |
def is_xml_article_set(filename: str) -> bool:
"""
Check if input file is pubmed xml compressed archive from name.
Arguments:
filename {str} -- the name of the file
Returns:
bool -- true if file is compressed pubmed article set
"""
if filename.endswith('.xml.gz'):
retur... | 7a05e9daadee32ff59e07fa05304e446e32e77cb | 646,041 |
def get_bd_addr(packet):
"""Helper function to get bd_addr filed from HCI CMD/EVT packet.
Args:
packet: packet object from pyshark.
Returns:
bd_addr value (MAC string). If the packet doesn't have bd_addr or not is not
HCI CMD/EVT, will return None.
"""
bd_addr = None
if 'bthci_evt' in packet:
... | 37b30d7b6770d526e9a60065358bcee1647e0726 | 646,043 |
from typing import Dict
from typing import Union
def od_parse(data: str) -> Dict[str, Union[str, list]]:
"""Parse od command output without argument, return a dict with the following keys: hex, ascii, list, text
Returns:
dict: with key hex, ascii, list, text
"""
text, asc_data, hex_data, list_... | c9eb69a988063009971af373dd88da6101a0dfe8 | 646,050 |
import re
def ShellEscape(arg):
""" Escape a single argument for passing into a remote shell
"""
arg = re.sub(r'(["\\])', r'\\\1', arg)
return '"%s"' % arg if re.search(r'[\' \t\r\n]', arg) else arg | 4fa85d982a7d8d64637ba524a1bba958a033f2c0 | 646,052 |
import re
def get_args(argv):
"""Store command-line args in a dictionary.
-, -- prefixes are removed
Items not prefixed with - or -- are stored as a list, indexed by 'args'
For options that take a value use --option=value
Consider using optparse or getopt (in Python standard library) instea... | 95395903a5fdfb8bc12c05df32e55006750cacf8 | 646,053 |
import math
def calc_term_count(order, var_count):
"""
Inputs: order- the order of the model
var_count- the number of variables in the model
Calculates the number of terms in a model.
"""
term_count = int(
math.factorial(order + var_count)
/ (math.factorial(order) ... | ac65c19885302bb8dae80ddd55721760c621fc6b | 646,054 |
import re
def timestamp_to_terraref(timestamp):
"""Converts a timestamp to TERRA REF format
Args:
timestamp(str): the ISO timestamp to convert
Returns:
The ISO string reformatted to match the TERRA REF time & date stamp. Returns the original
string if time units aren't specified
... | 0c571ce1b9fd39b0345cca68058bb6ee61c771e2 | 646,056 |
def min_point(points, n_points):
"""
Return the index of the closest point to (0,0)
:param points: tuple of list for each coordinate
:param n_points: number of points
:return: the index of the selected point in the list
"""
min_y_indexes = [0]
min_y = points[1][0]
# Find minimum y
... | c06117007693aba8877952f88b6155df143f663b | 646,062 |
import re
from bs4 import BeautifulSoup
def remove_html_tags(text):
""" Removes HTML tags from text. """
# prevent missing white space in further deletion of html symbols
text = re.sub('<p>', ' ', text)
# add punctuation after headings
text = re.sub('</h1>', '. ', text)
text = re.sub('</h2>'... | 34d2b3e1f0e27457d7296149b89bf5eded1b62b3 | 646,063 |
def _is_2xx_status(status_code):
"""Returns 'True' if a given status code is one of successful."""
return str(status_code).startswith("2") | 16cdb950c791c4217996821328823be99e817f4c | 646,068 |
from datetime import datetime
def output_filename(filename, cli_args):
"""
Construct the output filename
"""
if cli_args.timestamp:
date_time = datetime.now().strftime("%m-%d-%Y_%H.%M.%S")
lname = filename.split(".")[0]
rname = filename.split(".")[-1]
new_filename = f"{... | 6a9ff52d64727c3f7921f3f29c3839c381923f39 | 646,069 |
import math
def update_one_contribute_score(user_total_click_num):
"""
item cf update similarity score by user
:param user_total_click_num:
:return: 1/log(1 + input)
"""
return 1 / math.log10(1 + user_total_click_num) | f04d309c1be4a061beff692c1aa942d8ee5f3ee6 | 646,070 |
def nCr(n,r):
"""Calculate ways of selecting *r* members out of a collection of *n*
members.
:param n: Size of the collection
:param r: Number of members to be selected from the collection
:returns: n!/[r!(n-r)!]
.. note::
:sup:`n` C :sub:`r` is typically read as *n co... | a4bd8de9e4b3339ef2c23c2fd7731106d89b5fe7 | 646,071 |
import copy
def firecrown_sanitize(config):
"""Sanitizes the input for firecrown, that is removes keys that firecrown
doesn't recognize
Parameters:
----------
config : dict
The dictinary that is ready for firecrown to munch on, but might have
extra keys that are augur specific... | 432f6d8edde835b640ec832e6c0de5abd15e24af | 646,072 |
def _scalarize(value):
"""Scalarize a value.
If VALUE is a list that consists of a single element, return that
element. Otherwise return VALUE."""
if type(value) == list and len(value) == 1:
return value[0]
return value | d5eb2e0a42ed91472bf83d527c85e6adf4cc9200 | 646,074 |
def MeansOpenInProject(status, config):
"""Return true if this status means that the issue is still open.
Args:
status: issue status string. E.g., 'New'.
config: the config of the current project.
Returns:
Boolean True if the status means that the issue is open.
"""
status_lower = status.lower()... | 54e6d0b6047f9cf565b43c67126ba79bb5e594f0 | 646,075 |
def choose_peers(relay, relay_count, worker_count, min_w2r, min_r2w):
"""
Given `relay`, the position of relay within the affinity set for a
given service, the number of relays in that set (`relay_count`), the number
of workers for the service (`worker_count`), the minimum number of
connections requ... | 9539394c26d093f8f6fba1165e8119ca946226aa | 646,076 |
def str_as_bool(val):
""" Interpret the string input as a boolean
"""
if val.lower() in ("false", "none", "no", "0"):
return False
return True | f38e56b174a93523eb7adcd15ba5a1263d27922d | 646,077 |
def MakeCopyList(alist):
"""Make a copy of a list"""
#newlist = the copied list
newlist = []
for x in range(len(alist)):
newlist.append(alist[x])
return newlist | d2eb3f9d9613e9dee44c1e37182d22f6b48e9a33 | 646,078 |
import re
def scraping_txt_file(filetxt):
"""This scrape the data inside text files using regular expression. """
datum = []
with open(filetxt, "r", encoding="latin1") as foo:
for line in foo: # I think a genertator is imaginable here!
pattern = re.compile(
r"(?P<Date_... | 92bb74730bdaa4805b9c2fd664b28fb830bae534 | 646,083 |
def val_interpolate(x1, y1, x2, y2, x):
"""Perform linear interpolation for x between (x1,y1) and (x2,y2) """
d = [[x1, y1],[x2, y2]]
output = d[0][1] + (x - d[0][0]) * ((d[1][1] - d[0][1])/(d[1][0] - d[0][0]))
return(output) | a8ba1b89433a561b7a52d02031cee2f2633f7730 | 646,085 |
def subtract(x, y):
""" Returns the first vector minus the second. """
n = len(x)
assert len(y) == n
return map(lambda i: x[i]-y[i], range(0, n)) | dd66579b99d01c42b9773a116b4989910a6be3be | 646,088 |
import re
def remove_non_ascii(text):
"""
Remove non ascii characters in the text
Parameters
----------
text : str
Returns
-------
text: str
"""
return re.sub(r'[^\x00-\x7F]', ' ', text) | f32fcc3de385d5c16de7e821d48085f88389b4bd | 646,091 |
def lens(lists):
"""Returns the sizes of lists in a list."""
return list(map(len, lists)) | 495ed5e2c1dc598eea8c6e5016d63c251c597f2f | 646,093 |
import pickle
def load_transform(file):
"""
Load a transform object
"""
with open(file, 'rb') as input_file:
transform = pickle.load(input_file)
return transform | 0be183a69b3eb8a833edbd4a1241c7b940e24495 | 646,094 |
def report_file_path(report_path, report_label, report_extension):
"""
Function to create a path for report files.
Parameters:
report_path (path): Report file path
report_label (str): Report file label
report_extension (str): Report file extension. e.g. txt, csv
Return:
r... | f4c2f12f252f1afb8a66e88c3de2d694613211bc | 646,096 |
def random_walk_step(r, p0, W, pt):
"""
r = probability of restart
p0 = initial probability vector
W = column-normalized adjacency matrix
pt = probability vector at time step t
pt = probability vector at time step t + 1
"""
#print 'r', r
#print 'W', W
#print 'pt', pt
#print '... | 047ae6ff08a1a6f0bef579ab026a46c747de5953 | 646,099 |
import math
def distance_nautical_miles(ll1,ll2):
"""
Given two (lat,lon) points ll1 and ll2, returns the distance
between them in nautical miles.
"""
lat1,lon1=ll1
lat2,lon2=ll2
rad = math.pi / 180.0
yDistance = (lat2 - lat1) #* nauticalMilePerLat
xDistance = (math.cos(lat1 * rad) + math.cos(l... | cc3b9756cbcce66aeb9c023ab206aee7d42bdf90 | 646,102 |
def pairwise_diff(X, Y):
"""Compute pairwise difference of rows of X and Y.
Returns tensor of shape len(X) x len(Y) x dim."""
return X.unsqueeze(1) - Y | d7ed4e5f1ed5add306ed3e978620303b7b290946 | 646,108 |
import re
def _tracwiki_list_separate_from_paragraph(text: str):
"""
During conversion from TracWiki to RST, ensure an empty line
between each non-list-item and the list item following it, if any.
"""
lines = text.split('\n')
newlines = []
was_list_item_or_blank = True
for l in lines... | 7559d5fab4d39e174d12948ec8c5ebc24e08d20d | 646,112 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.