content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def yes_or_no(question, default="no"):
"""
Returns True if question is answered with yes else False.
default: by default False is returned if there is no input.
"""
answers = "yes|[no]" if default == "no" else "[yes]|no"
prompt = "{} {}: ".format(question, answers)
while True:
answe... | 496137bcd3d99a3f0bcc5bb87ab3dc090f8fc414 | 706,965 |
def decode(encoded: list):
"""Problem 12: Decode a run-length encoded list.
Parameters
----------
encoded : list
The encoded input list
Returns
-------
list
The decoded list
Raises
------
TypeError
If the given argument is not of `list` type
"""
... | 8fb273140509f5a550074c6d85e485d2dc1c79d0 | 706,966 |
def geom_cooling(temp, k, alpha = 0.95):
"""Geometric temperature decreasing."""
return temp * alpha | 4263e4cc8a5de21d94bc560e8ff364d8c07f97fd | 706,971 |
import re
def bytes_to_escaped_str(data, keep_spacing=False, escape_single_quotes=False):
"""
Take bytes and return a safe string that can be displayed to the user.
Single quotes are always escaped, double quotes are never escaped:
"'" + bytes_to_escaped_str(...) + "'"
gives a valid Python st... | fe8aa0ed3a8e3f2c7a2cf1aaeebc555b7281bde7 | 706,972 |
from datetime import datetime
def datetime_to_timestamp(dt, epoch=datetime(1970,1,1)):
"""takes a python datetime object and converts it to a Unix timestamp.
This is a non-timezone-aware function.
:param dt: datetime to convert to timestamp
:param epoch: datetime, option specification of start of ep... | 2fbd5b3d6a56bc04066f7aaa8d4bef7c87a42632 | 706,982 |
def connectivity_dict_builder(edge_list, as_edges=False):
"""Builds connectivity dictionary for each vertex (node) - a list
of connected nodes for each node.
Args:
edge_list (list): a list describing the connectivity
e.g. [('E7', 'N3', 'N6'), ('E2', 'N9', 'N4'), ...]
as_edges (b... | 58f24c6465fa1aaccca92df4d06662b0ce1e1e77 | 706,983 |
def calc_recall(TP, FN):
"""
Calculate recall from TP and FN
"""
if TP + FN != 0:
recall = TP / (TP + FN)
else:
recall = 0
return recall | 8f3513e11f8adad111eee32740c271aad31fbe28 | 706,992 |
def make_segment(segment, discontinuity=False):
"""Create a playlist response for a segment."""
response = []
if discontinuity:
response.append("#EXT-X-DISCONTINUITY")
response.extend(["#EXTINF:10.0000,", f"./segment/{segment}.m4s"]),
return "\n".join(response) | 8419b100409934f902c751734c396bc72d8a6917 | 706,993 |
from typing import Any
def from_dicts(key: str, *dicts, default: Any = None):
"""
Returns value of key in first matchning dict.
If not matching dict, default value is returned.
Return:
Any
"""
for d in dicts:
if key in d:
return d[key]
return ... | 508febc48fd22d3a23dc0500b0aa3824c99fdbc3 | 706,994 |
def time_in_words(h, m):
"""Hackerrank Problem: https://www.hackerrank.com/challenges/the-time-in-words/problem
Given the time in numerals we may convert it into words, as shown below:
----------------------------------------------
| 5:00 | -> | five o' clock |
| 5:01 | -> | one m... | 85f2247f01df36ef499105a9940be63eee189100 | 706,995 |
def concat_files(*files):
"""
Concat some files together. Returns out and err to keep parity with shell commands.
Args:
*files: src1, src2, ..., srcN, dst.
Returns:
out: string
err: string
"""
out = ''
err = ''
dst_name = files[-1]
sources = [files[f] for f ... | 101c37e5b3955c153c8c2210e7575a62341c768a | 706,998 |
def midi_to_chroma(pitch):
"""Given a midi pitch (e.g. 60 == C), returns its corresponding
chroma class value. A == 0, A# == 1, ..., G# == 11 """
return ((pitch % 12) + 3) % 12 | 25ef72f78269c3f494ca7431f1291891ddea594a | 707,005 |
import re
def _snippet_items(snippet):
"""Return all markdown items in the snippet text.
For this we expect it the snippet to contain *nothing* but a markdown list.
We do not support "indented" list style, only one item per linebreak.
Raises SyntaxError if snippet not in proper format (e.g. contains... | bdeb5b5c5e97ef3a8082b7131d46990de02a59af | 707,006 |
import itertools
import re
def parse_cluster_file(filename):
"""
Parse the output of the CD-HIT clustering and return a dictionnary of clusters.
In order to parse the list of cluster and sequences, we have to parse the CD-HIT
output file. Following solution is adapted from a small wrapper script
... | d50eaeb926be3a7b8d1139c82142e4a1b595c1a0 | 707,011 |
import base64
def decode_password(base64_string: str) -> str:
"""
Decode a base64 encoded string.
Args:
base64_string: str
The base64 encoded string.
Returns:
str
The decoded string.
"""
base64_bytes = base64_string.encode("ascii")
sample_st... | 0f04617c239fbc740a9b4c9c2d1ae867a52e0c74 | 707,015 |
from typing import Iterable
from typing import Any
from typing import List
def drop(n: int, it: Iterable[Any]) -> List[Any]:
"""
Return a list of N elements drop from the iterable object
Args:
n: Number to drop from the top
it: Iterable object
Examples:
>>> fpsm.drop(3, [1, 2... | 0732bd560f0da0a43f65ee3b5ed46fd3a05e26f5 | 707,017 |
def csv_args(value):
"""Parse a CSV string into a Python list of strings.
Used in command line parsing."""
return map(str, value.split(",")) | b2596180054f835bfe70e3f900caa5b56a7856a6 | 707,018 |
def reverse( sequence ):
"""Return the reverse of any sequence
"""
return sequence[::-1] | f08ae428844347e52d8dbf1cd8ad07cfbf4ef597 | 707,020 |
def kwargs_to_flags(**kwargs):
"""Convert `kwargs` to flags to pass on to CLI."""
flag_strings = []
for (key, val) in kwargs.items():
if isinstance(val, bool):
if val:
flag_strings.append(f"--{key}")
else:
flag_strings.append(f"--{key}={val}")
retu... | aa672fe26c81e7aaf8a6e7c38354d1649495b8df | 707,025 |
def _groupby_clause(uuid=None, owner=None, human_name=None, processing_name=None):
"""
Build the groupby clause. Simply detect which fields are set, and group by those.
Args:
uuid:
owner:
human_name:
processing_name:
Returns:
(str): "field, ..., field"
"""... | 21546efa19e841661ed3a7ad8a84cf9a9a76d416 | 707,027 |
def has_numbers(input_str: str):
""" Check if a string has a number character """
return any(char.isdigit() for char in input_str) | 5038cb737cdcfbad3a7bd6ac89f435559b67cebc | 707,028 |
import collections
def get_gradients_through_compute_gradients(optimizer, loss, activations):
"""Compute gradients to send to TPU embedding.
Args:
optimizer: a subclass of optimizer.Optimizer, usually CrossShardOptimizer.
Used to call compute_gradients().
loss: a Tensor to call optimizer.compute_gr... | 2a2ebca1e6024e11f541e3ccaf1fee4acd7ab745 | 707,035 |
def AdditionalMedicareTax(e00200, MARS,
AMEDT_ec, sey, AMEDT_rt,
FICA_mc_trt, FICA_ss_trt,
ptax_amc, payrolltax):
"""
Computes Additional Medicare Tax (Form 8959) included in payroll taxes.
Notes
-----
Tax Law Parameters:... | de0e35fbe5c7c09de384e1302cba082149ea5930 | 707,036 |
def get_parameter(dbutils, parameter_name: str, default_value='') -> str:
"""Creates a text widget and gets parameter value. If ran from ADF, the value is taken from there."""
dbutils.widgets.text(parameter_name, default_value)
return dbutils.widgets.get(parameter_name) | cf8359e6acea68ea26e24cc656847e5560019bd1 | 707,039 |
def aic(llf, nobs, df_modelwc):
"""
Akaike information criterion
Parameters
----------
llf : {float, array_like}
value of the loglikelihood
nobs : int
number of observations
df_modelwc : int
number of parameters including constant
Returns
-------
aic : f... | 3940c1c86325630248fdf4a50c2aa19b4f4df623 | 707,040 |
def packpeeklist1(n1, n2, n3, n4, n5):
"""
Packs and returns 5 item list
"""
listp = [n1, n2, n3, n4, n5]
return listp | 4b781ff3e8eb4a1bd51f8e834fab5462371a85c5 | 707,041 |
def gen_gap(Pn, T, Q):
"""Runs the generalization gap test. This test
simply checks the difference between the likelihood
assigned to the training set versus that assigned to
a held out test set.
Inputs:
Pn: (n X d) np array containing the held out test sample
of dimensio... | d57d16c06d05cea86e6f6ea89484574f20500170 | 707,043 |
def create_slice_obj(start, end, step):
"""Create slice object"""
return slice(start, end, step) | 88a5c5a9e0d3b714b4316d8744fcdd1a34f347a7 | 707,047 |
def scalar(typename):
"""
Returns scalar type from ROS message data type, like "uint8" from "uint8[100]".
Returns type unchanged if already a scalar.
"""
return typename[:typename.index("[")] if "[" in typename else typename | 729fb68bced11e190b3d32d03bbadd921f191bee | 707,048 |
from typing import Dict
from typing import Type
def remap_shared_output_descriptions(output_descriptions: Dict[str, str], outputs: Dict[str, Type]) -> Dict[str, str]:
"""
Deals with mixed styles of return value descriptions used in docstrings. If the docstring contains a single entry of return value descripti... | 06d589016a747230f88aa3507bd751fd30095222 | 707,050 |
def fitarg_rename(fitarg, ren):
"""Rename variable names in ``fitarg`` with rename function.
::
#simple renaming
fitarg_rename({'x':1, 'limit_x':1, 'fix_x':1, 'error_x':1},
lambda pname: 'y' if pname=='x' else pname)
#{'y':1, 'limit_y':1, 'fix_y':1, 'error_y':1},
#... | 151233d0f18eaea564afbc6d600d576407504b35 | 707,051 |
def _get_matching_stream(smap, itag):
""" Return the url and signature for a stream matching itag in smap. """
for x in smap:
if x['itag'] == itag and x.get("s"):
return x['url'], x['s']
raise IOError("Sorry this video is not currently supported by pafy") | dc83fd3207d5ab4e1c85eb719f5f7d023131565e | 707,053 |
def linear_search(alist, key):
""" Return index of key in alist . Return -1 if key not present."""
for i in range(len(alist)):
if alist[i] == key:
return i
return -1 | ab4c0517f9103a43509b0ba511c75fe03ea6e043 | 707,058 |
def extract_sigma_var_names(filename_nam):
"""
Parses a 'sigma.nam' file containing the variable names, and outputs a
list of these names.
Some vector components contain a semicolon in their name; if so, break
the name at the semicolon and keep just the 1st part.
"""
var_names = []
wit... | 930e855d47c4303cac28e9973982392489fb577d | 707,060 |
from typing import Any
def all_tasks_stopped(tasks_state: Any) -> bool:
"""
Checks if all tasks are stopped or if any are still running.
Parameters
---------
tasks_state: Any
Task state dictionary object
Returns
--------
response: bool
True if all tasks are stopped.
... | 98edffe71052cc114a7dda37a17b3a346ef59ef8 | 707,062 |
def dataclass_fields(dc):
"""Returns a dataclass's fields dictionary."""
return {name: getattr(dc, name)
for name in dc.__dataclass_fields__} | 4b82af3bfbc02f7bbfcf1aecb6f6501ef10d86e1 | 707,063 |
import pathlib
def _suffix_directory(key: pathlib.Path):
"""Converts '/folder/.../folder/folder/folder' into 'folder/folder'"""
key = pathlib.Path(key)
shapenet_folder = key.parent.parent
key = key.relative_to(shapenet_folder)
return key | 147539065c3d21ee351b23f2d563c662fe55f04a | 707,078 |
def text_to_string(filename, useEncoding):
"""Read a text file and return a string."""
with open(filename, encoding=useEncoding, errors='ignore') as infile:
return infile.read() | f879bb747699496204820b74944fd563658a7117 | 707,080 |
def iscomment(s):
"""
Define what we call a comment in MontePython chain files
"""
return s.startswith('#') | ab3a9d240e423c562c9e83cdd9599fddf144b7c3 | 707,081 |
def CommaSeparatedFloats(sFloatsCSV):
"""Read comma-separated floats from string.
[sFloatsCSV]: string, contains comma-separated floats.
<retval>: list, floats parsed from string.
"""
return [float(sFloat) for sFloat in sFloatsCSV.replace(" ","").split(",")] | 1aa12ca7297aa3bd809f6d2ffaf155233a826b49 | 707,089 |
def topological_sort(g):
"""
Returns a list of vertices in directed acyclic graph g in topological
order.
"""
ready = []
topo = []
in_count = {}
for v in g.vertices():
in_count[v] = g.degree(v, outgoing=False)
if in_count[v] == 0: # v has no constraints, i.e no incomin... | 5ac6261bf1b6fa92280abdc3fc95679ad9294e80 | 707,092 |
from typing import List
from typing import Tuple
def getElementByClass(className: str, fileName: str) -> List[Tuple[int, str]]:
"""Returns first matching tag from an HTML/XML document"""
nonN: List[str] = []
with open(fileName, "r+") as f:
html: List[str] = f.readlines()
for line in html:
... | 969e4070e16dec2e10e26e97cbaaab9d95e7b904 | 707,095 |
import math
def func (x):
"""
sinc (x)
"""
if x == 0:
return 1.0
return math.sin (x) / x | c91242e360547107f7767e442f40f4bf3f2b53e8 | 707,100 |
import copy
def db_entry_trim_empty_fields(entry):
""" Remove empty fields from an internal-format entry dict """
entry_trim = copy.deepcopy(entry) # Make a copy to modify as needed
for field in [ 'url', 'title', 'extended' ]:
if field in entry:
if (entry[field] is None) or \
... | d5b31c823f4e8091872f64445ab603bcbf6a2bef | 707,102 |
def _is_install_requirement(requirement):
""" return True iff setup should install requirement
:param requirement: (str) line of requirements.txt file
:return: (bool)
"""
return not (requirement.startswith('-e') or 'git+' in requirement) | 339f6a8a573f33157a46193216e90d62475d2dea | 707,104 |
def move_to_next_pixel(fdr, row, col):
""" Given fdr (flow direction array), row (current row index), col (current col index).
return the next downstream neighbor as row, col pair
See How Flow Direction works
http://desktop.arcgis.com/en/arcmap/latest/tools/spatial-analyst-toolbox/how-flow-direction-w... | d134bb35ed4962945c86c0ac2c6af1aff5acd06b | 707,105 |
from typing import Union
def addition(a:Union[int, float], b:Union[int, float]) -> Union[int, float]:
"""
A simple addition function. Add `a` to `b`.
"""
calc = a + b
return calc | b9adaf3bea178e23bd4c02bdda3f286b6ca8f3ab | 707,107 |
import contextlib
import sqlite3
def run_sql_command(query: str, database_file_path:str, unique_items=False) -> list:
"""
Returns the output of an SQL query performed on a specified SQLite database
Parameters:
query (str): An SQL query
database_file_path (str): absolute path o... | 705584db31fd270d4127e7d1b371a24a8a9dd22e | 707,110 |
def compact_float(n, max_decimals=None):
"""Reduce a float to a more compact value.
Args:
n: Floating point number.
max_decimals: Maximum decimals to keep; defaults to None.
Returns:
An integer if `n` is essentially an integer, or a string
representation of `n` red... | 827e49e05aaca31d497f84c2a8c8dd52cfad73d9 | 707,112 |
def arrToDict(arr):
"""
Turn an array into a dictionary where each value maps to '1'
used for membership testing.
"""
return dict((x, 1) for x in arr) | 3202aac9a6c091d7c98fd492489dbcf2300d3a02 | 707,118 |
def convert_to_dtype(data, dtype):
"""
A utility function converting xarray, pandas, or NumPy data to a given dtype.
Parameters
----------
data: xarray.Dataset, xarray.DataArray, pandas.Series, pandas.DataFrame,
or numpy.ndarray
dtype: str or numpy.dtype
A string denoting a... | ec3130311fe9c136707d5afb8f564b4f89067f4e | 707,120 |
import re
def match(text: str, pattern: str) -> bool:
"""
Match a text against a given regular expression.
:param text: string to examine.
:param pattern: regular expression.
:returns: ``True`` if pattern matches the string.
"""
return re.match(pattern, text) is not None | a59d71283766c5079e8151e8be49501246218001 | 707,125 |
from typing import Tuple
import math
def euler_to_quaternion(roll: float = 0, pitch: float = 0, yaw: float = 0) -> Tuple[float, float, float, float]:
"""
Convert Euler to Quaternion
Args:
roll (float): roll angle in radian (x-axis)
pitch (float): pitch angle in radian (y-axis)
yaw... | e8346172f07510c377e14827842eb18f1631402e | 707,128 |
def table_exists(conn, table_name, schema=False):
"""Checks if a table exists.
Parameters
----------
conn
A Psycopg2 connection.
table_name : str
The table name.
schema : str
The schema to which the table belongs.
"""
cur = conn.cursor()
table_exists_sql =... | c9b698afbe795a6a73ddfb87b2725c3c4205f35e | 707,132 |
def aggregate_by_player_id(statistics, playerid, fields):
"""
Inputs:
statistics - List of batting statistics dictionaries
playerid - Player ID field name
fields - List of fields to aggregate
Output:
Returns a nested dictionary whose keys are player IDs and whose values
a... | c137fc8820f8898ebc63c54de03be5b919fed97a | 707,133 |
import pickle
def loadStatesFromFile(filename):
"""Loads a list of states from a file."""
try:
with open(filename, 'rb') as inputfile:
result = pickle.load(inputfile)
except:
result = []
return result | cc2f64a977ff030ec6af94d3601c094e14f5b584 | 707,134 |
import re
def is_mismatch_before_n_flank_of_read(md, n):
"""
Returns True if there is a mismatch before the first n nucleotides
of a read, or if there is a mismatch before the last n nucleotides
of a read.
:param md: string
:param n: int
:return is_mismatch: boolean
"""
is_mismatc... | 1e41c67e29687d93855ed212e2d9f683ef8a88d7 | 707,135 |
def _read_txt(file_path: str) -> str:
"""
Read specified file path's text.
Parameters
----------
file_path : str
Target file path to read.
Returns
-------
txt : str
Read txt.
"""
with open(file_path) as f:
txt: str = f.read()
return txt | 5f0657ee223ca9f8d96bb612e35304a405d2339e | 707,137 |
def load_data(data_map,config,log):
"""Collect data locally and write to CSV.
:param data_map: transform DataFrame map
:param config: configurations
:param log: logger object
:return: None
"""
for key,df in data_map.items():
(df
.coalesce(1)
.write
.csv(f'{co... | 2b690c4f5970df7f9e98ce22970ce3eb892f15bc | 707,139 |
def extract_first_value_in_quotes(line, quote_mark):
"""
Extracts first value in quotes (single or double) from a string.
Line is left-stripped from whitespaces before extraction.
:param line: string
:param quote_mark: type of quotation mark: ' or "
:return: Dict: 'value': extracted value;
... | 4f614cbbb3a1a04ece0b4da63ea18afb32c1c86b | 707,141 |
def format_dependency(dependency: str) -> str:
"""Format the dependency for the table."""
return "[coverage]" if dependency == "coverage" else f"[{dependency}]" | 981a38074dbfb1f332cc49bce2c6d408aad3e9e2 | 707,143 |
def _unpickle_injected_object(base_class, mixin_class, class_name=None):
"""
Callable for the pickler to unpickle objects of a dynamically created class
based on the InjectableMixin. It creates the base object from the original
base class and re-injects the mixin class when unpickling an object.
:p... | 1821509506ad31dcdb21f07a2b83c544ff3c3eb3 | 707,148 |
import colorsys
def hsl_to_rgb(hsl):
"""Convert hsl colorspace values to RGB."""
# Convert hsl to 0-1 ranges.
h = hsl[0] / 359.
s = hsl[1] / 100.
l = hsl[2] / 100.
hsl = (h, s, l)
# returns numbers between 0 and 1
tmp = colorsys.hls_to_rgb(h, s, l)
# convert to 0 to 255
r = int... | 4417ce8468e71b7139b57fe270809c7030b2c3df | 707,151 |
import six
def strip(val):
"""
Strip val, which may be str or iterable of str.
For str input, returns stripped string, and for iterable input,
returns list of str values without empty str (after strip) values.
"""
if isinstance(val, six.string_types):
return val.strip()
try:
... | 893986e69f6d64167f45daf30dacb72f4b7f2bff | 707,153 |
import math
def tau_polinomyal_coefficients(z):
"""
Coefficients (z-dependent) for the log(tau) formula from
Raiteri C.M., Villata M. & Navarro J.F., 1996, A&A 315, 105-115
"""
log_z = math.log10(z)
log_z_2 = log_z ** 2
a0 = 10.13 + 0.07547 * log_z - 0.008084 * log_z_2
a1 = -4.424 - ... | ebef7d773eeb400ef87553fc5838ee2cb97d0669 | 707,154 |
def get_all_playlist_items(playlist_id, yt_client):
"""
Get a list of video ids of videos currently in playlist
"""
return yt_client.get_playlist_items(playlist_id) | c7a8cc806b552b1853eba1d8223aa00225d5539e | 707,155 |
def get_library_isotopes(acelib_path):
"""
Returns the isotopes in the cross section library
Parameters
----------
acelib_path : str
Path to the cross section library
(i.e. '/home/luke/xsdata/endfb7/sss_endfb7u.xsdata')
Returns
-------
iso_array: array
array of ... | d93d319b84c02b8156c5bad0998f5943a5bbe8ae | 707,156 |
import json
def odict_to_json(odict):
"""
Dump an OrderedDict into JSON series
"""
json_series = json.dumps(odict)
return json_series | d18a4e0f0d11a2c529edb395671052f15ad8071d | 707,157 |
def encode_data(data):
"""
Helper that converts :class:`str` or :class:`bytes` to :class:`bytes`.
:class:`str` are encoded with UTF-8.
"""
# Expect str or bytes, return bytes.
if isinstance(data, str):
return data.encode('utf-8')
elif isinstance(data, bytes):
return data
... | 3cd54389719439e8f18cf02b110af07799c946b5 | 707,158 |
from typing import Any
def safe_string(value: Any) -> str:
"""
Consistently converts a value to a string.
:param value: The value to stringify.
"""
if isinstance(value, bytes):
return value.decode()
return str(value) | 0ba8dcfe028ac6c45e0c17f9ba02014c2f746c4d | 707,163 |
from typing import List
def count_short_tail_keywords(keywords: List[str]) -> int:
"""
Returns the count of short tail keywords in a list of keywords.
Parameters:
keywords (List[str]): list with all keywords as strings.
Returns:
total (int): count of short tail keywords... | 1af42d71be75d9279584a8c3edc090a39ec6cf77 | 707,165 |
def is_odd(number):
"""Determine if a number is odd."""
if number % 2 == 0:
return False
else:
return True | 4efe5114f2e25431808492c768abc0f750e63225 | 707,166 |
def fmt_quil_str(raw_str):
"""Format a raw Quil program string
Args:
raw_str (str): Quil program typed in by user.
Returns:
str: The Quil program with leading/trailing whitespace trimmed.
"""
raw_quil_str = str(raw_str)
raw_quil_str_arr = raw_quil_str.split('\n')
trimmed_qu... | e95c26f3de32702d6e44dc09ebbd707da702d964 | 707,167 |
from typing import Optional
from typing import Callable
from typing import Literal
def _not_json_encodable(message: str, failure_callback: Optional[Callable[[str], None]]) -> Literal[False]:
""" Utility message to fail (return `False`) by first calling an optional failure callback. """
if failure_callback:
... | 6979261a5f14a32c1ae34d01bad346344f38ed14 | 707,168 |
def bitwise_dot(x, y):
"""Compute the dot product of two integers bitwise."""
def bit_parity(i):
n = bin(i).count("1")
return int(n % 2)
return bit_parity(x & y) | 074b09a92e3e697eb08b8aaefa6ffd05d58698f4 | 707,169 |
def validate_mash(seq_list, metadata_reports, expected_species):
"""
Takes a species name as a string (i.e. 'Salmonella enterica') and creates a dictionary with keys for each Seq ID
and boolean values if the value pulled from MASH_ReferenceGenome matches the string or not
:param seq_list: List of OLC Se... | 9eb4fd6e1f156a4fed3cc0be0c5b7153a05b038b | 707,171 |
def redirect_to_url(url):
"""
Return a bcm dictionary with a command to redirect to 'url'
"""
return {'mode': 'redirect', 'url': url} | 01e4deb80bbd8f8e119c99d64001866c6cd644d9 | 707,172 |
def sqrt(number):
"""
Calculate the floored square root of a number
Args:
number(int): Number to find the floored squared root
Returns:
(int): Floored Square Root
"""
assert number >= 0, 'Only square root of positive numbers are valid'
start = 0
end = number
res = None... | 7ed4d547e0dbabebff7ffdf1e368817a415cbb9e | 707,173 |
def sum_fn(xnum, ynum):
""" A function which performs a sum """
return xnum + ynum | 61a1ae2e4b54348b9e3839f7f2779edd03f181df | 707,176 |
def matlabize(s):
"""Make string s suitable for use as a MATLAB function/script name"""
s = s.replace(' ', '_')
s = s.replace('.', '_')
s = s.replace('-', '_')
assert len(s) <= 63 # MATLAB function/script name length limitation
return s | 5dccb9497a3ee28dae5fb7de6e15a1fa02f144cf | 707,177 |
def get_spec_res(z=2.2, spec_res=2.06, pix_size=1.8):
""" Calculates the pixel size (pix_size) and spectral resolution (spec_res) in
km/s for the MOCK SPECTRA.
arguments: z, redshift. spec_res, spectral resoloution in Angst. pixel_size
in sngst.
returns:
(pixel_size, spec_res) in km/s
"""
... | 597db8ce00c071624b0877fe211ab9b01ec889de | 707,178 |
import platform
def get_default_command() -> str:
"""get_default_command returns a command to execute the default output of g++ or clang++. The value is basically `./a.out`, but `.\a.exe` on Windows.
The type of return values must be `str` and must not be `pathlib.Path`, because the strings `./a.out` and `a.... | d06abdefab189f9c69cba70d9dab25ce83bebc75 | 707,182 |
def object_type(r_name):
"""
Derives an object type (i.e. ``user``) from a resource name (i.e. ``users``)
:param r_name:
Resource name, i.e. would be ``users`` for the resource index URL
``https://api.pagerduty.com/users``
:returns: The object type name; usually the ``type`` property of... | b74e373691edf8a8b78c2a3ff5d7b9666504330a | 707,183 |
def convert_to_roman_numeral(number_to_convert):
"""
Converts Hindi/Arabic (decimal) integers to Roman Numerals.
Args:
param1: Hindi/Arabic (decimal) integer.
Returns:
Roman Numeral, or an empty string for zero.
"""
arabic_numbers = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9,... | f970517a7c2d1ceb13ec025d6d446499ce5c21ff | 707,184 |
import re
def wikify(value):
"""Converts value to wikipedia "style" of URLS, removes non-word characters
and converts spaces to hyphens and leaves case of value.
"""
value = re.sub(r'[^\w\s-]', '', value).strip()
return re.sub(r'[-\s]+', '_', value) | dc4504ea6eb7905b5e18a1d1f473a4f337697b26 | 707,192 |
def _tolist(arg):
"""
Assure that *arg* is a list, e.g. if string or None are given.
Parameters
----------
arg :
Argument to make list
Returns
-------
list
list(arg)
Examples
--------
>>> _tolist('string')
['string']
>>> _tolist([1,2,3])
[1, 2, ... | e4293991eeb6d15470511281680af44353232c37 | 707,193 |
def ConvertToFloat(line, colnam_list):
"""
Convert some columns (in colnam_list) to float, and round by 3 decimal.
:param line: a dictionary from DictReader.
:param colnam_list: float columns
:return: a new dictionary
"""
for name in colnam_list:
line[name] = round(float(line[name])... | e95fd6cfa9bb57060fdd835eea139fd9c67bc211 | 707,194 |
from typing import List
import json
def transform_application_assigned_users(json_app_data: str) -> List[str]:
"""
Transform application users data for graph consumption
:param json_app_data: raw json application data
:return: individual user id
"""
users: List[str] = []
app_data = json.l... | 625c8f662b364bb3fe63bb26b06eaca57ae8be79 | 707,195 |
def get_day_suffix(day):
"""
Returns the suffix of the day, such as in 1st, 2nd, ...
"""
if day in (1, 21, 31):
return 'st'
elif day in (2, 12, 22):
return 'nd'
elif day in (3, 23):
return 'rd'
else:
return 'th' | 7d9277303357de5405b3f6894cda24726d60ad47 | 707,196 |
def power_law_at_2500(x, amp, slope, z):
""" Power law model anchored at 2500 AA
This model is defined for a spectral dispersion axis in Angstroem.
:param x: Dispersion of the power law
:type x: np.ndarray
:param amp: Amplitude of the power law (at 2500 A)
:type amp: float
:param slope: Sl... | 508227f332f652d00c785074c20f9acefbce9258 | 707,202 |
def extract_vuln_id(input_string):
"""
Function to extract a vulnerability ID from a message
"""
if 'fp' in input_string.lower():
wordlist = input_string.split()
vuln_id = wordlist[-1]
return vuln_id
else:
return None | 06673f2b401472185c8a3e6fc373d39c171791db | 707,203 |
from typing import Any
def _element(
html_element: str,
html_class: str,
value: Any,
is_visible: bool,
**kwargs,
) -> dict:
"""
Template to return container with information for a <td></td> or <th></th> element.
"""
if "display_value" not in kwargs:
kwargs["display_value"] ... | 4ce4d2ff9f547470d4a875508c40d3ae2a927ba0 | 707,205 |
def get_gene_summary(gene):
"""Gets gene summary from a model's gene."""
return {
gene.id: {
"name": gene.name,
"is_functional": gene.functional,
"reactions": [{rxn.id: rxn.name} for rxn in gene.reactions],
"annotation": gene.annotation,
"notes... | dd9cb3f8e9841a558898c67a16a02da1b39479d2 | 707,206 |
def tle_fmt_float(num,width=10):
""" Return a left-aligned signed float string, with no leading zero left of the decimal """
digits = (width-2)
ret = "{:<.{DIGITS}f}".format(num,DIGITS=digits)
if ret.startswith("0."):
return " " + ret[1:]
if ret.startswith("-0."):
return "-" + ret[2:... | 686cb4061e5cf2ad620b85b0e66b96a8cd1c3abf | 707,207 |
def is_vulgar(words, sentence):
"""Checks if a given line has any of the bad words from the bad words list."""
for word in words:
if word in sentence:
return 1
return 0 | f8ff64f1d29313c145ebbff8fef01961e14cfd1f | 707,209 |
import re
def matchNoSpaces(value):
"""Match strings with no spaces."""
if re.search('\s', value):
return False
return True | 6b33c6b500f78664c04ef8c507e9b25fa19c760d | 707,211 |
def get_number(line, position):
"""Searches for the end of a number.
Args:
line (str): The line in which the number was found.
position (int): The starting position of the number.
Returns:
str: The number found.
int: The position after the number found.
"""
word = ... | df41a1b53953b912e5ce5d6d9b3d69c4133460f1 | 707,213 |
def levelize_smooth_or_improve_candidates(to_levelize, max_levels):
"""Turn parameter in to a list per level.
Helper function to preprocess the smooth and improve_candidates
parameters passed to smoothed_aggregation_solver and rootnode_solver.
Parameters
----------
to_levelize : {string, tuple... | 8b302b8cae04adae010607c394c2e5059aa46eeb | 707,214 |
def get_max_num_context_features(model_config):
"""Returns maximum number of context features from a given config.
Args:
model_config: A model config file.
Returns:
An integer specifying the max number of context features if the model
config contains context_config, None otherwise
"""
meta_ar... | 1df5d220e30cfa5b440c0063149e2ebaf896352a | 707,215 |
def parse_encoding_header(header):
"""
Break up the `HTTP_ACCEPT_ENCODING` header into a dict of the form,
{'encoding-name':qvalue}.
"""
encodings = {'identity':1.0}
for encoding in header.split(","):
if(encoding.find(";") > -1):
encoding, qvalue = encoding.split(";")
... | 0d423ad51ff14589b5858681cf32a0f318e6dbfa | 707,217 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.