content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def xor(array, *lists):
"""Creates a list that is the symmetric difference of the provided lists.
Args:
array (list): List to process.
*lists (list): Lists to xor with.
Returns:
list: XOR'd list.
Example:
>>> xor([1, 3, 4], [1, 2, 4], [2])
[3]
.. versiona... | 210fe4d8e2fe17e36f637e1b0ab52cd83ce894ad | 684,299 |
import math
def rotation_matrix_xyz(rotation_angles):
"""
Converts given rotation angles to a rotation represented by the sequences of rotations around XYZ with given angles
"""
rad_angles = [math.radians(x) for x in rotation_angles]
x_angle = rad_angles[0]
y_angle = rad_angles[1]
z_angl... | a025e1817d5bdc3a653ad1b85f974880b172cacf | 684,300 |
def _guess_header(info):
"""Add the first group to get report with some factor"""
value = "group"
if "metadata" in info:
if info["metadata"]:
return ",".join(map(str, info["metadata"].keys()))
return value | 272b0a2e91d462e15f997a0ebecf371c4015562d | 684,301 |
import torch
def weighted_loss(loss, weights):
"""
Weighted loss
"""
if weights is not None:
return torch.mean(weights * loss)
else:
return torch.mean(loss) | 5e1b5feea324bc3c6a97eb9879c51e7acd6a1033 | 684,302 |
def pot_LJ_dl(r):
"""Dimensionless Lenard Jones potential, based on distances"""
r = r**-6 # Possibly improves speed
u = 4*(r**2 - r)
return u | 4e8491128690e0e31045e99e47fdb3c9ef7dc587 | 684,303 |
import sys
import os
import subprocess
def supports_color():
"""
Returns True if the running system's terminal supports color, and False
otherwise.
"""
plat = sys.platform
supported_platform = plat != 'Pocket PC' and (plat != 'win32' or
'ANSICO... | 673e32f9a1c2c5a13b73d48d88642e26e256d4b6 | 684,304 |
def fit_model(model, callbacks_list, sequence, outseq, n_epoch):
"""
Make RAENN model
Parameters
----------
model : keras.models.Model
RAENN model to be trained
callbacks_list : list
List of keras callbacks
sequence : numpy.ndarray
Array LC flux times, values and err... | e2f8982ba63b2f9fc10bbafd133c6b54676abd15 | 684,305 |
def get_named_object(pathspec):
"""Return a named from a module.
"""
parts = pathspec.split('.')
module = ".".join(parts[:-1])
mod = __import__(module, fromlist=parts[-1])
named_obj = getattr(mod, parts[-1])
return named_obj | d44969dcd18a0dcf1cfb50ab2f0e7ab593e46f77 | 684,306 |
def convert_percentage_number(decimal_percentage: float) -> str:
"""
Convert a decimal percentage in a hundred percentage
the percentage generated won't have fraction part
For example:
```
convert_percentage_number(0.1) # 10
convert_percentage_number(0.05) # 5
convert_percentage_number... | 39f5eefa0f3c8bc1b6b633aa857f21824eeee1a2 | 684,307 |
def validate_passport_star1(passport):
"""
Validate a single passport against required keys. returns 1 if valid otherwise 0
"""
required_keys = ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid']
for key in required_keys:
if passport.get(key) == None:
return False
return True | 2338da9080d25308ae7d582d8c642cf5062b1d30 | 684,308 |
def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
lstep, rstep = 0, 0
for i in nums:
lstep += 1
rstep = 0
for j in nums[::-1]:
rstep += 1
if (lstep + rstep) > len(nums):
break
... | ad715779019d8160c9bfa5c204e5b414d9a41824 | 684,309 |
def get_formatted_emg(emg_row):
"""
:param emg_row: dict [str] one row that represent data from Electromyograph sensor
example:
['2018-07-04T17:39:53.743240', 'emg', '-1', '-6', '-9', '-9', '1', '1', '-1', '-2', '2018-07-04T17:39:53.742082']
:return:
formatted emg row
example:
['2018-07-... | ea939fdf8e99a1048a48ce6f021d03ca4143b862 | 684,310 |
def sort_words(words):
"""this function will sort words
Args:
words ([string]): [the string to sort]
"""
return sorted(words) | 7d0c4ce6a07304dc614167dc632f79a917806c91 | 684,311 |
import os
import sys
def get_package_dir(value):
"""Get package directory"""
package_dir = os.path.split(value)[0]
if package_dir not in sys.path:
sys.path.append(package_dir)
return package_dir | 244051c67887063feb2c163d36abbfba8e9286e3 | 684,312 |
def getElementByName(cgx,name):
"""
get Element json object by using the element name
"""
res = cgx.get.elements()
if not res.cgx_status:
print(res.cgx_content)
raise ValueError(f"Can't retrieve element {name}")
for item in res.cgx_content["items"]:
if item["name"] == nam... | 2d2ac9a8ab85d2a6012d44f2a6e3884bc7372e8b | 684,313 |
def train_test_split(x, y=None, test_ratio=0.2):
""" Returns x_train, y_train, x_test, y_test """
train_size = int(len(x) * (1.0 - test_ratio))
if y is not None:
return x[:train_size], y[:train_size], x[train_size:], y[train_size:]
else:
return x[:train_size], x[train_size:] | e1f5f8dd354d9d42c30f982934722f7ba8192ffa | 684,314 |
def split_into_lines(text, split_tag='\n', len_upper_limit=800, is_skip_empty=True):
"""
使用指定分隔符来分句
:param text: 原文本
:param split_tag: 分隔符
:param len_upper_limit: 句子长度的最大上限,并且保证句子的完整性
:param is_skip_empty: 是否跳过空行
:return: 句子列表
"""
start = 0
spans = []
lines = []
text_spli... | 1883fffeb9a98d853ab471422d348d75db0f8022 | 684,315 |
from typing import OrderedDict
def get_companies(dbconnection, args):
"""
Return an ordered dictionary of information from the company table.
The key is the db key
"""
print('Companies')
cursor = dbconnection.cursor()
cursor.execute('SELECT * FROM Companies')
row = cursor.fetchone()
... | 6373a86142beb2f296926dff5bdb8f831fc1f0f7 | 684,316 |
def pear2(y_obs,y_mod):
"""
calculates squared Pearson correlation coeffcient
Examples
--------
>>> # Create some data
>>> y_obs = np.array([12.7867, 13.465, 14.1433, 15.3733, 16.6033])
>>> y_mod = np.array([12.8087, 13.151, 14.3741, 16.2302, 17.9433])
>>> # calculate Squared Pears... | 5a0e6164fd5c75ad0a495b32fc2838146b4f8317 | 684,317 |
def code() -> str:
"""
Example G-code module, a drawing of a crocodile.
Please simulate first, before milling.
"""
return """
G91
G17
G3 X20 Y0 I10 J0
G0 X40 Y0
G3 X6 Y0 I3 J0
G0 X0 Y3
G3 X-3 Y3 I-3 J0
G0 X-40 Y0
G2 X0 Y6 I0 J3... | 231f10f30b774dda7584871f220bbeecda8191ad | 684,318 |
import re
def remove_none_alphanumeric(string):
"""
remove non-alphanumeric characters
"""
pattern = re.compile("[\W_]+", re.UNICODE)
return pattern.sub("", string) | 64f131d5830604c82f6462a7aa5d1043737af58d | 684,319 |
def map_values(map_fn, dictionary):
"""Returns a dictionary whose values have been transformed by map_fn.
"""
return {k: map_fn(v) for k, v in dictionary.items()} | c2d7a843cfe45e52b8d1f0ba6760b98eaebb287f | 684,322 |
def v1(ss):
"""
soma de variavel, mas já está declarada
"""
ss += 1
if ss == 100:
try:
input(f"Atingiu {ss} vez!")
# yield ss
return 0
except KeyboardInterrupt:
print('\nObrigado por usar nosso programa teste!')
return -... | f22f892deb62e4382f1d4eb6338753e49146955a | 684,323 |
def create_poll(poll_options: list) -> dict:
"""
Creates a poll of a list of options
:param poll_options:
:return:
"""
poll_opts_map = {}
for opt in poll_options:
poll_opts_map.update({opt.lstrip(" ").rstrip(" "): 0})
return poll_opts_map | 7a9fdd56175f2f731fc9d73a54fbc38aff3d5575 | 684,324 |
import re
def loads(hesciiStr, prefix='x'):
"""
Takes a hescii-encoded string and returns the utf-8 byte string.
Args:
hesciiStr: a hescii-encoded string
prefix: string used to prefix all encoded hex values. Default 'x'
Returns:
A utf-8 byte string
"""
... | 35b380bc80a57bcc7c6e7c00b36e3001e1aafd8a | 684,325 |
def compute_xy_position_bin_inds(xy, bin_size):
"""Converts xy values to position bin indices assuming that
the first bin edge starts at 0.
:param xy: numpy.array position coordinate values
:param float bin_size: size of a bin
:return: same shape as xy, but values referring to bin indices
:rtyp... | a67d84cc5a5e5175d387cdbb022dc6a4974b78ac | 684,326 |
def is_ip(s):
"""
Check a string whether is a legal ip address.
:type s: string
:param s: None
=======================
:return:
**Boolean**
"""
try:
tmp_list = s.split(':')
s = tmp_list[0]
if s == 'localhost':
return True
tmp_list = s.... | a8e96c20c60c6454d13948e399d38cf3af7b38f8 | 684,327 |
def _make_package(x):
"""Get the package name and drop the last '.' """
package = ''
for p in x:
package += p[0] + p[1]
if package and package[-1] == '.':
package = package[:-1]
return package | 1455cdb7bf508ca5fb93046aba777ded9b55c81b | 684,328 |
def _conv(n):
"""Convert a node name to a valid dot name, which can't contain the leading space"""
if n.startswith(' '):
return 't_' + n[1:]
else:
return 'n_' + n | 291f075bc0d653949c9e35308e4ecb5c14e156e3 | 684,329 |
def val_or_none_key(getter_fcn):
"""Wraps getter_fcn, returning a key that is a tuple of (0 or 1, val) where
val=getter_fcn(obj), and the int is 0 if val is None."""
def result_key_fcn(obj):
val = getter_fcn(obj)
n = 0 if val is None else 1
return n, val
return result_key_fcn | e56270f48254a3b35393354ada00166564ecbfcb | 684,330 |
def strip_diagnostics(tracks):
"""Remove diagnostic information from a tracks DataFrame.
This returns a copy of the DataFrame. Columns with names that start
with "diag_" are excluded."""
base_cols = [cn for cn in tracks.columns if not cn.startswith('diag_')]
return tracks.reindex(columns=base_cols) | 84a6f84e0cea1446daf399caaa6190c523892713 | 684,331 |
def make_token(name, value=''):
"""Make a token with name and optional value."""
return {'name': name, 'value': value} | 0170bba93a001498e11af0cc3295321d4095b1b7 | 684,332 |
def convert_frac(ratio):
""" Converts ratio strings into float, e.g. 1.0/2.0 -> 0.5 """
try:
return float(ratio)
except ValueError:
num, denom = ratio.split('/')
return float(num) / float(denom) | 5503f0335a9371d4fb008b005fc0b268a86209e8 | 684,333 |
def k8s_url(namespace, kind, name=None):
"""
Construct URL referring to a set of kubernetes resources
Only supports the subset of URLs that we need to generate for use
in kubespawner. This currently covers:
- All resources of a specific kind in a namespace
- A resource with a specific name ... | 8d54770990fb500da1a42df891e21d1dce18bef9 | 684,334 |
def fixxpath(root, xpath):
"""ElementTree wants namespaces in its xpaths, so here we add them."""
namespace, root_tag = root.tag[1:].split("}", 1)
fixed_xpath = "/".join(["{%s}%s" % (namespace, e) for e in xpath.split("/")])
return fixed_xpath | 324f6c441061bafff4e59e62e4bd4de3937e1643 | 684,335 |
def inverse(upper, lower):
"""inverse
Solve inversion matrix by solving upper and lower matrix
:param upper: upper triangular matrix
:param lower: lower triangular matrix
:return: inversion matrix
"""
# solve y: Ly=B
n = len(lower)
y = []
for i in range(n):
y.append([0] *... | 55a4a69bca3947f4abee65503c287d14f9258be9 | 684,336 |
def _pad_vocabulary(vocab, math):
"""
Pads vocabulary to a multiple of 'pad' tokens.
Args:
vocab (list): list with vocabulary
math (str): Math precision. either `fp_16`, `manual_fp16` or `fp32`
Returns:
list: padded vocabulary
"""
if math == "fp16":
pad = 8
... | b48fc59dea22e5355811dd3c00184c11532a2c87 | 684,337 |
def convert_r_groups_to_tuples(r_groups):
""" Converts a list of R-Group model objects to R-Group tuples"""
return [r_group.convert_to_tuple() for r_group in r_groups] | aad1b55ae70b354d231c6765949b0ea587d5d28b | 684,338 |
def number_strip(meaning):
"""
strips numbers from the meaning array
:param meaning: array
:return: stripped list of meaning
"""
integer_array = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
returnVal = []
flag = False
for everyWord in meaning:
for everyChar in everyWord... | d2f0ce56f1b11b85a4d6626b6582428ce69cca81 | 684,339 |
def is_assessor_type(obj_type):
"""
Function to return if type is assessor.
:param obj_dict: dictionary to describe XNAT object parameters
:return: boolean
"""
_okeys = list(obj_type.keys())
return 'xsiType' in _okeys or 'procstatus' in _okeys | 8898f767ffcfc2cf740abd417445ef93c1a03b9a | 684,340 |
import re
def domain(url):
"""Get domain from url.
Domain must start with ``http://``, ``https://``
or ``/``.
Parameters
----------
url: str
URL to parse to extract the domain.
Raises
------
ValueError
If the URL pattern is invalid.
Examples
--------
... | ace1ecd6669a624febfb4f1b320a999ab0be006e | 684,341 |
import re
def filter_eligible_words(df, lowerbound_absolute, upperbound_relative):
"""
Keep only the words that appear enough time but not too often.
df : a dataframe with two column [cote, tokens]
cote : the cote of the document
tokens : the liste of preprocessed tokens
lowerbound... | d9d1e6e9f3b50062bd2ad256854e1b0ae228aa08 | 684,342 |
def cindex_rlscore_reference(Y, P):
"""
Function taken from the rlscore package: https://github.com/aatapa/RLScore as reference.
"""
correct = Y
predictions = P
assert len(correct) == len(predictions)
disagreement = 0.
decisions = 0.
for i in range(len(correct)):
for j in ran... | c2f7994e532360f0610ce2ee7d910c401b3bc219 | 684,343 |
def covariance(datapoints, num_features, mean_feature_vector_for_c):
"""
Calculates the Covariance Matrix that is needed for each cluster of data.
The covariance matrix is calculated as described by the Fisher Score PDF for the project
:param datapoints: datapoints in cluster
:param num_features: n... | fb5966edb4c6065f82ee3c5e0b7bb1386815b821 | 684,344 |
def scale(x, s):
"""Scales x by scaling factor s.
Parameters
----------
x : float
s : float
Returns
-------
x : float
"""
x *= s
return x | 30846643be0c37cfd2f13e38edc4e3b6b4b27026 | 684,345 |
def _clean_size_(bf,smin=0):
"""
This function cleans the nested ROI structure
by merging small regions into their parent
bf = _clean_size_(bf,smin)
Parameters
----------
bf the hroi.NROI to be cleaned
smin=0 the minimal size for ROIs
Results
-------
bf the cleaned hroi.NR... | 5420854f36bcb83d2bb32300e551eabffa280e53 | 684,346 |
def pop_sort(pop):
"""
This function sorts the population based on their fitnesses, using selection sort.
pop: The population that are sorted based on their fitnesses.
"""
for i in range(len(pop)):
min_index = i
for j in range(i+1, len(pop)):
if pop[min_index].fitnes... | 0615aa2a9fc96b9d7047e2cc5f087ade2ae5a984 | 684,347 |
def subverParseClient(s):
"""return the client name given a subversion string"""
return s[1:].split(":")[0] | 35de59e7a18603341154c26f5da3c19a80631976 | 684,348 |
import csv
def input_thresholds(name_moderate, name_good):
"""
Generates from a .csv file the dictionary of reference profiles and thresholds.
:param name_moderate: Name of the .csv file which must contain on the first
line the names of the criteria and on the following lines, for each criterion,... | e6ed3cd7dc5627048886e5ee48d26621eece9db3 | 684,349 |
import numpy
def slowness2vel(slowness, tol=10 ** (-8)):
"""
Safely convert slowness to velocity.
Almost 0 slowness is mapped to 0 velocity.
Parameters:
* slowness : array
The slowness values
* tol : float
Slowness < tol will be set to 0 velocity
Returns:
* velocit... | d1bf53bf2d8cf909c48dec6bdbb4f810d436fc36 | 684,350 |
import requests
def get_all_service_groups(asa):
"""
This function retrieves all service groups from ASA
:param asa: ASA device which to retrieve the objects from ASA
:return: Returns list of service objects.
"""
url = asa.url() + "/api/objects/networkservicegroups"
headers = {
'C... | ff62bec47f7bf306276e81dc2e710b3cb789986c | 684,351 |
import math
def genVector(width, height, x_mult=1, y_mult=1):
"""Generates a map of vector lengths from the center point to each coordinate
widht - width of matrix to generate
height - height of matrix to generate
x_mult - value to scale x-axis by
y_mult - value to scale y-axis by
"""
cen... | 2a4404d0678101668545122a03142dc48bff2b9c | 684,352 |
from typing import List
def _get_extent(bounds: List[float], offset_x: float,
offset_y: float) -> List[float]:
"""Get extent of image without collar
"""
minx, miny, maxx, maxy = bounds
minx = minx + (abs(minx) % offset_x)
miny = miny - (miny % offset_y) + offset_y
maxx = maxx ... | 30435cf7f9cb486e2262dc4cf3d03ce3cbc61faa | 684,353 |
def get_indexes(lst, sub_lst, compare_function=None):
"""Return the indexes of a sub list in a list.
:param lst: the list to search in
:param sub_lst: the list to match
:param compare_function: the comparaison function used
:type lst: list
:type sub_lst: list
:type compare_function: functi... | 6780b77157ba425384aeebc2ff3d93f19a6fb561 | 684,354 |
def _join_modules(module1, module2):
"""Concatenate 2 module components.
Args:
module1: First module to join.
module2: Second module to join.
Returns:
Given two modules aaa.bbb and ccc.ddd, returns a joined
module aaa.bbb.ccc.ddd.
"""
if not module1:
return module2
if not module2:
... | d528261fbe8fda829b59509612f3cee652024cbc | 684,355 |
def from_723(u: bytes) -> int:
"""Convert from ISO 9660 7.2.3 format to uint16_t
Return the little-endian part always, to handle non-specs-compliant images.
"""
return u[0] | (u[1] << 8) | 3665d3a4812e87a0d2d727027e6e69ce5da8e871 | 684,356 |
import base64
def decode_textfield_base64(content):
"""
Decodes the contents for CIF textfield from Base64.
:param content: a string with contents
:return: decoded string
"""
return base64.standard_b64decode(content) | 9f0ebc8cdfc4a7337e44451a3856df472bc07f56 | 684,357 |
from typing import Any
def default_key(obj: object, key: str, default: Any = None) -> Any:
"""Get value by attribute in object or by key in dict.
If property exists returns value otherwise returns `default` value.
If object not exist or object don't have property returns `default`.
Args:
obj... | 6dff248c8f463259b9c90239a812bc5d23034eaa | 684,358 |
def _get_lua_base_module_parts(base_path, base_module):
"""
Get a base module from either provided data, or from the base path of the package
Args:
base_path: The package path
base_module: None, or a string representing the absence/presence of a base
module override
... | eee4ef02108e49da8b601af7fcd1111257ece103 | 684,359 |
import configparser
def read_ini(src_filename):
"""
read configs in ini file
:param src_filename: source file path
:return: parsed config data
"""
config = configparser.ConfigParser()
config.read(src_filename)
return config | 816236b7f4a9848990a8fcba10dc6580f1a245fc | 684,362 |
def broken_bond_keys(tra):
""" keys for bonds that are broken in the transformation
"""
_, _, brk_bnd_keys = tra
return brk_bnd_keys | f499a912e4b11bb4fd71e6bb1a9a8991e26f44bb | 684,363 |
def formatSchool(school):
"""The name of the school where a thesis was written. """
return school | 269b8e94a8feadf0d839320a381ac739bb26e717 | 684,364 |
def named_field(key, regex, vim=False):
"""
Creates a named regex group that can be referend via a backref.
If key is None the backref is referenced by number.
References:
https://docs.python.org/2/library/re.html#regular-expression-syntax
"""
if key is None:
# return regex
... | b813179e87f8bf6cabc02d7746222787154aed3a | 684,365 |
def c1c2_deriv (h2o, co2, c, m):
"""
calculate derivatives for c1, c2 needed for density equation
!!! chain rule extravaganza !!!
"""
c1 = c['c1']
c2 = c['c2']
dc1 = {}
dc2 = {}
# derivatives for c1
c1_2 = c1*c1
dc1['dp'] = c1_2*(h2o['dp'] + co2['dp'] )... | f1bec0a7ddbd467b1e9234f0f3bf7a14f6115314 | 684,366 |
def _generate_qasm(gate_list, n_qubits, gate_options={1: "x", 2: "cx"}):
"""Convert a list of gates into a QASM string.
Args:
gate_list (list[(int, (int, int))]): The list of gates representing the
current circuit.
n_qubits (int): The number of nodes in the graph.
gate_optio... | 08860988075be9c4e99a83a3d4a3182acdb52c5c | 684,367 |
def prepro(I): #where I is the single frame of the game as the input
""" prepro 210x160x3 uint8 frame into 6400 (80x80) 1D float vector """
#the values below have been precomputed through trail and error by OpenAI team members
I = I[35:195] #cropping the image frame to an extent where it contains on the pad... | 237e90d0e495d95a73b58572366bb1ef407041b7 | 684,368 |
import os
def base_filename(path):
"""Returns the filename without the extension from the path"""
return os.path.splitext(os.path.basename(path))[0] | aca628301dbc63ccda9ee011e433e306bddf82b1 | 684,370 |
import torch
def _set_finite_diff_coeffs(ndim, dx, device, dtype):
"""Calculates coefficients for finite difference derivatives.
Currently only supports 4th order accurate derivatives.
Args:
ndim: Int specifying number of dimensions (1, 2, or 3)
dx: Float Tensor containing cell spacing i... | ef270d3a7538c54956410d86138f1b7d4c219428 | 684,371 |
def build_regex(pattern, pattern_name=None, **kwargs):
"""
Return regex string as a named capture group.
See: https://tonysyu.github.io/readable-regular-expressions-in-python.html
"""
pattern = pattern.format(**kwargs)
if pattern_name is not None:
return r'(?P<{name}>{pattern})'.format(... | 0625d70bc0b16416e3178c59100ab815e73c8b56 | 684,372 |
def number_of_patients(dataset, feature_files, label_files):
"""
Calculates number of unique patients in the list of given filenames.
:param dataset: string. Dataset train/val/test.
:param feature_files: list of strings. List of filenames with patient names containing features.
:param label_files: ... | ac8c0a269d9019768af67d20409a89d78e6f5512 | 684,373 |
def invert_dict(dic, sort=True, keymap={}, valmap={}):
"""Inverts a dictionary of the form
key1 : [val1, val2]
key2 : [val1]
to a dictionary of the form
val1 : [key1, key2]
val2 : [key2]
Parameters
-----------
dic : dict
Returns
-----------
dict
"""
dic_... | 4b7b55dcde48db84dbc853d06511f702090da422 | 684,374 |
from decorator import decorate
from decorator import FunctionMaker
def _decorate_polyfill(func, caller):
"""
decorate(func, caller) decorates a function using a caller.
"""
try:
return decorate(func, caller)
except ImportError:
evaldict = dict(_call_=caller, _func_=func)
fu... | 8c6c701670e277edf1104dd7abccc5be8bcd17ac | 684,375 |
def extractLESYT(item):
"""
LESYT
DISABLED
"""
return None | 099857d0e1ad626f6c55a296c580607341f08e9a | 684,378 |
def _mangle_recipients(name, *args):
"""Modify the recipient address if it's the same as alias
to prevent mail forwarding loops
Ref: https://serverfault.com/questions/471604/
"""
input_args = []
# Flatten the input list
for sublist in list(args):
for item in sublist:
in... | 379a5968e27e000a22084788fa55a2f5abcf1980 | 684,379 |
def insertStyles(htmlCode, stylesheet, name):
"""We break up the HTML code into a list"""
"""and insert the styles."""
htmlList = htmlCode.split('\n')
preamble = [
'<!DOCTYPE html>',
'<html>',
'<head>',
'<link rel="stylesheet" href="' + stylesheet + '"/>',
'<title>' + name + '</... | ce95138344875f31d75dffc3145cae8bd5db6e3a | 684,380 |
def byte_ord(b):
"""
Return the integer representation of the byte string. This supports Python
3 byte arrays as well as standard strings.
"""
try:
return ord(b)
except TypeError:
return b | a41594431549ccf70408f7c9180c6a8c5c487e7b | 684,381 |
import yaml
def yaml2config(yaml_path):
"""
convert yaml to dict config.
"""
final_configs = []
f = open(yaml_path, 'r')
origin_configs = yaml.load(f, Loader=yaml.FullLoader)
f.close()
for configs in origin_configs:
configs = configs['DistillConfig']
final_configs.e... | a790a147710a77eca5f378cafbeafd33bdb2862c | 684,382 |
def protolinks_simple(proto, url):
"""
it converts url to html-string using appropriate proto-prefix:
Uses for construction "proto:url", e.g.:
"iframe:http://www.example.com/path" will call protolinks()
with parameters:
proto="iframe"
url="http://www.example.com/path"... | c3edd087761a78d632fb5dcfe7a30071d2e52b3b | 684,383 |
import re
def parse_time(time_string) -> int:
""" Parse a time stamp in seconds (default) or milliseconds (with "ms" unit)
The "s" unit is optional and implied if left out.
Args:
time_string(str): timestamp, e.g., "0.23s", "5.234" (implied s), "1234 ms"
must be a number followed b... | b9d3d1cc4f388def47b3dd620a656f60f7c50929 | 684,384 |
import base64
def get_base64encode(arg):
"""
@summary: 获取唯一的base64编码值
---------
---------
@result: 字符串
"""
if not isinstance(arg, bytes):
arg = bytes(arg, encoding="utf-8")
result = str(base64.b64encode(arg), encoding="utf-8")
return result | 4e1b9cfd3910c5cc41ea020ad7f71c70b4775197 | 684,385 |
def clean_character(dataframe):
""" clean special characters """
dataframe['clean_text'] = dataframe['clean_text'].str.lower().str.replace("[^a-zA-Z#]", " ")
return dataframe | 58789c77931c0465e3c56426e07f784744ce7c27 | 684,386 |
def confidence_intervals_overlap(old_score, old_ci, new_score, new_ci):
"""Returns true if the confidence intervals of the old and new scores
overlap, false otherwise.
"""
if old_score < new_score:
old_score += old_ci
new_score -= new_ci
return old_score >= new_score
else:
... | fbf87f5c1997624c965b8bfb2b540d1c833a24e3 | 684,387 |
def n_ary(logical):
"""
@type: logical: LogicalExpression
@rtype: str
"""
return "{name}({terms})".format(
name=type(logical).__name__,
terms=", ".join(logical)
) | 8a1dbef12e0dc7328d2ed9505f33dc869c6011fa | 684,388 |
def get_insert_size_list(sv_record, bam_file, ref_flank):
"""
Get a list of insert sizes over an SV.
:param sv_record: SV record.
:param bam_file: BAM file to extract reads from.
:param ref_flank: Number of bases upstream and downstream of the SV that should be considered. This value should
... | d7d3da3d97dd8ec30632161caf5bc0cc34c73fcf | 684,389 |
def get_expected_num_audio_channels(
ambisonics_type, ambisonics_order, head_locked_stereo):
""" Returns the expected number of ambisonic components for a given
ambisonic type and ambisonic order.
"""
head_locked_stereo_channels = 2 if head_locked_stereo == True else 0
if (ambisonics_type ==... | 5b55b1987935a4aede3901ee39717f91f584118c | 684,391 |
def data2str(data):
"""
Convert some data to a string.
An empty or None value is returned unchanged (helpful for testing), e.g.:
'57 75 6e 64 65 72 62 61 72 49 52' -> 'WunderbarIR'
'' -> ''
"""
if not data: return data
text = ''.join([chr(int(v, 16)) for v in data.split()])
return ... | e41f69fc43fe62efc4a39839ef3b9b7c4aa297a0 | 684,393 |
import re
def get_task_args_and_kwargs(file_path):
"""Get the args and kwargs for the task."""
text = ''
with open(file_path, 'r') as f:
for line in f:
text += line.strip() + ' '
reg = re.search('Task was called with args: (\(.*?\)) '
'kwargs: ({.*?})', text)
... | d27b170879b4612637c5669ed6e2700d56861d49 | 684,394 |
def get_lower_dm_limit(dm_trials, dm_min=None):
""" 'dm_min' is the minimum DM enforced by the user """
if dm_min is not None:
return dm_min
else:
return min(dm_trials) | 79f1663e459e971b5a229b1c2e3aea1f1ffeca2c | 684,395 |
def to_milliseconds(days):
"""
:return: the number of days expressed as milliseconds. e.g to_milliseconds(1) -> 86400
"""
return days * 24 * 60 * 60 * 1000 | 627e96a5aa9d554d7a531c4d1914514a7ed8ee6d | 684,396 |
import os
def path_relative(rel: str) -> str:
"""Converts path relative to this file to absolute path"""
this_dir = os.path.dirname(__file__)
return os.path.join(this_dir, rel) | 9415f62cd115c089c6ce804c6ef43640128cf006 | 684,397 |
import yaml
def gen_lookup(file):
""" Generating the lookup table between api-endpoints and elasticsearch
instances from the configuration of the lod-api.
lookup table is of the form:
{"/api/endpoint": "http://elasticsearchhost:port/index/doctype",
"/resource": "http://el... | a007a0be1c18b585b9ebf66b194e55458f764146 | 684,398 |
def get_global_host(config, name):
""" find global host in config with its name and return it """
for host in config['hosts']:
if host['name'] == name:
return host
return None | e77ac1e86f59240c85651100f979f08d1e63c1af | 684,399 |
from typing import Any
def default_tile_extras_provider(hyb: int, ch: int, z: int) -> Any:
"""
Returns None for extras for any given hyb/ch/z.
"""
return None | 7e7c77481c06e836a531406f18468fa0edad327b | 684,400 |
import subprocess
def run_prog (pargs):
"""
Runs executable program with arguments.
Returns status along with stdout and stderr
"""
ret = subprocess.run(pargs, stdout = subprocess.PIPE, stderr = subprocess.PIPE, check=False)
retc = ret.returncode
output = None
errors = None
if re... | 93751c8e9cecee123e07b1e068a5d9aef2066dea | 684,401 |
from typing import Dict
from typing import Any
def copa_preformat_fn(ex: Dict[str, Any]) -> Dict[str, Any]:
"""format for COPA tasks.
Args:
ex: Dictionary with one sample
Returns:
ex: Formatted dictionary
"""
premise, question = ex['premise'].decode(), ex['question'].decode()
input_prompt = f'{p... | 0f156d2efe6c6609a133fcb69073022ad2af735a | 684,402 |
def bfs(G, s, f):
"""
Breadth-first search
:param G: The graph object
:param s: The start node
:param f: The goal node
:return: The explored set
"""
explored, frontier = [], [s]
while frontier:
v = frontier.pop(0)
if v == f:
pass
else:
... | f63dc3aaa2c3f0d4ad09ddc1dd43acca29fe37d3 | 684,403 |
def vec_rotate(vec, direction):
"""direction: 'R' or 'L' """
if direction == "L":
# (1, 13) -> (-13, 1)
return (-vec[1], vec[0])
else:
# (-13, 1) -> (1, 13)
return (vec[1], -vec[0]) | 7289251e8be0e2b3aae76a0b60d538c4335a32ed | 684,404 |
import sys
def load_class(location):
""" Take a string of the form 'fedmsg.consumers.ircbot:IRCBotConsumer'
and return the IRCBotConsumer class.
"""
try:
mod_name, cls_name = location.strip().split(':')
except ValueError:
raise ImportError('Invalid import path.')
__import__(mo... | 40e11944150ba95cf2dcfb980eaf227a8274a8f7 | 684,405 |
import copy
def norm_rda_deficit(norm_rda_arr):
""" Returns a modified list of nutrient dicts in which value represents
a fraction of how much a given nutrient has been satisfied. A value of
0 represents full satisfaction, and 1 represents no satisfaction. """
r_nut = copy.deepcopy(norm_rda_arr)
... | dc0c06e92a97c281973d340dc6f0f541615344ee | 684,407 |
def add_dicts(*args):
"""
Combine dicts. If there are duplicate keys, raise an error.
"""
new = {}
for arg in args:
for key in arg:
if key in new:
raise ValueError("Duplicate key: %r" % key)
new[key] = arg[key]
return new | aba33e1b81ba4398f4a46672fc5086a6cc9cbcd2 | 684,408 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.