content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def needs_escaping(text: str) -> bool:
"""Check whether the ``text`` contains a character that needs escaping."""
for character in text:
if character == "\a":
return True
elif character == "\b":
return True
elif character == "\f":
return True
e... | 43110dacad107ab835e76997edc56bba113694b8 | 695,854 |
import torch
def _update_mem(inp_tokens, memory):
"""This function is for updating the memory for transformer searches.
it is called at each decoding step. When being called, it appends the
predicted token of the previous step to existing memory.
Arguments:
-----------
inp_tokens : tensor
... | ef4dc9ed0fd32d207cf584a3c180bf0bb3d6082f | 695,856 |
def CalculateBoxSize(nmol, molwt, density):
"""
Calculate the size of a solvent box.
Parameters
----------
nmol : int
Number of molecules desired for the box
molwt : float
Molecular weight in g/mol
density : float
Estimated density in kg/m3 (this should be about ... | 9508b740c07edd78e33be9cf6f30414e32ab8953 | 695,858 |
def tril_count_from_matrix_dim(matrix_dim: int):
"""Computes the number of lower triangular terms in a square matrix of a given
dimension `(matrix_dim, matrix_dim)`.
Args:
matrix_dim (int): Dimension of square matrix.
Returns:
int: Count of lower-triangular terms.
"""
tril_count... | d1e350986a09c239959de77b821003b5189f6c98 | 695,859 |
def get_bound_indices(str1, str2):
"""Returns the aligned and not bound indices of str1, str2
:param str str1: the first string to align
:param str str2: the second string to align
Caution: order matters, a lot! --> str1 is going to be traversed the other way around # noqa
:return: the free alon... | 8734e23aff50c855cf88044106f501bc90b7e5dc | 695,860 |
def sgd(l_rate, parameters, grads):
"""
Stochastic Gradient Descent.
Parameters
----------
:type lr: theano.tensor.scalar
:param lr: Initial learning rate
:type parameters: theano.shared
:params parameters: Model parameters to update
:type grads: Theano variable
:params grads: Gradients of cost w.r.t t... | aaa1d11788669801b4edd89aca29b38258043ff1 | 695,861 |
def formatResponse(subject, response):
"""Formata a resposta do server e do cliente para a exibição.
Parameters
----------
subject : str
Identifica se é CLIENT ou SERVER.
response : str
Resposta do servidor/client
Returns
-------
formatedResponse : str
... | a87baba551ee8afe684c11b9f3be4a33c4033a90 | 695,863 |
import os
import subprocess
def createThumbnail(originPath, destinationPath, size='200x200') :
"""Creates a thumbnail image out of originPath in destinationPath of size (which defaults to maxWidth:200, maxHeight:200) and keeps ratio. The function creates directory if not exists already. Returns the subprocess's r... | da9691d9fb02cf6b98e9be911d96a5844315ac20 | 695,864 |
def nearest(last, unvisited, D):
"""Return the index of the node which is closest to 'last'."""
near = unvisited[0]
min_dist = D[last, near]
for i in unvisited[1:]:
if D[last,i] < min_dist:
near = i
min_dist = D[last, near]
return near | 8b9ad31fbcba52ee9b9bfbf7c2b0caa78959e6dc | 695,865 |
import logging
import sys
def config_logging():
"""Configure base logging
Function set default logging level and configure outut to stdout
Returns:
logging -- configured loggger
"""
root_logger = logging.getLogger()
root_logger.setLevel(logging.INFO)
formatter = logging.Formatte... | 1c1ffff361912b6f4d0875813998a8f2a24c4ad3 | 695,866 |
import hashlib
def md5_file_hash(file_path):
"""
A method generating MD5 hash of the provided file.
:param file_path: file's path with an extension, which will be opened for reading and generating md5 hash
:return: hex representation of md5 hash
"""
hash_md5 = hashlib.md5()
with open(file... | be8241fd0c254bbfc4d0e1e4330cf36228e0a040 | 695,868 |
def line_coeff_from_endpoints(p1, p2):
"""Given two points on a line, find the coefficients of the line
equation ax + by + c = 0"""
a = p1.y - p2.y
b = p2.x - p1.x
c = -a * p1.x - b * p1.y
return a, b, c | fdbed65cbd3dbabd920817367005c8f05c7dadaf | 695,869 |
import math
def butterfly(theta: float) -> float:
"""Butterfly function"""
return math.e ** math.sin(theta) - 2 * math.cos(4 * theta) | 5d48df3df396fd666770f61e841b3dee2e967ab9 | 695,870 |
from typing import List
from typing import Optional
from typing import Set
def create_exp_name(flags_and_values: List[str],
flag_skip_set: Optional[Set[str]] = None,
skip_paths: bool = False) -> str:
"""
Creates an experiment name based on the command line arguments (be... | e8c6c114a62146a5a3200e88315b1921c28b258f | 695,871 |
def extract_plotly_plot_from_html(html_string, div_id):
"""
extract_plotly_plot_from_html
=============================
Method to extract the Plotly javascript string from an html string create from the python plotly .to_html() function
Only the Plotly javascript string will be extract and returned... | eb78d196411151fed84921261de218d0c1f432ea | 695,872 |
def bisect_left(func, val, low, high):
"""
Like bisect.bisect_left, but works on functions.
Return the index where to insert item x in list a, assuming a is sorted.
The return value i is such that all e in a[:i] have e < x, and all e in a[i:] have e >= x. So if x already appears
in the list, a.in... | de7b72585657c183176b4cd1c6b5301e0f837a01 | 695,873 |
def is_shared(resource):
"""Checks if a resource is shared
"""
return resource['object'].get('shared', False) | dd54a631cff0e79b00942ca4b1e43b1fb2a70c04 | 695,874 |
def _escape(message):
"""Escape some characters in a message. Make them HTML friendly.
Positional arguments:
message -- the string to process.
Returns:
Escaped string.
"""
translations = {
'"': '"',
"'": ''',
'`': '‘',
'\n': '<br>',
}
... | f92b394fcefc9cc9859f4bf8df2c5ea959ddac93 | 695,875 |
def three_digits_palindrome():
"""Function that returns all the possibles aplindromes made from the product
of two three-digit numbers"""
palindrome = []
for index_i in range(100, 999):
for index_ii in range(100, 999):
if str(index_i*index_ii)[::-1] == str(index_i*index_ii):
... | 7438e3952ee089d5f1b8c4c0c1562a63dc1a0ef5 | 695,877 |
def mongo_query(**kwargs):
"""Create a MongoDB query based on a set of conditions."""
query = {}
if 'start_date' in kwargs:
if not ('CreationDate' in query):
query['CreationDate'] = {}
query['CreationDate']['$gte'] = kwargs['start_date']
if 'end_date' in kwargs:
if no... | 6a6636c8d44eb267f6e33fafbe46b8ccf438e37b | 695,878 |
def h1(curr_state, goal_dict):
"""
Heuristic for calculating the distance of goal state using Manhattan distance
Parameters:
curr_state(np.ndarray): A 3x3 numpy array with each cell containing unique elements
goal_dict(dict[int, tuple[int, int]]): A mapping of cell contents to a tuple
conti... | e7d353dcfe5dacee5319dc7b8c4fbae43294acd3 | 695,879 |
import importlib
def plugin_import(plugin):
"""Import a plugin from string.
:param plugin: Python import in dot notation.
:type plugin: String
:returns: Object
"""
return importlib.import_module(plugin, package="directord") | 147c1c053eda10935c1f597cbde1a2d71451f843 | 695,880 |
def arrayManipulation(n, queries):
"""
Args:
n (int): len of zero arr.
queries (list): 2d list with queries
Returns:
int: max element"""
arr = [0] * (n + 1)
# increase first el by query amount and decrease last of query amount
for i in queries:
arr[i[0] - 1] += i... | 14ace75fd238fd0d7086dca9b973b399831e94cd | 695,881 |
def to_selector(labels):
"""
Transfer Labels to selector.
"""
parts = []
for key in labels.keys():
parts.append("{0}={1}".format(key, labels[key]))
return ",".join(parts) | fe17b745f99fb2a5452bbe31264b69c206ece14a | 695,882 |
def inconsistent_info2():
"""
ALso ensures that b and c are very likely to be different
"""
uvw_list = [
('a', 'b', 0.8),
('c', 'd', 0.8),
('b', 'c', 0.001),
('a', 'c', 0.2),
('a', 'd', 0.2),
('b', 'd', 0.99999),
]
pass_values = [
[0, 1, 1,... | 36fa9ec414449f375817cb6ebd17e2b7410a26ae | 695,883 |
def read_unitig_order_file(unitig_order_file):
"""Read unitig directions"""
unitig_order = {}
with open(unitig_order_file) as f:
for line in f:
line = line.rstrip()
tokens = line.split(',')
unitig = tokens[0]
... | a2dad25d5ed119fcdde6291fb734c23b9b6d637d | 695,884 |
def __get_odata_parameter(top=0, skip=0, format="", orderby="", filter=""):
"""統一整理odata的固定參數指定回傳
Keyword Arguments:
top {int} -- 回傳幾筆 (default: {0})
skip {int} -- 跳過前面幾筆 (default: {0})
format {str} -- 回傳格式 json or xml (default: {""})
orderby {str} -- 排列順序, 傳入response欄位名稱 (defau... | 93820d1ac8c16574694331c6bfc60662fc7d89f0 | 695,885 |
def search_escape(url):
"""Escape URLs such that preexisting { and } are handled properly.
Will obviously trash a properly-formatted qutebrowser URL.
"""
return url.replace('{', '{{').replace('}', '}}') | ad0a1d3ff499cbf2706838c44f03df60bd40e1a9 | 695,886 |
def Edges_Exist_Via(G, p, q):
"""Helper for del_gnfa_states
---
If G has a direct edge p--edgelab-->q, return edgelab.
Else return "NOEDGE". We maintain the invariant of
at-most one edge such as edgelab for any p,q in the GNFA.
"""
edges = [ edge
for ((x, edge), St... | 53af339eb5317321a8f125a289215bff89a95b5d | 695,887 |
import csv
import requests
def get_words(min_length=5,max_length=5,capitalization='lower',use_file=''):
"""Gets a list of english words from instructables of a desired length.
Args:
min_length (int, optional): Keep words of this length or longer. Defaults to 5.
min_length (int, optional): Kee... | ceeacd7772ced20c86d3a66cb966cb25ea286d85 | 695,888 |
import hashlib
import binascii
def multipart_etag(digests):
"""
Computes etag for multipart uploads
:type digests: list of hex-encoded md5 sums (string)
:param digests: The list of digests for each individual chunk.
:rtype: string
:returns: The etag computed from the individual chunks.
""... | 1d6d13d3f28cdbae6a56fe903329bd8f91b53000 | 695,889 |
def Tsorties_echangeur(Te1,Te2,mf1,mf2,Cp1,Cp2,eff):
"""
Calcul les températures au niveau des sorties d'un échangeur thermique'
Parameters
----------
Te1 : Température d'entrée du fluide chaud
Te2 : Température d'entrée du fluide froid
mf1 : Débit massique du fluide chaud
mf2 : Débi... | ebae4e1f99bc0eea1941e85dbd5087f825bb5105 | 695,890 |
import json
def load_schema(filename):
"""Load schema from a JSON file.
Parameters
----------
filename : str
The path to your file.
Returns
-------
schema : dict
A dictionary containing the schema for your table.
"""
with open(filename) as f:
schema = jso... | 55b475a4cc7bfb184c0f2db3e41d6e3408b888e6 | 695,891 |
def define_path(use_jaad=True, use_pie=True, use_titan=True):
"""
Define the correct paths to datasets'annotations and images
"""
all_anns_paths = {'JAAD': {'anns': '../../DATA/annotations/JAAD/JAAD_DATA.pkl',
'split': '../../DATA/annotations/JAAD/splits'},
'PIE': {'anns': '..... | 7113772b29ded254059451b8f5317c91ea4c2e18 | 695,892 |
import inspect
def get_linenumbers(functions, module, searchstr='def {}(image):\n'):
"""Returns a dictionary which maps function names to line numbers.
Args:
functions: a list of function names
module: the module to look the functions up
searchstr: the string to search for
Retu... | b2cc1bc104cdae6bbbfb3680ac940540396db08a | 695,893 |
def cron_to_dict(cron_keys, time_data):
"""
将crontab风格的时间, 组成dict
:param time_data: str cron风格的时间
:param cron_keys: str cron 使用的时间关键词
:return: dict cron按照给定的时间key组成dict
"""
cron_dict = dict(zip(cron_keys, time_data.split()))
return cron_dict | 1a75999198fdb7383fd87e3b6f15e5900648cdb5 | 695,894 |
def get_lrs(optimizer):
"""Return the learning-rates in optimizer's parameter groups."""
return [pg['lr'] for pg in optimizer.param_groups] | 6e32c90e42321d070cc1f444a6f117b72ad59adb | 695,895 |
def highlight_min(s):
"""
highlight the minimum in a Pandas dataframe series yellow
"""
is_min = s == s.min()
return ["background-color: yellow" if v else "" for v in is_min] | ee74a19721fc7312744847b0c4d6de9255f312b0 | 695,896 |
import torch
def Rotz(t):
"""
Rotation about the z-axis.
np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]])
-- input t shape B x 1
-- return B x 3 x 3
"""
B = t.shape[0]
Rz = torch.zeros((B, 9, 1), dtype=torch.float)
c = torch.cos(t)
s = torch.sin(t)
ones = torch.ones(B)
Rz[:, 0, 0] = c
Rz[:, 1, 0]... | 6a078e033f6ad6b497da05999433ef745c76d2ed | 695,897 |
def __get_edge_dict(uid, source, target, color, edge_type):
"""
Create dictionary for edges
:param uid:
:param source:
:param target:
:param color:
:param edge_type:
:return:
"""
return {
'id': uid,
'source': source,
'target': target,
'color': col... | 3ef239f3f19d584b9157b8e320074a7d4bf6f630 | 695,898 |
def calc_Flesh_Kincaid_Grade_rus_adapted(n_syllabes, n_words, n_sent, X, Y, Z):
"""Метрика Flesh Kincaid Grade для русского языка с параметрами"""
# n = 0.59 * (float(n_words) / n_sent) + 6.2 * (float(n_syllabes) / n_words) - 16.59
if n_words == 0 or n_sent == 0: return 0
n = X * (float(n_words) / n_sent... | a3fd7cc72bf701f8b8f2ff47bb123eca855dba5a | 695,899 |
import sys
def is_booted_volume():
"""
Returns True if the script / package (pkg) is being executed on
the booted volume, or False if being executed on a targeted volume.
"""
# sys.argv will only have more than 3 arguments when running within a pkg
# (which means scripts are always targeting ... | 534c857c42a93f0eeb36bfc67771f8b6679398c7 | 695,900 |
import tokenize
import codecs
def read_pyfile(filename):
"""Read and return the contents of a Python source file (as a
string), taking into account the file encoding."""
with open(filename, "rb") as pyfile:
encoding = tokenize.detect_encoding(pyfile.readline)[0]
with codecs.open(filename, "r",... | a6fce0f2acdb5156872ef572ab7e77ba6507873d | 695,901 |
def parse_version_string(version):
"""
Returns a tuple containing the major, minor, revision integers
"""
nums = version.split(".")
return int(nums[0]), int(nums[1]), int(nums[2]) | a8d50804ebe82541e57c83a813843d255b3b6fbb | 695,902 |
def interpc(coef, lat):
""" linear interpolation (lat step=15) """
i = int(lat/15.0)
if i < 1:
return coef[:, 0]
if i > 4:
return coef[:, 4]
d = lat/15.0-i
return coef[:, i-1]*(1.0-d)+coef[:, i]*d | f5ae562febeacbe51aaba5f9c187f47591a936fc | 695,903 |
def choosePokemon():#a function that allow user choose a pokemon and store its value
""" """
Pokemon=""
while Pokemon != "charmander" and Pokemon != "squirtle" and Pokemon != "bulbasaur":#allow user choose again if the input is not one of the three
Pokemon = input("Which Pokemon woul... | ce18f020ed12a4e8b1a78f4ebbdb750775925b5d | 695,904 |
import os
def greet():
"""
Greet our user.
"""
return {
'message': 'Hi there fella',
'hostname': os.environ.get('HOSTNAME'),
} | 63068865c91504c6fc408ff22ecf0329d22b464c | 695,905 |
def autocomplete(s: str, d: list):
"""
:param s: query
:param d: words
:return:
"""
return [word for word in d if word[:len(s)] == s] | b23df7fcf1bab63e0f4bda3a064bd9da40416949 | 695,906 |
import functools
def dual_decorator(func):
"""This is a decorator that converts a paramaterized decorator for no-param use.
source: http://stackoverflow.com/questions/3888158.
"""
@functools.wraps(func)
def inner(*args, **kw):
if ((len(args) == 1 and not kw and callable(args[0]) and
... | 145c640fd9a6a7fd4dd9b0fba4b0c9e42b30b734 | 695,907 |
def get_building_coords(town):
"""
Generates a dictionary of all (x,y) co-ordinates that are within buildings
in the town, where the keys are the buildings' numbers (or "pub" for the
pub) and the values are lists of co-ordinates associated with the building.
Data must have 25 houses (numbered as mu... | 085c95d40d9d84569180155f5b0b150334dbc526 | 695,908 |
import inspect
def is_simple_scheduler(scheduler_class):
"""
Determines whether a scheduler is a "simple" scheduler, i.e. it doesn't consider feedback from the runner.
"""
methods = inspect.getmembers(scheduler_class, inspect.isfunction)
method_names = [name for name, _ in methods]
return not ... | c7ee776ad9305c52d851e2f02c934f161e5b49ec | 695,909 |
import os
def get_document_assets_data(current_version):
"""
Retorna os dados dos ativos da versão atual de um documento registrado
no Kernel
"""
LAST_VERSION = -1
# agrupa items que representam o mesmo ativo
assets_by_prefix = {}
assets_data = []
assets = current_version.get("asse... | 53b2da615cea5eba926e56a1656fbea11e637d30 | 695,910 |
def promptConfirm(message: str) -> bool:
""" Prompts confirming a message. Defaults to "no" (False).
:param message: Message to prompt.
:return: Whether the prompt was confirmed.
"""
result = input(message + " (y/N): ").strip().lower()
return result == "y" or result == "yes" | 4d0ba40150231939571915676740a1e6b5857f0d | 695,912 |
def IntegerConversionFunction(character):
"""
Helper function for file reading.
"""
if(character == ' '):
return 0
elif(character == '+'):
return 1
elif(character == '#'):
return 2 | 6d2bf6a32cd78405b95722cc043bd529b77da0c4 | 695,913 |
def _check_state(monomer, site, state):
""" Check a monomer site allows the specified state """
if state not in monomer.site_states[site]:
args = state, monomer.name, site, monomer.site_states[site]
template = "Invalid state choice '{}' in Monomer {}, site {}. Valid " \
"state... | 8f61c91ddae5af378503d98377401446f69c37db | 695,914 |
def get_merged_areas_recursion(merge, areas):
"""
Merge nodes recursively according to area superposition
"""
for index, n1 in enumerate(merge):
if len(merge) != 1:
n2 = merge[index + 1]
if min(n2[0]) <= max(n1[0]):
if min(n1[1]) <= min(n2[1]) <= max(n1[1]... | 9ab0c392ab3dc824ce9b6445ec0648da4e32ec7e | 695,915 |
import unicodedata
def unicode_to_ascii(s):
"""
Takes in a unicode string, outputs ASCII equivalent
:param s: String of unicode
:return: String of ASCII
"""
return ''.join(c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn') | 03781e1286aef5a67ea389dad4fcf59cc9317f23 | 695,916 |
def read_value(value):
"""Helper function to asynchronously call read() on a Calculator::Value and
return a promise for the result. (In the future, the generated code might
include something like this automatically.)"""
return value.read().then(lambda result: result.value) | 6a4176950210cec9b13aff1d88deb420894a5971 | 695,917 |
def wrap_fn_hessian(fn, i, j, **kwargs):
"""
A wrapper for the QCA batch downloader for Hessians
"""
# out_str = kwargs["out_str"]
# kwargs.pop("out_str")
# prestr = "\r{:20s} {:4d} {:4d} ".format(out_str, i, j)
# elapsed = datetime.now()
objs = [obj for obj in fn(**kwargs)]
# ... | d46626c8f5d01f66f397a5688826cefa8af5501b | 695,918 |
def check_form(form_data):
"""
Function that perform a small check on submited form data
"""
# check if there are any empty fields
for key, value in form_data:
if value == "":
return None
return form_data | 366c5edcf37e453b2f10b29610c898cac6adc3a3 | 695,919 |
import subprocess
def cli(path):
"""
Run a test coverage report
Args:
path (str): test coverage path
:return: Subprocess call result
"""
cmd = 'py.test {0}'.format(path)
return subprocess.call(cmd, shell=True) | 03188c67ccd38ec7f93922f01b7a6f7f54a076c8 | 695,920 |
def make_stun(action):
"""Return a new action method that does nothing.
action -- An action method of some Bee
"""
# BEGIN Problem EC
def new_action(colony):
pass
return new_action
# END Problem EC | fbabcedc4a325f7557fa4ab13e784612086a6276 | 695,921 |
def building_block(case_data):
"""
A :class:`.BuildingBlock` instance.
"""
return case_data.building_block | 5619f1363919072012123db906a84b9dfc744b77 | 695,922 |
def image_layers(state):
"""Get all image layer names in the state
Parameters
----------
state : dict
Neuroglancer state as a JSON dict
Returns
-------
names : list
List of layer names
"""
return [l["name"] for l in state["layers"] if l["type"] == "image"] | 6c843855e01957386871f90d54eee69800f08c37 | 695,923 |
import numpy
def fill_with_zeros(evecs, from_res, to_res, width):
"""
In the IC case we have an initial residue with only one angle
"""
real_from_res = from_res - 1
real_to_res = to_res - 1
real_width = (width*2)-1
ending_left_pad_index = (real_from_res*2)-1
start_right_pad_index... | 45cf3ecc1b5fe86f40d56547969ec076d099ec29 | 695,924 |
def station_name_filter(name: str, filter_dict: dict[str, str]) -> str:
"""Applies filters to the names of stations as described in generate_filter. But it also adds
' station' to the end of each station name.
filter_dict: filter generated by generate_filter
returns: modified station name
"""
... | b5ac0dc011d07021b299b28f10bda413063f8536 | 695,925 |
def task_compile_prod_requirements():
"""generate prod requirements for service"""
return {
"file_dep": ["../requirements.prod.in"],
"actions": ["../venv/bin/pip-compile -o ../requirements.txt ../requirements.prod.in"],
} | 90a3b91c58eab31f997e948e2462f694963f7328 | 695,926 |
import requests
def coordinate_finder(result: requests.Response) -> tuple:
"""
One filter function for the send_get_request function. This filter function is used for
getting a tuple (lat, long) from the wikipedia geoData api with type props=coordinate.
More information found: https://www.mediawiki.or... | 3069e7c3782d292fc708f79a7d178a4b4f40ebb7 | 695,928 |
import argparse
import sys
def Get_Arguments():
"""
Parse command-line arguments. Imported with argparse.
Returns: object of command-line arguments.
"""
parser = argparse.ArgumentParser(description="Converts directory of FASTA files to input file for CLADES for species delimitation", add_help=Fals... | 163bccb6c0b1b64e4e7fb185f11b3d7dfd90538c | 695,929 |
def filter_merge_clusters(clusters, max_block_size_multi=5, min_block_pop=50, buffer_amount=150):
"""
The vectors created by create_clusters() are a single square for each raster pixel.
This function does the follows:
- Remove overly large clusters, caused by defects in the input raster.
- Remove clusters with pop... | 8b6091baeb55e0c72c468aa6eb4300c4db40ecbd | 695,931 |
import re
def remove_special_phrases(s):
"""
:param s:
:return:
"""
special_phrases = ['480p',
'720p',
'1080p',
'H.264',
'H265',
'Ac3',
'Aac2',
... | 632838e9d0436ddca48122a7a047b7349717c78e | 695,932 |
def makeShapeTranslation ():
"""Makes a character translation for the 'shape' feature, which maps upper/lowercase letters to X/x and digits to 'd'."""
source = ""
target = ""
source += "aeiou"
source += "bcdfghjklmnpqrstvwxyz"
target += "x" * 26
source += "AEIOU"
source += "BCDFGHJKLMNPQ... | 9c2be5953c6db36f2f510f89dee1cff62548c017 | 695,933 |
import pickle
def load(path):
"""
Load pickled pandas object (or any other pickled object) from the specified
file path
Parameters
----------
path : string
File path
Returns
-------
unpickled : type of object stored in file
"""
f = open(path, 'rb')
try:
... | 6ed0b0ae944fa8bdaacfd4cbd8cdb3864f1adb47 | 695,934 |
from datetime import datetime
def totimestamp(datetime_object):
"""Because in python2 datetime doesn't have timestamp() method,
so we have to implement in a python2,3 compatible way.
"""
return (datetime_object - datetime(1969, 12, 31, 20, 0)).total_seconds() | 68b6e19aac974a17a7c0f9980c6fcec347e8a861 | 695,935 |
def get_y_indicator_variable_index(i, j, m, n):
"""
Map the i,j indices to the sequential indicator variable index
for the y_{ij} variable.
This is basically the (2-dimensional) 'array equation' (as per
row-major arrays in C for example).
Note that for MiniSat+, the variables are juist indexed... | 8c6dc999ebe3120084ae741403f15acdd900e783 | 695,936 |
def truncate_string(s,length):
""" Truncate string to given length.
"""
return s[0:min(length,len(s))] | 9b44cf31c7905109497e485d0ffa707dada9d67b | 695,937 |
import base64
def base64_encode(input_val):
"""
:param input_val: bytes to be base64 encoded
:type input_val: buffer or str
:return:
"""
return base64.b64encode(input_val) | ba0b7d72b6ceda9ad9687caa88ee9e566d15562a | 695,938 |
import torch
def inverse_sigmoid(x, eps=1e-5):
"""Inverse function of sigmoid.
Args:
x (Tensor): The tensor to do the
inverse.
eps (float): EPS avoid numerical
overflow. Defaults 1e-5.
Returns:
Tensor: The x has passed the inverse
function of sig... | 01d02c9f04d4a9318f0ec0d4bb8cf7301181c8f5 | 695,939 |
def keypress_to_dispatch_key(key, scancode, codepoint, modifiers):
"""Converts the key_down event data into a single string for more convenient
keyboard shortcut dispatch.
:returns: The dispatch key in format ``109+alt,shift`` -- key number, ``+``,
and the modifiers joined by commas.
"""
if... | 16dd835511b3e31eeb2278013b6a194172aa2e06 | 695,940 |
def thermo_data_text(species_list, note, input_type='included'):
"""Returns thermodynamic data in Chemkin-format file.
Parameters
----------
species_list : list of cantera.Species
List of species objects
input_type : str, optional
'included' if thermo will be printed in mech file, 'f... | 600be4eb4a2420d1c4ebb8f2285f5ece0ad1b9a9 | 695,941 |
def get_best_sales_rep(df):
"""Return a tuple of the name of the sales rep and
the total of his/her sales"""
best_rep_df = df.groupby(['Rep'])['Total'].sum()
return (best_rep_df.idxmax(), best_rep_df.loc[best_rep_df.idxmax()])
pass | e4313cf517ecb513918944fdbb55caea3f20fb0c | 695,942 |
def _calc_time_threshold(seg_mean: float, seg_std: float) -> float:
"""
Auxiliary function for calculating the threshold based on the
mean and standard deviation of the time transitions between
adjacent places on discrete MoveDataFrame.
Parameters
----------
seg_mean : float
The t... | 82e4a605327f20e39794e4a23ab6c9d422a06274 | 695,943 |
def _solveX(L, U, b):
"""Use forward and backwards substitution to calculate the x vector to solve the linear system of equations.
Parameters
----------
L: numpy.arrays
Lower triangular matrix
U: numpy.arrays
Upper triangular matrix
b: numpy.array
Column vector of constant terms
Returns
-------
x: nu... | 997b472ea45796268a1d87c5ade3de4ab66115a0 | 695,944 |
def nearest_square(num):
"""
Find the nearest square number to num
"""
root = 0
while (root + 1) ** 2 <= num:
root += 1
return root ** 2 | 53b899958a053c8bfe6383e240d3b8ddb7d291c1 | 695,945 |
import socket
def create_rawsock(iface):
"""Creates a new raw socket object.
The socket sends/receives data at the link layer (TCP/IP model)/data-link
layer (OSI model).
Args:
iface: A string specifying the name of the network interface to which
the raw socket should be ... | ea56408403ada6b9750265547677028c197ae933 | 695,946 |
import math
def atan(x):
"""
x est un nombre
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Retourne un angle en radians dont la tangente vaut x.
"""
return math.atan(x) | a11a046f4017678d5276adb776018ba7904b7148 | 695,947 |
def vector_mul(k, a):
"""Multiplication of a vector by a scalar.
>>> vector_mul((1, 2), 2)
(2, 4)
"""
return tuple(map(lambda x: k * x, a)) | cdc289430ab87ac70e8387d4dd807fb4dfd1e1da | 695,949 |
def fetch_annotations(blast_results, ref_file):
"""
Fetch protein annotations from a reference file
for the proteome of SfMNPV 3AP2.
"""
# Store reference annotations into a dictionary
with open(ref_file, 'r') as fh:
next(fh)
references = {line.split(",")[0]: line.split(",")[1]
... | 6e951fc8d6251209e4e8b78ce87e9ec2d60003c0 | 695,950 |
def floret_vectors_vec_str():
"""The top 10 rows from floret with the settings above, to verify
that the spacy floret vectors are equivalent to the fasttext static
vectors."""
return """10 10
, -5.7814 2.6918 0.57029 -3.6985 -2.7079 1.4406 1.0084 1.7463 -3.8625 -3.0565
. 3.8016 -1.759 0.59118 3.3044 -0.... | 5b9321ba6cae72760ced79085073de812b1c8070 | 695,951 |
import random
def crossover(chromosome1, chromosome2):
"""
We only swap single weights.
Half from the father, half from the mother. The half aspect will be done with RNG w/ 50% chances.
Alternatives would be to swap weights of a whole neuron, or an entire layer.
"""
offspring_chromosome = []
for i in range(len... | 04d1f50b91d56d993154afc4381e14682268e1fd | 695,952 |
def null_compare(path_test, path_ref, rtol, atol):
"""A null comparison. This is used when a result file is required to be
produced by a test, but it is not possible to compare to a benchmark.
"""
return True | 66e7706950435828776ea67c0b6940cc32bad85c | 695,953 |
import math
def replace_invalid_values(row):
"""Replace float values that are not available in BigQuery.
Args:
row: List of values to insert into BigQuery.
Returns:
List, `row` with invalid values replaced with `None`.
"""
invalid_values = [math.inf, -math.inf, math.nan]
return [x if x not in in... | c07c16780a52870f9d0954b3f8bba5a91baf6b58 | 695,954 |
def abbreviate(words):
"""
return an acronym that represent 'words'
"""
return(''.join([letter for (index, letter) in enumerate(words)
if index == 0 or words[index-1] in [' ', '-']]).upper()) | 605082359b57deba84e8d1524a4543c798cfc587 | 695,955 |
import logging
def getLogger():
"""
Get a :class: `logging.getLogger` object
:return: logging oject
:rtype: :class:`logging.getLogger`
"""
return logging.getLogger() | a0e5b7cb8f8ffe1ffc8b18eb6bbacc5e50b3fc5b | 695,956 |
import os
def _python_files_in_dir(builder, root_dir):
"""Return a list of the ``*.py`` files in the specified directory.
This includes subdirectories.
Arguments:
builder (FileBuilder): The ``FileBuilder``.
root_dir (str): The directory.
Returns:
list<str>: The files.
""... | 2b10602b73f79d128a77f29222d113c00f9f04cc | 695,957 |
def interp_from_u(idx, w, y):
"""
compute Wy
W.shape: (n, u)
y.shape: (u,)
"""
return (y[idx] * w).sum(axis=1) | b0312063699a16a75307774dbf54cb758082d678 | 695,959 |
def parse_offered(course_description):
"""Parses which quarters a course is offered from a course description.
Args:
course_description: The course description text.
Returns:
The quarters the course is offered.
"""
if 'Offered:' not in course_description:
return []
parts = course_description.... | 75005e4eae61717e64a7cfa821e6f772d4a93420 | 695,960 |
def A004767(n: int) -> int:
"""Integers of a(n) = 4*n + 3."""
return 4 * n + 3 | 5f97cccc4f540b46029e57c11d1ab718a59e227c | 695,961 |
def convertXML(imagePath, labels):
"""
Convert imagePath, labels to string.
Args:
imagePath
labels
Return:
outString: a string of image path & labels.
"""
outString = ''
outString += imagePath
for label in labels:
for i in label:
... | 21a1154b6202131a3fea51156590c299fd540069 | 695,962 |
import warnings
def test_pqtb_values(p, q, T, b_interslice):
""" Tests that p, q have valid values; prints warnings if necessary; and returns valid values.
"""
# Convert parameter ints to floats
if isinstance(p,int):
p = float(p)
if isinstance(q,int):
q = float(q)
if isinstanc... | c82af66ea91048b10edb8246895642cb9e91be6f | 695,964 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.