content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import re
def replace_version(line, new_version, regex):
"""
COPIED FROM TITO
Attempts to replace common setup.py version formats in the given line,
and return the modified line. If no version is present the line is
returned as is.
Looking for things like version="x.y.z" with configurable ca... | d394cdca52be26bcde5a70d20b9c6b9c6ddd8753 | 633,895 |
from typing import Union
def fibonacci(num: int, *, ret_text: bool = False) -> Union[list, str]:
"""
Generates the sequence of Fibonacci
>>> from snakypy import helpers
>>> helpers.calcs.fibonacci(50)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
>>> helpers.calcs.fibonacci(50, ret_te... | 99969eff62b2d4bcd1f79c16e4a378cfdf64d925 | 633,897 |
def simplify(ints: list) -> list:
"""
In order to speed up the process we should simplify
the input list by reducing duplicate values, see sample below:
[1,4,5,1,1,1,1,1,4,7,8] >>> [1,4,5,1,4,7,8]
:param ints: a list of integers
:return: simplified list of integers
"""
result = list()
temp = -1
for i in in... | d01efca30b790983035bf4837cb62848124d431f | 633,898 |
def hex_uid(uid_raw):
"""
Convert key to Hex string
:param uid_raw: Input UID
:return: Hex string
"""
uid_list = list(uid_raw)
uid_hex_str = ""
for uid_item in uid_list:
uid_hex = format(uid_item, 'x')
if len(uid_hex) == 1:
uid_hex = "0" + uid_hex
uid_... | c4d8a9fe6cfc50ea42efb8d11c1f1954b01ae93e | 633,899 |
import re
def search_prs(log):
"""
Search lines of text for PR numbers
"""
# Find all matches using regex iterator, using the PR # as the group match
resultlist = [str(m.group(1)) for m in re.finditer(r"erge pull request #(\d+)", log)]
return sorted(resultlist) | f2628dc6457cc3b1aa2b6e89b4cdefbfd1078b47 | 633,900 |
import csv
def load_inputs(inputs_file):
"""Load Inputs for AutoSpider."""
with open(inputs_file, 'Ur') as f:
data = list(tuple(rec) for rec in csv.reader(f, delimiter=','))
return data | fb6f53eea739237c96489ef10f653aab96d0e6c5 | 633,904 |
def _quote(text):
"""
Quote the given string so ``_split_quoted`` will not split it up.
:param str text: The string to quote:
:return: A str string representing ``text`` as protected from
splitting.
"""
return (
'"' +
text.replace("\\", "\\\\").replace('"', '\\"') +
... | 24224ed6a0cac7cf4cb6207081e87ad095c07e59 | 633,906 |
def mergeTwoListsIntoOne(list1, list2):
"""
Function that takes two lists and assembles them into one list
such that each entry of the final list is a list containing the
two corresponding entries of the two input lists
"""
if len(list1) != len(list2):
raise ValueError("Input lists not o... | d6eec1b20b1cecf64e7ae457b1a62e34db79d68e | 633,913 |
def int_to_str(num, max_num=0):
"""
Converts a number to a string. Will add left padding based on the max value to ensure numbers
align well.
"""
if num is None:
num_str = 'n/a'
else:
num_str = '{:,}'.format(num)
max_str = '{:,}'.format(int(max_num))
return num_str.rjust(... | d6bcdef45a545f354b0c3889c7ef35fdae20e668 | 633,914 |
def nested_haskey(x, keys):
"""
For a nested dictionary 'x' and list of keys, checks
if all keys exist in the nested key path.
"""
if len(keys) == 1:
return (keys[0] in x)
if keys[0] in x:
return nested_haskey( x[keys[0]], keys[1:])
else:
return False | 6c99bb9d1d8b6a63f2670394ea266564b3435122 | 633,917 |
import pathlib
import pkg_resources
def get_path(resource_name):
""" Returns a path to a resource
WARNING: existence of file is not guaranteed. Use resources.exists
WARNING: resource files are supposed to be used as read-only!
"""
resource_path = pathlib.Path( pkg_resources.resource_filen... | 33a4d12b19aa0276ff0fc9464b757713dc9a6a01 | 633,918 |
def parse_flag(value):
""" Convert string to boolean (True or false)
:param value: string value
:return: True if the value is equal to "true" (case insensitive), otherwise False
"""
return value.lower() == "true" | 4555e655ecd39f362d11065718e10b144ecf2b85 | 633,919 |
def capacity_cost_rule(mod, g, p):
"""
The capacity cost for new-build generators in a given period is the
capacity-build of a particular vintage times the annualized cost for
that vintage summed over all vintages operational in the period.
"""
return sum(
mod.GenNewBin_Build[g, v]
... | 5cf427ad93f8a34cdb2d75b4e503622dbe2be9aa | 633,922 |
def nillable_dict(func):
"""Decorator that retuns empty dictionary if input is None"""
def wrapper(cls, element):
if element is None:
return {}
else:
return func(cls, element)
return wrapper | 80e424bf84ab64db5ec99d8c9a91298d67e790b1 | 633,928 |
def get_reqs(path):
"""Parse a pip requirements file.
:param str path: The path to the requirements file
:returns list: A list of package strings
"""
reqs = []
with open(path) as req_file:
for line in req_file:
# Remove any comments
line = line.split("#", 1)[0].... | 8f625a24973aed42617107e3be2e0e18e471c9ef | 633,934 |
def order_by_length(*items):
"""Orders items by length, breaking ties alphabetically."""
sorted_items = sorted(items, key=lambda item: (len(str(item)), str(item)))
return ' '.join(sorted_items) | dc0b8406c531d96e8192de5702c702fd4e533f5a | 633,935 |
import torch
def prepare_batch(batch):
"""This is the collate function.
The mass spectra must be padded so that they fit nicely as a tensor.
However, the padded elements are ignored during the subsequent steps.
Parameters
----------
batch : tuple of tuple of torch.tensor
A batch of d... | 56ba032b5e2a8d27d1d589d4eb0c96153d47cc88 | 633,939 |
def task_type_args_are_valid(instance):
"""Determines whether a task type's argument fields are valid.
The argument fields are valid if the argument keys in the
required_arguments_default_values field are a subset of its required
arguments.
Arg:
instance: A task type instance.
Returns:... | bb45d1bcd174001e96a7f07fce86b6de294cf232 | 633,941 |
def sign_split(M):
"""Given a matrix M, return two matrices. The first contains the
positive entries of M; the second contains the negative entries of M,
multiplied by -1.
"""
M_plus = M*(M>0).astype(int)
M_minus = -M*(M<0).astype(int)
return M_plus, M_minus | af573a2c68a6156cd92b5f3076c0fa6fb3c3c95e | 633,946 |
import re
def get_usfm3_word_links(usfm3_line):
"""
Retrieves the tW links from a usfm3 word
:param usfm3_line:
:return:
"""
links = []
if usfm3_line and re.match(r'.*x-tw=', usfm3_line):
links = re.findall(r'x-tw="([^"]*)"', usfm3_line, flags=re.IGNORECASE | re.UNICODE)
return... | e568dc7da2852c6ac309f1e8ccfca8b7abf4229f | 633,949 |
from datetime import datetime
def to_datetime_from_date(value):
"""
converts the input date to it's equivalent python datetime.
the time info will be set to `00:00:00`.
:param date value: date value to be converted.
:rtype: datetime
"""
return datetime(year=value.year, month=value.mont... | 7bd31f1df9b6c418c72b955dfca1d7af865fe235 | 633,950 |
def jaccard_similarity(list1, list2):
"""
Calculate Jaccard Similarity between two sets
"""
intersection = len(list(set(list1).intersection((set(list2)))))
union = len(list1) + len(list2) - intersection
return float(intersection) / union | 31da84ce335c8c404197e6ac7b8500178005e935 | 633,952 |
def render_menu_children(request, parent, items, menu_tag):
"""
Recursively render menu children.
"""
childs = []
output = []
for menu in items:
if menu['parent_id'] == parent['id']:
childs.append(menu)
if childs:
output.append('<%s class="ul_sublevel">' % menu_... | c047ec7508b5f51f57dd9a5a3ef38eeb9e020dc4 | 633,955 |
def toAdjacencyList(molecule, label='', pattern=False, removeH=False):
"""
Convert the `molecule` object to an adjacency list. `pattern` specifies
whether the graph object is a complete molecule (if ``False``) or a
substructure pattern (if ``True``). The `label` parameter is an optional
string to pu... | e6f194be8bcbaf94c31c42dfacc9b4ee2831076b | 633,958 |
def defaultBBoxDeltaFun(w):
"""
When we reduce the width or height of a bounding box, we use this function to compute the deltaX or deltaY
, which is applied on x1 and x2 or y1 and y2
For instance, for horizontal axis
x1 = x1 + deltaFun(abs(x1-x2))
x2 = x2 + deltaFun(abs(x1-x2))
... | c5aefadfd32def3f80815836be11c123e714da38 | 633,959 |
def _GetLineNumberOfSubstring(content, substring):
""" Return the line number of |substring| in |content|."""
index = content.index(substring)
return content[:index].count('\n') + 1 | 444bad1aeef0f264ebe26b9b0ee15d066ff6c472 | 633,961 |
def is_success_type(qtype):
"""
Interprets a qtype (BINARY, UNKNOWN, etc.) as a "success" or "failure"
"""
return qtype[0] == 's' | e6224154e17620f98ce947fdf9769b9a935eef7a | 633,963 |
import re
def string_to_list(option):
"""Convert string to list.
List may be enclosed in [], {}, (), or not enclosed. List entries must be comma delimited.
Args:
option (str)
String to convert.
Returns: (list)
List of strings.
"""
PATTERN = r"[\{\[\(](.*)[\}\]\)]"... | 78c3e82b845a73b354f4840393a3a2d3a511c30a | 633,965 |
def add_percent_sign(n):
"""Add a % sign to the end of x, unless x is empty"""
if not isinstance(n, str):
n = str(n)
if len(n) > 0:
return n + "%"
return n | 83f5d89cb80ab8ebc6de75a3f30728f4c30d1747 | 633,966 |
def _int_or_str(c):
"""Return parameter as type integer, if possible
otherwise as type string
"""
try:
return int(c)
except ValueError:
return c | f569257b5114ad7c8317bd60469993b604b1cfc4 | 633,971 |
import random
def seeds(count):
"""Return a list of random values of the specificed length."""
return [random.randint(0, 1 << 32 - 1) for i in range(count)] | 2768e9cba10694b6f76bd4080ebab5cc2fec6ea0 | 633,975 |
import math
def ent(x):
""" Entropy [bits] given a vector of log probabilities """
x = [ math.exp(-val) for val in x ]
logs = [ math.log(val, 2) for val in x ]
prods = [ a * b for a,b in zip(x, logs) ]
return - sum(prods) | eaada453d12171b461c5e9f476ed5b1dab2fe52b | 633,976 |
from pathlib import Path
def is_package_file(f: Path, sap_code: str, name_pattern: str) -> bool:
"""Determine if the file is the right application JSON file
:param f (Path): json file path
:param sap_code (str): Adobe SAP code for product being processed
:param name_pattern (str): json filename patter... | d9e9be639d7388f21a345938bd666f0bb5dfaa8b | 633,979 |
def _str2float(s):
"""Cast string to float if it is not None. Otherwise return None.
Args:
s (str): String to convert or None.
Returns:
str or NoneType: The converted string or None.
"""
return float(s) if s is not None else None | 78fcf41c91c41795b2b8c9e4465c6da5c8f2701a | 633,980 |
def round_scores(df):
"""
Some labels were interpolated by the data provider, so they must be rounded
to the nearest integer to be used as a label.
"""
return df.score.round() | 7c37ae909b0a3ad521c884ddd4b50f52fc567cbd | 633,982 |
def lint_codeblock(styleguide, tmp_path):
"""Fixture which runs the styleguide's `lint` subcommand when executed."""
def run_linter(
codeblock,
*styleguide_args,
# We ignore unused import warnings as most of the codeblocks which produce this warning
# are just demonstrations of ... | 67ad6ed2184c9d30de9d60491463c7ac18fe5690 | 633,983 |
import torch
def cat_batch(*args):
"""
Concatenates batches of tensors
:return: concatenated tensor
:rtype: torch.Tensor
"""
return torch.cat(args, dim=0) | 9678fdccf4e55adc761b9ac5c343233448bf3943 | 633,984 |
import hashlib
def _rehash(value, salt2=""):
"""Rehash a value."""
for idx in range(1, 20):
value = hashlib.sha256(f"{value}{idx}{salt2}".encode()).hexdigest()
return value | 678d96dbbaeadb0bf57b166511eab1eba8963a30 | 633,987 |
def format_variable_assignment(step):
"""Format an assignment statement."""
asn = step['detail']
lhs, rhs, binary = asn['lhs'], asn['rhs-value'], asn['rhs-binary']
binary = '({})'.format(binary) if binary else ''
return '{} = {} {}'.format(lhs, rhs, binary) | 91a9c873ab7095eb99661bb74b5d1db0ef122755 | 633,993 |
def create_internal_cookie(name, value, expires):
"""Create individual cookie to be stored inside Target cookie"""
return {
"name": name,
"value": value,
"expires": expires
} | 099315018a4235457f2acbbd344bd4530f09822d | 633,995 |
def inflate_lvol_bdev(client, name):
"""Inflate a logical volume.
Args:
name: name of logical volume to inflate
"""
params = {
'name': name,
}
return client.call('inflate_lvol_bdev', params) | 0826f77c6b9da7e8cce00b48b1e6236440c7a8bf | 633,997 |
import requests
import json
def get_token_data(oauth_service, token):
"""
Gets the OAuth2 user attributes using the supplied token
:param OAuthSSHCertSigningService oauth_service: an
OAuthSSHCertSigningService object
:param basestring token: an OAuth2 token
:return: a json object of user a... | f4ddcb5985f67a7fbbb488b167127b7652edbb8a | 633,998 |
def add_sort_list(
l1: list,
l2: list,
) -> list:
"""Add two lists and sort them
Parameters
----------
l1 : list
The first list to be added
l2 : list
The second list to be added
Returns
-------
list
The added and sorted list
"""
# Add ... | fc213db09e029d2f7e8052801593dc318fb87e3f | 634,002 |
def trapezoidal(f, a, b, n=10000):
"""trapez method for numerical integration"""
s = 0.0
h = (b - a) / n
for i in range(0, n):
s += f(a + i * h)
return h * (s + 0.5 * (f(a) + f(b))) | 113a6a047e3fe320f5e0d511dc3119d6564fffa5 | 634,005 |
import optparse
def parse_args(argvish):
"""
Build OptionParser and evaluate command line arguments.
"""
parser = optparse.OptionParser()
parser.add_option('-r', '--region', type="int",
help="Region")
parser.add_option('-z', '--zone', type="int",
hel... | a8fa21d013b4455947d808bfd2dadf628d608318 | 634,008 |
import json
def jsonify(*args, **kwargs):
"""
Helper based on flask jsonify and helsp convert lists and dicts into valid reponses.
"""
indent = None
separators = (',', ':')
headers = {'Content-Type': 'application/json'}
headers.update(kwargs.get('headers', {}))
if args and kwargs:
... | 606c04663bc594c939489340dafc9bc7313ce432 | 634,010 |
def adjust_asymp_with_chronic(asymp_column, chronic_column):
"""
Remove asymptomatic flag for people with chronic disease
Parameters
----------
asymp_column : A boolean array storing people with asymptomatic infection
chronic_column : A boolean array storing people with chronic diseas... | 7848b09c36ee183e6a884647326822ab6f254ac5 | 634,021 |
def modulus(angka1: float, angka2: float) -> float:
"""
hasil dari modulus antara angka1 dan angka2
>>> modulus(3.0, 2.0)
1.0
"""
return angka1 % angka2 | 13442aabaecff54ebd036f48d5c27af002584354 | 634,022 |
def flip_dict_of_lists(dict_of_lists, dict_type=None, key_func=lambda k: k):
"""
Returns a "flipped" dictionary of lists from the given dictionnary of lists.
What I mean by "flipped" is this:
>>> d = {'a': [1, 2], 'b': [3, 1], 'c': [2]}
>>> flip_dict_of_lists(d)
{1: ['a', 'b'], 2: ['a', 'c'], ... | 041b50f8bb3855145e6867eea30db61dc333235e | 634,025 |
def wrap_text (text, font, base_width):
"""Wraps given text into multiple lines to fit into the given width
Breaks the given text into a list of lines, so that the text when
rendered with font won't horizontally overflow beyond base_width.
If possible, lines are broken after complete words.
Args:
... | f79eca00a8e1f10e540313e13a9bf2feeea1b83e | 634,026 |
import hashlib
def HashFile(file_path):
"""Calculate the sha256 hash of a file.
Args:
file_path: (str) path to the file.
Returns:
[str]: The sha256 hash of the file.
"""
sha256 = hashlib.sha256()
with open(file_path, 'rb') as f:
for b in iter(lambda: f.read(2048), b''):
sha256.update(b... | 709125489af5596a241f9f888c5068f51b38c74e | 634,030 |
import re
def do_slugify(inp):
"""Convert an arbitrary string into a url-safe slug."""
inp = re.sub(r'[^\w\s-]+', '', inp)
return re.sub(r'\s+', '-', inp).lower() | 1d42419169e3fcc323a39bdcd636507d500acd8f | 634,034 |
def find_count(substring, string):
"""finds the number of occurences of substring in string"""
counter = 0
index = string.find(substring)
while index >= 0:
counter += 1
index = string.find(substring, index + 1)
return counter | 4cf562045c20d8acbfe372bc315c50f089925663 | 634,035 |
def HSVtoRGB(h, s, v):
""" Convert Hue-Saturation-Value into Red-Green-Blue equivalent.
Parameters:
h - Hue between [0.0, 360.0) degrees. red(0.0) to violet(360.0-).
s - Staturation [0.0, 1.0]
v - Value [0.0, 1.0]
Return Value:
(r, g, b) 3-tuple with each color betw... | a160c3c38b56f335f32e6b8080dcc12fca2b2829 | 634,036 |
import torch
def squared_distance(x1, x2=None):
"""
Given points x1 [n1 x d1] and x2 [n2 x d2], return a [n1 x n2] matrix with
the pairwise squared distances between the points.
Entry (i, j) is sum_{j=1}^d (x_1[i, j] - x_2[i, j]) ^ 2
"""
if x2 is None:
return squared_distance(x1, x1)
... | ed6662ea36b0c95b89b01c6ca1b6b9ccdd3c4e9e | 634,037 |
import math
def straightness_imperfection(z, length, delta_global, oos_axis, **kwargs):
""" Returns the out-of-straightness imperfection of the node.
:param float z: z coordinate of node
:param float length: total length of the component
:param float delta_global: maximum amplitude of the out-of-stra... | 6148eb8d9f24b55a5ee1efa5eb43f23f4476b02a | 634,041 |
def filter_hsv_to_h(hsv, output_type="int", display_np_info=True):
"""
Obtain hue values from HSV NumPy array as a 1-dimensional array. If output as an int array, the original float
values are multiplied by 360 for their degree equivalents for simplicity. For more information, see
https://en.wikipedia.o... | 0ae0940442cd9dfa7aeb7728d3b596d88362f312 | 634,042 |
def get_viewstate_value(page):
"""
Find for content of the viewState param in source code
:param page: The code of the page for search in it
:return: The content of the viewstate param or None
"""
page = str(page).replace("\\n", "\n")
full_param = "name=\"javax.faces.ViewState\""
for i ... | 47aad086f761ed7bec91bb318bbe31a5c1db47d5 | 634,043 |
def count(seq):
"""Count the number of items in sequence that are interpreted as true."""
return sum(map(bool, seq)) | 7ab0b238f8f5110f06e35876bd76431df69c559c | 634,044 |
def convert_inf(x):
""" The tqdm doesn't support inf values. We have to convert it to None. """
if x == float('inf'):
return None
return x | 8c20588ed1905a8d8df8f4be78a3f8e0f9a2c36f | 634,046 |
def number_to_digits(num):
"""Return sorted list of digits in number."""
return sorted(int(ch) for ch in str(num)) | cc09154db0f587da5042bc06236e793411a0c5ab | 634,048 |
from bs4 import BeautifulSoup
def parseCategoryHTML(HTML_Source):
"""
カテゴリページを解析し、ランキングページのURLを取得する。
Parameters
----------
HTML_Source : str
カテゴリページHTMLソース。
Returns
-------
ranking_pg_list : str[]
ランキングページリスト。
"""
soup = BeautifulSoup(HTML_Source, 'html.parse... | 91456fac09cf5f57fbf06acb1984735b3d59446e | 634,050 |
def strescape(txt):
"""
Convert bytes or text to a c-style escaped string.
"""
if type(txt) == bytes:
txt = txt.decode("cp1251")
txt = txt.replace("\\", "\\\\")
txt = txt.replace("\n", "\\n")
txt = txt.replace("\r", "\\r")
txt = txt.replace("\t", "\\t")
txt = txt.replace('"',... | 63dedacbcf355016fba153ed4565053d02b3459f | 634,055 |
def get_counts_and_averages(ID_and_ratings_tuple):
"""Given a tuple (bookID, ratings_iterable)
returns (bookID, (ratings_count, ratings_avg))
"""
nratings = len(ID_and_ratings_tuple[1])
return ID_and_ratings_tuple[0], (nratings, float(sum(x for x in ID_and_ratings_tuple[1]))/nratings) | 537cda9c9dab8cdf73a85ebff0d788b8af2b1d19 | 634,056 |
def get_edge_label_dict(graph, attr_type="label"):
""" Return a dict with edge tuple as key and edge attr/label as
value. If both are required, the label will be the first entry in
the list, and the remaining attributes will come after"""
d = {}
if len(graph.es.attributes()) > 0:
if len(att... | 5a9c7901781f16e39c01ba2dfe6c116f3d399f91 | 634,058 |
def get_parameters(function, **kwargs):
"""
Return a list of parameters from a SSM function, like
describe_parameters or get_parameters_by_path.
"""
next_token = ""
response = function(**kwargs)
parameter_list = response["Parameters"]
while "NextToken" in response:
next_token = r... | ca9fe2f942399040d78e6a2ed9e49a11ceed4c6a | 634,059 |
from typing import Union
def _decode(str_like: Union[str, bytes]) -> str:
"""Convert to string from bytes/str/...
"""
if isinstance(str_like, bytes):
return str(str_like, 'utf-8')
return str(str_like) | 827f6ca4915eae992992504968808d1f773007c1 | 634,060 |
def format_time(start, end):
"""
Format length of time between start and end.
:param start: the start time
:param end: the end time
:return: a formatted string of hours, minutes, and seconds
"""
hours, rem = divmod(end-start, 3600)
minutes, seconds = divmod(rem, 60)
return "{:0>2}:{... | 5e6879251c6f253c0260dd31fc455f0c87901ab9 | 634,061 |
from typing import List
def _ternary_search(array: List[int], value, low: int, high: int) -> int:
"""
The implementation detail of the recursive implementation of ternary search.
:param array: is the array to search.
:param value: is the value to search for.
:param low: is the lower bound of the p... | f07a81c640ef9bafe31f01c72bf7ce5af6d30604 | 634,063 |
def encode_dict_in_bash(dictionary: dict) -> str:
"""
Make dict into a series of key value pairs readable on command line.
"""
pairs = []
for key, value in dictionary.items():
pairs.append(f"{key}={value}")
return " ".join(pairs) | 363557734487d3ac6f7e209d76df1f780d553b47 | 634,064 |
def create_address(house_number, post_code):
"""
Creates immutable address data structure
:param house_number: user's house number (string)
:param post_code: user's post code (string)
:return: (tuple)
"""
return (house_number, post_code) | f24ba0bcbfe396fd120d07748f31fab006ee21b7 | 634,066 |
def chunks(items, size):
""" Split list into chunks of the given size.
Original order is preserved.
Example:
> chunks([1,2,3,4,5,6,7,8,9], 2)
[[1, 2], [3, 4], [5, 6], [7, 8], [9]]
"""
return [items[i:i+size] for i in range(0, len(items), size)] | 960bc6ba7775ce66c3deb6c07966a9157b3e3e2c | 634,069 |
def strpar(cfg, section, key):
"""String representation of a section/key combination"""
return "[{}] {} = {}".format(section, key, cfg[section][key]) | 3c1137e3e8b539e3bb1b9e621d916bc1d70b30bd | 634,073 |
def add_commas(n):
"""
Receives integer n, returns string representation of n with commas in thousands place.
I'm sure there's easier ways of doing this... but meh.
"""
strn = str(n)
lenn = len(strn)
i = 0
result = ''
while i < lenn:
if (lenn - i) % 3 == 0 and i != 0:... | 5f064d4bf4f5bf8330fe68e69bd29178d7d857f4 | 634,081 |
def split_args(args):
"""
Split a list of argument strings into a dictionary where each key is an
argument name.
An argument looks like ``crop``, ``crop="some option"`` or ``crop=my_var``.
Arguments which provide no value get a value of ``True``.
"""
args_dict = {}
for arg in args:
... | ae51f09da1c40395c4edc24f9528285f0e48d136 | 634,083 |
def phi_psi_omega_to_abego(phi: float, psi: float, omega: float) -> str:
"""
:param: phi: The phi angle.
:param: psi: The psi angle.
:param: omega: The omega angle.
:return: The abego string.
From Buwei
https://wiki.ipd.uw.edu/protocols/dry_lab/rosetta/scaffold_generation_with_piecewise_blue... | 0fb849b0f9600e6bb9fdc721718aa564dd6639f0 | 634,085 |
def get_feature_3(token1: str, token2: str) -> str:
"""Conjunction of features 1 and 2."""
if token1 == "":
token1 = "..."
if token2 == "":
token2 = "..."
return token1 + "^" + token2 | 4e6298da19cf9c1172c8df1c77bc42ac131fb596 | 634,087 |
def disqus_id_for(obj):
"""
Returns a unique identifier for the object to be used in
DISQUS JavaScript.
"""
return "%s-%s" % (obj._meta.object_name, obj.id) | f610a18d3567be669b202e1897ec50fef1c8405e | 634,088 |
import codecs
def complete_vocabulary(filename, initial_words, wordlength, vocsize, encoding="utf-8"):
"""
Reads words of length <wordlength>, from <filename>, until the number_of_words_read+len(initial_words)=vocsize. Returns a dictionary of words and their frequency.
:param filename: text file, without... | e2b6ba39ce82a0147064d3a33781cda3d63d3112 | 634,090 |
from typing import Union
from typing import Optional
import re
def get_error_code(error_field: Union[str, None]) -> Optional[int]:
"""Get the error code part of the `error\
<https://docs.cometd.org/current/reference/#_code_error_code>`_, message \
field
:param error_field: `Error\
<https://docs.c... | 45c8b9cce27650652c126e5840f4fb610a08796d | 634,097 |
def hill_equation(val, diss_cf, hill_cf):
"""
Hill equation
:param val: input value
:param diss_cf: dissociation coefficient
:param hill_cf: Hill coefficient
:return: Hill equation for input *val*
"""
if val == 0:
return 0
else:
return 1 / (1 + (diss_cf / val) ** hill... | 96ee40c173a160ee4f557bd7ee125869927a3cd4 | 634,098 |
def get_words_prob(test_words_list:list, normal_words_freq:dict, spam_words_freq:dict, normal_file_number:int, spam_file_number:int,
max_prob_num:int):
"""
Calculate the probability of spam for every words, p(s|wi)
Args:
test_words_list: the words list to test
normal_words... | 87fa23b721a26a526f3f5a80b4bb74aa45606199 | 634,100 |
def list_materials(client, file_=None, material=None):
"""List materials on a part.
Args:
client (obj):
creopyson Client.
`file_` (str, optional):
File name. Defaults is currently active model.
material (str, optional):
Material name pattern.
... | bcd70f4003f4b7499bf939f1d3f9810558f6c719 | 634,104 |
def heading(title, fgcol, bgcol,extras='',add=' <br>'):
"""Format a page heading."""
return '''
<table width="100%%" cellspacing=0 cellpadding=2 border=0
summary="heading">
<tr bgcolor="%s">
<td valign=bottom>%s
<font color="%s" face="helvetica, arial"> <br>%s</font></td
><td a... | ff4b11710812aaab28e96e02f8f7777471a226a0 | 634,107 |
from typing import Callable
def contains(substring: str, false_prob: float = 0.0,
true_prob: float = 1.0) -> Callable:
"""Generate a function that checks whether a substring is present."""
def call(value: object) -> float:
if not isinstance(value, str):
return 0.0
retu... | be91f8db341f51e44de45aec296c1e1c6804ff18 | 634,108 |
import requests
def perform_query(query):
"""Performs a SPARQL query to the wikidata endpoint
Args:
query: A string containing a functional sparql query
Returns:
A json with the response content.
"""
endpoint_url = "https://query.wikidata.org/sparql"
try:
response =... | d429c3c2291557ab2d1b3ecee126e63f6f89ed99 | 634,109 |
import six
def first_where(pred, iterable, default=None):
"""Returns the first element in an iterable that meets the given predicate.
:param default: is the default value to use if the predicate matches none of the elements.
"""
return next(six.moves.filter(pred, iterable), default) | 508e67feeb9c190f67297495e242e67e0b05cce0 | 634,111 |
def size_mb(size):
"""
Helper function when creating database
:param size: interger (size in Mb)
:return: integer (bytes)
"""
return int(1024*1024*size) | 0da4523a3ddb86a3212a729ad078751a28eef4ae | 634,112 |
def flatten(lists):
"""
Return a new (shallow) flattened list.
:param lists: list: a list of lists
:return list
"""
return [item for sublist in lists for item in sublist] | 3dc11ae9c41cfae0abe88d5b905fb06e30658826 | 634,114 |
def createExportString(clip, delimiter=" ", badValue="nan"):
"""Create a line of text for the exporter
Inputs:
------------
clip
A clipboard object
Optional Inputs:
-----------------
delimiter:
(string) The character, or set of characters to separate elements
... | c84253e848b418fe4f92d4de1910793c6c607a25 | 634,119 |
def air_flux(air_flow: float, co2_source: float, co2_target: float) -> float:
"""
Equation 8.46
Args:
co2_source, co2_target: CO2-concentration at location (mg m^-3)
air_flow: the air flux from location 1 to location 2 (m^3 m^-2 s^-1)
return: CO2 flux accompanying an air flux from locat... | 891ec9dedfa9a4ecfa496acd29d0afcf9e7aed98 | 634,122 |
def add_newline_chars_to_list(list_of_filelines):
"""
adds a newline character to each string in a list
:param list_of_filelines: list of strings
:return: list of strings
"""
new_filelines = []
for i in range(len(list_of_filelines)):
new_filelines.append(list_of_filelines[i] + "... | 24447eafe730efdda0ec28dac54f76de43ec3034 | 634,125 |
import uuid
def uuid4(short: bool = False) -> str:
"""
Create custom version of uuid4.
:param short: If ``True`` only returns the first 8 chars of the uuid, else, 18
:return: UUID of 18 chars
"""
return str(uuid.uuid4())[:18 if not short else 8] | 2e08d8b8772cc40efdac24b382eaa11d49247c21 | 634,126 |
def read_ascii_data_cols(_file_path, _str_sep, _i_col_start=0, _i_col_end=-1, _n_line_skip=0, _float=True): #OC24112019
#def read_ascii_data_cols(_file_path, _str_sep, _i_col_start=0, _i_col_end=-1, _n_line_skip=0):
"""
Auxiliary function to read-in data comumns from ASCII file (2D table)
:param _file_path:... | da932c7d3a99b6c4c302918e795ccd802829c2b8 | 634,128 |
from typing import Union
from typing import Tuple
def parse_lat_lng(kwargs) -> Union[Tuple[float, float], Tuple[None, None]]:
"""Parses latitude and longitude values stated in kwargs.
Can be called with an object that has latitude and longitude properties, for example:
lat, lng = parse_lat_lng(objec... | 24414d624132ed506f967c9dfcef64e35530c3b5 | 634,129 |
def polynomial_3(x, a, b, c, d):
"""Polynomial order 3 where f(x) = a + b * x + c * x**2 + d * x**3"""
return a + x * (b + x * (c + x * d)) | ff7d51b96580d6f053c4874dc4d8af1260a0139c | 634,135 |
def get_config_part(config_parent, match_key, match_value):
"""
helper function to filter a dict by a dict key
:param dict_: ``dict``
:param key: dict key
:param value: dict key value
:returns: filtered ``dict``
"""
return {k: v for (k, v) in config_parent.items() if v[match_key] == m... | d92a5ad9135df3fb827701ecf0fdc31ba69c4f8d | 634,136 |
from typing import MutableMapping
def test_mock_nested_dict() -> MutableMapping:
"""Mock nested dictionary."""
return {"a": 1, "c": {"a": 2, "b": {"x": 5, "y": 10}}, "d": [1, 2, 3]} | 29b12b28f02238ef91767af235d865ec04a19568 | 634,138 |
def _get_updated_values(before_values, after_values):
""" Get updated values from 2 dicts of values
Args:
before_values (dict): values before update
after_values (dict): values after update
Returns:
dict: a diff dict with key is field key, value is tuple of
(before_va... | 4644549803c16e310677ce6b0cd9770d0299a02c | 634,139 |
from typing import Union
import re
def extract_id_from_message(content: str) -> Union[int, None]:
"""
Scans string to extract user/guild/message id\n
Can extract IDs from mentions or plaintext
:return: extracted id
"""
# matching string that has 18 digits surrounded by non-digits or start/end ... | dfee4595efea16f56c11cf66a4ea8ebb0dcd7313 | 634,140 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.