content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def application(environ, start_response):
"""
符合WSGI标准的一个HTTP处理函数,web程序入口
:param environ: 请求的信息
:param start_response: 返回响应的回调函数
:return:
"""
# 响应信息
start_response("200 OK", [("Content-Type", "text/html")])
text = "<h1>hello world</h1>"
for i in environ.items():
print(i)... | 7b2a8fd72192d3c4791018a09598598bfe3c1b77 | 654,374 |
def merge(dct1, dct2):
"""Merges two dictionaries"""
return {**dct1, **dct2} | f58de5109cdfc88913edfd60b954e63b5584b831 | 654,377 |
def validFSUNum(req):
"""
Valid FSU Num
- returns False if FSU Num contains characters, True otherwise
"""
return str(req['FsuNum']).isdigit() | 63f330222eefb15b3b5960224f0e868db663c762 | 654,378 |
def remove_duplicates(lst):
""" Return input list without duplicates. """
seen = []
out_lst = []
for elem in lst:
if elem not in seen:
out_lst.append(elem)
seen.append(elem)
return out_lst | b06ca47b843a941c653bd4127104625cd61456ce | 654,382 |
def add_dicts(*args, **kwargs):
"""
Utility to "add" together zero or more dicts passed in as positional
arguments with kwargs. The positional argument dicts, if present, are not
mutated.
"""
result = {}
for d in args:
result.update(d)
result.update(kwargs)
return result | 8a2ee0486798d7a292610a2b197445cc6d902235 | 654,384 |
def in_board(pos, board):
"""returns True if pos (y, x) is within the board's Rect."""
return bool(board.rect.collidepoint(pos)) | fd25f12b09d1f365bd10f274d93e6a30765fee6a | 654,386 |
from typing import Dict
def update_nested_dict(d: Dict, u: Dict) -> Dict:
"""
Merge two dicts.
https://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth
:param d: dict to be overwritten in case of conflicts.
:param u: dict to be merged into d.
:return:
... | dd83799110eb2f118910aa12fc57a1d4c3d934f4 | 654,391 |
def to_list(v):
"""Convert any non list to a singleton list"""
if isinstance(v, list):
return v
else:
return [v] | 97136a291c136fbc0032bc617c06031bc90e374a | 654,392 |
import pickle
def debrine(filename, encoding='latin1'):
"""pickle.load(open(filename))
Use encoding='latin1' to load datetime, numpy, or scikit objects pickled in
Python 2 in Python 3. (Latin-1 works for any input as it maps the byte
values 0-255 to the first 256 Unicode codepoints directly:
http... | dfe187b3b44cad09ad7b5022381a20e0a2bad7fe | 654,394 |
def __indent_text_block(text):
""" Indent a text block """
lines = text.splitlines()
if len(lines) > 1:
out = lines[0] + "\r\n"
for i in range(1, len(lines)-1):
out = out + " " + lines[i] + "\r\n"
out = out + " " + lines[-1]
return out
return tex... | 9d2e933a7b8ae2a82d91e18ca67f795f6db7d089 | 654,395 |
def get_tag_list(element_tree):
"""
Function to generate a list of all element tags from an xml file
:param element_tree:
:return:
"""
return list(set([c.tag for c in element_tree.iter()])) | e011011e12c41033ba03c53b3c4fdabcf3f5b305 | 654,397 |
def scan(ln, char_maps, tokenize=True):
"""Scan beginning of each line for BASIC keywords, petcat special
characters, or ascii characters, convert to tokenized bytes, and
return remaining line segment after converted characters are removed
Args:
ln (str): Text of each line segment to pars... | 381921fe75839b83b4aac00528ad92f3acc9e510 | 654,398 |
def discrete_signal(signal0, step_size):
"""
SNIPPET 10.3 - SIZE DISCRETIZATION TO PREVENT OVERTRADING
Discretizes the bet size signal based on the step size given.
:param signal0: (pandas.Series) The signal to discretize.
:param step_size: (float) Step size.
:return: (pandas.Series) The discre... | 279fc47068c706f7634d37e1e49d44cf291bd9dd | 654,400 |
def overlap_coefficient(label1, label2):
""" Distance metric comparing set-similarity. """
#the original formula used float, but it doesn't seem to make any difference
#return float(len(label1 & label2)) / min(len(label1), len(label2))
if min(len(label1), len(label2)) == 0:
return 0
else:
return len(label1.int... | 72406ed3820dc59adb9c41a52abe2aa0d9be10d6 | 654,401 |
from typing import OrderedDict
def separate_orders_by_ticket_type(list_in, ticket_types):
"""
Inputs:
list_in - List containing ticket orders
ticket_types - List of all ticket types
Outputs:
dict_out - A dictionary keyed to ticket types, containing a list of
ticket ord... | 3d5fe2e1489c4902bee23254a926e5f96be000eb | 654,402 |
def import_module(dotted_path):
"""Import a module path like 'a.b.c' => c module"""
mod = __import__(dotted_path, globals(), locals(), [])
for name in dotted_path.split('.')[1:]:
try:
mod = getattr(mod, name)
except AttributeError:
raise AttributeError("Module %r has ... | ae20284dbf86d86bea7d4fd9e89dd392a8f49ba4 | 654,407 |
def getOverlap(a, b):
"""Return the overlap of two ranges. If the values of a overlap with
the values of b are mutually exclusive then return 0"""
return max(0, 1 + min(a[1], b[1]) - max(a[0], b[0])) | dbd74e31b63a512649ff7082a4ffc6ec92994446 | 654,409 |
def html_path(request, goldendir):
"""NYU Academic Calendar HTML file path"""
path = 'New York University - University Registrar - Calendars - Academic Calendar.html' # noqa
return goldendir.join(path) | bb31deca3003b7afad4ab6eb951a8c7e927b51c0 | 654,410 |
def brightness_from_percentage(percent):
"""Convert percentage to absolute value 0..255."""
return (percent * 255.0) / 100.0 | fa3ca902e0edba34db2b864a94d895ee47841879 | 654,411 |
import torch
def _log_sum_exp(mat, axis=0):
"""
Computes the log-sum-exp of a matrix with a numerically stable scheme,
in the user-defined summation dimension: exp is never applied
to a number >= 0, and in each summation row, there is at least
one "exp(0)" to stabilize the sum.
For instance, ... | 6c5302c3542ac441698b9ace3a2e8ea42631cd51 | 654,412 |
import json
def to_json_sorted(text):
"""
Converts text to sorted(alphabetically on the attribute names) json value
:param text:
text to be converted to json
:return:
sorted json value
"""
json_value = json.dumps(json.loads(text), sort_keys=True, indent=0)
retur... | a99f08e7536565630824aa38c4982868ebd76a5b | 654,414 |
def get_column_headers(results):
"""Return the columnHeaders object from a Google Analytics API request.
:param results: Google Analytics API results set
:return: Python dictionary containing columnHeaders data
"""
if results['columnHeaders']:
return results['columnHeaders'] | e86b6363e74ea50872c1fa85cb6841d8bc194026 | 654,417 |
def true_fracture_stress(fracture_force, initial_cross_section, reduction_area_fracture):
"""
Calculation of the true fracture stress (euqation FKM Non-linear (static assessment))
Parameters
----------
fracture_force : float
from experimental results
initial_cross_section : float
... | 4da4aa2f6fac253803e107c0d81b0348d1b3a5a2 | 654,419 |
def build_url(video_id: str) -> str:
"""Converts a YouTube video ID into a valid URL.
Args:
video_id: YouTube video ID.
Returns:
YouTube video URL.
"""
return f"https://youtube.com/watch?v={video_id}" | a5e69ba3092e9deb3be9faac2f7c40bc7979b949 | 654,421 |
def partition_seq(seq, size):
"""
Splits a sequence into an iterable of subsequences. All subsequences are of the given size,
except the last one, which may be smaller. If the input list is modified while the returned
list is processed, the behavior of the program is undefined.
:param seq: the list... | 599e48da0db19b7fe7a5730a0659ac7ca130abf2 | 654,424 |
def write_file(filename="", text=""):
"""
Writes a string to a text file (UTF8) and
returns the number of characters written.
"""
with open(filename, 'w') as f:
return f.write(text) | 502790654937b63290d4219e901a8f8febe48a9c | 654,426 |
def ts(avroType):
"""Create a human-readable type string of a type.
:type avroType: codec.datatype.AvroType
:param avroType: type to print out
:rtype: string
:return: string representation of the type.
"""
return repr(avroType) | ef7b0adbe798644eb7259cb386bccdbacd037683 | 654,430 |
import ntpath
def path_leaf(path):
"""Return the base name of a path: '/<path>/base_name.txt'."""
head, tail = ntpath.split(path)
return tail or ntpath.basename(head) | c09f79f359e4008517c517431a42d052770b1d06 | 654,431 |
import torch
def generate_attention_masks(batch, source_lengths):
"""Generate masks for padded batches to avoid self-attention over pad tokens
@param batch (Tensor): tensor of token indices of shape (batch_size, max_len)
where max_len is length of longest sequence in the batch
@... | 5e9549f2419c7839bba427da9d03129185a6fc75 | 654,435 |
def new_in_list(my_list, idx, element):
"""Replace an element in a copied list at a specific position."""
if idx < 0 or idx > (len(my_list) - 1):
return (my_list)
copy = [x for x in my_list]
copy[idx] = element
return (copy) | 48fa685d9c9fbad89b36074dc8af92163b957460 | 654,436 |
def canonicalize_eol(text, eol):
"""Replace any end-of-line sequences in TEXT with the string EOL."""
text = text.replace('\r\n', '\n')
text = text.replace('\r', '\n')
if eol != '\n':
text = text.replace('\n', eol)
return text | 7ff5a8ed1ede1f854c3bb18aa6a9076ea16667c9 | 654,439 |
import torch
def soft_cross_entropy_tinybert(input, targets):
""" Soft Cross Entropy loss for hinton's dark knowledge
Args:
input (`Tensor`): shape of [None, N]
targets (`Tensor`): shape of [None, N]
Returns:
loss (`Tensor`): scalar tensor
"""
student_l... | 93aa378509a098c6020dcede78ebd228e54cf318 | 654,441 |
def sanitize_sacred_arguments(args):
"""
This function goes through and sanitizes the arguments to native types.
Lists and dictionaries passed through Sacred automatically become
ReadOnlyLists and ReadOnlyDicts. This function will go through and
recursively change them to native lists and dicts.
... | 07849b685bbbd84e9164352c1cf03f69f9ef731d | 654,443 |
def get_psr_name(psr):
"""
Get the pulsar name from the Tempo(2)-style parameter files by trying the
keys "PSRJ", "PSRB", "PSR", and "NAME" in that order of precedence.
Parameters
----------
psr: PulsarParameter
A :class:`~cwinpy.parfile.PulsarParameters` object
Returns
-------... | b847df5c11e486a224e9309d9e87c71771adc8fa | 654,448 |
def read_smi_file(filename, unique=True, add_start_end_tokens=False):
"""
Reads SMILES from file. File must contain one SMILES string per line
with \n token in the end of the line.
Args:
filename (str): path to the file
unique (bool): return only unique SMILES
Returns:
smiles... | 62423c1e54d2ba311c6deff8290f0e2a232dcf7d | 654,452 |
def predict(interpreter, audio):
"""Feed an audio signal with shape [1, len_signal] into the network and get the predictions"""
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
# Enable dynamic shape inputs
interpreter.resize_tensor_input(input_deta... | 3a180de0724861b1c4d29b97fc607c5b78d65c63 | 654,456 |
def convert_tuple_to_string(creds_tuple):
"""Represent a MAAS API credentials tuple as a colon-separated string."""
if len(creds_tuple) != 3:
raise ValueError(
"Credentials tuple does not consist of 3 elements as expected; "
"it contains %d."
% len(creds_tuple))
r... | 8e4bf77c8c8254439f624bc041bb7737286f8693 | 654,457 |
def detectEavesdrop(key1, key2, errorRate):
"""Return True if Alice and Bob detect Eve's interference, False otherwise."""
if len(key1) == 0 or len(key2) == 0:
return True
if len(key1) != len(key2):
return True
tolerance = errorRate * 1.2
mismatch = sum([1 for k in range(len(key1)) ... | 3e00c9cac94bd44c04f20ca314fa6fec9b00d33f | 654,460 |
def get_interaction(element_1, element_2, matrix_dimension):
"""Gets singular interaction between 2 elements of an ising matrix and returns the hamiltonion
Args:
element_1 ([int, int]): x, y coordinate of element 1 on the ising matrix
element_2 ([int, int]): x, y coordinate of element 2 on the ... | 423e68922d677a7f8f6f78213050ce6f92176091 | 654,462 |
def bps2human(n, _format='%(value).1f%(symbol)s'):
"""Converts n bits per scond to a human readable format.
>>> bps2human(72000000)
'72Mbps'
"""
symbols = ('bps', 'Kbps', 'Mbps', 'Gbps', 'Tbps', 'Pbps', 'Ebps', 'Zbps', 'Ybps')
prefix = {}
for i, s in enumerate(symbols[1:]):
prefix[s... | 753cc2dc4b529947eae7dae59a81459e677b2b86 | 654,464 |
def get_pos(i):
""" return key positions in N253 (1..10) from Meier's Table 2:
0 = blank, if you want to use the peak in the cube
11 = map center, the reference position of N253
"""
pos = [ [], # 0 = blank
['00h47m33.041s', '-25d17m26.61s' ], ... | 66902f2fc3b6bfde1fa79ec598aec17466f34541 | 654,465 |
def check_weekend(x: int) -> int:
"""
Checks if the extracted day from the date is a weekend or not.
"""
return 1 if x > 5 else 0 | ab0e39403ce0987ca33be85ac8af4e4763defbb5 | 654,466 |
def get_first(mapping, *keys):
"""
Return the first value of the `keys` that is found in the `mapping`.
"""
for key in keys:
value = mapping.get(key)
if value:
return value | b9a436ec411cad8fdf007f19b076a0f9c1bacda6 | 654,471 |
def calc_exposure_time(num_integrations, ramp_time):
"""Calculates exposure time (or photon collection duration as told
by APT.)
Parameters
----------
num_integrations : int
Integrations per exposure.
ramp_time : float
Ramp time (in seconds).
Returns
-------
exposur... | 8e54ee76d21ea9196fc2049e6171ad82b7b807e3 | 654,473 |
import re
def _is_camel_case(string: str) -> bool:
"""
Helper method used to determine if a given string is camel case or not. See the below details on the
exact rules that are applied.
1. First series of characters should be lower case
2. Every character group afterwards should string with an up... | c4af6ea950712b9d14f49bd67cf4d3a866474404 | 654,478 |
def str2intlist(s, repeats_if_single=None):
"""Parse a config's "1,2,3"-style string into a list of ints.
Args:
s: The string to be parsed, or possibly already an int.
repeats_if_single: If s is already an int or is a single element list,
repeat it this many times to create ... | b9a043807141810fc9b30d8f0c29279492c6ecbe | 654,481 |
def parseStyle(s):
"""Create a dictionary from the value of an inline style attribute"""
if s is None:
return {}
else:
return dict([[x.strip() for x in i.split(":")] for i in s.split(";") if len(i)]) | e3d196d22b546bffee3f6f014c61c9d9045e8da1 | 654,482 |
def get_top_n_kmers(kmer_count, num):
"""Get a list of top_n most frequent kmers."""
return [item[0] for item in sorted(kmer_count.items(), key=lambda x: x[1], reverse=True)[:num]] | c42c5722a5d0e578d451336896afaeb1f84a03d8 | 654,483 |
def _break(req, *opts):
"""
Break out of a pipeline.
:param req: The request
:param opts: Options (unused)
:return: None
This sets the 'done' request property to True which causes the pipeline to terminate at that point. The method name
is '_break' but the keyword is 'break' to avoid conflicting with python built... | 8c9cacd38d3268a7d11993ea3870bc61be52cd38 | 654,484 |
def w12(x):
"""12bit unsigned int"""
return 0b1111_1111_1111 & x | 9bbc10de0380afadb67ed57b5b6d7e7f75cff92c | 654,485 |
def get_padded_second_seq_from_alignment(al):
"""For a single alignment, return the second padded string."""
alignment_str = str(al).split("\n")[2]
return alignment_str | 4c1abab04b9631411e383956a5215665921b5036 | 654,490 |
import json
def read_json(json_file):
""" (file) -> dict
Read in json_file, which is in json format, and
output a dict with its contents
"""
with open(json_file) as data_file:
data = json.load(data_file)
return data | c49067c54a04d7760a468298052d62c8cd536bb5 | 654,492 |
def mask_bits(n: int, bits: int) -> int:
"""mask out (set to zero) the lower bits from n"""
assert n > 0
return (n >> bits) << bits | 6a54c7e460db520b5fb5f04edb814062bf3083f3 | 654,501 |
def l2rowg(X, Y, N, D):
"""
Backpropagate through Normalization.
Parameters
----------
X = Raw (possibly centered) data.
Y = Row normalized data.
N = Norms of rows.
D = Deltas of previous layer. Used to compute gradient.
Returns
-------
L2 normalized gradient.
"""
... | 584c9408bfc4eb4da144062a36affaa864cf549f | 654,507 |
def seq2batch(x):
"""Converts 6D tensor of size [B, S, C, P, P, P] to 5D tensor of size [B * S, C, P, P, P]"""
return x.view(x.size(0) * x.size(1), *x.size()[2:]) | 799eada00f9c7899db35fee8f2d10a8a8e3a0db5 | 654,510 |
def get_sort_key(sorting) -> list:
"""Return the sort colum value for sorting operations."""
return sorting["hostname"] | 7d337fb1f31af6844811c5cfd92617d73ebe956a | 654,511 |
import json
def open_json(_file):
"""Loads the json file as a dictionary and returns it."""
with open(_file) as f:
return json.load(f) | c7d2ca5170dd91dbb343b0e15469a78f03e35403 | 654,513 |
def math_wrap(tex_str_list, export):
"""
Warp each string item in a list with latex math environment ``$...$``.
Parameters
----------
tex_str_list : list
A list of equations to be wrapped
export : str, ('rest', 'plain')
Export format. Only wrap equations if export format is ``re... | f632246a14317309054e85310e83ee077ffdbc9f | 654,517 |
def read_file(filename):
"""
opens and read a file from file system
returns file content as data if ok
returns None is error while reading file
"""
try:
fhnd = open(filename)
data = fhnd.read()
fhnd.close()
return data
except:
return None | 7a43af8c0bdb073de8498c4cac8872f3594b1307 | 654,520 |
def remove_from(message, keyword):
"""
Strip the message from the keyword
"""
message = message.replace(keyword, '').strip()
return message | 7a173915cf0a17b5cf0d7a143012203b0b9a1835 | 654,524 |
import math
def poisson_distribution(gamma):
"""Computes the probability of events for a Poisson distribution.
Args:
gamma: The average number of events to occur in an interval.
Returns:
The probability distribution of k events occuring.
This is a function taking one parameter (k... | 287d5b9c1289d170c013652dc981749403a21707 | 654,525 |
def repo(request) -> str:
"""Return ECR repository to use in tests."""
return request.config.getoption("--repo") | 52eaf96e03368d9bc2e4bf4a2b0346e164465a64 | 654,528 |
def list_unique_values(dictionary):
"""
Return all the unique values from `dictionary`'s values lists except `None`
and `dictionary`'s keys where these values appeared
Args:
dictionary: dictionary which values are lists or None
Returns:
dict where keys are unique values from `dicti... | 7e6a18c6130b830c343a9594342c3daaf1696843 | 654,531 |
def py2(h, kr, rho, cp, r):
"""
Calculate the pyrolysis number.
Parameters
----------
h = heat transfer coefficient, W/m^2K
kr = rate constant, 1/s
rho = density, kg/m^3
cp = heat capacity, J/kgK
r = radius, m
Returns
-------
py = pyrolysis number, -
"""
py = h ... | 5a9868feeeaa5a99cf06e2c47671beeab7d45156 | 654,542 |
def format_for_IN(l):
""" Converts input to string that can be used for IN database query """
if type(l) is tuple:
l = list(l)
if type(l) is str:
l = [l]
return "(" + ','.join(['"' + str(x) + '"' for x in l]) + ")" | a2a755041c49af612e13e11da8148344b64a7926 | 654,547 |
def _sortByModified(a, b):
"""Sort function for object by modified date"""
if a.modified < b.modified:
return 1
elif a.modified > b.modified:
return -1
else:
return 0 | 03b3b0b97774b67ca04d2ebd97ca7d05307ff08d | 654,548 |
def impedance(vp, rho):
"""
Given Vp and rho, compute impedance. Convert units if necessary.
Test this module with:
python -m doctest -v impedance.py
Args:
vp (float): P-wave velocity.
rho (float): bulk density.
Returns:
float. The impedance.
Examples:
>>>... | 3031eb86087c17e5e72723b38b7fe9a87d610ca5 | 654,551 |
def zaid2za(zaid):
"""
Convert ZZAAA to (Z,A) tuple.
"""
# Ignores decimal and stuff after decimal.
zaid = str(int(zaid))
Z = int(zaid[:-3])
A = int(zaid[-3:])
return (Z, A) | 58643b9d7adb3c0756e4de5d51c5a7d68a7a65e0 | 654,558 |
def filter_active_particles(particles):
"""Filter active particles from particles dict."""
return {particle_number: particle
for particle_number, particle in particles.items()
if particle['active']} | 68e7d028e4f8cc94fc003af0eff5bfaa90f451a4 | 654,562 |
def extract_keys(feature_dict, feature_cls):
"""Extracts keys from features dict based on feature type.
Args:
feature_dict: `tfds.features.FeaturesDict` from which extract keys
feature_cls: `tfds.features.FeatureConnector` class to search.
Returns:
List of extracted keys matching the class.
"""
... | a1f514304ea0ca08b7350991303d8b7576ea9eee | 654,563 |
import torch
def split_last_dimension(x, n):
"""Reshape x so that the last dimension becomes two dimensions.
The first of these two dimensions is n.
Args:
x: a Tensor with shape [..., m]
n: an integer.
Returns:
a Tensor with shape [..., n, m/n]
"""
x_shape = x.size()
m = x_shap... | bf8fcf41315b11221d7a931c152f5ffc9ac83b5b | 654,564 |
def contains(collection, target):
"""Determine whether collecitons contains target """
return target in collection | 2973fe1ad055bffd837f1db39cf34a18ce42314a | 654,566 |
def _GetDownloadZipFileName(file_name):
"""Returns the file name for a temporarily compressed downloaded file."""
return '%s_.gztmp' % file_name | 6fa71745fc97847d5e8ae21f22d73b0dd9663e7a | 654,569 |
def simple_sanitize(s: str):
"""
Sanitize SQL string inputs simply by dropping ';' and '''
"""
if s is not None:
return s.replace(';', '').replace('\'', '')
return None | 02a89693ded22ce63ed45a7d50caf88697e11b39 | 654,570 |
def _transform_activation(phi, params):
"""Transform an activation function phi using the given parameters."""
params = params.copy()
input_scale = params.pop("input_scale", None)
input_shift = params.pop("input_shift", None)
output_shift = params.pop("output_shift", None)
output_scale = params.pop("outpu... | 6d8cd5ba9d3fc4284d6f6e02746c18fab6df3f78 | 654,572 |
def pofiles_to_unique_translations_dicts(pofiles):
"""Extracts unique translations from a set of PO files.
Given multiple pofiles, extracts translations (those messages with non
empty msgstrs) into two dictionaries, a dictionary for translations
with contexts and other without them.
Args:
... | e88053759f78a7a5d210ce84819e290f33708396 | 654,576 |
import inspect
def _isFunction(fn):
"""
Python class is also callable, so we need to deal with such pattern.
class A:
def b(self):
return False
a = A()
callable(A) # True
callable(a) # False
callable(a.b) # True
inspect.isclass(A) # True
inspect.isclass(a) # False
inspect.isclass(a.b) # ... | f8775e15c8a6f7c30f3dd0a7aa6a27c340f09b38 | 654,578 |
def is_label_ranker(estimator):
"""Return ``True`` if the given estimator is a :term:`label ranker`.
Parameters
----------
estimator : object
The estimator object to test.
Returns
-------
out : bool
``True`` if ``estimator`` is a label ranker and ``False`` otherwise.
""... | 10c4ad8b45218a708245995522476f32596e4d8e | 654,582 |
def generateInd(size_nodal_mu, corner13theta, corner24theta, corner12mu, corner34mu, num_nodes):
"""Generates the ind list based on nearest nodal points and the size of the nodal mu array
args:
size_nodal_mu (int): Size of nodal mu array
corner13theta - corner34mu (ints): Indices of nearest nodal points
num_n... | e3f9d05bf99ae574252d1d2cc28ccc2eb22d3359 | 654,591 |
def get_par_dict(e3d_par):
"""
return e3d.par as a dict
:param e3d_par: path to e3d.par
:return: dict
"""
d = {}
with open(e3d_par, "r") as e1:
t1 = e1.readlines()
for line in t1:
k, v = line.strip().split("=")
d[k] = v
return d | 6216133d901accec2bac668f628e59700a57b7e6 | 654,593 |
def convert_string_tf_to_boolean(invalue):
"""Converts string 'True' or 'False' value to Boolean True or Boolean False.
:param invalue: string
input true/false value
:return: Boolean
converted True/False value
"""
outvalue = False
if invalue == 'True':
outvalue = True
... | 29c59a95f7f308dadb9ac151b1325069cdfd3cdc | 654,596 |
def lines(string, keepends=False):
"""
Split a string into a list of strings at newline characters. Unless
*keepends* is given and true, the resulting strings do not have newlines
included.
"""
return string.splitlines(keepends) | cde9be4207dba6897de274be304c55f4b28ed916 | 654,598 |
def BuildCampaignOperations(batch_job_helper,
budget_operations, number_of_campaigns, campaign_names):
"""Builds the operations needed to create a new Campaign.
Note: When the Campaigns are created, they will have a different Id than those
generated here as a temporary Id. This is jus... | faca10dd14c2902f4bb8cc4eb782c97f76829f72 | 654,600 |
import base64
def encode_group_id(group_id):
"""Encode group_id as returned by the websocket for use with other endpoints."""
return "group." + base64.b64encode(group_id.encode("ascii")).decode("ascii") | 9779f344864b0ec1325a9d8628c86c4177fe9c94 | 654,601 |
def get_effective_power(unit):
"""Get effective power of unit."""
return unit['count'] * unit['damage'] | 3dc131cc0c4223644307ef75b3d913b35e1f5bb5 | 654,606 |
import six
from contextlib import suppress
def is_valid_aesthetic(value, ae):
"""
Return True if `value` looks valid.
Parameters
----------
value : object
Value to check
ae : str
Aesthetic name
Returns
-------
out : bool
Whether the value is of a valid loo... | c15e8dde3ffdde428016559555bb08c677f9003f | 654,608 |
def lag(series, i=1):
"""
Returns a series shifted backwards by a value. `NaN` values will be filled
in the beginning.
Same as a call to `series.shift(-i)`
Args:
series: column to shift backward.
i (int): number of positions to shift backward.
"""
shifted = series.shift(i)... | c026a54b1288301c1ae757a146f36dfdf5a87c2b | 654,609 |
from typing import List
import json
def get_extensions() -> List[str]:
"""Carica le estensioni dal file extensions.json. Si aspetta di trovare una lista con
i nomi delle estensioni da aggiungere al bot. Se non trova il file o ci sono errori ritorna
una lista vuota.
:returns: la lista coi nomi delle e... | 808d638b15e56ab1e7a58ac2c955ace07efdd061 | 654,610 |
def aero_force(rho, V, C, A):
"""
Aerodynamic lift/drag equation
Input variables:
rho : Fluid density
V : Fluid velocity
C : Lift/drag coefficient
A : Reference area
"""
F = 0.5 * rho * (V**2) * C * A
return F | b8f13f945e8a55acde35cac0cabb97475b8adc59 | 654,612 |
def is_anagram(word1, word2):
"""Checks whether two words are anagrams
word1: string or list
word2: string or list
returns: boolean
"""
return sorted(word1) == sorted(word2) | dd1417f0ced25149e029ec87c0064fbaed7156c9 | 654,615 |
import string
def name_make_safe(name, safe_chars = None):
"""
Given a filename, return the same filename will all characters not
in the set [-_.0-9a-zA-Z] replaced with _.
:param str name: name to make *safe*
:param set safe_chars: (potional) set of characters that are
considered safe. Def... | b93e5d8ca5cb992a389b4ad44ed0db9c0e6abf7f | 654,617 |
def get_most_complete_version(versions):
""" Return the most complete version.
i.e. `versions=['1.4', '1.4.4']` it returns '1.4.4' since it's more complete.
"""
if not versions:
return
return max(versions) | 2cf0b4d94388699b59eacad75d3c10464f659ad7 | 654,621 |
def rename_columns(df, columns_dictionary):
"""Renames provided columns.
"""
return df.rename(columns=columns_dictionary) | b30b095a95edfb634af474a4542d1cd8253e6b45 | 654,622 |
def shorten(thelist, maxlen, shorten):
"""
If thelist has more elements than maxlen, remove elements to make it of size maxlen.
The parameter shorten is a string which can be one of left, right, both or middle
and specifies where to remove elements.
:param thelist: the list to shorten
:param max... | 72aa428b04b34737225717396946bce009be6bc1 | 654,623 |
def ByteToHex( byteStr ):
"""
Convert a byte string to it's hex string representation e.g. for output.
"""
return ''.join( [ "%02X " % ord( x ) for x in byteStr ] ).strip() | bb2c5898d99d39463fa8fe71293a6154d4339b0e | 654,624 |
def update_parameters(parameters, grads, learning_rate = 1.2):
"""
Updates parameters using the gradient descent update rule given above
Arguments:
parameters -- python dictionary containing your parameters
grads -- python dictionary containing your gradients
Returns:
parameters ... | 8dc071f7d10b61ccdfd33e00404f805ad5b7ce1c | 654,627 |
from typing import Sequence
import fnmatch
def _should_ignore(fd_name: str, patterns: Sequence[str]) -> bool:
"""Return whether `fd_name` should be ignored according to `patterns`."""
return any(fnmatch.fnmatchcase(fd_name, pattern) for pattern in patterns) | e41d8b8f8c80331f24210bd6e79c10b3e77f727b | 654,628 |
import torch
def unnormalize(img, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]):
"""
Convert a normalized tensor image to unnormalized form
:param img: (B, C, H, W)
"""
img = img.detach().cpu()
img *= torch.tensor(std).view(3, 1, 1)
img += torch.tensor(mean).view(3, 1, 1)
... | 496ced9481afa5ef8a9a097f36bcf6b7d83157ad | 654,629 |
from typing import Counter
def num_reviews_with_token(profTokenDict):
""" Returns a Counter with the number of reviews a given token appears in.
"""
counter = Counter()
for profCounts in profTokenDict.values():
for revCtr in profCounts:
counter += Counter(revCtr.keys())
return counter | 0f247f93174b72482278220c163cba057a9caec9 | 654,634 |
def cache_dir(tmp_path_factory):
"""Return temporary location of DATALAD_REGISTRY_DATASET_CACHE."""
return tmp_path_factory.mktemp("cache_dir") | 648d8c9a47974490c83d2004bed6ca86b1f4a706 | 654,635 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.