content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def paths_same_disk(photos_path:str, export_path:str)->bool:
"""
Checks if the provided input path and the export path are "located" on the same disk.
:param photos_path: path to photos
:type photos_path: str
:param export_path: path to the directory where the photo folder structure will be created... | 07476953bbaec5ad0045b064ea5ce09e246ebca1 | 681,135 |
def check_bibtex_entry(entry, fix = False):
"""
Check whether an entry is suitable for the database. Returns None if all is ok, else
returns a user-readable string describing the error.
If fix is set to true then will 'fix' any problems by replacing errors with dummy values.
This is only useful during testing and... | 924fd267b8a9dd4023bf8731ff7ef2da8c9ddd45 | 681,136 |
def get_handcrafted_feature_names(platform):
"""
Returns a set of feature names to be calculated.
Output: - names: A set of strings, corresponding to the features to be calculated.
"""
names = set()
###############################################################################################... | ccdf430b0403c1152f40c9c0bdf5fbb380d8f0c1 | 681,137 |
import torch
def torch_get_device_according_to_device_type(device_str):
"""
:param device_str: e.g.: 'cpu', 'gpu', 'cuda:1'
:return:
"""
# enabling GPU vs CPU:
if device_str == 'cpu':
device = torch.device('cpu') # default CPU. cpu:0 ?
elif device_str == 'cuda:1':
device =... | 12077ed6a7ed7bbbbb6e43fbdf9a7e444d2576d5 | 681,138 |
def get_batch(batch):
"""Get the batch into training format.
Arg:
batch: The iterator of the dataset
Returns:
batch_data: The origin processed data
(i.e batch_size * (triples, summary))
batch_idx_data: The indexing-processed data
(e.g bat... | 33d20b206796e8d2278a999e4aa0928cba055a09 | 681,139 |
import inspect
import os
def get_caller_dir():
""" """
# get the caller's stack frame and extract its file path
frame_info = inspect.stack()[3]
filepath = frame_info.filename
del frame_info # drop the reference to the stack frame to avoid reference cycles
# make the path absolute (optional)
... | 10990b387e4266cb6374fd39aef9915101e033dc | 681,140 |
def get_key_name_as_convention(desired_name: str):
"""
:param desired_name: The name you would
like to convert
:return: The key name as a personal
convention I'm using for brightness.ini
"""
return desired_name.lower().replace(" ", "").replace(":", "") | 6cba92a552d9f51b9e3811c9d3b0afe63682c2b8 | 681,141 |
def firstn_A(n):
"""List generation method"""
num, nums = 0, []
while num < n:
nums.append(num)
num += 1
return nums | a7bea94a38671ee661faeb4cf7361b18dad99973 | 681,142 |
from pathlib import Path
def make_path_like(path_like):
"""Attempts to convert a string to a Path instance."""
if isinstance(path_like, Path):
return path_like
try:
return Path(path_like)
except TypeError:
raise TypeError(f'could not convert to Path: {path_like}') | 5b3eeffc8cad733c684deae0338218a1eaac494b | 681,143 |
import tempfile
import json
def write_json_temp_file(data):
"""Writes the provided data to a json file and return the filename"""
with tempfile.NamedTemporaryFile(delete=False, mode='wb') as temp_file:
temp_file.write(json.dumps(data).encode('utf-8'))
return temp_file.name | 15c0b5df8b56fed6d7016d3dd34de203ab56a62e | 681,144 |
import argparse
def get_args():
"""Get arguments from command line."""
parser = argparse.ArgumentParser(
description='Get a list of rhyming words.',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('word', help='Word to be rhymed')
return parser.parse_args() | 3f80be0c25c74d03f74cf6eb43ac07b80e6b5c20 | 681,145 |
def read_input(path: str) -> list:
"""
Read game board file from path.
Return list of str.
>>> read_input("check.txt")
['***21**', '412453*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***']
"""
with open(path, 'r') as lines:
state = []
for line in lines:
s... | 87fcbe0af89167c1c76f81118ab0164b56940087 | 681,146 |
def pairs(clustergenerator, labels):
"""Create an iterable of (N, {label1, label2 ...}) for each
cluster in a ClusterGenerator, where N is "1", "2", "3", etc.
Useful to pass to e.g. vambtools.writer_clusters.
Inputs:
clustergenerator: A ClusterGenerator object
labels: List or array of c... | 5751e2e58a2e4694067ec0c4b7f8e3c3953ef171 | 681,147 |
def lstsq(X,Y):
"""
最小二乘法线性回归
"""
n = len(X)
sumX,sumY,sumXY,sumXX =0,0,0,0
for i in range(0,n):
sumX += X[i]
sumY += Y[i]
sumXX += X[i]*X[i]
sumXY += X[i]*Y[i]
a = (n*sumXY -sumX*sumY)/(n*sumXX -sumX*sumX)
b = (sumXX*sumY - sumX*sumXY)/(n*sumXX-sumX*sum... | 65ccc93d6c17f1b8290feeba816848f1b5d9dd9c | 681,148 |
def message_is_nonzero(incoming_message):
"""
returns True if all slots and subslots are nonzero
False otherwise
Note: tested only with geometry messages Twist()
"""
slots_objects = incoming_message.__reduce__()[2]
for slot_object in slots_objects:
value_list = slot_object.__reduce_... | 35133daa38bf26c2679b8900c6cbe25b4c843282 | 681,149 |
import cProfile
def profile_me(func): # pragma: no cover
""" Profiling decorator, produce a report <func-name>.profile to be open as
`python -m snakeviz <func-name>.profile`
Parameters
----------
func : func, function to profile
"""
def profiled_func(*args, **kwargs):
filename =... | 538080c01659f19ad89ece28b754bbe38488f43c | 681,150 |
def cubec_to_cubei(cubec):
"""Cube centimetre to cube inch"""
return cubec * 0.061 | 1db3f73336d4322405a9aabddfb186a0e882f3d8 | 681,151 |
def create_plain():
"""Create string of plain characters alphabetized."""
return "abcdefghijklmnopqrstuvwxyz" | 870e3d4c18e7d86927225ec1ea41c20d20a1c6f5 | 681,152 |
import math
def determine_padding(filter_shape, output_shape="same"):
"""Method which calculates the padding based on the specified output shape
and the shape of the filters."""
if output_shape == "valid":
return (0, 0), (0, 0)
elif output_shape == "same":
filter_height, filter_widt... | 12ef1c8d624f0dfd161c8723736610fa86c9ce1d | 681,154 |
def no_conditions(node_conditions):
"""
:param node_conditions:
:return:
"""
for node in node_conditions:
if bool(node):
return False
return True | 9d06c99f4ed8117186c583807d38c9b5e22ada1c | 681,155 |
from typing import Sequence
from typing import Optional
from typing import Callable
def make_add_field_names_preprocessor(
field_names: Sequence[str], field_indices: Optional[Sequence[int]] = None,
) -> Callable:
"""Make a preprocessor to add field names to a dataset.
Create a preprocessor that converts ... | 55389339ffd44669cfb7f0571bb893524c7df0a4 | 681,156 |
def strip_parentheses(string):
"""
Remove parentheses from a string, leaving
parentheses between <tags> in place
Args:
string: the string to remove parentheses from
Returns:
the processed string after removal of parentheses
"""
nested_parentheses = nesting_level = 0
res... | dc05344a9c5f9de2e53546104ffff2925ca2c628 | 681,157 |
def parse_multplt(path):
"""
Parses multplt.def file and returns list of lists like: [station, channel type (e.g. SH), channel (E, N or Z)].
"""
data = []
with open(path, "r") as f:
lines = f.readlines()
tag = "DEFAULT CHANNEL"
for line in lines:
if line[:len(tag... | c1d0d33c60c200bf16a6277f5e9110af334c98c2 | 681,158 |
import time
def calculate_time(func):
"""
this higher-order function calculates and print out
the execution time of the arg function
"""
def inner(*args, **kwargs):
# storing time before function execution
begin = time.time()
result = func(*args, **kwargs)
# storing... | 0d25ce70e312d2a40d5179e823d20247063bd167 | 681,160 |
def count_neighbors(grid2count, posInRow, posInCol):
"""returns number of ALIVE neighbors from a given position on a given grid using try except approach"""
count = 0
for x in range(-1, 2):
for y in range(-1, 2):
try:
if grid2count[posInRow + x][posInCol + y] == 1:
... | 109768eb5531cc3842fc95630fc6617be8c668d8 | 681,162 |
def run_query(client, query):
"""
Runs BigQuery queryjob
:param client: BigQuery client object
:param query: Query to run as a string
:return: QueryJob object
"""
return client.query(query) | d75c2aedd3855b1d4c3881a74539e1ffdd4dc174 | 681,163 |
import os
def _path(*args):
"""Join args as path."""
return os.path.join(*args) | c436bb8d22a16f7d590fcb095ce560a93c813821 | 681,164 |
def isRoot(obj, scene=None):
"""Returns whether or not the object passed to obj is a Phobos model root.
Args:
obj(bpy.types.Object): The object for which model root status is tested.
scene: (Default value = None)
Returns:
"""
rootdefinition = obj is not None and obj.phobostype in ['li... | e81bac9ef9382869c63b6edc7fd2652a7d7eb28d | 681,165 |
def add_scalebar(image_obj, scalebar_px):
""" Adds a scalebar to the input image and returns a new edited image
"""
## set the indentation to be ~2.5% inset from the bottom left corner of the image
indent_px = int(image_obj.height * 0.025)
## set the stroke to be ~0.5% image size
stroke = int(im... | 23a155ecae997f5b871ffddbc63c581029ae780b | 681,167 |
def sentence_case(sentence, exciting=False):
"""Capitalise the first letter of the sentence and add a full stop."""
sentence = sentence[0].upper() + sentence[1:]
if sentence[-1] in {'.', '!', '?'}:
return sentence
elif exciting:
return sentence + "!"
else:
return sentence + "." | 6abcf11f2ab6529fa3450b9a058f8961c8a690e3 | 681,168 |
import time
def get_cpu_time_unit():
"""
a unit of time independent on cpu run this code for simulating time
"""
started_at = time.time()
for i in range(1, 10000):
if i % 2 == 0:
temp = i / 2
else:
temp = 2 * i
ended_at = time.time()
return ended_a... | 51cb66c6ad7263994de58027647224f67b38c2fb | 681,169 |
def lerp(a, b, x):
"""Linear interpolation between a and b using weight x."""
return a + x * (b - a) | b6790c221e797bfa0fe063a22ebced60eab877db | 681,170 |
def grid_search_params(params):
"""
Given a dict of parameters, return a list of dicts
"""
params_list = []
for ip, (param, options) in enumerate(params.items()):
if ip == 0:
params_list += [{param: v} for v in options]
continue
_params_list = [dict(_) f... | fa12fc66637c0563097741113949c9278834ba93 | 681,172 |
def pretty_eta(seconds_left):
"""Print the number of seconds in human readable format.
Cited from baselines (OpenAI)
Examples:
2 days
2 hours and 37 minutes
less than a minute
Paramters
---------
seconds_left: int
Number of seconds to be converted to the ETA
Returns
... | 15f9b3f679fe671e0c19fb76ecd5d6129d89c3a6 | 681,173 |
import os
def xisfile(somefile):
"""tests the given file is available for reading."""
if (somefile is None):
return False
if os.path.isabs(somefile) and os.path.isfile(somefile):
return os.access(somefile, os.F_OK ^ os.R_OK)
return os.path.isfile(os.path.abspath(somefile)) | bc4d6381d2c2e9fd38dd806f1e9fb4a7343b6de4 | 681,174 |
import copy
def update_categories(desired_name2id: dict, coco_dict: dict) -> dict:
"""
Rearranges category mapping of given COCO dictionary based on given category_mapping.
Can also be used to filter some of the categories.
Arguments:
---------
desired_name2id : dict
{"big_veh... | 2a2e18d50ce20742406c400fcee341442d35a7da | 681,175 |
def term_frequency(term, tokenized_document):
"""Tokenized document is the list of tokens(words in a document)"""
return tokenized_document.count(term) | d5e73c779298acca0ad17e2be6c41fb27430588b | 681,177 |
def _EdgeStyle(data):
"""Helper callback to set default edge styles."""
flow = data.get("flow")
if flow in {"backward_control", "backward_data", "backward_call"}:
return "dashed"
else:
return "solid" | 22a43f452cf365bd405d458992986995cb573f44 | 681,178 |
import math
def _flat_hex_coords(centre, size, i):
""" Return the point coordinate of a flat-topped regular hexagon.
points are returned in counter-clockwise order as i increases
the first coordinate (i=0) will be:
centre.x + size, centre.y
"""
angle_deg = 60 * i
angle_rad = math.pi / 180... | eeb1e7539ae182e5ed720d35ba85c019e9dc6529 | 681,180 |
import requests
def make_get_request(uri: str, payload):
"""
Function to make a GET request to API Endpoint
:param uri:
:param payload:
:return:
"""
response = requests.get(uri, payload)
if response.status_code != 200:
return None
else:
return response.json() | cf7c97415658b3d7a059f862a7251b66ecf2ca59 | 681,182 |
def matrix_have_value(matrix, value):
"""
判断递增矩阵中是否有某个值
:param matrix:
:param value:
:return:
"""
if not matrix:
return False
m = len(matrix)
n = len(matrix[0])
point = (0, n - 1)
while True:
if point[0] >= m or point[1] < 0:
break
if mat... | 64f87220e2a334c86ee92a7bd5dbe8b3a06976f3 | 681,183 |
def has_two_adjacent(password):
"""Check if the password contains a pair of adjacent digits"""
last_char = None
num_adjacent = 0
for char in password:
if char == last_char:
num_adjacent += 1
else:
if num_adjacent == 1:
return True
las... | debd82c62f859296ed2227de8ed1705fc9f7c288 | 681,184 |
def assemble_flag_arguments(args):
"""Assemble dict of flag arguments into string."""
return ' '.join([name for name, use in args.items() if use]) | 609b9e1a39ad0885ee50441ac9ff2884eab19dc6 | 681,185 |
import torch
def dot(A, B, dim=-1):
"""
Computes the dot product of the input tensors along the specified dimension
Parameters
----------
A : Tensor
first input tensor
B : Tensor
second input tensor
dim : int (optional)
dimension along the dot product is computed (... | b8859730dec5987cf566f6292b66d5087b230e97 | 681,186 |
def PGetTableList (inUV):
""" Return the member tableList
returns tableList
inUV = Python UV object
"""
################################################################
if ('myClass' in inUV.__dict__) and (inUV.myClass=='AIPSUVData'):
raise TypeError("Function unavailable for "+inUV.m... | 463f0469ead962de6cac1857776e4e6eaa239938 | 681,187 |
from typing import Union
def check_prefix(prefix: Union[str, tuple, list], content: str):
"""Determines whether or not the prefix matches the content.
Parameters
----------
prefix : Union[str, tuple, list]
The affix that appears at the beginning of a sentence.
content : str
The s... | 1dfbe3efdd8540c6f1c6af29fe73811543e2a48b | 681,188 |
def check(msg):
"""Check if a letter is entered. If it is tell the user that doesn't work then prompt them again."""
while True:
try:
msg = (int(input()))
except ValueError:
print("You Have to enter numbers and only numbers.")
continue
return msg | ce3fe5930cbcf928f4768bd6329ad2b89d8aafdd | 681,189 |
def _account_data(cloud):
"""Generate the auth data JSON response."""
claims = cloud.claims
return {
'email': claims['email'],
'sub_exp': claims['custom:sub-exp'],
'cloud': cloud.iot.state,
} | 2ff4233ef3e45b538400853a06497a2991957b9a | 681,190 |
import os
def authentication_headers():
"""Get authentication headers."""
headers = {
'Content-Type': 'application/json',
'Renku-User-Id': 'b4b4de0eda0f471ab82702bd5c367fa7',
'Renku-User-FullName': 'Just Sam',
'Renku-User-Email': 'contact@justsam.io',
'Authorization': '... | 5f90a61182aa64ccc1ae27b34ea02a86eff38096 | 681,191 |
def move_effective(board):
"""Returns the list of the move that would have an effect on the game"""
list = []
for i in range(board.height):
for j in range(board.width):
if board.read_tile(i,j) == None:
list.append(3*i+j)
return list | 1fc8ae728d225ef054e60094890e24b5ec9507d4 | 681,192 |
def _determine_start(lines):
"""
Determines where the section listing all SMART attributes begins.
:param lines: the input split into lines.
:type lines: list[str]
:return: the index of the first attribute.
:rtype: int
"""
cnt = 0
for idx, val in enumerate(lines):
if lines[... | 157805d2d028eea1d0627758e3c0f49344da215d | 681,193 |
def preprocess_nonunique(df_psms):
"""
Return unique dataframe.
Parameters
----------
df1 : TYPE
DESCRIPTION.
Returns
-------
df2 : TYPE
DESCRIPTION.
"""
# columsn to create unique id
# grp_cols = ["PepSeq1", "PepSeq2", "exp charge", "LinkPos1", "LinkPos2"]... | 81a25528d745c23dda5f38b37ee07c2041f1a651 | 681,195 |
import torch
def featuremap_to_greymap(feature_map):
"""
feature_map: (C, sizey, sizex)
grey_map: (sizey, sizex)
"""
if len(feature_map.shape) == 3:
feature_map = feature_map.unsqueeze(dim=0) # (b, c, sizey, sizex)
elif len(feature_map.shape) == 4:
pass
else:
raise ... | f957b4fede15b2d325fc668dc8b62edd48928c68 | 681,196 |
def globals():
"""Return the dictionary containing the current scope's global variables.
:rtype: dict[string, unknown]
"""
return {} | 4f0a650567d03a97fed96964195da13f2cf52c7b | 681,197 |
def specificrulevalue(ruleset, summary, default=None):
"""
Determine the most specific policy for a system with the given multiattractor summary.
The ruleset is a dict of rules, where each key is an aspect of varying specificity:
- 2-tuples are the most specific and match systems with that summary.
... | 8ec24d461fcc875be7df6b7fabba5cdcb7cc7244 | 681,199 |
def join_speech(utt1, utt2):
"""
Joins two conversations using a '\n'
Join texts and doesn't care about segments
Assumption: utt1 is the one being popped off from the stack and the utt2
is the one trying to be added. This is so that I check for 'ctr'
field only in one of ... | 19655902b4fdc4f44fb8000ccf073383f16ce2d2 | 681,200 |
def rotate90_point(x, y, rotate90origin=()):
"""Rotates a point 90 degrees CCW in the x-y plane.
Args:
x, y (float): Coordinates.
rotate90origin (tuple): x, y origin for 90 degree CCW rotation in x-y plane.
Returns:
xrot, yrot (float): Rotated coordinates.
"""
# Translate ... | 172b74f4aaa5453520ed9669d1f76d3103c51b06 | 681,201 |
def is_dict(value):
"""Checks if value is a dict"""
return isinstance(value, dict) | 9c20c4a0f83a4003eb22ab077fb10c1e25bb8c53 | 681,202 |
import argparse
def parse_args(argv=None) -> argparse.Namespace:
"""
Parses module-specific arguments. Solves argument dependencies
and returns cleaned up arguments.
:returns: arguments object
"""
parser = argparse.ArgumentParser()
parser.add_argument(
'-a', '--architecture', typ... | 90ef44eef921ada2bc460ae74d6d64ac71161603 | 681,203 |
def get_ordinal_suffix(number):
"""Receives a number int and returns it appended with its ordinal suffix,
so 1 -> 1st, 2 -> 2nd, 4 -> 4th, 11 -> 11th, etc.
Rules:
https://en.wikipedia.org/wiki/Ordinal_indicator#English
- st is used with numbers ending in 1 (e.g. 1st, pronounced first)
... | 854a33897b73892346ec3094caae0dfe7d8fef1d | 681,204 |
from typing import Any
def _getattr(obj: object, name: str) -> Any:
"""Convenience wrapper to work around custom __getattribute__."""
return object.__getattribute__(obj, name) | 371e04b8bbc70fcb6c7809f6d621f3c4b51d0441 | 681,205 |
import time
def get_time():
"""Returns the current minutes past the hour."""
return int(time.strftime("%M")) | 022decd1e5a65c67ac31f6aaf3a74f690e602319 | 681,206 |
def noamwd_decay(step, warmup_steps, model_size, rate, decay_steps, start_step=0):
"""Learning rate schedule optimized for huge batches"""
return (model_size ** (-0.5) * min(step ** (-0.5), step * warmup_steps**(-1.5)) *
rate ** (max(step - start_step + decay_steps, 0) // decay_steps)) | 053d57d96ba1e4e86edee951451bab82433a3b52 | 681,207 |
import hashlib
def unique_hash(input_str: str) -> str:
"""Uses MD5 to return a unique key, assuming the input string is unique"""
# assuming default UTF-8
return hashlib.md5(input_str.encode()).hexdigest() | 206912b345e1dff3139b53ba94569bdb7ad565de | 681,208 |
def converter_parameter_to_int(value):
"""
Converts the given value to string.
Parameters
----------
value : `str`
The value to convert to string.
Returns
-------
value : `None` or `int`
Returns `None` if conversion failed.
"""
try:
value = int(v... | aaf347d5232cd21359ce3cc7f8018977a1345cc4 | 681,209 |
def open_door(open_door_media, open_door_permission):
"""
This fixture returns a tuple containing the Media and Permission objects corresponding to the open door test
data
"""
return (open_door_media, open_door_permission) | 73b8c5a55785c86566801dbb23ea45b3ecce0cd1 | 681,210 |
def show_price(price: float) -> str:
"""
>>> show_price(1000)
'$ 1,000.00'
>>> show_price(1_250.75)
'$ 1,250.75'
"""
return "$ {0:,.2f}".format(price) | 3c3c9a7532e1a84ddcf5b58d348dda778fdf5e59 | 681,211 |
def Kargs2Attr( ):
"""
This Decorator Will:
Read **kwargs key and add it to current Object-class ClassTinyDecl under current
name readed from **kwargs key name.
"""
def decorator( func ):
def inner( **kwargs ):
for ItemName in kwargs.keys():
set... | e65cfb43af7999b26a6e992aa792255bbd7ac15b | 681,212 |
def binary():
"""Binary representation."""
return "{:b}".format(2**8-1) | 3aaf2a25620fa7ca4932a61ae118aec27c364b39 | 681,213 |
import os
def exists(path):
"""Returns True if a file/dir exists at the given path."""
return os.path.isfile(path) or os.path.isdir(path) | e16f9ea6c56c7a8dd0b239d2008e06f710b35cf4 | 681,214 |
def format_title(title, first_title):
"""
Generates the string for a title of the example page, formatted for a
'sphinx-gallery' example script.
Parameters
----------
title : string
The title string.
first_title : boolean
Indicates whether the title is the first title of the ... | 836b973caa1da8f849e52be6a34ffb5ca09ff66a | 681,215 |
import torch
def get_saliency(interpreter, inputs, target):
""" Perform integrated gradient for saliency.
"""
# define saliency interpreter
# interpreter = captum.attr.Saliency(net)
attribution = interpreter.attribute(inputs, target)
attribution = torch.squeeze(attribution)
return torch.su... | 5767e2addd0b23c350ad5c7924100f713ec12d6a | 681,216 |
import re
def _get_story(story_all):
"""
Function to extract story text without date and source line.
Parameters
----------
story_all: String.
Content of a news story as pulled from the web scraping
database.
Returns
-------
story: String.
... | 5be620b16a2267e72970b25d3cb0af6b5ccdf950 | 681,217 |
import collections
def parse_gtid_range_string(input_range):
"""Converts a string like "uuid1:id1-id2:id3:id4-id5, uuid2:id6" into a dict like
{"uuid1": [[id1, id2], [id3, id3], [id4, id5]], "uuid2": [[id6, id6]]}. ID ranges are
sorted from lowest to highest"""
# This might be called again for a value... | 285d99b35857235e8205657eb0bb366ca1b536d1 | 681,219 |
import argparse
def get_args():
"""This function manages the arguments in this main function"""
# Define aguments
parser = argparse.ArgumentParser()
parser.add_argument('num', type=int, default=10**2)
args = parser.parse_args()
return args | e52d0aabf9358024ebb55c237f9809cbf4820c7a | 681,222 |
def base36_to_int(s):
"""
Convertd a base 36 string to an integer
"""
return int(s, 36) | ed2d60a8b760618289117a24c132beef95ec292c | 681,223 |
import string
def _clean_string(s):
"""Clean up a string.
Specifically, cleaning up a string entails
1. making it lowercase,
2. replacing spaces with underscores, and
3. removing any characters that are not lowercase letters, numbers, or
underscores.
Parameters
----------
s: s... | 5e7f26e6e18cad549ec1115900b961f8b738b4b4 | 681,224 |
def invert_grayscale(mnist_digits):
""" Makes black white, and white black """
return 1 - mnist_digits | 94deb88258dfde8469478394f1c8f9f6bd59ad91 | 681,225 |
import csv
def setup_time_delta(time_delta_begin, time_delta_end, time_delta_step, time_delta_config_file):
"""Returns a timedelta specification"""
time_delta_config = dict()
time_delta_config['default', 'default'] = (
min(time_delta_begin, -time_delta_begin), time_delta_end, time_delta_step)
... | 0d758ae91ece464a50d2e20277a923bd1534a6fb | 681,226 |
import uuid
def get_everything_to_post_except_timeseries(source_name, path, obj_uuid, timezone = "US/Pacific", units="kW", additional_metadata={}):
"""
This function deals with handling all the metadata. i.e. everything that isn't a (timestamp, value) pair.
Since one of the fields is actually cal... | 30a7a24e6e4b7b1ce932815c28f32ca916f9fb1e | 681,227 |
import random
def random_chance(players):
""" creates random chances of the players
players: dict(name -> [beed,number])
returns: """
random_players = list(players.keys()).copy()
random.shuffle(random_players)
return random_players | 0aa75e205ed4112b1cbeced96752fdd14af287cb | 681,228 |
import os
def get_project_sequence(path):
"""
Returns project sequence for a given path
Args:
path (str): full project file path
Returns:
([str]): list of project parts
"""
root, file = os.path.split(path)
file = file.split(".")[0]
file_parts = file.split("_")
re... | e2bdf528c43d186d6d3d4f4816efdf32c6d681c7 | 681,229 |
def frontiers_from_time_to_bar(seq, bars):
"""
Convert the frontiers in time to a bar index.
The selected bar is the one which end is the closest from the frontier.
Parameters
----------
seq : list of float
The list of frontiers, in time.
bars : list of tuple of floats
The b... | 97402b27ffd69a68adc350e95e663bd6e7ee13d5 | 681,230 |
def frange(start, stop, step):
"""frange(start, stop, step) -> list of floats"""
l = []
if start <= stop and step > 0:
x = start
while x <= stop:
l.append(x)
x += step
return l
elif start >= stop and step < 0:
x = start
while x >= stop:
... | 64bca01d701c29ca8176dd386bc135e198da3a96 | 681,231 |
def format_aws_tags(resource_id, tags):
"""
Refine the format of tags under AWS tag syntax
:type resource_id: string
:param resource_id: AWS Resource Id
:type tags: list
:param tags: a list of tags to refine
"""
api_tags = []
for key, value in tags.iteritems():
new_tag = {}... | ce1159a43c58297fce7cd2d79a7ba66691e7ad9f | 681,232 |
def start_build(cloudbuild, build_body):
"""Start a build."""
build_info = cloudbuild.projects().builds().create(
projectId='google.com:clusterfuzz', body=build_body).execute()
return build_info['metadata']['build']['id'] | b3f616019d85207b5a102124f61b675ea7d50489 | 681,233 |
def split_int(i, p):
"""
Split i into p buckets, such that the bucket size is as equal as possible
Args:
i: integer to be split
p: number of buckets
Returns: list of length p, such that sum(list) = i, and the list entries differ by at most 1
"""
split = []
n = i / p # min ... | 2aedf0a008d91f1635aa1117901ae525fbdb7d7e | 681,234 |
def create_dialog_from_url(ctx,dlg_url):
"""Create dialog from URL."""
dp = ctx.getServiceManager().createInstanceWithContext(
'com.sun.star.awt.DialogProvider', ctx)
return dp.createDialog(dlg_url) | d9af3f12845205f07322b5cae66762c4ef3bef3c | 681,235 |
def get_instance_info(instance):
"""Get some information about an instance.
Returns a tuple:
(name, flavour, key, security, image, userdata)
"""
data = instance.describe_attribute(Attribute='instanceType')
name = data['InstanceId']
flavour = data['InstanceType']['Value']
data = i... | 99e8e1b0e80096125e77aac986dbf4589e6a94b8 | 681,236 |
def getClientId():
"""Returns a hex-string that represents a number unique to the
running client's session.
You are guaranteed that this number is unique between all running
clients.
Returns:
str: A special code representing the client's session in a
unique way.
"""
ret... | d83b81516a0e3790534670cddcb7c2fc0b580e8f | 681,237 |
def findNthFibonnachiNumberIterative(n: int) -> int:
"""Find the nth fibonacchi number
Returns:
int: the number output
"""
if n <= 2:
return 1
first, second = 0, 1
while n-1:
third = first + second
first = second
second = third
n -= 1
return... | 6767cc7b46774c7ced74b2b82e380dc41dcfbdfb | 681,238 |
def eval_string(input_string, locals):
"""Dynamically evaluates the input_string expression.
This provides dynamic python eval of an input expression. The return is
whatever the result of the expression is.
Use with caution: since input_string executes any arbitrary code object,
the potential for ... | b86248a901bfa2feddfcd807e885f2f622897707 | 681,239 |
def get_provenance_record(attributes, tags, **kwargs):
"""Get provenance record.
Parameters
----------
attributes : dict
Plot attributes. All provenance keys need to start with
``'provenance_'``.
tags : list of str
Tags used to retrieve data from the ``attributes`` :obj:`dic... | fe3a482647ab8b94eea0b3ce5cb8c7683ccfed21 | 681,240 |
def load_factor(ts, resolution=None, norm=None):
"""
Calculate the ratio of input vs. norm over a given interval.
Parameters
----------
ts : pandas.Series
timeseries
resolution : str, optional
interval over which to calculate the ratio
default: resolution of the input ti... | 0478f96a494d798bf034cd8f7fc64176e9a26b0f | 681,241 |
def construct_iscsi_bdev(client, name, url, initiator_iqn):
"""Construct a iSCSI block device.
Args:
name: name of block device
url: iSCSI URL
initiator_iqn: IQN name to be used by initiator
Returns:
Name of created block device.
"""
params = {
'name': name,... | e4ea3f17077207d1fb78286ced63e9a14f39f170 | 681,242 |
import numpy
def points_in_triangle(tri, points, tol=1e-8):
"""
Test if the points are inside the triangle.
Input:
tri - the triangle as a matrix where the rows are the xy points.
points - the points as a matrix where the rows are the xy points.
Returns a vector of boolean values.
... | 976a247ed0cf44c9d47d2041ddc7f9261e469ddf | 681,243 |
def min_interp(interp_object):
"""
Find the global minimum of a function represented as an interpolation object.
"""
try:
return interp_object.x[interp_object(interp_object.x).argmin()]
except Exception as e:
s = "Cannot find minimum of tthe interpolation object" + str(interp_object.... | ab2f719fe493c1b7a52bd883946a0e44040c0816 | 681,244 |
def enforce_list_inds(inds,list_ofs):
"""Return itenms in a list from a list of their indices.
Mostly used when taking indices from unq2List(rxn_list) and
applying them in K,GStr, F lists."""
out=list() # Empty list to hold things for output.
# Loop over all items turn into arrays so we... | 47272e627939584f7b54216d277f329bd6b4fbd4 | 681,245 |
def filter_science_message(message):
"""Strips the vehicle science message.
vehicle_scalar_science_queue (SDQ 4)
SentryScalarScience.msg
float32 oxygen_concentration
float32 obs_raw
float32 orp_raw
float32 ctd_temperature
float32 ctd_salinity
float32 p... | 1d5fedf47c127051501321710a7b4a34596941af | 681,246 |
def hasSchema(sUrl):
"""
Checks if the URL has a schema (e.g. http://) or is file/server relative.
Returns True if schema is present, False if not.
"""
iColon = sUrl.find(':');
if iColon > 0:
sSchema = sUrl[0:iColon];
if len(sSchema) >= 2 and len(sSchema) < 16 and sSchema.islower... | 69fa64c6e7079aa554aef24aed21ddb9634400fe | 681,247 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.