content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import os
import getpass
def get_auth(s):
""" Parse USER[:PASS] strings and prompt for password if none was
supplied. """
user, _, password = s.partition(':')
password = password or os.environ.get('PASS') or getpass.getpass()
return user, password | 98b20551077e515d08b5e2042bb4d722b7877358 | 694,512 |
def _R2FromGaussian(sigmax, sigmay, pixel=0.1):
"""
R2.
"""
return (sigmax*pixel)**2 + (sigmay*pixel)**2 | 90a2db0d8c7f9c29870308e83afa23ac8747af61 | 694,513 |
import logging
import sys
def init_logger(quiet_mode, log_level=logging.INFO):
""" Initializes the Python logging module for DVR-Scan.
The logger instance used is 'dvr_scan'.
"""
logger = logging.getLogger('dvr_scan')
logger.setLevel(log_level)
if quiet_mode:
for handler in logger.ha... | 51273ed7e1c82a96fd800eac14d801caf92df41e | 694,514 |
import glob
import os
def FindFilesIn(directory, pattern):
""" Returns the list of all files in 'directory' matching the glob 'pattern'. """
return glob.glob(os.path.join(directory, pattern)) | bac4bd208c4cda0558791e691ede52c5c479a45b | 694,515 |
import math
def freqToBark(freq):
"""
Converts from frequency into Bark scale.
"""
return 13 * math.atan(0.00076 * freq) + 3.5 * math.atan( (freq/7500) ** 2) | 0d2a4b9fbb0398f1e1452e861058f30eec50be79 | 694,517 |
def merge_nested_dicts(base, more):
"""Given two dictionaries that may contain sub-dictionarie, merge *more* into
*base*, overwriting duplicated values.
"""
for key, val in more.items():
if isinstance(val, dict):
base_val = base.setdefault(key, {})
if not isinstance(bas... | d6a2d835dfcb56739dd10554c4138f747b4b1f0e | 694,518 |
def convert(number):
"""
Convert a number into a string that contains raindrop sounds corresponding
to certain potential factors.
"""
raindrop = ""
if number % 3 == 0:
raindrop += "Pling"
if number % 5 == 0:
raindrop += "Plang"
if number % 7 == 0:
raindrop += "Pl... | 671804dbe1122cdc86e3aac16ee1415b00b3b274 | 694,519 |
from pathlib import Path
def validate_path(path, allow_none=True):
"""
When we have multiple types of files and directories, some may be allow to be None as they will not be required
whilst others like the working directory will always be required. This method is a generalisation of individual
setters... | 7cfffa844438b76ee00a69b30b5ba8347c48615c | 694,520 |
def _xor(mat,other,obj,m):
"""
Can only be used with '^' operator
"""
if mat.BOOL_MAT:
if isinstance(other,obj):
if mat.dim!=other.dim:
raise ValueError("Dimensions of the matrices don't match")
if not other.BOOL_MAT:
raise TypeError("Can'... | 8e3f08236897c91edabf6a80383f0b886c35cfb6 | 694,521 |
def _default_config() -> dict:
"""
Creates a default configuration, used if none was provided or if the provided configuration did not cover all values.
Please be careful with the spelling of the dictionary.
:return: The default configuration of the program.
"""
default_config = {}
# Progra... | 80e3c380153976ffb50fd71f969810fe93fa5c68 | 694,522 |
def expandBox(box, facs):
"""Expands a `box` about its center by the factors ``(x-factor, y-factor)``.
The box is given as ``(x0, y0, x1, y1)``"""
w, h = box[2]-box[0], box[3]-box[1]
cen = cx, cy = (box[2]+box[0])/2.0, (box[1]+box[3])/2.0
nw2 = w*facs[0]/2.0
nh2 = h*facs[1]/2.0
box = [cx-nw2... | 4d80e5d6e0b1db31cc615f1b1a6fdb265623775f | 694,523 |
def sum_hex_digits(ascii_hex_str):
"""
This method will take an ascii hex string and sum each of the bytes
returning the result as hex.
:param ascii_hex_str: The ascii hex string to sum
:return:
"""
len_of_ascii_hex = len(ascii_hex_str)
if len_of_ascii_hex % 2 != 0:
raise Value... | 2976111c89477aa8e34b6b89124f3f73c89a02c7 | 694,524 |
def get_unique_name(name, elems):
"""
Return a unique version of the name indicated by incrementing a numeral
at the end. Stop when the name no longer appears in the indicated list of
elements.
"""
digits = []
for c in reversed(name):
if c.isdigit():
digits.append(c)
... | ead72253480ae774b830b82119e91db848504348 | 694,525 |
def remove_comment(stream):
""" Remove the tokens until the end of the comment is reached.
Assumes the comment *is* there.
:param stream: A token stream.
:type stream: shlex.shlex
:returns: new_stream
:rtype: shlex.shlex
"""
stream.get_token()
for token in stream:
if token == "`":
stream.push_token... | cd0394a1c526dee46add38d2d9972903579f1739 | 694,526 |
from argparse import ArgumentParser
from argparse import RawTextHelpFormatter
def create_parser():
"""Parse command line args"""
descr = '''Trigger build on Jenkins using a configuration from yaml files'''
op = ArgumentParser(description=descr, formatter_class=RawTextHelpFormatter)
op.add_argument(... | 4c8518d90bac2ffdcad92e682e54612dbc79bb00 | 694,527 |
import os
def get_api_key() -> str:
"""Gets the api key from environment variable. In the future, this
can be extended to also get from disk or something."""
API_KEY = os.environ.get("RIOT_API_KEY", "")
return API_KEY | e9f6700f893028ea9305e9226872da3ea7522ccc | 694,528 |
import re
def flair_template_checker(input_text):
"""Small function that checks whether a given input is valid as a
Reddit post flair ID.
"""
try:
regex_pattern = r"^[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}$"
valid = re.search(regex_pattern, input_text)
except T... | 242717f499a632d57765754f9872728ae6433fcc | 694,529 |
def _index_to_timestamp(index):
"""Convert a pandas index to timestamps if needed.
Needed to parse pandas PeriodIndex to pyplot plotting functions."""
return index.to_timestamp() if hasattr(index, 'to_timestamp') else index | 93fdd7bff3e32247b9b4648c75e75e63244ad17c | 694,530 |
import time
def gen_timestamp() -> int:
"""gen_timestamp.
Generate a timestamp.
Args:
Returns:
int: Timestamp in integer representation. User `str()` to
transform to string.
"""
return int(1.0 * (time.time() + 0.5) * 1000) | 1197eee6d349d6c1e3e5fd017920fa56f15a0f0b | 694,531 |
def read_rttm(rttm, lines):
"""Reads in SPEAKER lines from RTTM file."""
with open(rttm) as f:
for line in f:
if "SPEAKER" in line:
fname = line.split()[1]
if fname not in lines:
lines[fname] = []
lines[fname].append(line)
... | d45a836a9c04918e97dbe4c715dfe42336fd1dd4 | 694,532 |
def receive_data_in_chunks(sock, buffersize):
"""Receive data in chunks of size buffersize from the socket"""
chunk = sock.recv(buffersize)
chunks = [chunk]
# keep reading until chunks are available
while len(chunk.strip()):
chunk = sock.recv(buffersize)
chunks.append(chunk)
da... | a3953a9240c021b41495f58e06ae77d2f5e0d9c9 | 694,534 |
def italic(s):
"""Returns the string italicized.
Source: http://stackoverflow.com/a/16264094/2570866
:param s:
:type s: str
:return:
:rtype: str
"""
return r'\textit{' + s + '}' | 333685c359212d4db1177a951e873f7652faa65d | 694,535 |
def pilatus_300K_mask():
"""Hard coded mask regions for a Pilatus 300K instrument."""
return [[1, 487, 196, 212], [1, 487, 408, 424]] | 2bad00c5ec3c1fd2bcb0685e7fc2416d3d8d0f9a | 694,536 |
def _nt_sum(cobj, prop, theta):
"""
Create sum expressions in n-t forms (sum(n[i]*theta**t[i]))
Args:
cobj: Component object that will contain the parameters
prop: name of property parameters are associated with
theta: expression or variable to use for theta in expression
Retur... | 7ef4674b27069d2e254ef2cb1839fbc67c571029 | 694,537 |
def normalize(f, means, stddevs):
"""
"""
normalized = (f/255 - means) / stddevs
return normalized | 67000bbc2ce8e9bf0c1dadd15c52a395460478ee | 694,538 |
def progress_sidebar_dialog():
"""
Generate the HTML to display analyze progress in a sidebar.
"""
html_message = '''
<script>
var interval = 1250; // ms
var expected = Date.now() + interval;
setTimeout(progressUpdate, 10);
function progressUpdate() {
var dt = Date.now() - ex... | 07f4ed824e9a67936414400d5c1ba30caea13cba | 694,539 |
def calc_max_length(tensor):
"""Find the maximum length of any tensor"""
return max(len(t) for t in tensor) | 21ad43f14d8952261a45b8efcd927b82eadc83bd | 694,540 |
def make_tuple(t):
"""
return the input if it's already a tuple.
return a tuple of the input if the input is not already a tuple.
"""
return t if isinstance(t, tuple) else (t, t) | 70fd74c76db30f866b3d248d6444c2d02b31f36c | 694,541 |
def intersection(v1, v2):
"""
Returns the intersection of v1 and v2. Note however that these are not 'bezier lines', x1, y1, x3, and y3
are all *changes* in x, not describing a point. So, rather than x0 + (x1 - x0)*t, its just x0 + x1*t.
It just made the algebra slightly easier.
list v1 = [x0, x1, y... | 159015b0c46a1079712f89ba7105eee034bb691c | 694,542 |
def char_array_to_string(arr):
"""
Converts a NumPy array of byte-long ASCII codes into an ASCII string.
e.g. [65, 67, 71, 84] becomes "ACGT".
"""
return arr.tostring().decode("ascii") | b5bc74ad96a34d619311ca6226075a3378989f3d | 694,544 |
def get_column_headers(worksheet) -> list:
"""Get list of column headers from Excel sheet."""
num_columns = worksheet.max_column
headers = []
for j in range(1, num_columns+1):
cell_obj = worksheet.cell(row=1, column=j)
headers.append(cell_obj.value)
return headers | 3181f8e9d3e9fa1e0967f4edd1090032e0f773ed | 694,545 |
def combine_atomco_dict(dict_1, dict_2):
"""
Combine 2 dict of atomco_dict.
Return a new combined dict.
>>> a.atomco_dict
>>> {'C': [['2.01115823704755', '2.33265069974919', '10.54948252493041']],
'Co': [['0.28355818414485', '2.31976779057375', '2.34330019781397'],
['2.76900... | d892443e28f69493e4ded5bc50a42fa74fcc2395 | 694,546 |
def unpacked_properties(full_prop_name, count=2):
"""Return properties that "unpack" a tuple property
For example, if a class defines::
x, y = unpacked_properties('pos')
then ``obj.x`` will return the same as ``obj.pos[0]``, and setting
``obj.x`` will update ``obj.pos`` to (new x, old y).
""... | cfd911afc1a313d8a5fda7d82e2a3825566ea59a | 694,547 |
import re
def get_coffecient_3d(equation):
"""
Returns the coefficients and intercept of the 2nd degree term in an equation.
:param : eg: 2x+3y=7
:return: eg: (2,3,7)
"""
try:
coef_x = re.findall('-?[0-9.]*[Xx]', equation)[0][:-1]
except:
coef_x = 0.0
try:
coef... | 89ebb176941f10a659ad03f789a0ccd1617f44c6 | 694,548 |
import os
def find_packages():
"""adapted from IPython's setupbase.find_packages()"""
packages = []
for dir,subdirs,files in os.walk('zmq'):
package = dir.replace(os.path.sep, '.')
if '__init__.py' not in files:
# not a package
continue
packages.append(packa... | 61ea0267f414f0e2769c0ca24f363e5ac1a37790 | 694,550 |
def SetWriterMolProps(Writer, Mol):
"""Setup molecule properties for a writer to output.
Arguments:
Writer (object): RDKit writer object.
Mol (object): RDKit molecule object.
Returns:
object : Writer object.
"""
PropNames = list(Mol.GetPropNames())
if len(PropNames... | 2e4553c99fbd9c82e1ef451530d8bc10d7e18cf7 | 694,551 |
def retrive_experiments(experiment_paths):
""" Grab all experiments from paths
"""
all_dat_files = []
all_info_files = []
all_recording_message_files = []
for experiment_loc in experiment_paths:
dat_files = list(experiment_loc.glob("**/*.dat"))
info_files = list(experiment_loc.gl... | 41a92787732f78539dd4f94b7aa2373e783c5e44 | 694,552 |
def apply_noun_verb(initial_program, noun, verb):
""" Applies noun verb to program
>>> [1,2,3,4]
[1,12,2,4]
>>> [5,5,5,5]
[5,12,2,5]
"""
return initial_program[:1] + [noun,verb] + initial_program[3:] | fe3c400ecb053b9d6e60e8c82657b32914562e71 | 694,553 |
def init_task(parts, name='init-pdpart'):
"""Create a doit task to initialize a Partitioned directory.
Parameters
----------
parts : pdpart.Partitioned
Partitioned object to be initialized
name : str
name of task, defaults to 'init-pdpart'
"""
def _wrapper():
"""with... | a8c1cb27461b48b5c9f0a8733b058a24403a5227 | 694,554 |
def check_created_project_structure(context):
"""Behave step to check the subdirectories created by kedro new."""
def is_created(name):
"""Check if path exists."""
return (context.root_project_dir / name).exists()
for path in ("README.md", "src", "data"):
assert is_created(path) | 1e92ec7bf16d2c2cfb40a6be43c60b835765e757 | 694,555 |
def partition(l, size):
"""
Partition the provided list into a list of sub-lists of the provided size. The last sub-list may be smaller if the
length of the originally provided list is not evenly divisible by `size`.
:param l: the list to partition
:param size: the size of each sub-list
:retur... | 6d24bdf1b8e46450b7070c2819180cf40fd418b3 | 694,556 |
from datetime import datetime
def time_fin(start_time):
"""
Return the execution time of a script.
It requires the initialization with the function time_ini().
"""
return str(datetime.now()-start_time) | 1a9f6c1f665edb86425f57006c24b2cb71011f2e | 694,558 |
def is_even(x):
"""
Return whether or not an integer ``x`` is even, e.g., divisible by 2.
EXAMPLES::
sage: is_even(-1)
False
sage: is_even(4)
True
sage: is_even(-2)
True
"""
try:
return x.is_even()
except AttributeError:
return x ... | 6149a4e266070d6d0dd0b7f03df30e3ee1685edf | 694,559 |
import logging
def get_logger(name='default'):
"""Return the logger with name value automatically or editable by name param."""
name = locals().get('__name__') if name == 'default' else name
return logging.getLogger(name) | f73f507b588e085dd1d261cef6f72a9d390b3285 | 694,561 |
def drop(n):
"""Drop n items from collection (first in dropped)."""
def generator(coll):
for i, item in enumerate(coll):
if i >= n:
yield item
return generator | 1852389372010ba6652e653e9c605a94859a24ca | 694,562 |
def key_set(d):
"""A set of all the keys of a dict."""
return set(d.iterkeys()) | e5e6ad8d1ad25003689d5a1135c2bd9919ae7729 | 694,563 |
def gimmick(message):
"""Detect if a message is the result of a gib gimmick."""
if message is None:
return False
if message.lower().count("oob") > 3:
return True
if message.lower().count("ob") > 4:
return True
if message.isupper():
return True
return False | 91f8ffa77e8ddddeb7b7de2b39809b964ffb502b | 694,564 |
import string
def get_first_link(links: str):
""" Get first link from base64 string """
index = 0
length = len(links)
while index < length:
if not links[index] in string.printable:
return links[:index]
index += 1 | c250098043cb1393732a73946aa3f40056803e0b | 694,565 |
import logging
def find_files(wavdir, txtdir):
"""Search for files in given directories."""
files_dict = {}
dir_txt_list = list(txtdir.glob("**/*.txt"))
for wav in wavdir.glob("**/*.wav"):
stem = wav.stem
txt = None
for item in dir_txt_list:
if item.stem == stem:
... | 80eec845ae0df97a750e3114e2ed527483abd226 | 694,566 |
def print_results(content: dict):
"""
:param content:
:return:
"""
print("[+] Listing results ({}) :".format(len(content["result"])))
for index, elt in enumerate(content["result"]):
print("[-] {}-) {}".format(index + 1, elt["key"]))
return int(input("\n[?] Your choice (0 to quit):"... | bb96e7aec631c18304cd865add191160a9491fa5 | 694,567 |
import yaml
def load_yaml(data):
"""Parse a unicode string containing yaml.
This calls ``yaml.load(data)`` but makes sure unicode is handled correctly.
See :func:`yaml.load`.
:raises yaml.YAMLError: if parsing fails"""
class MyLoader(yaml.SafeLoader):
def construct_yaml_str(self, node)... | f55e144582707d603d263066ef3555049d2ea377 | 694,568 |
def getReadTimeout():
"""Returns the read timeout in milliseconds for all
client-to-gateway communication.
This is the maximum amount of time allowed for a communication
operation to complete. The default is 60,000 ms (1 minute).
Returns:
int: The current read timeout, in milliseconds. De... | 107d30b1c95fad3db963fa87eba9e1071c93c0bf | 694,569 |
def convert_number(n):
"""
Convert number to , split
Ex: 123456 -> 123,456
:param n:
:return:
"""
if n is None:
return '0'
n = str(n)
if '.' in n:
dollars, cents = n.split('.')
else:
dollars, cents = n, None
r = []
for i, c in enumerate(str(dollar... | 4c722bb1a0ca65d956ef8fa3118acd7c23359e5e | 694,570 |
def _serialize_agent(controlamp):
"""
Serialize a connected ``ControlAMP`` to the address of its peer.
:return: A string representation of the Twisted address object describing
the remote address of the connection of the given protocol.
:rtype str:
"""
return str(controlamp.transport.g... | f3f7382ed9a117e3575349c7067215964dfa33a2 | 694,571 |
def merge(l_arr, r_arr):
"""
:param l_arr:
:param r_arr:
:return:
"""
l_idx = r_idx = 0
res = []
while len(l_arr) > l_idx and len(r_arr) > r_idx:
if l_arr[l_idx] < r_arr[r_idx]:
res.append(l_arr[l_idx])
l_idx += 1
else:
res.append(r_ar... | c55a548a56eb3a996029dbe26506e483b49354a6 | 694,572 |
from typing import Dict
from typing import List
def process_group_mappings(
group_mapping_config: Dict[str, dict], sso_attributes: dict, groups: List[str]
):
"""Processes the groups from the mapping rule config into discourse compatible formats
Args:
group_mapping_config (Dict[str, dict]): Predef... | 53643ab55607837ce04ce4a7a3637b558780fd08 | 694,573 |
import hashlib
def _plan_hash_str(fn):
"""returns a hash digest for a file, ideally a super-unique one"""
# from: http://stackoverflow.com/questions/3431825/generating-a-md5-checksum-of-a-file
afile = open(fn, 'rb')
hasher = hashlib.sha256()
blocksize = 65536
buf = afile.read(blocksize)
wh... | 62841a3dc2ca44b9e7f1902175462c884494b758 | 694,574 |
def get_literal_type(value):
"""Get the data type
:param value: The data
:return: The data type as a string
:rtype: str
"""
return type(value).__name__ | ed0fe2541f2439f98be14345bc622c9d49b3165b | 694,575 |
import yaml
def parsed_site_config(site_config_yml):
"""Fixture that returns the parsed contents of the example site config YAML file in the resource directory"""
return yaml.load(site_config_yml, Loader=yaml.SafeLoader) | 71c692dc80cb631d813bf9e53d98b0e1cd9e5a9d | 694,576 |
import numpy
def _centers_dense(X, sample_weight, labels, n_clusters, distances,
X_sort_index):
"""
M step of the K-means EM algorithm.
Computation of cluster centers / means.
:param X: array-like, shape (n_samples, n_features)
:param sample_weight: array-like, shape (n_samples... | 509e0e64f6a4cebac1ec6fc4f78857becee73c64 | 694,578 |
import inspect
import six
def _GetArgSpecFnInfo(fn):
"""Gives information pertaining to computing the ArgSpec of fn.
Determines if the first arg is supplied automatically when fn is called.
This arg will be supplied automatically if fn is a bound method or a class
with an __init__ method.
Also returns the... | 939d7e0a5f49f317d881638fd77be26f379f5e9a | 694,579 |
def parse_raw_data_catalog(raw_data_catalog):
""" Clean up the raw data catalog dataframe """
filtered_data_catalog = raw_data_catalog[
[
"tocL1",
"tocL2",
"tocL3",
"reference_designator",
"platform_code",
"mooring_code",
... | adc0fcc2da25ccaa899f5f833dc56b339d1d838b | 694,580 |
from typing import Dict
from typing import Any
from typing import Tuple
import os
def check_status(data: Dict[str, Any]) -> Tuple[int, str]:
"""Check if the process is alive.
Return (pid, sockname) on success.
Raise SystemExit(<message>) if something's wrong.
"""
if 'pid' not in data:
ra... | e5f243885b9bdcb8ab92be2c925eeb6b4996bf5e | 694,581 |
import torch
def sample_gumbel(score, sampling_number=5, eps=1e-10):
"""
Args:
score : [batch x num_tasks]
"""
tmax, _ = torch.max(score, dim=-1)
tmin, _ = torch.min(score, dim=-1)
score = score / (tmax - tmin).unsqueeze(1)
score = score * score.size(1)
batch_size = score.si... | 61df970ab25aa9c32d539252f60738c526823617 | 694,582 |
def to_str(name=None, email=None):
""" To Str """
string = ""
if name:
string += name
if name and email:
string += " "
if email:
string += "<" + email + ">"
return string | 1cc8a6a5dc68f05d8193ce2c41e88d76a012a2f6 | 694,583 |
def gradezero(evtdata):
""" Only accept counts with GRADE==0.
Parameters
----------
evtdata: FITS data class
This should be an hdu.data structure from a NuSTAR FITS file.
Returns
-------
goodinds: iterable
Index of evtdata that passes the filtering.
"""... | 370bbf16b25d9543b7e485f0e366b709d6261dfb | 694,584 |
def unicode_replacements(latex):
"""Take in latex and replaces specific unicode characters with latex symbols."""
operations = (
# unicode operators
("\xe2\x88\x92", '-'),
("\xc3\x97", r'\times'),
# unicode_superscripts
("\xc2\xb0", r'\text{$^\circ$}'),
("\xe2\x8... | 0d0c7a00bd2d5bd327398639833d447d433f7156 | 694,585 |
def exists_db(connection, name):
"""Check whether a database exists.
:param connection: A connection
:param name: The name of the database
:returns: Whether the db exists
:rtype: bool
"""
exists = connection.execute("SELECT 1 FROM pg_database WHERE datname = {}".format(name)).first()
co... | 2a729b85cbf9e9cdc30970bcaa4258a7ff8a97fb | 694,586 |
def _ggm_qcondwait_whitt_ds3(cs2):
"""
Return the approximate E(V^3)/(EV)^2 where V is a service time; based on either a hyperexponential
or Erlang distribution. Used in approximation of conditional wait time CDF (conditional on W>0).
Whitt refers to conditional wait as D in his paper:
See Whitt, ... | fb6f4cadafeae2f3cb29200a4ae3402a0317c63a | 694,587 |
def is_blank_line(p):
"""
If p is all whitespace then p.strip will be null (hence false)
thus not p.strip is true if p is all whitespace
"""
if not p.strip():
return True
return False | e0ecf3eba7b2a5a4dcc193150cc483457df557cc | 694,589 |
import argparse
def _get_parser():
"""Returns an argument parser for this script."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output', required=True, help='The output file name')
parser.add_argument('--name', required=True, help='The library name')
parser.add_ar... | 35cfc8ea92e7b97e0f1ebcd810860e793dc251a2 | 694,590 |
import re
import click
def validate_mfa_device_name(ctx, param, value):
"""Validates a virtual MFA device name."""
try:
if not all([re.match(r"[\w+=/:,.@-]+", value), 9 <= len(value) <= 256]):
raise ValueError(value)
return value
except ValueError:
click.echo('Invalid d... | be3801383ebe2e4c2aed42b2e29601987dffc283 | 694,591 |
import re
def listWithRedshift(filenames):
"""reorder the files by redshift and return a dictionary
{z,filenames}
"""
shortdict=[]
longdict={}
for filename in filenames:
match=re.search('_z([0-9.]+)',filename)
if match:
z=float(match.group(1))
else:
... | 90b928fa17a89a953d8e4f51d8f541d0a32339f1 | 694,592 |
import typing
from datetime import datetime
def create_timestamp(
time: typing.Optional[typing.Union[datetime, int, float]] = None,
style: typing.Optional[str] = None,
) -> str:
"""Creates a markdown timestamp from the given datetime object or unix timestamp.
Parameters
----------
time: Opti... | 38a18e5f8f5d00092ff9bee5efa25534451667d7 | 694,593 |
def is_prime(n, s=[], ps=[]):
""" Check whether a reasonably small number is prime or not.
The user has the responsability to provide a big enough list of primes.
The function will return True if it can't find a prime that divides n.
Parameters
----------
n: int
Number to check
... | 4b6ff4891ea3eb59313dc849d383828ecc9876d2 | 694,594 |
import os
def file_status(filename):
""" confirms that a raw file isn't empty """
if os.path.exists(filename):
with open(filename, "r") as testfile:
line = testfile.readline()
if line:
status = "ok"
else:
status = "bad"
else:
status = "... | f284a85cf5d5e3a3c51cf826f8cfd35142cf7304 | 694,595 |
def set_vacuum_chamber(the_line):
"""."""
# -- default physical apertures --
for i in range(len(the_line)):
the_line[i].hmin = -0.018
the_line[i].hmax = +0.018
the_line[i].vmin = -0.018
the_line[i].vmax = +0.018
return the_line | 43b95d7e4110c4620e26f6fb56c23cd80331dba6 | 694,596 |
import json
def write_to_json_file(obj, filename):
"""
Write on file filename the object in JSON format
:param obj: object to be written on the JSON file
:param filename: filename to be used to store the obj
:return: success (bool)
"""
f = open(filename, "w")
try:
json.dump(o... | c074e379c51b0cc3468f812552ee3176e64eda51 | 694,597 |
def orbital_eccentricity(t: float) -> float:
"""
Calculate the eccentricity of earth's orbit around the sun.
Parameters:
t (float): The time in Julian Centuries (36525 days) since J2000.0
Returns:
float: The earth's orbital eccentricity at the given time
"""
# t must be in the ... | d971c059259c875b00041a7cd558af628af1df09 | 694,598 |
def chain(*brules):
"""
Compose a sequence of brules so that they apply to the expr sequentially
"""
def chain_brl(expr):
if not brules:
yield expr
return
head, tail = brules[0], brules[1:]
for nexpr in head(expr):
for nnexpr in chain(*tail)(n... | bec1967e391963bcf05e60d6ad4667de29e7c046 | 694,600 |
def tagsAssoPerson(cnx,person,domain):
"""
Function to determine tags related to a person in the given domain
:param cnx: connection object
:param person: user with whom the tags are associated
:param domain: domain id of the desired topic
:return: list of tags associated with the user
"""
... | 188363fdee34a1ccbc94941e5fdb60dcbc529b3a | 694,601 |
def type_prefix(typ) -> bytes:
"""
Return the prefix string for the given type.
The prefix determine the type of the expected object.
"""
return b'o' | 852d5802e912d0efd685e99c581e11670674d23e | 694,602 |
import sys
def is_interactive() -> bool:
"""Determines whether shell is interactive.
A shell is interactive if it is run from `python3` or `python3 -i`.
"""
return hasattr(sys, "ps1") | 52d058166381b9900e8ee032fec585b9148ad0f0 | 694,603 |
def parseEntries(data, type):
"""
parse the results of CEA or CPA task in both old and new notation
returns new notation as in { key1: X, key2: x, mapped: y }
"""
# no data at all
res = []
if not data:
pass
# new notation
elif isinstance(data, list):
res = data
# ... | ac4d7cc03ae9708e255a9d4a5a469ff84eade2d5 | 694,604 |
import argparse
def create_arg_parser():
""""Creates and returns the ArgumentParser object."""
parser = argparse.ArgumentParser(description='Converts Dataturks output JSON file for Image bounding box to Pascal VOC format.')
parser.add_argument('dataturks_JSON_FilePath',
help='Path to ... | 65c835561719036dbc1a8daa944fdd73dabe6e51 | 694,605 |
def get_options_dict(activation, lstm_dims, lstm_layers, pos_dims):
"""Generates dictionary with all parser options."""
return {
"activation": activation,
"lstm_dims": lstm_dims,
"lstm_layers": lstm_layers,
"pembedding_dims": pos_dims,
"wembedding_dims": 100,
"rem... | 3188383baf1023b2bd0bc4352dbad14e184192af | 694,606 |
def adjust_learning_rate(optimizer, epoch, cfg):
"""decrease the learning rate at 200 and 300 epoch"""
lr = cfg['lr']
if epoch >= 20:
lr /= 10
if epoch >= 60:
lr /= 10
for param_group in optimizer.param_groups:
param_group['lr'] = lr
return lr | 51f702c665bd933cf67faa933adb9fcc32e75031 | 694,607 |
def update_grad_w(grad, grad_old, grad_new):
"""Update the global gradient for W
Parameters
----------
grad: theano tensor
The global gradient
grad_old: theano tensor
The previous value of the local gradient
grad_new: theano tensor
The new version of the local gradient... | 74015b8987fa7af0bc6bbb4d9de3d96c1d83b5d8 | 694,608 |
def product(list):
"""
Returns a product of a List
:param list:
:return:
"""
prod = 1
for e in list:
prod = prod * e
return prod | 900ff8b30be04a0f6e440fa47ece772846c890e3 | 694,609 |
def fake_chat_dict():
"""Return a fake, minimalist Telegram chat as dict."""
return {
'id': 123,
'type': 'group'
} | 012b4a07d02e46870a5cbd27e09f2a9a089de365 | 694,610 |
def map_indices_py(arr):
"""
Returns a dictionary with (element, index) pairs for each element in the
given array/list
"""
return dict([(x, i) for i, x in enumerate(arr)]) | d045d57ec95be50f2c1ab3f46e22b93ab3568637 | 694,611 |
import re
def update_pr_links(repo_name, notes_list):
"""
Replace the internal repo PR link with the external repo PR link
in each release note.
"""
result = []
matcher = re.compile(".*\(#(?P<pr_number>[0-9]+)\)$")
# e.g. gets the PR number ("12") from "some description (#12)"
for note... | edb6e399af5a0aeded6c970c1602e6b742119055 | 694,612 |
import numpy
def _img_color_distance(img, color):
"""calculate the distance of each pixel to a given color
:param img: a numpy.array of shape (y, x, 3)
:param color: a color tuple (r, g, b)
:return: a numpy.array of shape (y, x) where each value is a float 0-1
representing the distance t... | af85f22d68d2e0b2a1d0ba0da8bb7c9452f11d09 | 694,613 |
def group_data_by_column(dataframe, columns=('label',)):
"""
Transform any dataframe to dataframe with groupped data by given fields
:param dataframe: pandas dataframe
:param columns: fields to group by
:return:
"""
return dataframe.groupby(list(columns)) | 36596d116da94ae43844f7d29dd1600c93c23b2f | 694,614 |
import pathlib
import os
def create_hugectr_backend_config(
model_path,
model_repository_path='/models'):
"""Creates configurations definition for HugeCTR backend."""
p = pathlib.Path(model_path)
model_version = p.parts[-1]
model_name = p.parts[-2]
model_path_in_repository = os.path.join(model_repo... | 750c33370628a34824403431bcc1e8d1b70da816 | 694,615 |
import requests
def _download_collection(url):
"""
Download all pages in a paginated mgnify data collection
This returns a single structure with all entries appended to result['data']
"""
result = {'data': []}
while url is not None:
resp = requests.get(url, params={'page_size': 100}).j... | 31c5af3480a40f0cc700cfb81235cca7ab094469 | 694,616 |
def get_lineitems(actblue_values, mapping):
"""
Parse information we need from ActBlue line items.
Returns a list of dictionaries, one dict per line item.
"""
knack_lineitems = []
lineitems = actblue_values['lineitems']
amount_key = mapping['lineitems#amount']
entity_key = mapping['line... | 31e0a00635332a44b6815403e0c2dc3b51eb2461 | 694,617 |
def has_function(faker, key):
""" helper function to check if a method is available on an object"""
return hasattr(faker, key) | c57020222be5f7a336f2773a2e80a85c4eac867f | 694,619 |
def outlierStats(outlier_list):
"""Takes a list of outliers and computes the mean and standard deviation"""
try:
outlierMean = outlier_list.mean()
outlierStdev = outlier_list.std()
return outlierMean, outlierStdev
except TypeError :
explanation = "Cannot compute statistics on... | 98aeec98faa3eff4ce576e9ad4a3331f54d7a25d | 694,620 |
import os.path
def get_c_sources_dir():
"""
Return directory containig sources for building your own modules.
"""
return os.path.abspath(os.path.dirname(__file__)) | d9017fdd9b4baf5a9d0f65a1b288adbe05a331d6 | 694,621 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.