content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def distance_between(origin_x, origin_y, destination_x, destination_y):
"""Calculate the distance between two points. """
return ((origin_x - destination_x)**2 + (origin_y - destination_y)**2)**.5 | fd71bb437e55d3a811c7153e03ea0525f3cd6536 | 626,586 |
def metricsKwargs(args, single=False):
"""Extra parameters given to compute_metrics.py"""
if single:
kwargs = {}
else:
kwargs = dict(piecewise=args.piecewise, offsetTracks=args.offsetTracks, comparisonList=args.compare, exportAlignedData=args.exportAlignedData)
kwargs['metric_set'] = ar... | 21d8192530d1f8f377d36819e67752d7442b4720 | 626,587 |
import itertools
def filterfalse():
"""Remove matching element."""
filtered = itertools.filterfalse(lambda x: 'B' < x < 'E', 'ABCDEF')
return ''.join(filtered) | 839d58d97f531b091bd9b3755a1996f46a1f4e62 | 626,588 |
def download(image):
"""Download IMAGE."""
return image.image | 26b7f9c5f27a8d5deb780df9f035283e56789778 | 626,591 |
def isPrime(n):
"""Return True if n is a prime."""
if n > 2 and n % 2 == 0:
return False
for x in range(3, int(n**0.5 + 1), 2):
if n % x == 0:
return False
return True | c9cd5d2346c4548860bda2cf7a5f1f9ced4d1e68 | 626,592 |
def _upload_event_trigger_file(blob_service_client, trigger_file_path, container_name, local_trigger_file_path):
"""Helper function that upload event trigger file to target container of storage account.
Args:
blob_service_client (BlobServiceClient): Azure Storage Account service client
trigger_... | 109dd8d7c823165d7829afb907984d0c8ede3662 | 626,594 |
def triplo(num):
"""
-> Calcula o triplo de um número
:param num: Número que terá seu triplo calculado
:return: retorna o triplo de 'num'
"""
return num*3 | f4d2f7c486fd55c1f3689a6179de6ba15805a093 | 626,595 |
def eliminate(a, args, ak, i, j):
"""
Gauss–Jordan elimination
"""
return a[i][j] - args[i] * ak[j] | f48e44248d4bd4ca6fafe779b608f8c2760d61c7 | 626,596 |
def valid_login_pairs(dictionary={'John Doe': "secret"}):
"""
:param dictionary: valid username password pairs
:type dictionary: dict
:return: dictionary
:rtype: dict
"""
return dictionary | 1ad869387ab58a670bc126c772eab578e23248ee | 626,597 |
def gen_user_name(from_user):
"""from_user has username or full_name"""
if from_user.username:
new_name = from_user.full_name + " (@" + from_user.username + ")"
else:
new_name = from_user.full_name
return new_name | b61f7f5fb5371b96eea8e574364bcbcd2e17c0e5 | 626,599 |
def mean_squared_error_loss(ypred, ytrue, loss):
"""
Torch nn.MSELoss(reduction='mean')
"""
return loss(ypred, ytrue) | dc947497d11e6f5e237a634df860e9250465eb56 | 626,601 |
def playback_state(state):
"""Generate user-friendly playback states.
Args:
state (str): The Sonos-supplied state string.
Returns:
str: A user-friendly playback state description.
"""
playback_mapping = {
"STOPPED": "stopped",
"PAUSED_PLAYBACK": "paused",
"P... | 0da7a620211030280212a13b51ed24ebe1918713 | 626,602 |
def _to_list(a):
"""Return a as list for unroll_scan."""
if isinstance(a, list):
return a
elif isinstance(a, tuple):
return list(a)
elif a is None:
return []
else:
return [a] | 6cf88e2735df8c33925376cc71520b160aa3a9f5 | 626,603 |
def partition_hostname(hostname):
"""Return a hostname separated into host and domain parts."""
parts = hostname.partition('.')
return dict(hostname=parts[0],
domainname=parts[2] if parts[1] == '.' else None) | fd56a97ed369e33252dc44e474c10bd1fe7daba0 | 626,604 |
def solve(tokens):
"""
Given a list of tokens where
each token is subdivided into
a frequency range, a character,
and a string, count the total
number of tokens that are valid
where a token is valid if and only
if the frequency of the character
appearing in the given string lies
... | 3ac31bebe80ac2a75eadc955f79f6a6c971d2b54 | 626,605 |
def get_trigger_name(field):
"""
:param field: Field instance
:return: unicode
"""
if field._trigger_name:
name = field._trigger_name
else:
name = '{1.db_table}_{0.name}'.format(field, field.model._meta)
return 'concurrency_{}'.format(name) | bbe5be633a1d08f7a7855249121d2c19a6fc606d | 626,606 |
import numpy
def build_sample_ace_problem_wang04(N=100):
"""Build sample problem from Wang 2004."""
x = [numpy.random.uniform(-1, 1, size=N)
for _i in range(0, 5)]
noise = numpy.random.standard_normal(N)
y = numpy.log(4.0 + numpy.sin(4 * x[0]) + numpy.abs(x[1]) + x[2] ** 2 +
... | 396795e41ae52259dd5c0ea4378a2336449bd909 | 626,609 |
import os
import sys
def resource_path(relative_path):
"""
Get absolute path to resource, works for dev and for PyInstaller.
See more on topic here:
https://stackoverflow.com/questions/7674790/bundling-data-files-with-pyinstaller-onefile/7675014#7675014
"""
return os.path.join(getattr... | e61799e141ab2696d1bd2df6dfa54b67841cc660 | 626,610 |
def remove_multiple_blank_lines(instring):
"""
Takes a string and removes multiple blank lines
"""
while '\n\n' in instring:
instring = instring.replace('\n\n', '\n')
return instring.strip() | b28f64a20301def88f098018d9992b8a8889cc04 | 626,612 |
def incremental_value_calculator(repository, undeployed_value_tuple, deployed_value_tuple):
"""
Add the undeployed value to the previous data point's value, if one exists.
"""
# If the undeployed SHA is the same as the deployed SHA, the value
# differential is 0.
if undeployed_value_tuple[0] == ... | e0ce1d7099abe095de5689d9ff8f316970b554aa | 626,614 |
def parse_custom_command(command: str) -> list:
"""
Convert custom medusa command from string to list to be usable in subprocess.
:param command: Custom medusa command
:return: Parameters for medusa command
"""
command_split = command.split(" ")
command_list = []
for parameter in comma... | 40d4d62b0ec2f5ee950587cdf5cc92e04d580af8 | 626,615 |
def _find_SNPs_which_overlap_sign_neighbour_region(sign_snp_neighbour_region, x):
"""
"""
x_size = len(x)
reg_size = len(sign_snp_neighbour_region)
index = []
tmp_index = 0
for i in range(x_size):
_x = x[i]
is_overlap = False
iter_index = range(tmp_index, reg_size)
... | 63175dc4d329a39c4fbf4de2be31533bc5fa989c | 626,618 |
def percentage(percent, whole):
"""
get <what> for percent of whole
"""
return (percent * whole) / 100.0 | fee9b80d0ee9570ecfdec316b0db3fae3867a5c9 | 626,619 |
import logging
import sys
def _configure_root_logger(level="info", format=None):
"""Configure root log level and format.
This is a helper function that can be called form
"""
log = logging.getLogger() # Get root logger
# Set log level
# level = getattr(logging, level.upper())
numeric_le... | c247fd4cc36df45fd1925d1c7f59929535e8cd63 | 626,620 |
import random
def random_element_from_list(element_list):
"""Returns a random element from list."""
return element_list[random.SystemRandom().randint(0, len(element_list) - 1)] | 4ee390d22fa3cfdd32a031fc3b6ec4714b027a9a | 626,621 |
import math
def sqrt(x):
"""Return sqare root of input"""
square = math.sqrt(x)
return square | 75a6626518af1aab06ad68d82cd415aa105737e5 | 626,622 |
def get_or_create_metrics(run):
"""Returns the "subfolder" of the HDF5 file "run/metric" where metrics may be stored."""
if "metrics" not in run:
run.create_group("metrics")
return run["metrics"] | 928e7098252df2b8e562b24024137d5270da9f4b | 626,624 |
import random
def flip_coin(bias=0.5):
"""Flip a biased coin."""
return random.random() <= bias | 09d968888740fff767dbd35cce2d21e602f672a1 | 626,625 |
def rev_c(seq):
"""
simple function that reverse complements a given sequence
"""
tab = str.maketrans("ACTGN", "TGACN")
# first reverse the sequence
seq = seq[::-1]
# and then complement
seq = seq.translate(tab)
return seq | f6951fb2088effeb8326ae415dc664cf8e9a08d2 | 626,626 |
def refresh(session, *entities):
"""Refresh entities from the current session."""
if not entities:
return []
return [session.query(entity.__class__).get(entity.id) for entity in entities] | 771bbf6d2b3671ed70e714a8eaf40b9ca2e3cf9b | 626,627 |
import re
def remove_spaces(text):
"""
Remove all the tabs, spaces, and line breaks from the raw text
Args:
text(str) -- raw text
Returns:
text(str) -- text clean from tabs, and spaces
"""
# remove \t, \n, \r
text = text.replace("\t", "").replace("\r", "").replace("\n", "")... | 64e0da2b0a6c274476ed1a560fd814479608908b | 626,628 |
from io import StringIO
from typing import Tuple
import re
import json
def parse_timewarrior_data(input_stream: StringIO) -> Tuple[dict, list]:
"""
Parse data passed to report from timewarrior.
"""
header = 1
config = dict()
body = ""
for line in input_stream.readlines():
# Extract... | 942a12348f41b35dc10c8780bafa647c6460c05a | 626,629 |
import os
def go_higher_dir_levels(path_to_dir, level=0):
"""
Gien directory path, go up number of levels defined by level
:param path_to_dir:
:param level:
:return:
"""
up_dir = path_to_dir
for lev in range(level):
up_dir = os.path.dirname(path_to_dir)
return up_dir | bbc2f05adcfd7ef273feb93ec8d71d52cf8f5965 | 626,630 |
def compute_gene_pathogenicity(filtered_gff, bedgraph):
"""Compute mean pathogenicity score of a gene."""
# intersection = pybedtools.BedTool(bedgraph).intersect( b=filtered_gff)
intersection = bedgraph.intersect(b=filtered_gff)
total_num_bases = 0.
patho_score = 0.
for entry in intersection:
... | f0c101076d89355cd7675f0854acb3a35b7d24cc | 626,632 |
def mint(string):
"""
Convert a numeric field into an int or None
"""
if string == "-":
return None
if string == "":
return None
return int(string) | 1820bce7bf94c7735204336f98a0a6ad53cdee6f | 626,633 |
def pp(n, p, l, t):
"""calculate pp,qq for SBM given p from ER
p : p from G(n,p)
l : # of communities
t : ratio of pp/qq
"""
pp = p * n * (n - 1) / (n ** 2 / l - n + t * n ** 2 * (l - 1) / l)
qq = t * pp
return pp, qq | 1a57eaf74a1b38813e2aac249d4bfbfe5de2a50b | 626,634 |
import string
def remove_punctuation_and_lower(s):
"""
This will return a string without puntuation and all words are in lower-case.
The punctuation symbols are get from the module 'string'.
The set of punctuation symbols are '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
"""
return s.translate(str.make... | 056f3d49626080ca0e3d64794980ea039e073f8e | 626,636 |
import sys
import json
import os
def get_config():
"""Reads default configuration and update it according
to command line arguments given by user"""
# read user override of parameters from console
user_override = {}
for k, v in ((k.lstrip('-'), v) for k, v in (a.split('=') for a in sys.argv[1:])... | a5c369b406f72960f2554589161d420e2445bbef | 626,637 |
import os
def read(name: str) -> str:
"""https://pythonhosted.org/an_example_pypi_project/setuptools.html#setting-up-setup-py - reference."""
return open(os.path.join(os.path.dirname(__file__), name)).read() | fbb79bb37f2d6fe33cf122720128d9116b0853e0 | 626,638 |
import argparse
def get_raw_process_parser():
""" Parse the arguments for ASERParser
:return: parameters
:rtype: argparse.ArgumentParser
"""
parser = argparse.ArgumentParser()
# Dataset
parser.add_argument('--data', type=str, default="nyt",
help='which dataset to ... | a3481319e78afa2b53e4825ba057cc3498390df9 | 626,639 |
import itertools
def remove_intersection(dict_of_sets):
"""Removes the intersection of any two sets in a list."""
for i, j in itertools.combinations(list(dict_of_sets.keys()), 2):
set_i = dict_of_sets[i]
set_j = dict_of_sets[j]
dict_of_sets[i] = set_i - set_j
dict_of_sets[j] = set_j - set_i
retu... | 78cd7b94b6bd9b552f27f74d95fd3070bb234c06 | 626,641 |
def to_bool(bool_str):
"""Convert a string to bool.
"""
return True if bool_str.lower() == 'true' else False | a581f9a4970b9d363326bdd2780e23897bc9791a | 626,642 |
import numpy
def label_electrons(electrons, is_data, options):
"""
"""
if is_data:
label = numpy.zeros(len(electrons))
else:
label = numpy.ones(len(electrons))
electrons["label"] = label
electrons["is_photons"] = numpy.zeros(len(electrons))
electrons["is_dy"] = numpy.one... | 3188b8021e8dfe3d07de298b507c27b48babe2a5 | 626,643 |
def hs_library_pattern(name, mode = "static", profiling = False):
"""Convert hs-libraries entry to glob patterns.
Args:
name: The library name. E.g. HSrts or Cffi.
mode: The linking mode. Either "static" or "dynamic".
profiling: Look for profiling mode libraries.
Returns:
L... | c432eda9162d7bc7be4e7c84cae446b6583839c4 | 626,644 |
import struct
import fcntl
import termios
def terminal_size() -> tuple:
"""
Get terminal width and height
"""
packed_struct = struct.pack('HHHH', 0, 0, 0, 0)
h, w, hp, wp = struct.unpack('HHHH', fcntl.ioctl(0, termios.TIOCGWINSZ,
packed_struct)... | e7cb16ef46c57fcc57d45cc3fbac302eff869249 | 626,645 |
def split_by_lines(text, remove_empty=False):
"""
Split text into lines. Set <code>remove_empty</code> to true to filter out
empty lines
@param text: str
@param remove_empty: bool
@return list
"""
lines = text.splitlines()
return remove_empty and [line for line in lines if line.strip()] or lines | 875405e0c3ef981ed4c2cee367577d233558955d | 626,646 |
def clip(text, max_len=80):
"""Return text clipped at the last space before or after max_len
"""
end = None
if len(text) > max_len:
space_before = text.rfind(' ', 0, max_len)
if space_before >= 0:
end = space_before
else:
space_after = text.rfind(' ', max_... | 79621a272f7f4fc1c2274c9579ac7bc8da515779 | 626,647 |
def CloneXml(xml):
"""Returns a deep copy of the given XML element.
Args:
xml: The XML element, which should be something returned from
ParseXml() (i.e., a root element).
"""
return xml.ownerDocument.cloneNode(True).documentElement | 4389f255bb26fa67a6af3749c8a93c56299927eb | 626,648 |
import os
import random
def background(path):
"""Returns image to use as background.
Images are public domain, found at: https://www.pexels.com/
Args:
path(str): Location of folder to choose picture from
Returns:
path(str): Location of randomly chosen picture in a given file"""
p... | bee98a6d747142a8cf1daff40b72149d852dc59f | 626,649 |
import argparse
def empty_parser(prog_name='bin/ott_blah'):
"""
create a generic OTP commandline arg PARSER
"""
parser = argparse.ArgumentParser(
prog=prog_name,
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
return parser | 5065dd651f77c9d739ba51f50e35a11e329fc2d1 | 626,650 |
import hashlib
import os
import mmap
def calculate_hash(hash_name, file_path_or_handle):
"""
Calculate a hash for the given file.
:param hash_name: name of the hash algorithm in hashlib
:type hash_name: str
:param file_path_or_handle: source file name (:py:obj:`str`) or file
handle (:py:o... | 42e478acf663695666c9c29eef5181ee8baafb30 | 626,651 |
def gain_map(meta):
""" map keywords to true gain values according to the CCD manual """
# Currently it's just a map to gain=1.1 e-/adu
return 1.1 | 3232a0541a04a34859744f5ba7694f3ca7b30de7 | 626,652 |
import torch
def elementwise_intersection_and_union(boxes1, boxes2):
"""
elementwise-intersection and elementwise-union.
Expected format of the box left-top, right-bottom coordinates.
"""
area1 = torch.prod(boxes1[:, 2:] - boxes1[:, :2], dim=-1)
area2 = torch.prod(boxes2[:, 2:] - boxes2[:, :2], d... | c86413017b6057db78c9acfd67cb9c6f8fdf9053 | 626,653 |
def server_role(server_tag, role_map):
"""
1) given server name, determine node id from HostnameMap
2) given node id, determine role
a) remove stack name from the beginning of the node id
b) replace node id index with %index%
c) find matching Scheduler Hints
"""
print("Tag: {}, R... | c379f4d4cc9f5bf20a2b6da34d75afbff2f989ad | 626,655 |
import re
def expand_distances(d_expression):
"""
Check if a distance expression contains at least one term d[x]. If yes, then
the distances are expanded and we assume the user has specified an
expression such as d[0] + d[2].
"""
regexpr = re.compile(r'.*d\[\d*\].*')
if regexpr.match(d_exp... | 1b0d4d2eac123615a16ee6d92009a6c079d21447 | 626,656 |
def eliminate_from_neighbors(csp, var) :
"""
Eliminates incompatible values from var's neighbors' domains, modifying
the original csp. Returns an alphabetically sorted list of the neighboring
variables whose domains were reduced, with each variable appearing at most
once. If no domains were reduce... | 2a37e8dc89650f5b1bac80f0f7f2ba1746e15f54 | 626,657 |
from itertools import chain, count, islice, tee
def groupwise(iterable, num=2, circular=False):
"""Iterate through in iterator in pairs (or groups of n length).
For example, list(groupwise(range(10),3)) == [(0, 1, 2), (1, 2, 3),
(2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7), (6, 7, 8), (7, 8, 9)]
"""
... | f37964d0aa42943b0b1f419894086d71fe04d9c1 | 626,658 |
from typing import Callable
def _view_function_tuple_failure() -> tuple[Callable, int]:
"""
To test if an endpoint that cannot be converted into a JSON
raises a TypeException.
"""
return lambda x: 1, 20 | 0f86065a5ba234a321b7ecf8b7ba026cff6b274e | 626,659 |
def generate_triangular_board(edge=7, mirrored=False):
"""
Creates a board with a shape of equilateral triangle.
The size of the triangle's side (in fields) is specified by the edge argument.
By default the resulting board will be a triangle pointing down (pointy top)
of right (flat top). Setting m... | 61b19fa464444952a04c17d3d060e7e1b70f187b | 626,660 |
def emblinken(msg):
"""Blink the message for a terminal
"""
return '\033[5m%s\033[0m' % msg | f6efdd732cb9d4465a794fc0145330de50affa88 | 626,661 |
def compose(func_1, func_2, unpack=False):
"""
compose(func_1, func_2, unpack=False) -> function
The function returned by compose is a composition of func_1 and func_2.
That is, compose(func_1, func_2)(5) == func_1(func_2(5))
"""
if not callable(func_1):
raise TypeError("First argum... | 2b1cd3acc28533a766adeb935f57a31563f92f60 | 626,662 |
def datetime_to_simple(datetime):
"""Convert Time to tuple.
Parameters
----------
datetime : `astropy.time.Time`
The time to simplify.
Returns
-------
mjds : `tuple` of (`float`, `float`)
The two MJDs in TAI.
"""
tai = datetime.tai
return (tai.jd1, tai.jd2) | 740ef62f4fb600c74ee9a21ca279a0365cacad19 | 626,663 |
import logging
import json
def loadjson(jsonfile):
"""Load content from json file as dictionary.
Parameters
----------
jsonfile : str
Path to json file to be read.
Returns
-------
d : dict
Dictionary of the content stored in the json file.
"""
logging.info("... | 920787e4cd7c314ed836a7afe2768f12a29342b0 | 626,666 |
def datetime_to_ds_nodash(dt):
"""Convert a Python datetime object to a string with the format YYYYMMDD"""
return dt.strftime('%Y%m%d') | 0fc8ef07fb3153bc9a3b561fdbf3b6fdfe33de7a | 626,668 |
def init_model_with_data(model_obj, data_dict):
"""instantiate the generated tfp model object with data
Parameters
----------
model_obj : tfd.Distribution
an un-instantiated model object
data_dict : dict
data for the model
Returns
-------
tfd.Distribution
... | f71bab16321d3e2d0413e5483b320c8097930ae1 | 626,669 |
import functools
def reduce():
"""Apply recursively a function to an iterable."""
reverse = functools.reduce(lambda result, x: x + result, 'MooD')
return reverse | b3504560424f0fe089c4e7684150fdcafb97a0be | 626,670 |
def preprocessing(x_tra, y_tra, x_tst):
"""
* The method at first eliminates constant features from both train and test data.
* Then, the method runs selectKBest algorithm on the dataset, returning top 350 features.
----------
x_tra: features of training data
y_tra: labels of training data
... | 4d3f02cc8b576b10ad9764b66ed3a93398f01b28 | 626,671 |
def day_num(x):
"""function returning the next compass point in the clockwise direction"""
res = {"Sunday":0, "Monday":1, "Tuesday":2, "Wednesday":3, "Thursday":4,
"Friday":5, "Saturday":6}
ans = res.get(x, None)
return ans | 3ec77d996e4e263fbac6ae3f78b4078caf371f1d | 626,672 |
from typing import List
def flatten_labels(labels: List[str]) -> List[str]:
"""
labels from controller has no leading index,
just split it as csv to get all the names
"""
return [name for label in list(labels) for name in label.split(",")] | 1ce54fa75b5f801d8025edf77b2c35aed2bfcbc5 | 626,673 |
def torch_memoize(tensor, methodname, *args):
"""
Computes ``tensor.methodname(*args)`` memoizing the result for the lifetime
of ``tensor``. This enables sharing when used inside
:func:`~opt_einsum.shared_intermediates`.
"""
cache = vars(tensor).setdefault('_pyro_memoized', {})
key = methodn... | 34e54ec438b6c28b53825691be430869c3d23a4e | 626,674 |
import os
import subprocess
def fetch_db(c, destination="."):
"""
Dump the database on the remote host and retrieve it locally.
The destination parameter controls where the dump should be stored locally.
"""
dump_path = c.conn.dump_db("~")
filename = os.path.basename(dump_path)
subproces... | 5986a88ba1498e54773cc7723dc5f218fbba97a3 | 626,675 |
def quintic_easein(pos):
"""
Easing function for animations: Quintic Ease In
"""
return pos * pos * pos * pos * pos | 2a5c722315940d00e5be50e3c597d42a0b627268 | 626,676 |
def show_tags(context, tags):
"""Show tags"""
splits = tags.split(',')
for index, tag in enumerate(splits):
splits[index] = tag.lstrip()
return {
'tags': splits,
} | 4f776f5d1b84e691407b7a44164d942a3c09cbc0 | 626,677 |
def _format_exception(exception):
"""Formats the exception into a string."""
exception_type = type(exception).__name__
exception_message = str(exception)
if exception_message:
return "{}: {}".format(exception_type, exception_message)
else:
return exception_type | ca1fd85ade965172531a0b5db0e84eefb4520c2a | 626,678 |
import os
import argparse
def folder_str(f):
"""return string provided only if this folder exists"""
if not os.path.exists(f):
raise argparse.ArgumentTypeError('"%s" does not exist, you must create this folder' % f)
return f | e7c6f28d814a3fd01710e38110cc9515545a9a6a | 626,679 |
def query_attr_where(params, table_ref=True):
"""
Construct where conditions when building neighbors query
Create portion of WHERE clauses for weeding out NULL-valued geometries
Input: dict of params:
{'subquery': ...,
'numerator': 'data1',
'denominator': ... | 57f653044843db4dea0cacc32c9165632362169b | 626,681 |
def strclass(cls):
""" Return the classname of a class"""
return "%s" % (cls.__module__) | 5ae40d9d474deffe9dfa327c278b9282ac91e9f2 | 626,685 |
import re
def get_gene_ids(fusion_bed):
"""
Parses FusionInspector bed file to ascertain the ENSEMBL gene ids
:param str fusion_bed: path to fusion annotation
:return: dict
"""
with open(fusion_bed, 'r') as f:
gene_to_id = {}
regex = re.compile(r'(?P<gene>ENSG\d*)')
fo... | ab8ca07889580fa10c233c8e44a3a17859f73cad | 626,686 |
import smtplib
def login(username, password):
"""
Attempts to login to user's Gmail account.
Parameters:
username (str): User's email ID
password (str): User's email password
Returns:
server (smtplib.SMTP): SMTP object after logging in to email
"""
server = smtplib.SMT... | 5be587f676a6f95c5027ac3a9c0c78c157e09e0a | 626,688 |
def round_nearest(value, multiple_of):
"""round to `multiple_of` value.
based on: https://stackoverflow.com/a/28425782/574981
"""
return round(value / multiple_of) * multiple_of | e103cf748b0c7bf15f7eb0600561bda96a7c93ca | 626,689 |
import json
def get_connection_string(credential_path):
"""Converts credentials JSON to a connection string."""
with open(credential_path) as file_ptr:
credential_dict = json.load(file_ptr)
connection_string = credential_dict['connection_string']
full_connection_string = connection_string.f... | 90a41fc4e260012cfe67a4ac5d997a5df0b9b119 | 626,690 |
import os
def get_filenames(directory, extension=None):
"""
Return all filenames in a directory with an arbitrary extension.
Parameters:
-----------
directory: A string representing absolute or relative path.
extension: Extension that you want to look for. E.g. 'mp3'
Retur... | f32de28c9b079fc93c688f872c737dd021365933 | 626,692 |
def nbest_ascending_wins(limit, rlen, numdocs):
"""
Primitive curve-fitting to see if nbest ascending will beat
timsort for a particular limit/rlen/numdocs tuple. XXX This needs
work, particularly at small index sizes. It is currently
optimized for an index size of about 32768 (98% accuracy); it g... | a466d1658a73de064b0ab5d72d865b2cb0369066 | 626,693 |
import functools
import time
def timer(func):
"""
Starts the clock, runs func(), stops the clock. Simples.
Designed to work as a decorator... just put @timer in front of
the original function.
"""
# Preserve __doc__ and __name__ information of the main function
@functools.wraps(func)
d... | f4821ee750c6eeebe20d633c392b3f81078dee18 | 626,694 |
from typing import Union
from datetime import datetime
from typing import Optional
def prepare_timestamp(value: Union[datetime, int, None]) -> Optional[int]:
"""Returns a UTC UNIX timestamp from given input."""
if value is None:
return None
if isinstance(value, int):
return value
if ... | 0e5526716d4d7cb4005468c9656210cfaba13785 | 626,695 |
import json
def get_lum():
"""
Handles displaying the temperature data for a specific user. Takes in id of the user
and returns the temperature data displayed in HTML
"""
f = open("info_pipe", 'r')
luminosity = f.read()
luminosity = luminosity.split(',')[0]
f.close()
s = {'temp': l... | 07719a7e93ebfa7e07962d79063a0ebebf6447f7 | 626,697 |
def feat_step(r, ndim):
""" Solid disc. """
return (r <= 1).astype(float) | a90500e91f3777746f2ad99f513273a1f194c78c | 626,698 |
def sextodec(xyz, delimiter=None):
"""Decimal value from numbers in sexagesimal system.
The input value can be either a floating point number or a string
such as "hh mm ss.ss" or "dd mm ss.ss". Delimiters other than " "
can be specified using the keyword ``delimiter``.
"""
divisors = [1, 60.0, 3600... | 01a18426e3dd63a2f411647b83ee72c40eccd847 | 626,699 |
def highlight_cluster(query, cluster):
"""Colour assigned cluster in Microreact output"""
if str(cluster) == str(query):
colour = "red"
else:
colour = "blue"
return colour | 34aa42f101e27471e7934854bca4f1839e407845 | 626,700 |
def get_batchjob_parameters_keys():
""" Return list of bachjob parameters required for cluster computation
Args:
Return:
compulsory and noncompulsory list of parameters on slurm cluster
"""
compulsory = ['name', 'mem', 'core', 'partition', 'time', 'no_machine', 'python_cmd']
noncompul... | a265fd85eb3dbf9ca34fd0d71652c7eeb00b2fe9 | 626,701 |
from functools import reduce
def escape(text: str) -> str:
""" Escape special characters
@param text:
@return:
"""
# List of text characters to replace
_ = (
('&', 'and'),
('<', ''),
('>', ''),
('\"', ''),
('\'', '')
)
return reduce(lambda t, ... | c2b7459cd7433e5aabab08e42465ed79919ae545 | 626,702 |
def from_db(x):
"""
Convert from decibels to original units.
Inputs:
- x [float]: Input data (dB)
Outputs:
- y [float]: Output data
"""
return 10**(0.1*x) | 2262aaff83b8064f17a52b5f46263caaca4d6913 | 626,703 |
import os
def are_same_filesystem(file1, file2):
""" Test if the files are on the same file-system. """
return os.stat(file1).st_dev == os.stat(file2).st_dev | e61f56ac5d69606751ebbad19208e42fdfc0c925 | 626,704 |
def index(seq):
"""
Build an index for a sequence of items. Assumes
that the items in the sequence are unique.
@param seq the sequence to index
@returns a dictionary from item to position in the sequence
"""
return dict((k,v) for (v,k) in enumerate(seq)) | 1367da75882ea1d7daaff0a515b09a3d72d38815 | 626,705 |
def calc_variables(df, var_list):
"""Calculate area-weighted values for variables.
Formula: x_pre=A_intersect1 / A_pre * x_bg1 + A_intersect2 / A_pre * x_bg2
Args:
df (DataFrame): the dataframe containing census spatially merged with precincts
var_list (list): names of variables to calcul... | 09f122842a5f32447e7c89ae6cae730976a50921 | 626,706 |
import requests
def request_ct(url):
"""Performs a get request that provides a (somewhat) useful error message."""
try:
response = requests.get(url)
except:
raise IOError(
"Couldn't retrieve the data, check your search expression or try again later."
)
else:
... | 0c1299724ae1141358349d4fd7b98b94c9a3154f | 626,708 |
def replace_spaces(text):
"""
Replace spaces with a dash.
"""
if not isinstance(text, str):
return text
return text.replace(" ", "-") | fb32adfc90f9aba00cc65473a6a4cf09b01968a5 | 626,709 |
def log_format_metadata(metadata):
"""Return a string representation of the metadata formatted for log output.
"""
return ", ".join("{}={}".format(k, v) for k, v in metadata.items()) | a3449491996a8412fd6fb6c579283267f2ab8e26 | 626,710 |
import math
def shubert04(ind):
"""Shubert04 function defined as:
$$ f(x) = \sum_{i=1}^n \sum_{j=1}^5 j cos((j+1)x_i) + j $$
with a search domain of $-10 < x_i < 10, 1 \leq i \leq n$.
"""
return sum(( sum((-j * math.cos((j+1) * ind[i] + j) for j in range(1, 6))) for i in range(len(ind)))), | ed764bffa7b37286d1caa6e16dfe96804976e75e | 626,711 |
import os
def normalized(path):
"""Normalizes a given path on the filesystem. Symlinks will be
dereferenced along with path aliases like "~".
@param path <str>:
Path on the file sytem
@return npath <str>:
Returns a normalized and absolute path
"""
# Normalize references to hom... | 60d787efad9949701350765894fa89b2b9307a56 | 626,712 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.