content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def batch_the_offer(product_id, time, payload):
"""Batch the object to simple dictionary."""
batch = payload
batch["vendor_id"] = batch["id"]
del batch["id"]
batch["timestamp"] = time
batch["product_id"] = product_id
return batch | 6fd57fefa1a717f5432cfac4f4875b112d24d560 | 662,302 |
import re
import ipaddress
def ipv6_to_snmp_format(ipv6_str):
"""converts ipv6 address separated with space,'.' or '-' to SNMP format
:param ipv6_str: ipv6 address to change format
:type ipv6_str: string
:return: ipv6 address in snmp format(ex: 1.4.16.254.128.0.2.0.0.0.0.2.224.184.255.254.48.53.45)
... | 4069701961c8f579f3b9ee6242bf4c6c7d97b190 | 662,303 |
import re
import requests
def search(mode, query, api_key):
"""
Find the first Where On Earth ID for the given query. Result is the etree
node for the result, so that location data can still be retrieved. Returns
None if there is no result, or the woeid field is empty.
"""
results = None
... | d4cc3cafaaa8e9d35908e12460a3d307853b537e | 662,304 |
def validate_output(callback_kwargs, ctx, param, value):
"""
"""
return value | ab543eb8dcc2a6f29f9dc1ea2c7dab178c06ad67 | 662,305 |
def replaceAll(initialString, translationHash):
""" for each (toReplace, replacement) in `translationHash`
applying the query-replace operation to `initialString`
"""
result = ''
if initialString is not None:
result = initialString
for key, value in translationHash:
r... | 26c74930883f4babad17da573b8789df659d8d88 | 662,306 |
def get_history_resource_data(session, team, date, hour, storage):
"""Return the history energy usage of the team for the date and hour."""
return storage.get_history_resource_data(session, team, date, hour) | e0e0f9233c95e69313f97c432bebb0f36252bd4c | 662,307 |
import platform
def is_windows():
""" Returns whether the build system is windows """
return platform.system().lower() == "windows" | 28b18ac6c053cd61df2c2ceceb53e3e506897cdf | 662,308 |
def list2cmdline(lst):
""" convert list to a cmd.exe-compatible command string """
nlst = []
for arg in lst:
if not arg:
nlst.append('""')
else:
nlst.append('"%s"' % arg)
return " ".join(nlst) | 33a469357406377d8ca772d4a91b0a64ee82896b | 662,310 |
def get_directory_contents(directory):
"""
return a sorted list of the contents of a directory
"""
contents = []
for child in directory.iterdir():
contents.append(child)
return sorted(contents) | 6df92b20bff12df5aeb7ecb98431710a8a19a660 | 662,311 |
import os
import csv
def _get_population(region_id):
"""Return the population for a given region.
Returns
-------
population : int
population for the given region_id.
"""
if (int(region_id) >= 0 and int(region_id) <= 16):
path = os.path.join(os.path.dirname(__file__), 'dat... | cb69f07e557504128bdfdb1c5e6eb4ad7b9726e9 | 662,313 |
def square(n):
"""Returns the square of a number."""
squared = n ** 2
print
"%d squared is %d." % (n, squared)
return squared | 794bdf9a7806226695a870d944a11a5374265b73 | 662,314 |
def list_remove(lines,black_strs):
""" list 中如果有 black_strs 的字串,就會被移除,例如用在找到的檔案中,某些不需要
"""
ret = []
for line in lines:
for black_str in black_strs:
if line.find(black_str)>=0:
pass
else:
ret.append(line)
return ret | 151e43849e160252ea20d55c544c567a02a43d61 | 662,315 |
def is_date_time(file_type, path):
"""
Return True if path is an object that needs to be converted to date/time string.
"""
date_time_objects = {}
date_time_objects["Gzip"] = ("mod_time",)
date_time_objects["PE"] = ("pe.coff_hdr.time_date_stamp",)
date_time_objects["Windows shortcut"] = ("he... | e9f722fcbc6de94a2794a2639db68f21be538e41 | 662,316 |
def sent_ngrams_list(words, n):
"""
Create a list with all the n-grams in a sentence
Arguments:
words: A list of strings representing a sentence
n: The ngram length to consider
Returns:
A list of n-grams in the sentence
"""
return [tuple(words[i:i + n]) for i in range(len(words) - n ... | bc090aad5108d828251263ad1f5dce7ce8020d7d | 662,317 |
def index_fact(fact, index, negated=False):
"""
Returns a representation of 'fact' containing the step number and a
leading 'not-' if the fact is negated
"""
name = str(fact)
if negated:
name = 'not-' + name
return "%s-%d" % (name, index) | be15921b2ad14a3b76841f588bfd2a7a8643cb9c | 662,318 |
def sum67_loop(nums):
"""
A basic loop method. the key is to keep a flag
set to know whether a 6 has been encountered
"""
total = 0
is6 = False
for num in nums:
print("adding:", num, is6)
if num == 6 or is6:
is6 = True
else:
total += num
... | 97ec25821b5dd240404751296cdbb0fc47302b5e | 662,319 |
def get_db_from_view(exp):
"""Transitional method to move away from mongodb"""
return exp._storage._db._db | 8c963feed3291f82b2709e941b61875be236a99b | 662,321 |
def __predict(X_test, model, X_scaler):
"""
Do prediction for provided fetures
Arguments:
X_test: the test data [n_samples, n_features]
model: the classification predictive model
X_scaler: the standard scaler used to scale train features
Return:
predicted labels as array ... | 7e4c3819d261e7bee0512362a1022a9ef25b4c74 | 662,322 |
def get_num_channels(image5d):
"""Get the number of channels in a 5D image.
Args:
image5d (:obj:`np.ndarray`): Numpy arry in the order, `t,z,y,x[,c]`.
Returns:
int: Number of channels inferred based on the presence and length
of the 5th dimension.
"""
return 1 if image5d i... | 6c389d51cfe3eeec49a491bebf732d0573200535 | 662,323 |
def is_e164_format(phone):
"""Return true if string is in E.164 format with leading +, for example "+46701740605" """
return len(phone) > 2 and phone[0] == "+" and phone[1:].isdigit() and len(phone) <= 16 | 2773030b9c8e7b2004e0c233abc23258b3200f7d | 662,324 |
def dcf_to_swap(dcf):
"""
Helper function transforms sorted discount factors to swap rates.
:param dcf: discount factors
:return: par swap rates
"""
num_dcf = len(dcf)
swap_rates = num_dcf * [0]
for index, dcf_ in enumerate(dcf):
if index == 0:
swap_rates[index] = (1... | 9b03b2b6e0e08515b1e1b78cb1a72810a343926f | 662,325 |
import os
import json
def load_config(exp_name):
""" Loads the configuration file
Args:
path: A string indicating the path to the configuration file
Returns:
config: A Python dictionary of hyperparameter name-value pairs
learning rate: The learning rate of the optimzer
... | 456278dacf47030f84a14fe249ec1b4020928892 | 662,326 |
def search_ancestor(node, *node_types):
"""
Recursively looks at the parents of a node and returns the first found node
that matches node_types. Returns ``None`` if no matching node is found.
:param node: The ancestors of this node will be checked.
:param node_types: type names that are searched fo... | 709cbda37e591088c600736c36cf5c09b06f2d89 | 662,327 |
import torch
def to_torch(tensor):
"""Converts an array-like object (either numpy or pytorch) into a pytorch tensor."""
if tensor is None:
return None
elif isinstance(tensor, torch.Tensor):
return tensor
torch_tensor = torch.from_numpy(tensor)
if torch_tensor.dtype == torch.fl... | 6d537ee1a6778547da66164ad9c5c8d6f706a0f1 | 662,328 |
import linecache
def clang_range_str(source_range):
"""Get the text present on a source range."""
start = source_range.start
stop = source_range.end
filename = start.file.name
if filename != stop.file.name:
msg = 'range spans multiple files: {0!r} & {1!r}'
msg = msg.format(filename... | c855c0c04db0cf00c47166ad1566228b730bd561 | 662,329 |
import os
def execute_with_django_path(django_path, command):
"""
Execute the given command (via os.system), putting django_path
in PYTHONPATH environment variable.
Returns True if the command succeeded.
"""
original_pythonpath = os.environ.get('PYTHONPATH', '')
try:
os.environ['P... | 043c0e51e73a0880d3a35c9898b15069224f4d62 | 662,330 |
def collisionRC(x1, y1, w, h, x2, y2, r):
"""
Détection d'intersection entre un rectangle et un cercle :
renvoie `true` si les deux objets se rencontrent
Arguments:
x1 et y1 (float): coordonnées du centre du rectangle
w et h (float): largeur et hauteur du rectangle
x2 et y2 (flo... | 40a9d18f0d817fff0b9603c48390f67be6048558 | 662,331 |
def flattenByCol(A):
""" Turn matrix into vector by column. Out of place operation
"""
B=A.copycm
return B.block.bind(0,1,A.rowlength*A.collength) | e31e3ca436bdde8c907218d2cdee1d1664905168 | 662,333 |
def measure_lexical_diversity(tokenized_string):
"""
Given a tokenized string (list of tokens), return the fraction of unique tokens to total tokens.
"""
return len(set(tokenized_string)) / len(tokenized_string) | 018b07d6ebeb02439f41b496e512d2bb0713f6b7 | 662,334 |
def get_primary_language(programming_language_tallies):
"""
Return the most common detected programming language as the primary language.
"""
programming_languages_by_count = {
entry['count']: entry['value'] for entry in programming_language_tallies
}
primary_language = ''
if program... | 0500d23a13eeab17580c3c94703251b133eb7a73 | 662,335 |
def wind_consistency(windspeed, winddirection, variablelimit):
"""
Test to compare windspeed to winddirection.
:param windspeed: wind speed
:param winddirection: wind direction in range 1-362
:param variablelimit: maximum wind speed consistent with variable wind direction
:type windspeed: float... | ae713cdd5ee3a0d27d47bf0eb7a2fd5045628d29 | 662,337 |
def compute_net_sales_booking(target_object):
"""
Return net sales booking data by finding the difference
of object's, which is an argument, revenue and cost data
"""
net_sales_booking = int(target_object._booking) - int(target_object._booking_cost)
return net_sales_booking | 7923813316df88fdf0ba3fae71b4f2f5a2503645 | 662,338 |
def filter_deleted_items(items, flag):
"""Filter deleted items
:param items: target
:param flag: deleted flag name, always True means deleted
:return: list does not contain deleted items
"""
# just return if parameter is not a list
if not isinstance(items, list):
return items
... | 0f494d3515f7bd78661b3e5bed00055eeea6f7d3 | 662,339 |
def number(selection_string: str, minimum: int, maximum: int, default = None) -> int:
"""
Asks the user for a number within the provided minimum and maximum with optional default and returns their response
"""
while True:
if default:
input_string = f"{selection_string} default={defau... | 4f2f17b94c362e5e5c919a1e6df989c7881892c6 | 662,341 |
def get_list_nodes_from_tree(tree, parameters=None):
"""
Gets the list of nodes from a process tree
Parameters
---------------
tree
Process tree
parameters
Parameters
Returns
---------------
list_nodes
List of nodes of the process tree
"""
if paramet... | 0d0178407d7675d3b245965606462c23ead232b7 | 662,342 |
def des_score(resume):
"""
Returns resume score based on Designation
"""
des_score = 0
for word in resume.split(" "):
if word.strip() in ["Sr.","Senior"]:
if des_score<3:
des_score=3
elif word.strip() in ["Associate", "Scientist", "Engineer"]:
... | b4ab132fcc2238341975bb9ec7e97daa0d7f9391 | 662,343 |
import argparse
def parse_args(args):
""" Parse arguments from command line input
"""
parser = argparse.ArgumentParser(description='Training parameters')
#
parser.add_argument('--type', type=str, default='DDQN',help="Algorithm to train from {A2C, A3C, DDQN, DDPG}")
parser.add_argument('--is_at... | 251a46a37abace53be872b12fcb5c4b9cade9b35 | 662,344 |
def getrecursionlimit(space):
"""Return the last value set by setrecursionlimit().
"""
return space.newint(space.sys.recursionlimit) | 9acf9d018eb0a54d5507dfc5f6e6775ac6c36c9a | 662,345 |
def trim_parameters(first_num, second_num, num_of_nums, the_quantity, negative, bottom_limit, top_limit, number_limit):
"""对用来生成算式的参数进行剪裁
使得各参数合法,并且不会造成过大计算负载。
:param first_num: int型,算式中允许出现的最小或最大数字
:param second_num: int型,算式中允许出现的最小或最大数字
:param num_of_nums: int型,组成算式的数字数量
:param the_quantity:... | 5e4584da9bf33dd03316064db2667f525b1794dc | 662,346 |
def is_standard_website(href):
"""
Function to remove urls belonging to some famous sites
:param str href: the url
:return bool: True or False
"""
if 'google' not in href and 'youtube' not in href and 'twitter' not in href and 'facebook' not in href:
return True
else:
return... | de4bb090644816acb65a8a59a1840364a6f479af | 662,347 |
def _status_str(statuses):
"""Generate a string to describe the route statuses."""
if statuses:
statuses.sort(key=lambda x: (x["route"], x["method"]))
method_pad = max([len(route["method"]) for route in statuses])
lines = ["{} {}".format(
route["method"].upper().ljust(method... | a12ecd316dc2388075fa6e25ec55ff126f6a84d0 | 662,348 |
def get_sort_dirs(sorts, page_reverse=False):
"""Extract sort directions from sorts, possibly reversed.
:param sorts: A list of (key, direction) tuples.
:param page_reverse: True if sort direction is reversed.
:returns: The list of extracted sort directions optionally reversed.
"""
if page_reve... | a525e2f1e19c0c5e5f1774b38f7de6f949dec640 | 662,349 |
def make_header(pandoc_format, title, categories):
"""
Generate pandoc header based on given metadata.
"""
lines = [
"---",
"format: " + pandoc_format,
"title: " + title,
"...",
]
if categories is not None and len(categories) > 0:
lines.insert(2, "cate... | 6b383ee02ff7075afa38ddc5d2dfe91b2c3d7b1f | 662,350 |
def assemble_transcripts(run_parallel, samples):
"""
assembly strategy rationale implemented as suggested in
http://www.nature.com/nprot/journal/v7/n3/full/nprot.2012.016.html
run Cufflinks in without a reference GTF for each individual sample
merge the assemblies with Cuffmerge using a reference G... | 988c61f1c75991e5c4bb22ed343ade54d90c6af2 | 662,351 |
def null_safe(rule):
"""Return original expr if rule returns None."""
def null_safe_rl(expr):
result = rule(expr)
if result is None:
return expr
else:
return result
return null_safe_rl | 964997cf5ac6369f89f7e93390aeba5b610c68e7 | 662,352 |
def course_order(num_courses, prerequisites):
"""Return a course schedule according to the prerequisites provided.
Utilizes topological sort, using Kahn's Algorithm.
"""
# A: calculate the in-degree of each course (a vertex)
course_in_degrees = dict()
for course_pair in prerequisites:
... | 17548ba7be622cc2b03392a5f6a41ffef08e4203 | 662,353 |
def xmltag_split2(tag, namespaces, colon=False):
"""Return XML namespace prefix of element"""
try:
nsuri = tag.split('}')[0].split('{')[1]
nsprefix = [key for key, value in namespaces.items()
if value == nsuri]
value = nsprefix[0]
if colon:
return ... | 9e4685c262aca9a55c12455eda2d6e3fab751c90 | 662,354 |
def median(xs, sort=True):
"""Returns the median of an unsorted or sorted numeric vector.
@param xs: the vector itself.
@param sort: whether to sort the vector. If you know that the vector is
sorted already, pass C{False} here.
@return: the median, which will always be a float, even if the vector... | f21ca802f30391ac8d1e365c63d3cb98432c4e6b | 662,355 |
def get_version(name: str, version: str) -> str:
"""
Get the version of a script.
Parameters
----------
name : str
Name of the script.
version : str
Version of the script, in format major.minor.patch.
Returns
-------
str
Script's version.
"""
return... | 3fb554bdeef00e4900730212dd4b96680fefc80b | 662,356 |
def find_relationship_helper(relationship, club_object, found):
"""
Format and retrieve all parents or children of a club into tree.
"""
children = getattr(club_object, relationship).all().prefetch_related(relationship)
children_recurse = []
for child in children:
if child.code not in fo... | ba5fbdd6b09649ba9e9de076d26126560247702d | 662,357 |
def average(x):
"""This function calculates the average of a list of provided values.
:param x: A list of values to be averaged.
:type x: List of Integers
:return: The average of the provided list.
"""
return sum(x) * 1.0 / len(x) | 61c50ee4b1837ca5aac213c967e61f0f53f361f3 | 662,360 |
def tag_dictkeys(tag, dictionary):
"""Return the dictionary with tagged keys of the form 'tag.key'"""
tagged = {}
for key, val in dictionary.items():
tagged[tag+'.'+key] = val
return tagged | 62e3a0082ff28ff5f5520450e3b6f0ddf630d04c | 662,361 |
import os
def multi_join(paths, *path_segments):
"""apply os.path.join on a list of paths"""
return [os.path.join(*(path_segments + (path,))) for path in paths] | 4646e27789c7d7f9daa6421dd68cccf87a82f504 | 662,362 |
import random
def shuffle_coupling_graph(coupling_map, seed, strict_direction=True):
"""Create a shuffled coupling graph from a coupling map."""
if strict_direction:
cm_graph = coupling_map.graph
else:
cm_graph = coupling_map.graph.to_undirected(multigraph=False)
cm_nodes = list(cm_gra... | 7a92602848a45254903749bd25969c310d2d817e | 662,363 |
def sort_tuple(tup, n=2):
"""Sort a tuple by the first n values
tup: tuple
input tuple
n : int
values to sort tuple by (default is 2)
Returns
-------
tup : tuple
tuple sorted by the first n values
"""
return tuple(sorted(tup, key=lambda t: t[:n])) | 094c855935ed568e384f09d466e9fdb522de2a90 | 662,364 |
def check_description(description, title):
"""
Verifies that the description is within the specified bounds
(20 < x < 20000) and that the description is longer than the
inputted title.
:param description: product description
:param title: product title
:return: True if the description meets... | 38c4b7c66e7e35586dba12cb82347011836e7c56 | 662,365 |
def is_valid_error(error):
"""
Checks if the text written on stderr is an error or not,
a local server can push logs on this stream,
it looks for keywords such as ``Exception``,
``Error``, ``TraceBack``...
@param error text
@return boolean
"""
lines = erro... | 70af21a74f5588d28444f9d112e098ea114f82b8 | 662,366 |
def op_ckernel(op):
"""
Create a pykernel for a ckernel for uniform interpretation.
"""
deferred_ckernel = op.args[0]
def pykernel(*args):
dst = args[0]
srcs = args[1:]
dst_descriptor = dst.ddesc
src_descriptors = [src.ddesc for src in srcs]
out = dst_desc... | 9660c7a9b37bb751cea0dd0e3c0c6b3546bd4218 | 662,367 |
def get_strings(public, private):
"""
Get the string values for a public and private key.
:param public: Public key to convert
:param private: Private key to convert
:type public: rsa.PublicKey
:type private: rsa.PrivateKey
:returns: a tuple (str, str)
:rtype: tuple
"""
retur... | 0093373ce3149c909fa7ef95bba3d5f82c038b68 | 662,368 |
def upload_media(request, form_cls, up_file_callback, instance=None, **kwargs):
"""
Uploads media files and returns a list with information about each media:
name, url, thumbnail_url, width, height.
Args:
* request object
* form class, used to instantiate and validate form for upload
* call... | 3e8fa5429cfd9f19b69525a4d7d97d414fb02820 | 662,369 |
from typing import IO
def load_cmd(file: IO[str], cmds: str):
"""Load a file and type check it.
"""
cmds_ = cmds.strip().split(',') if cmds else None
return ('load', {'file': file, 'cmds': cmds_}) | 4acdb509c3c86eec17420045532fa12ccfe33ef0 | 662,370 |
def Split_Dataset_B_Res(sub, feature, label, channels):
"""
Split one subject's data to evaluate the results of LOSO-CV on Dataset B.
Args:
sub: leave one subject out.
feature: input fNIRS signals.
label: input fNIRS labels.
channels: fNIRS channels.
Returns:
X_... | 7639521f82c48205e05ab6d1c039f6556e45b29b | 662,371 |
def int_subtract(a, b):
"""
Subtract the arg of the value.
"""
try:
return int(a) - int(b)
except (ValueError, TypeError):
return '' | b9e7480cfee24ac154ac1526c35ce72e6439d5f1 | 662,373 |
import re
def get_parent_compseg_or_ted_uid(tixi3, xpath):
"""
Finds the uid of the nearest parent which is a component segment or trailing edge device
:param tixi3: TiXI 3 handle
:param xpath: XPath of the element to start the search
"""
end = [it.end() for it in re.finditer('(componentSegmen... | 3bca3829baa465bbbd48a29602c09a3a147f1fc9 | 662,374 |
def _float(value: str) -> float:
"""Convert string to float value
Convert a string to a floating point number (including, e.g. -0.5960D-01). Whitespace or empty value is set to 0.0.
Args:
value: string value
Returns:
Float value
"""
if value.isspace() or not value:
r... | 501e73417178744a6f620438773e34708908c0de | 662,375 |
import numpy
from typing import Collection
from typing import Hashable
def cast_npint(obj: numpy.integer, brief_dims: Collection[Hashable]):
"""Single dispatch specialised variant of :func:`cast` for all numpy scalar
integers (not to be confused with numpy arrays of integers)
"""
return int(obj) | 8ab1040f368b07b9ce35f85a6500d1c8ebe1c9ef | 662,376 |
def task_wrapper(task):
"""Task wrapper for multithread_func
Args:
task[0]: function to be wrapped.
task[1]: function args.
Returns:
Return value of wrapped function call.
"""
func = task[0]
params = task[1]
return func(*params) | 7ea69ef64dbc9fbed43083169beb0e6cee7fe4d5 | 662,377 |
def print_molecule(molecule):
"""Return molecule record for DL CONTROL"""
return molecule["id"] | 3b9927ee804be8357c8a9bfe14748d1a0e956a95 | 662,378 |
import os
def resolve_targets(target_org):
"""
Resolve targets based on input
"""
query_targets = list()
if os.path.isfile(target_org):
with open(target_org) as input_file:
input_lines = [input_line.rstrip() for input_line in input_file]
query_targets += input_line... | 66e7b6073b3beb3a7ee56573feb7089917c3355f | 662,379 |
def escape_for_sql_like(string):
"""Function that escapes % or _ symbols provided by user
SQL LIKE syntax summary:
- ``%`` -> match any number of characters
- ``_`` -> match exactly one character
"""
return string.replace('%', '\\%').replace('_', '\\_') | 69a4a1c3c263508ff15c8c8836fa0b35bb4f7649 | 662,380 |
def _add_weight_decay(net, l2_value, skip_list=()):
"""
Divide parameters into 2 groups.
First group is BNs and all biases.
Second group is the remaining model's parameters.
Weight decay will be disabled in first group (aka tencent trick).
"""
decay, no_decay = [], []
for name, param in ... | 91461193e4bde03a3ce8337a6a01c9ad8de971f2 | 662,381 |
def make_max_dict(group_str):
"""We need to create mock MAX data at multiple points in these tests"""
return {
'cas:serviceResponse': {
'cas:authenticationSuccess': {
'cas:attributes': {
'maxAttribute:Email-Address': 'test-user@email.com',
... | 1057e6deb02759cc539b2935e90031e2141a9ddf | 662,382 |
from typing import Tuple
def get_error_from_value(value: str) -> Tuple[float, float]:
"""
Returns the error value from a number string.
"""
try:
value = value.replace(" ", "")
except AttributeError:
return float(value), 0.0
if "(" in value:
vval, err = value.split("(")
... | 4444fe102d994934bf4bd39cc643982308145cca | 662,383 |
import json
import re
def dict_to_jsonl(dict_input):
"""
takes a dict object and turns it into a jsonl doc
"""
jsonl_contents = json.dumps(dict_input)
jsonl_contents = re.sub(f"\n","",jsonl_contents)
return jsonl_contents | 20dca5ae5be83aa6156720ce92040793e6f1f0aa | 662,385 |
def validate_ingredients(value):
"""
Returns 'Valid' if ingredient field is not empty
"""
if not value:
return 'Please enter ingredients.'
return 'Valid' | 690e189dd0e79029bc3464b9dff6c8fe80eee16e | 662,386 |
def _txx_P(P, xx):
"""Define the boundary between 3x-3y, T=f(P) where xx represent the subregions options: cd, gh, ij, jk, mn, qu, rx, uv
>>> "%.7f" % _txx_P(25,"cd")
'649.3659208'
>>> "%.7f" % _txx_P(23,"gh")
'649.8873759'
>>> "%.7f" % _txx_P(23,"ij")
'651.5778091'
>>> "%.7f" % _tx... | 507afa17c5778820c061263c0d9ca98efbc86a5f | 662,387 |
def is_binary(array):
""" Fast check that array consists of 0 and 1 only. """
for item in array:
if item not in (0., 1.):
return False
return True | a395b980a74eedc14a4b2c56374cc9cdc34a2cfe | 662,388 |
def parse_desc(tokens):
"""
>>> parse_desc(Tokenizer("0 01BWA Helix Collective 000000Payroll31Mar310315 "))
{'FinancialInstitutionName': 'BWA', 'ProcessDate': '310315', 'ApcaNumber': 0, 'GeneratedBy': 'Helix Collective', 'EntriesD... | 9687498db13a90d6ab9e0c0246bb35ca14a007c6 | 662,389 |
def _deserialize_set(s, cls):
"""Deserialize a list of dicts into classes."""
return set(
cls.from_jsonld(x) if hasattr(cls, 'from_jsonld') else cls(**x)
for x in s
) | e990d195f0b6681e6289c6812df2e0bacc8dd34c | 662,390 |
def addListsElementWise(a, b):
"""Add corresponding elements of two lists.
The two lists do not have to have the same length. Nonexisting elements are assumed to have a value of 0.
A new list is constructed and returned.
"""
if len(b) > len(a):
a, b = b, a
# Now len(a) >= len(b)
r =... | d11d36d14869001f0a14a5201d63ed575e67eeeb | 662,391 |
def merge_two_dicts(dict1, dict2):
"""
Merges two dictionaries into one
:param dict1: First dictionary to merge
:param dict2: Second dictionary to merge
:return: Merged dictionary
"""
merged_dict = dict1.copy()
merged_dict.update(dict2)
return merged_dict | 40dbb033e63c71c16f2b6cfe012a07ab7b2f41b9 | 662,392 |
import re
def separate_math(body):
"""Returns math, text split in body"""
math_re = re.compile(r"\$+.*?\$+" +
r"|\\begin\{equation\*?\}.*?\\end\{equation\*?\}" +
r"|\\begin\{align\*?\}.*?\\end\{align\*?\}" +
r"|\\\[.*?\\\]",
... | 1e645f356f3c0606417316cc433216a10b9fef4b | 662,393 |
def pretty_tree(x, kids, show):
"""Return a pseudo-graphic tree representation of the object `x` similar to the
`tree` command in Unix.
Type: `(T, Callable[[T], List[T]], Callable[[T], str]) -> str`
It applies the parameter `show` (which is a function of type `(T) -> str`) to get a
textual represe... | 7a92a0048fa8efedf86eff2ba7deeb5b4fa40f66 | 662,394 |
import sys
def algo_params_close_domain(param_str, search_budget=100, dataname='cifar10'):
"""
Return params list based on param_str.
These are the parameters used to produce the figures in the paper
For AlphaX and Reinforcement Learning, we used the corresponding github repos:
https://git... | e6e2cc82257d19b0044ee42ae5fe1237a87a586d | 662,395 |
import torch
def is_f_contig(tensor: torch.Tensor, strict: bool = False) -> bool:
"""Check if a pytorch Tensor is column-contiguous (Fortran order)
Column-contiguity means that the stride of the first dimension (of
a 2D tensor) must be equal to 1.
In case of 1D tensors we just check contiguity
P... | b3fe41475430e1c7780215f376d1a0d9eb6c15da | 662,396 |
def _find_machine(oneandone_conn, instance):
"""
Validates that the machine exists whether by ID or name.
Returns the machine if one was found.
"""
for _machine in oneandone_conn.list_servers(per_page=1000):
if instance in (_machine['id'], _machine['name']):
return _machine | 4a0d83c696891b032cb88817c52c8265bef68a97 | 662,397 |
def extract_user(event):
"""
:param event: (required) the event from the request
:return: The username of the user who made the request
"""
return event["requestContext"]["authorizer"]["claims"]["cognito:username"] | 9404bcc7468230a354c2cd41d1c3949e237660d7 | 662,398 |
def _bool(xml_boolean):
"""Converts strings "true" and "false" from XML files to Python bool"""
assert xml_boolean in ["true", "false"], \
"The boolean string must be \"true\" or \"false\""
return {"true": True, "false": False}[xml_boolean] | 27803aace78f1ee1ecaa5c271955218dfcd0458a | 662,399 |
import torch
def eval_model(img, model, test=False):
"""
Put model into eval mode and evaluate test images.
Parameters
----------
img: str
test image
model: architecture object
architecture with pretrained weigths
Returns
-------
pred: n 1d arrays
predicte... | f6cc6cac221efdc17e9e068ff0e46311c805d3b5 | 662,400 |
def binary_search(value, array, start_idx=None, end_idx=None):
"""
Выболняет бинарный поиск значения в отсортированном по возрастанию массиве.
:param value: Значение, которое необходимо найти.
:param array: Массив поиска.
:param start_idx: Начальный индекс поиска (для рекурсивного вызова)
:para... | efb1396d00d44cc669c1c8d344d3334894181ae7 | 662,401 |
def append_data_frames(data_frame1, data_frame2):
"""Append rows of data_frame2 the end of data_frame1"""
return data_frame1.append(data_frame2) | 7fb4a16f3fe0b2ea0663f778b49b3f60e41202db | 662,402 |
import unittest
import os
def run_python_tests():
""" Runs the Python tests.
Returns:
True if the tests all succeed, False if there are failures. """
print("Starting tests...")
loader = unittest.TestLoader()
# Get the directory this module is in.
dir_path = os.path.dirname(os.path.realpath(__file__))... | d87035e71c15a72e32d0a9bb338ffb52031f2669 | 662,403 |
def make_s3_key_path(job_config, course = None, filename = None, session = None, mode = None, job_id = None):
"""
Create a key path following MORF's subdirectory organization and any non-null parameters provided.
:param job_config: MorfJobConfig object.
:param course: course slug (string).
:param fi... | 2aca0240a25baa0abbbac0502236f6898805b509 | 662,404 |
def get_rare_elements_number(d, n):
"""
Count the number of rare elements
:param d: dictionary to use
:param n: the threshold for rarity
:return: the number of rare elements as a string
"""
i = 0
for k, v in d.items():
if v < n:
i += 1
return str(i) | 367aab5fdf4efb945cccfb9dffd95573cbd72a3c | 662,405 |
import argparse
def parse_cli_args() -> argparse.Namespace:
"""
Parse arguments passed via Command Line Interface (CLI).
:return:
namespace with arguments
"""
parser = argparse.ArgumentParser(description='Standalone synthesizer')
parser.add_argument(
'-i', '--input_path', type... | 7d336830c6867cfe36d415e377fc9d70a00e4bf4 | 662,406 |
def no_by_per(totalhp, percentage):
"""
rtype: num of `percentage` from total
eg: 1000, 10 -> 10% of 1000 (100)
"""
return totalhp * percentage / 100 | 7884f94634863d434afb358a1612c5b57cb56744 | 662,407 |
from typing import List
def csv_first_column(lines: List[str]) -> List[str]:
"""
pre: all(',' in line for line in lines)
post: __return__ == [line.split(',')[0] for line in lines]
"""
return [line[: line.index(",")] for line in lines] | cc9a2672f0679030a8a40c7d5f0e6a39cebc4c51 | 662,409 |
def first_compromise_times(start_time, end_time, stats_list):
"""Turns compromise stats into first times of guard/exit/guard&exit compromise."""
time_len = float(end_time - start_time)/float(24*60*60)
guard_times = []
exit_times = []
guard_and_exit_times = []
for stats in stats_list:
... | 03ff88bac3404ddbf2a7284547990843250ef24b | 662,411 |
def relative_error(U, V, product=None):
"""Compute error between U and V relative to norm of U."""
return (U - V).norm(product) / U.norm(product) | d6babc4cdca0c2095e36c63ed08a1f87e774a8a0 | 662,412 |
def reconst_orderdict(orderdict):
"""
Parameters
-----------
orderdict : Orderdict
"""
keys = []
val_1 = []
val_2 = []
val_3 = []
val_4 = []
val_5 = []
val_6 = []
val_7 = []
for key, vals in orderdict.items():
keys.append(key)
val_1.append(vals[0]... | 0e35e579ac1442e0adc47da147c4788947a8e14e | 662,413 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.