content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def xstr(s):
"""Handle NoneType in strings"""
if s is None:
return "Unknown"
return str(s) | 5e28ac7d615aa660ad01c078501dbdcc16b9dee4 | 631,603 |
import re
def make_regex_from_words(words):
""" Used with get_blocks_within_rect() to make a regex to match only the tokens inside a rect"""
# [romt)]
return re.compile(r".\s*".join([w[4].strip() for w in words if w[4] not in [" ", "\n", "\t"]]), re.DOTALL) | f05d3491ec20636c8b42e245d73975f17897f94f | 631,604 |
def display_filename_input():
"""display function for inputting filenames"""
print("FILENAMES: The full or partial names of the files to apply this rule to.")
print("To apply the rule without regard to filename, press enter without adding any filenames.")
return input("Enter a comma-separated list of or... | 1870f003fbc84487764fbd3056c370740c9ee7e3 | 631,605 |
def create_hello_world(graph):
"""
Produces the string "hello world"
Provided as demonstration and test bed for entrypoint-based registration.
"""
return "hello world" | c6ba5a425805b1f1e688999d291ad26240705e8b | 631,606 |
def say_hello_ingestion(to):
"""
this method will say hello to the person named 'to'
params:
======
to: str, name of the person to which greetings is made
return: 1 on success
"""
#print('hello there {}'.format(to))
return 'hello there {} - ingestion'.format(to) | 7311129a81030f85118970c2cb5788d6704ec459 | 631,608 |
def exporter():
"""Export utility modified from https://stackoverflow.com/a/41895194
Returns export decorator, __all__ list
"""
all_ = []
def decorator(obj):
all_.append(obj.__name__)
return obj
return decorator, all_ | 2d5695e739474990d8c6336341b821fb25606ce1 | 631,609 |
from typing import Dict
import json
import os
def _warm_pool_node_counts() -> Dict[str, int]:
"""
Leave some buffer for warm pool. This code makes sure to always leave X instances in idle while scaling down.
For example: 5 instances running, 3 in idle, WARM_POOL_SIZE set to 2. This code will remove only 1... | bd4fdfe7476b2e9b965b5c30f15bd4e6be5418d0 | 631,611 |
def calculate_tco_for_each_asset(capex, opex, discount_rate, current_year, year_deployed, asset_lifetime, end_year, repeating):
"""
- capex
- opex
- discount rate
- current year
- year deployed
- asset lifetime
- end_year
- repeating
"""
repeating_capex_cost_year1 = capex / ... | d492b70560936b611657ef470a48fbabb7daeb7e | 631,612 |
import os
def get_currently_deployed_opentree_branch(request):
"""Read local git configuration and return the current branch"""
# Backtrack to the real (vs. symlinked) filesystem path for this app
real_app_path = os.path.realpath(request.folder)
infilepath = os.path.join(real_app_path, '..', '.git', '... | 580259e2da55dcf47228f0ee6303318d9a92746f | 631,613 |
def part2(maze):
"""
Parameters
----------
maze : list
A mutable sequence of integers that defines
the maze to be escaped for part 2 of the test
Returns
-------
int
The number of steps required to escape the maze
"""
ptr = 0
step = 0
while 0 <= ptr ... | 185c79d351055653a388bfb7e246aed25970f476 | 631,614 |
def is_basevar_node(graph, node):
"""Returns True if this node represents an
actual input or output variable.
"""
return 'var' in graph.node.get(node, '') and \
'basevar' not in graph.node.get(node, '') | 86c3ced51d007fd44add16e2925ff30d2c6ff109 | 631,615 |
def groupby(equivalence_relation, xs):
"""
warning: this has slightly different semantics than
itertools groupby which depends on ordering.
"""
groups = []
for x in xs:
group_found = False
for group in groups:
if equivalence_relation(x, group[0]):
gro... | 091cfc5b51146b5710330dc667136a85347b08ca | 631,616 |
import os
import glob
import imghdr
def get_files(path: str) -> list:
"""
Get all files image files within in the path.
Args:
path (str): path to image or folder
Returns:
files (list): paths to all image files in folder and subfolders
"""
if os.path.isfile(path):
file... | c173c55b0ba8aca1eb72d68269b1d1f9bc4174e6 | 631,617 |
from math import floor
def uniform_int_from_avg(a, m, seed):
""" Pick a random integer with uniform probability.
Returns a random integer uniformly taken from a distribution with
minimum value 'a' and average value 'm', X~U(a,b), E[X]=m, X in N where
b = 2*m - a.
Notes
-----
p = (b-floor... | 3d7f6053b06a9868bedc47a488571816ea3278c5 | 631,618 |
import math
def Zscore(r,n,N,R):
"""where N is the total number of events measured:
R is the total number of events meeting the criterion:
n is the total number of events in this specific reference gene-set:
r is the number of events meeting the criterion in the examined reference gene-set: """
... | 2d8f9bb0a37005b0470b2cac777b81ba7d5a35e0 | 631,620 |
def ascii_join(data):
"""Convert sequence of numbers to ASCII characters"""
return ''.join([chr(n) for n in data]) | 36dcc04ea469a093ff9af89fc989388681815ba9 | 631,621 |
def get_var(n, c, attr, pop=False):
"""
Retrieves variable references for a given static or time-depending
attribute of a given component. The function looks into n.variables to
detect whether the variable is a time-dependent or static.
Parameters
----------
n : pypsa.Network
c : str
... | 84edcdfba6784d5cd3a265f4b2b75467db2a276a | 631,622 |
def is_decorated_with_attrs(
node, decorator_names=('attr.s', 'attr.attrs', 'attr.attributes')):
"""Return True if a decorated node has
an attr decorator applied."""
if not node.decorators:
return False
for decorator_attribute in node.decorators.nodes:
if decorator_attribute.as_s... | ad98d3ae27b898bba95d1c3febe11204099e9f65 | 631,623 |
import inspect
def get_kwargs(func, info):
"""
Creates a key word dictionary to use as input to "func"
:param func: Function
:param info: Dictionary with info to include in kwargs
:return: kwargs
"""
funcargs = inspect.getfullargspec(func)
kwargs = {key: info.get(key) for key in funcar... | e28fd44dadecf5f3495a2ce1c733a70c7149a513 | 631,624 |
import os
def parse_sonar_tb(sonar_tb_filepath):
"""
From the passed in sonar_tb_filepath, extract the name of the file and
the directory relative to which the generated files will be created
Args:
sonar_tb_filepath (str): Path to the file used to create the
testbench_config
... | ac705fcb2a7a8cab3f9b2d178be2527b24bf7b55 | 631,625 |
def a_is_not_b(a, b):
"""
This is `not (a is b)`
"""
return a is not b | 1b85180acdab4b56ffbb29108380007cdf1373ef | 631,626 |
def Echotimes(firstnumber, secondnumber):
"""
Multiply 2 numbers
"""
return firstnumber * secondnumber | 0ff0d2dbd3d0296209fdf9474a7439d3f8979b97 | 631,627 |
from typing import Mapping
def _remove_empty_dicts(dct: dict, recurse=True) -> dict:
"""Remove all (nested) keys with empty dict values from `dct`"""
for k, v in list(dct.items()):
if isinstance(v, Mapping) and recurse:
_remove_empty_dicts(dct[k])
if v == {}:
del dct[k]... | b73cb8d1c4ce76caef52ec0531e220c2a533d611 | 631,628 |
def input_checker(s):
"""
This function takes a string input and returns false if it contains one or more non terminal spaces.
If not, the function returns an integer.
Args:
s (string): string which needs to be checked
Returns:
boolean: False if the string contains one or more non ... | 0b121f0e2aa079462086773621b154529529381c | 631,629 |
import numpy
def _get_dates_needed_for_renaming_storms(
working_date_index, num_dates_in_period):
"""Returns dates needed for renaming storms.
For more details on renaming storms, see the public method `rename_storms`.
:param working_date_index: Index of working date.
:param num_dates_in_per... | 2141c040b7aae6c507b870d0fae90f93dcd164ba | 631,630 |
def _net_cost(net, placements, has_wrap_around_links, machine):
"""Get the cost of a given net.
This function, in principle at least, should estimate the total network
resources consumed by the given net. In practice this estimate is based on
the size of the bounding-box of the net (i.e. HPWL). This sh... | 2e505fa17cae813a53e3b823d7d9ec01079e5cbe | 631,631 |
import logging
def get_log(name, log_set, level=logging.INFO, propagate=False):
"""
获取日志句柄
:param name:
:param log_set:
:param level:
:return:
"""
# 强制utf-8
log_set['encoding'] = 'utf-8'
log_set['mode'] = 'a'
log_set['delay'] = True
formatter = logging.Formatter(
... | 7629ece2c23ff0c5bc83efe5e353e27e6276c32e | 631,632 |
def reverse_complement(dna):
"""Takes a RNA or DNA sequence string and returns the reverse complement"""
complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'U':'A', 'N':'N'}
return ''.join([complement[base] for base in dna[::-1]]) | f66bd47de037e49d6007c3f41987ce442133bfb8 | 631,633 |
def signal_rhs(
S,
S_delay,
Adj,
sender_idx,
beta_func,
beta_args,
alpha,
k,
p,
delta,
lambda_,
g,
rho,
):
"""
Right-hand side of the transciever circuit delay differential
equation. Uses a matrix of cell-cell adjacency `Adj`.
"""
# Get signaling ... | 1b894b80ab652595ad6b2e6615c279b5558ad3ac | 631,634 |
import os
def fixture_paths():
"""Change to the fixtures dir in the current directory of the test."""
dir = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'fixtures')
return [os.path.join(dir, i) for i in os.listdir(dir)] | ca8e0d15cb65e8d7e2de9f5b358a64ef7c864802 | 631,635 |
import sys
def get_platform():
"""Returns the current platform/operating system as one of "osx", "linux"
or "windows". The function is intentionally coarse-grained and doesn't
differentiate between different versions of these operating systems.
If the platform can't be determined, something is probab... | 44c5d45cc4a3d28f9dc58cb1f7b4705ba901408d | 631,636 |
def get_repetition_index(distributions):
"""
Count repetition index of a distribution arrangement
:param distributions: distributions already determined
:return: repetition index count
output example 19
"""
repetition_index = 0
# check each pair without permutation
num_distri... | a7ff84d40b7df6938f8eb27b09faaeb4fa7b2c9c | 631,637 |
from typing import List
def join_list_into_message(lst: List[str], joiner="-") -> str:
"""
Helper function that converts a list into a *bulleted list*
:param lst: the list of strings that we want to convert into bullets
:param joiner: the character that will be used to denote a bullet
:returns: ... | 575e7a48ee4816c4de3988287438338bacffe420 | 631,638 |
from typing import Any
from typing import Optional
from typing import Union
def convert_literal(literal: Any) -> Optional[Union[bool, str]]:
"""Convert JSON literals to Python ones."""
# Map for the literals
map_ = {
"true": True,
"false": False,
"null": None
}
# Check if l... | 20eb7c950c94d6c7cf161fec4e7ddb8e288a9c86 | 631,639 |
def rgb2xyz(im):
"""rgb to xyz"""
rgb2xyz = (0.412453, 0.357580, 0.180423, 0, 0.212671, 0.715160, 0.072169, 0, 0.019334, 0.119193, 0.950227, 0)
out = im.convert("RGB", rgb2xyz)
return out | f0568464c9d16ace0bf345f040e2522be1ac4aa4 | 631,640 |
from importlib.util import find_spec
from imp import find_module
import sys
def module_exists(module_path):
"""
Determines if a module exists without loading it (Python 3)
In Python 2, the module will be loaded
"""
if sys.version_info >= (3, 4):
try:
return find_spec(module_pat... | a863474b0d7aeb49ee7cb89d6ee797d8a615560a | 631,642 |
def _get_hdr_values(extns, key):
"""
Helper function to get the all header values from a list of extensions.
The return value is a dict keyed on the EXPID value.
Parameters
----------
extns : iterable of :any:`astrodata.Astrodata`
AstroData extensions to be examined
key : str
... | c0715b626079375738d05443028c92caa4888d08 | 631,643 |
def getEdgeBlocks(blocks,boundaryPoints,blocksize):
"""Use this function to highlight edge points."""
edgeBlocks = tuple()
for block in blocks:
edgeSet = list()
for set in block:
edgeSet.append(set[:boundaryPoints*2]+set[-2*boundaryPoints:])
edgeBlocks += edgeSet,
ret... | c6e9eef09500fe45fe7a2e1951d89c5938671b38 | 631,644 |
def _GetGradSource(op_or_tensor):
"""Identify which call to tf.gradients created this gradient op or tensor.
TensorArray gradient calls use an accumulator TensorArray object. If
multiple gradients are calculated and run in the same session, the multiple
gradient nodes may accidentally flow through the same ac... | e59be86338d920f650db12eaf028882bd1197d79 | 631,645 |
from typing import List
import random
def generate_new_symbol(symbol: List[str]) -> str:
"""
Select a new currency symbol.
Parameters:
symbol: The list of currency symbols available.
Returns:
str: The symbol selected randomly
"""
index = random.randint(0, len(symbol) - 1)
... | 33ad99bba5de0ad44c53c75882f4482276c218ff | 631,647 |
def title(text, level=0):
"""Given a title, format it as a title/subtitle/etc."""
return '\n' + text + '\n' + '=-~_#%^' [level] * len(text) + '\n\n' | 739d11a9a085feb0bdf6748b9854d436dc1b0295 | 631,648 |
import hashlib
def fixed_hash(message, q):
""" Fixed sized Hash value m for the elgamal DSS."""
try:
q = q -1
h = hashlib.sha3_256(message.encode("utf-8"))
m = int(h.hexdigest(), 16) % q
return m
except Exception as e:
print("Something went wrong: ",e.__str__())
... | f2828cf5bc028bc2af386b8198ffc5fd8949fd0c | 631,649 |
def DFS_RF(node, basket, stopnode):
"""Depth-first search from the right of a tree."""
if len(node.subnodes) > 0:
newnode = node.subnodes[-1]
else:
newnode = node.get_leftnode(moveup=True, stopnode=stopnode)
return newnode | 1cecc01a33b990219dde893fc8001bca01099b8f | 631,650 |
def SplitIntoPolygons(shape):
"""Returns a list of closed polygons."""
ret = []
this_polygon = []
restart_indices = set(shape.parts)
for idx, point in enumerate(shape.points):
if idx in restart_indices:
if this_polygon:
ret.append(this_polygon)
this_polygon = [[point[0], point[1]]]
... | 12bbaef250333db72516db42c531251aff0a0983 | 631,651 |
def cipher(message):
""""
Cifra el mensaje recibido como parámetro con el algoritmo de cifrado
XOR.
Parámetro:
message -- el mensaje a cifrar.
'"""
messagecrip = ""
for elem in message:
code = ord(elem)^1
messagecrip += chr(code)
return messagecrip | fce8e9873c2d4e84b020c3f97c23bcfa7f22969a | 631,652 |
def dms_to_sex(d, m, s):
"""Converts degrees, minutes and decimal seconds to sexagesimal seconds.
Example: (41, 24, 12.2) -> 149052.2
:param int d: degrees
:param int m: minutes
:param float s: decimal seconds
:rtype: float
"""
return (d * 3600) + (m * 60) + s | 32085070d6b6802dc45d8f97985439e121f4ec41 | 631,654 |
def boundary_conditions(layer_outer_radii, boundary_temp):
""" This function defines the temperature on the outer radius of the particle
Inputs
--------
-layer_outer_radii: calls on layer_outer_radii for the last point
-boundary_temp: User input of the temperature at the outer radius [K]
Outp... | e4849de68b66a17f32ecb3355d666b98b9334fdd | 631,655 |
def get_contact_suggestions(host: str):
"""
Makes a basic suggestion based on host (+1 and -1 computer).
"""
host_list = list(host)
contact_list = []
if (host[6].isnumeric()):
s = int(host[5:7])
for i in [-1, 1]:
host_list[5:7] = str(s + i)
contact_list.append("".join(host_list))
else:
s = int(host[5... | de0bdf19f6c7a3b2af37f8997c56214e4ea4baef | 631,656 |
def get_reduction_level(indsize, optlevel, slicesize, chunksize):
"""Compute the reduction level based on indsize and optlevel."""
rlevels = [
[8, 8, 8, 8, 4, 4, 4, 2, 2, 1], # 8-bit indices (ultralight)
[4, 4, 4, 4, 2, 2, 2, 1, 1, 1], # 16-bit indices (light)
[2, 2, 2, 2, 1, 1, 1, 1, ... | 122149df98fc804a5493473de6a36ea614da3e8f | 631,657 |
def has_nan(x):
"""Checks if a Tensor/Array has NaNs."""
return bool((x != x).sum() > 0) | bfd211b4044b65334619952c4b53fa40c1a78ea7 | 631,658 |
def PyDict_Values(space, w_obj):
"""Return a PyListObject containing all the values from the
dictionary p, as in the dictionary method dict.values()."""
return space.call_method(space.w_dict, "values", w_obj) | d7b640ed7abe857f6f11b361908260d5f240749b | 631,660 |
def default_check_DICOM_dict():
"""Get default values for check DICOM dictionary"""
check_DICOM_dict = {
"SeriesDescription": ["RODILLA AP", "RODILLAS AP", "X106aL Tibia AP"],
"BodyPartExamined": ["LOWER LIMB", "KNEE", "EXTREMITY"],
}
return check_DICOM_dict | 9005f3a9625cb68ca53aa8b2cc01267b084f02ff | 631,662 |
def configget(config, section, var, default, datatype='str'):
"""
Gets a string from a config file (.ini) and returns a default value if
the key is not found. If the key is not found it also sets the value
with the default in the config-file
Input:
- config - python ConfigParser object
... | 78954f6f796fb164aa9f1eb487f054aa813df6c8 | 631,663 |
import binascii
def _read_signify_ed25519_signature(signature_file):
"""
Read a Ed25519 signature file created with OpenBSD signify.
http://man.openbsd.org/OpenBSD-current/man1/signify.1
"""
with open(signature_file) as f:
# signature file format: 2nd line is base64 of 'Ed' || 8 random oc... | 4b748cb800599f644b2d0d5e30da70cfd1e07107 | 631,664 |
def is_positive(x: float) -> bool:
""" Return if x is positive
:param x: float
:return: bool
"""
return x > 0 | 4378417fe26624b3f208ab961b44c8577d3b1572 | 631,666 |
import subprocess
def run_cmd(cmd_args, change_working_directory="./", shell=False,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
env=None):
"""
Function used to execute the shell commands
Arguments:
cmd_args (list): This is the list of commands to be appended in case
... | db6de303d0865cb73d6035aea438cdc5ba31cd03 | 631,667 |
import re
def nyl_split(st):
"""
(str) -> str, str, str
Function returns splitted line: name, year of filming and location
"""
splitted = st.split("\t")
year = "(????" if ("(????") in splitted[0] else re.findall(
"\([1-3][0-9]{3}", splitted[0])[-1]
name = splitted[0][:splitted[0].... | 54c95b450f40c00ac2cc5b4cf6d665777b27df14 | 631,668 |
import array
def isarray(x):
"""Same as ``isinstance(x, array)``.
"""
return isinstance(x, array) | 8aa78a0d1568d6e87fd9dd71f6d61ca86aff5fe1 | 631,669 |
def unit_conversion(current_values, unit_type, current_unit, new_unit):
"""
Converts given values between the specified units
:param current_values: the current values that you want converted between units. It can be any type, so long as
arithmetic operations with scalars behave appropriately. A numpy a... | fae5a955619d134116333d8f4e2bb69e366ffbbe | 631,670 |
import csv
def create_list_dict(map_data_file):
"""read file and create list of dictionaries
Args:
map_data_file (string): filename of .csv file with cities
Returns:
[list]: list of dictionaries (each dictionary is one city)
"""
with open(map_data_file, encoding="utf8") as f:
... | b5d68cf1f08671d42e175f6867caeacd4451c714 | 631,671 |
def minDepth(self, root): # ! 56ms 使用广度优先搜索
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
depth = 1
queue = []
queue.append(root)
count = 0
lastnum = 1
while queue:
node = queue.pop(0)
print(node.val)
if not node.left ... | b4ff3fe1d645e9a149b6178124f3314c9a99b661 | 631,672 |
def trunc_time(time, freq):
"""
Truncates values in provided time array to provided frequency. E.g. 2018-01-15T12:00 with
freq = 'M' becomes 2018-01-01.
"""
return time.astype('<M8[' + freq + ']') | 826ade5852da8e757bb0392654ac1c295364020b | 631,673 |
def decode_to_string(file):
"""
makes the byte object into a proper string
:param byte_object:
:return: raw string of the website
"""
# print(file)
# trying to get the Content-Type from the server, if provided. Otherwise, take a bet.
try:
charset = file.info().get_content_charse... | b200d8cd80db872b7fc2ca80e300708283a9a5f8 | 631,674 |
def _check_sequence(graph_seq, known_seq):
"""
Check that the sequence matches up to a certain point for the known sequence. If it does
return the index to where it matches. If it doesn't return 0.
:param graph_seq: Actual sequence in the graph
:param known_seq: One of the known sequences
:retur... | c936b0dbb4aa3cfcb603647768fe2b1eef2a1174 | 631,675 |
from typing import List
def _median_even(xs: List[float]) -> float:
"""If len(xs) is even, it's the average of the middle two elements"""
sorted_xs = sorted(xs)
hi_midpoint = len(xs) // 2 # e.g. length 4 => hi_midpoint 2
return (sorted_xs[hi_midpoint - 1] + sorted_xs[hi_midpoint]) / 2 | 02dd8835aa85f8cb490c2c779e3437ed099def0d | 631,678 |
def isSubset(name, atoms, ag, error=ValueError):
"""Perform an argument type and relation check."""
issubset = atoms in ag
if issubclass(error, Exception) and not issubset:
raise error('{0:s} ({1:s}) must be a subset of {2:s}'
.format(name, str(atoms), str(ag)))
ret... | 9cbc4754026ad79e42d064f7a368506a722c626c | 631,679 |
def board_max(vals):
"""
board_max: return max of a list when contains strings and ints
"""
max_val = -float("inf")
for val in vals:
if isinstance(val, int) and val > max_val:
max_val = val
return max_val | f00e1920d796ccb10d57c9ef6a9870f1290988a2 | 631,680 |
def RoughIntegrate(y_array,x_array):
"""
Returns the area under the y_array for the range of the
x_array. The bin width for y_array[i] is defined here as
x_array[i+1] - x_array[i].
"""
print("NOTE: Final endpoint of array is not considered in integral.")
integral = 0.0
for i,y in enumer... | 4769d3c74f4ff83a56a829f5e72f222638ab9b7d | 631,681 |
def thumbnail_location(instance, filename):
""" returns a string with filename and slug
"""
return "%s/%s" % (instance.product.slug, filename) | 61f8a5e42b360e461c10867e6aa3c4bfbac03bb6 | 631,682 |
def expct_val(Op, psi):
"""
compute expecation value of operator 'Op' with state 'psi'
Args:
Op - operator corresponding to observable to be measured
psi - state-vector (on sub-Hilbertspace)
Returns:
<psi| Op |psi>
"""
return (psi.conj().T).dot(Op.dot(psi)) | 55777f3fd8fd6ae16362468837d68421a43a3c5d | 631,683 |
from typing import List
def find_closest_value_in_list(list_request: List, value_request: int) -> int:
"""
Find the closest value within one list to the value of interest.
"""
return min(list_request, key=lambda list_value: abs(list_value - value_request)) | e69f65bb65ebf0bf4f0eeb9b7058fc3ee7c262ba | 631,684 |
def getParenthesesContext(text : str, frontC = "(", endC = ")") -> str:
"""소괄호 내용을 찾습니다. 없으면 빈 str를 반환합니다."""
start = text.find(frontC)
end = -1
if(start > -1):
start += len(frontC)
tmpEnd = text.find(endC, start)
while(tmpEnd > -1):
end = tmpEnd
tmpEnd = ... | 9ae0fc5d09d3f6534077bdcbd39c1181a7b2c7f2 | 631,685 |
def create_colocation_group_to_ops_map(op_graph):
"""Generate a dict that maps a colocation group to its op id list."""
retval = {}
for op_id, op_data in op_graph.nodes().items():
# assume there is only one group
group = op_data['colocation_group']
if group in retval:
re... | be8b8567d2ff6988c9f8bbdcd9b3753547b2eccc | 631,686 |
import decimal
def scinotation(x,n=2):
"""
Displays a number in scientific notation.
:param x: number
:param n: number of significant digits to display
"""
fmt='%.'+str(n)+'E'
s= fmt % decimal.Decimal(str(x))
return s | 29cdaa4e4747a981f38cfb8815628d887fdb5047 | 631,687 |
import json
def load(filename):
"""Load the configuration file"""
config = None
# Try to load config
try:
fin = open(filename, 'r')
config = json.load(fin)
except Exception as e:
print("Failed to load config file: {}".format(filename))
print("Please ensure the... | ffe73834dce8a8f07e1af5f97b24e1f85a99c455 | 631,688 |
import requests
def callWakatimeAPI(params, route):
"""handles the API requests
:params: object
:route: string
:returns: json
"""
headers = {'Accept':'application/x-www-form-urlencoded'}
r = requests.get(route, headers=headers, params=params)
return r.json() | 967509e4ad2246ff7e5a0dcad3e8594020b4baf2 | 631,690 |
import os
import glob
def import_train_data(data_set_name, train_data_type):
"""
This function takes the dataset name and returns the files for the spam and ham text files for the train data
:param train_data_type: In this if it is true then we have train data else test data
:param data_set_name: This... | 169f550d3a3f39e0da478c2fcbad37bff1ede010 | 631,691 |
def apply_to(x, f):
"""Takes a value and applies a function to it.
This function is also known as the thrush combinator"""
return f(x) | 0a51fca4e46c623241974b6c4e2f97ecc2e0d66c | 631,692 |
import os
def path_of(filename):
"""Determine a full pathname of a test file."""
return os.path.join(os.path.dirname(os.path.realpath(__file__)), 'test_file_data', filename) | de475cc4d932964b02c55a656cf7996f933c6e5c | 631,693 |
def discard_suspended_races(data):
""" Remove races containing laps slower than double the pole lap, they have probably been interrupted """
# Divide by the pole time
data['nextLap'] = data['nextLap'] / data['pole']
# Find lap times abnormally high
anomalies = data[data['nextLap'] > 2]
races_t... | 7e2bfb7f93390b96358ec2396e4b235e6abf5daf | 631,694 |
def dump_populations(populations):
"""
Dump a dictionary of populations in a archive
Args:
populations(dict): the dictionary of the populations
Returns:
set: the set of filenames (extension '.npy')
which have been produced
"""
files = []
for label, pop in pop... | 6e706037742cbfea40d13480a4a651aefe8d4e48 | 631,695 |
def split_list(list, size=108):
"""
Splits the list into batches consisting of 108 PNG images.
The function returns a list of a sub-lists.
"""
return [list[i:i+size] for i in range(0, len(list), size)] | affe4aa0cf9dd21626d92d5f363dc2869eecb9c8 | 631,697 |
def zipf_to_freq(zipf):
"""
Convert a word frequency from the Zipf scale to a proportion between 0 and
1.
The Zipf scale is a logarithmic frequency scale proposed by Marc Brysbaert,
who compiled the SUBTLEX data. The goal of the Zipf scale is to map
reasonable word frequencies to understandable... | f28f1b7d34d7573029901e57b6aaba9eee35a6cc | 631,698 |
import torch
def get_percentile_min_max(input, lower_percentile, upper_percentile, output_tensor=False):
"""
Calculate the percentile max and min values in a given tensor
Parameters:
----------
input: tensor
the tensor to calculate percentile max and min
lower_percentile: float
... | a38981dc7afb476bb0d49273d87bc0930cf0bcf1 | 631,699 |
def check_incompatible(dict_in, inc_list):
"""
Check any conflicting keys in the dictionary
"""
for incomp in inc_list:
c = 0
for k in dict_in:
if k in incomp:
c += 1
if c > 1:
return incomp
return | 42d596a3dbf69c4d8696eb0ec8ea62a096130c7e | 631,701 |
import copy
import ast
def set_ctx(node, ctx=None):
""" Replace AST context without mutation.
"""
node = copy.copy(node)
node.ctx = ctx or ast.Load()
return node | ee54b693819b2e6148552be0ea77a2c2714f77ae | 631,702 |
import torch
def dot_product_scores(q_vectors, ctx_vectors):
"""
calculates q->ctx scores for every row in ctx_vector
:param q_vector:
:param ctx_vector:
:return:
"""
return torch.matmul(q_vectors, torch.transpose(ctx_vectors, 0, 1)) | 3b43a9fe5af4a6c36cc8eefc78860cc8272f4d2e | 631,703 |
def return_config_without_apis(*, config: dict): # pylint: disable=redefined-outer-name
"""
A helper test function to help when mocking functions such as filter_config
Returns the provided config dict after removing the "apis" keys
"""
del config["apis"]
return config | 1ebea05451d846f8a1e305fb5165bdfdc3c71270 | 631,704 |
def calc_coulomb_spin_pot(pot1, pot2):
""" calculate spin mixing and coulomb part of potential """
# first do consistency checks
if len(pot1)!=len(pot2):
exit('ERROR: potential1 and potential2 inconsistent in calc_coulomb_spin_pot')
# now calculate coulomb part and spin part and save them in vc and vs
vc,... | 05275fe4d36dad4301f7e96c738b188d8f41ec64 | 631,705 |
def canonicalize_address(addr):
"""
Encases addresses in [ ] per RFC 2732. Generally used to deal with ':'
characters which are also often used as delimiters.
Returns the addr string if it doesn't contain any ':' characters.
If addr contains ':' and also contains a '[' then the addr string is
... | 745e79b5fcb1f6240b194920eef74bc68de0ee26 | 631,707 |
import struct
def _pack_frame(payload):
"""
Creates a complete frame by prepending a header to the given payload
Data type: normal data(2)
Target buffer ID:
Sequence number
Frame size
Payload
"""
data_type = 2
buffer_id = 10
seq_no = 0 # Will be set at a later time
fra... | 667daf03dbacbb1b795ddbb1c8833ac4eaca8f92 | 631,708 |
def _get_url(git_repo, verbose=False):
"""
Gets the org url.
:param git.Remote remote:
:return: The url
:rtype: unicode, unicode
"""
url = git_repo.remotes.origin.url
return url | d60452094ab147dbe1a2d847e5240e69b05614c4 | 631,709 |
import email
def fetch_email(M, msg_id):
"""Returns the given email message as a unicode string."""
res, data = M.fetch(msg_id, '(RFC822)')
if res == 'OK':
# Data here is a list with 1 element containing a tuple
# whose 2nd element is a long string containing the email
# The conten... | 2e091a04452e7b721b4d2058083935e289c502ca | 631,710 |
import re
def slug_creator(weird_string):
"""
This creates slugs in the ASCII character space.
"""
slug = weird_string.encode('ascii', 'ignore').lower().decode()
slug = slug.replace(' ', '-')
slug = re.sub(r'!|,|\*|\?|\.', r'', slug)
return slug | 8158e531a9217efafd54190612a7f281ac333b3f | 631,711 |
import os
def parse_rc(logger, rc_file):
"""Parse servodrc configuration file
The format of the configuration file is described above in comments to
DEFAULT_RC_FILE. I the file is not found or is mis-formatted, a warning is
printed but the program tries to continue.
Args:
logger: a logging instance us... | 7262a261e21197f1ac4a974c4441883e98a4aa61 | 631,713 |
import os
import yaml
import logging
def read_configs(config_file: str) -> dict:
"""Function to parse the config file.
Args:
config_file (str): File path to the config file.
Returns:
dict: The configurations in the form of a dict
"""
file_types = ['\.md']
whitelisted_files ... | 26f218ddd3456266013dc8c39bf41bec22c0393b | 631,715 |
import csv
import hashlib
import json
def load_csv(fp, key=None):
"""
:param fp: file to read
:param key: Column to use as a unique ID for each row
:return: if key precised, {keyfn(r): r for r in rows} will return {'1': {'id': '1', 'name': 'Cleo', 'age': '4'}, '2': {'id': '2', 'name': 'Pancakes', 'age... | 8cdd919750a3c458f9e2e25717e4247358ccb36d | 631,716 |
def emap(fn, iterable):
"""eager map because I'm lazy and don't want to type."""
return list(map(fn, iterable)) | 58b209844d65c25fba9d6f68790e5bb0f040e09b | 631,717 |
def case_selection(df):
""" Filter relevant cases. """
case_1 = (df["iso3"].eq("SRB") & df["year"].eq(2000))
case_2 = (df["iso3"].eq("GEO") & df["year"].eq(2003))
case_3 = (df["iso3"].eq("UKR") & df["year"].eq(2004))
case_4 = (df["iso3"].eq("KGZ") & df["year"].eq(2005))
case_5 = (df["iso3"]... | 38675fe0e09d96972fcb039b77005f440782ef8b | 631,718 |
def build_url(serializer, url):
"""
Return the full url for a file or picture
:param serializer: serializer object
:param url: the ending url locating the file
:return: full url
"""
request = serializer.context.get('request', None)
if request is not None and url[0] == '/':
url = ... | 3abbca6e41a22d7b592e0d6bfc98e43d3c3663d7 | 631,719 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.