content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import logging
def get_string_from_comment(comment):
"""Extract a string from a comment formatted like this:
'/u/<username> string' or
'/u/<username>
string' """
lines = comment.body.split("\n")
try:
if lines[0] != "/u/check_em_out":
assert lines[0].startswith("/u... | 6446243bd31040999e257cf4fe05414894777b4d | 672,909 |
def Nu_dist(Re_outtube_dist, Pr_coolwater_dist):
"""
Calculates the Nusselt criterion of coolwater.
Parameters
----------
Re_outtube_dist : float
The Reynold criterion, [dimensionless]
Pr_coolwater_dist : float
The Prandtl criterion, [dimensionless]
Returns
-------
Nu... | 5ab8684977a83902d6dd386432310a00c8cbdd9f | 672,912 |
def get_rb_blob_attribute(blobdict, attr):
"""Get Attribute `attr` from dict `blobdict`
Parameters
----------
blobdict : dict
Blob Description Dictionary
attr : string
Attribute key
Returns
-------
ret : Attribute Value
"""
try:
value = blobdict['BLOB'][... | 3f3768057cde529c467774da93cc33bb83571a78 | 672,916 |
def bxor(*args):
"""Return the bitwise xor of all arguments."""
res = 0
for arg in args:
res ^= arg
return res | 8e2c7f93888ac2bbebc0bdd4e280db39305b88d7 | 672,917 |
def b_count(pattern):
"""
Count the number of B's that occur in a site pattern
Input:
pattern --- a site pattern
Output:
num_b --- the number of B's in the site pattern
"""
num_b = 0
for char in pattern:
if char == "B":
num_b += 1
return num_b | 99f32f92057b663f59bef3f7431477d6821c766c | 672,920 |
import torch
def adaptive_add_fusion(z: torch.Tensor, p: torch.Tensor):
"""Adds a point cloud to a noise tensor that can have a smaller dimension.
The noise tensor `z` with `dim_z` channels will be added to the first `dim_z`
channels of the point cloud `p`.
Args:
z: Reference point cloud of ... | cb49c8b1607da108d2a4ea8b682bcfc5b5730007 | 672,922 |
import logging
def Aggregate_median_SABV_AGE(rnaseq):
"""Compute median TPM by gene+tissue+sex+age."""
logging.info("=== Aggregate_median_SABV_AGE:")
logging.info(f"Aggregate_median_SABV_AGE IN: nrows = {rnaseq.shape[0]}, cols: {str(rnaseq.columns.tolist())}")
rnaseq = rnaseq[["ENSG", "SMTSD", "SEX", "AGE", "... | ef41a3929c5c052c434151dce4fae8fd85da027b | 672,924 |
def try_mine(block):
"""Updates the nonce and sees if it's valid.
"""
block.nonce += 1
return block.is_valid() | 8b3d5842c36783d17b24250a08578c1cfeca8432 | 672,925 |
def v0_is_perfect_square(number):
"""Return True if given number is the square of an integer."""
return int(number**0.5)**2 == number | 0e2950429a84d622c7a386e9f54e1289689b9367 | 672,926 |
def unpack_and_split_nodes(data, path):
"""Unpack a list of results
Args:
data: A dictionary containing the results
path: A list of fields indicating the fields to select.
final one should be a list of nodes
Returns:
issues: A list of dicts; each dict is the data for some of
the results
... | 1f8063ba52350a8408fcfe6a3300d7c88d4b248e | 672,928 |
def evaluate(function, param1, param2):
"""
Returns <function>, called with <param1> and <param2>
"""
return function(param1, param2) | 9c2310936049dce931e94058634e94dca4585517 | 672,934 |
import torch
def _linear_interpolation_utilities(v_norm, v0_src, size_src, v0_dst, size_dst, size_z):
"""
Computes utility values for linear interpolation at points v.
The points are given as normalized offsets in the source interval
(v0_src, v0_src + size_src), more precisely:
v = v0_src + v_... | 7e664fec2d3198c8124131541f2d07658a9f1f83 | 672,935 |
def is_truthy(data):
"""
Returns True if the data is a truthy value, False otherwise.
"""
string = str(data).lower()
return string in ['true', '1', 'f'] | a5e6b743f11e7b18c6f249ef8a9f4f764ed9c927 | 672,938 |
def get_toolchain_dir(toolchain_dir_output):
"""Find the toolchain directory."""
prefix = 'vs_path = '
for line in toolchain_dir_output.splitlines():
if line.startswith(prefix):
return line[len(prefix):].strip('"')
raise Exception('Unable to find toolchain dir in output:\n%s' % (
too... | 43017a4afc8ec5a5318129f57f465f8a66bca2cd | 672,941 |
def cal_accuracy_on_2(sample_label_prob_dict_list, test_label_list):
"""
:param
sample_label_prob_dict_list:
[
{1: 0.2, 2:0.15, 3:0.2, ..., 9:0.1}
{1: 0.2, 2:0.15, 3:0.2, ..., 9:0.1}
...
]
test_label_list:
[1,2,5... | 38f39920e0bfbc159bfe697cecfccac4e349c346 | 672,944 |
def fileSizeStrToInt(size_str):
"""Converts file size given in *iB format to bytes integer"""
unit_dict = {"KiB": (2 ** 10), "MiB": (2 ** 20), "GiB": (2 ** 30), "TiB": (2 ** 40)}
try:
num = float(size_str[:-3])
unit = size_str[-3:]
return int(num * unit_dict[unit])
except Except... | ccdbebef08297a47d276d43d75a96d2f78daf760 | 672,948 |
def reciprocate_currency(dataframe, reciprocal_list):
"""
Reciprocate the values of columns for currencies subordinate to USD
:param dataframe: dataframe to reciprocate values
:param reciprocal_list: list of currencies to reciprocate values for
:return: dataframe with reciprocated values
"""
regex_reciprocal =... | 83773361c84dc7340ab39d3df627acb9a53a369d | 672,949 |
import socket
import struct
def unpack_ip_addr(addr):
"""Given a six-octet BACnet address, return an IP address tuple."""
if isinstance(addr, bytearray):
addr = bytes(addr)
return (socket.inet_ntoa(addr[0:4]), struct.unpack('!H', addr[4:6])[0]) | eb92776c1854782c2f7b6094627eab52148e5244 | 672,952 |
def get_provenance(
software_name="x", software_version="y", schema_version="1", environment=None,
parameters=None):
"""
Utility function to return a provenance document for testing.
"""
document = {
"schema_version": schema_version,
"software": {
"name": soft... | 9883da0d6905c757c9a12531968255b8eafe9968 | 672,954 |
import pickle
def load_metrics(filestr:str):
"""
Load metric dict from filestr
Args:
filestr (str): strig to save dict to
Return:
metrics (dict): loaded metrics
"""
# pickle load
with open(filestr, 'rb') as f:
metrics = pickle.load(f)
return metrics | 199a30d7391e81a78ba7f4567de35e8c4f0a13a5 | 672,956 |
def leap_year(year: int) -> bool:
"""Report if a year is leap.
:param year: int - year.
:return: bool
"""
return (year % 4 == 0 and not year % 100 == 0) or year % 400 == 0 | 6c4c63c92431e363b82f25df6d4c2910fe8ea6e4 | 672,958 |
def check_pkt_filter_report_hash(mode):
"""Check if Flow Director hash match reporting mode is valid
There are three modes for the reporting mode.
* none
* match (default)
* always
"""
if mode in ['none', 'match', 'always']:
return True
else:
return False | c044df224e49ea5ac8ae77df91554aa64503dded | 672,960 |
def causal_estimation(cpi, rate):
"""
Calculate all the data to make a causal estimation of the exchange rate,
according to the PPP theory: ex_rate_USD_UYU ~= a * CPI_uy / CPI_us
The constant "a" is calculated with the expanding mean of the previous
values. The function makes no predictions into the... | 3b98fb79e06995c1876183e5dbf6bdc151ca1e76 | 672,962 |
def volume_prisma(area_dasar: float, tinggi: float) -> float:
"""
kalkulasi dari volume prisma
referensi
https://en.wikipedia.org/wiki/Prism_(geometry)
>>> volume_prisma(10, 2)
20.0
>>> volume_prisma(11, 1)
11.0
"""
return float(area_dasar * tinggi) | f792ca88398346d1e673a97c903421349cb7d889 | 672,964 |
def getSeqPos(ref_profile, seq):
"""
Get the start and end position when mapped to refSeq.
Sequence to feed to the func should be afa format
(e.x. one from mothurAligner).
Parameters:
-----------
ref_profile : list
a gap profile, 0 is gap and 1 is real base pair.
seq : str
... | 5161a6a3eee701e4c299f3c0c50682282c8dafc3 | 672,967 |
import struct
def parse_arrayindexandlength(number):
"""
Returns an array index and length tuple for the given number.
"""
# Could just use >> and & for this, but since we have to be more
# careful with LinkIdAndLinkedBehavior anyway, since that one's
# weirder, we may as well just use struct ... | 47a30bec6f2cb934e0d5bc0abeab930d9cb504ff | 672,968 |
def prepare_special_error_type(source, target, error_type, charset=None):
"""
Remove all non-matching words from both the source and the target string.
Args:
source (str): Source string.
target (str): Target string.
error_type (str): One of: 'copy_chars', 'uppercase', 'digits',
... | 108f60e04d8044e7bc36708d78ef7301b680655b | 672,970 |
def self(client):
"""Requests information on role of the current user."""
return client.get_role_self() | 88342e26c847928467907440fb0f8e70ff93be90 | 672,972 |
def no_c(my_string):
"""
removes all instances of 'c' & 'C' from string
"""
new_str = ""
for i in range(len(my_string)):
if my_string[i] != 'c' and my_string[i] != 'C':
new_str += my_string[i]
return (new_str) | af49292fe65ae0e905e7d808ac9b7196dc5a0c8b | 672,973 |
import math
def abs(x):
"""Return the absolute value of x"""
return math.fabs(x) | 6dd0df1fc8e288245a520a39bcbe91096371c30b | 672,975 |
def jupyter_get_variable(name, magic_command_instance):
"""
Retrieves the value of a local variable in a notebook.
@param name variable name
@param magic_command_instance instance of `Magics <http://ipython.readthedocs.io/en/stable/api/
... | e8c717540c0100f4d1104decda7c3c39d91db09d | 672,976 |
def get_tx_input_amount(tx):
"""Returns the the total input amount"""
inp_amount = 0
for inp in tx.inputs:
inp_amount += inp.witness_utxo.value
return inp_amount | fc882f709e4f80caaa5d6d7cd01298eed277edf4 | 672,977 |
def xor(string, byte):
"""Exclusive-ors each character in a string with the given byte."""
results = []
for ch in string:
results.append(chr(ord(ch) ^ byte))
return ''.join(results) | b4d93995d64065e1752263f0e1600f97f0a4a3fd | 672,979 |
def CheckChangeHasTestField(input_api, output_api):
"""Requires that the changelist have a TEST= field."""
if input_api.change.TEST:
return []
else:
return [output_api.PresubmitNotifyResult(
'Changelist should have a TEST= field. TEST=none is allowed.')] | 451b10a4ad6cc61f03b253d8183f813386410828 | 672,981 |
def shorter_name(key):
"""Return a shorter name for an id.
Does this by only taking the last part of the URI,
after the last / and the last #. Also replaces - and . with _.
Parameters
----------
key: str
Some URI
Returns
-------
key_short: str
A shortened, but more... | b185c52efb6642d5c691bf8947a4e0b210fb7be8 | 672,983 |
def _catmull_rom_weighting_function(x: float) -> float:
"""Catmull-Rom filter's weighting function.
For more information about the Catmull-Rom filter, see
`Cubic Filters <https://legacy.imagemagick.org/Usage/filter/#cubics>`_.
Args:
x (float): distance to source pixel.
Returns:
fl... | 7b4213289af57a782962b437087dd094ff112890 | 672,984 |
def convert_neg(arr, size):
"""
Convert any negative indices into their positive equivalent.
This only works for a 1D array.
Parameters
----------
arr : ndarray
Array having negative indices converted.
size : int
Dimension of the array.
Returns
-------
ndarray
... | 9040cb636210071015449784ff7db20b3a53f849 | 672,990 |
def gf_neg(f, p, K):
"""Negate a polynomial in `GF(p)[x]`. """
return [ -coeff % p for coeff in f ] | 3a83fa82bf7fc12ec63bca3c7a45c958d0faed72 | 672,998 |
import torch
def tvr_loss(y):
"""Calculate Total Variation Regularization Loss of Generated Image"""
loss = torch.sum(torch.abs(y[:, :, :, :-1] - y[:, :, :, 1:])) + torch.sum(
torch.abs(y[:, :, :-1, :] - y[:, :, 1:, :])
)
return loss | 44f2a577b5d8d9e4fa2d8f8ccbede8c28a276bb3 | 673,002 |
def transform_to_factory_kwargs(data, original_kwargs=None, prefix=""):
"""
Transforms factory data into the correct kwargs to pass to the factory
Args:
data (dict): dictionary of data from the factory_data file
original_kwargs (dict): kwargs passed into the factory function from code
... | 819be74ae16cf56e758e61834365295184fc98b8 | 673,003 |
def can_user_perform(user, account_id, action):
"""
Utility method for checking arbitrary actions are applicable to a specific account for a user.
:param user: A dict object representing user
:param account: A string representing an AWS account to validate permission for.
:param action: A string rep... | 400c485a7040010a7b172e2229dde03ebccd0ef6 | 673,007 |
def run_single_identify(run_identify): # pylint: disable=redefined-outer-name
"""
Fixture to run the identification step for a given sample file which should
contain only one cluster, and return the result for that cluster.
"""
def inner(sample_name):
res = run_identify(sample_name)
... | fde8b415d48d6aa212e9e4b7f908c258c3c4a9a9 | 673,009 |
import re
def parseNeighbors(urls):
"""Parses a urls pair string into urls pair."""
parts = re.split(r'\s+', urls)
return parts[0], parts[1] | 17728ef54d10ebe4239661f26f30ed8fc10fde57 | 673,012 |
def join_lines(strings):
"""
Stack strings horizontally.
This doesn't keep lines aligned unless the preceding lines have the same length.
:param strings: Strings to stack
:return: String consisting of the horizontally stacked input
"""
liness = [string.splitlines() for string in strings]
... | 072b8cab3bc989053581c52d41b610f88ed8921d | 673,013 |
import re
def wrap_line(line, breakable_regex, line_cont,
base_indent=0, max_width=80, rewrap=False):
"""Wrap the given line within the given width.
This function is going to be exported to be used by template writers in
Jinja as a filter.
Parameters
----------
line
Th... | 70e076188dbea29b7d8e5e8dea7a31897ad3e9a6 | 673,014 |
def makehist(vals, incr=1, normalize=0):
"""Makes a histogram for the given vals and returns a dict.
Incr is how much each item counts for
If normalize is true, then the sum of return values is normalize.
"""
ret = {}
sum = 0
for v in vals:
if v not in ret:
ret[v] = 0
... | 2501396bf9bdee4bc59f70411b961b75881b4a36 | 673,015 |
def gravity(z, g0, r0):
"""Relates Earth gravity field magnitude with the geometric height.
Parameters
----------
z: ~astropy.units.Quantity
Geometric height.
g0: ~astropy.units.Quantity
Gravity value at sea level.
r0: ~astropy.units.Quantity
Planet/Natural satellite rad... | 3386b5be505fb3759c691c3ea8e166af41ecd151 | 673,017 |
def first(lst):
"""Return the first element of the given list - otherwise return None"""
return lst[0] if lst else None | 5e92dadbc0a0bf6a7cc390ca80b45e93d1e3c82c | 673,025 |
import functools
def single_or_multiple(f):
"""
Method wrapper, converts first positional argument to tuple: tuples/lists
are passed on as tuples, other objects are turned into tuple singleton.
Return values should match the length of the argument list, and are unpacked
if the original argument was not a tu... | 82313931130538ea1f78eb4caf14663cc6cb36eb | 673,027 |
from typing import Union
import requests
def validate_request_success(resp: Union[requests.Response, str]):
"""
Validate the response from the webhook request
"""
return not isinstance(resp, str) and resp.status_code in [200, 201] | 13fa27f2c71780f7f33a62ff767eccae45722b91 | 673,028 |
from typing import List
from typing import Optional
import re
def filter_list(arr: List[str], pattern: Optional[str] = None) -> List[str]:
"""Filter a list of strings with given pattern
```python
>> arr = ['crossentropy', 'binarycrossentropy', 'softmax', 'mae',]
>> filter_list(arr, ".*entropy*")
>... | 22b644fa7cd1c35151b4edfd3f196aa561434c5f | 673,033 |
def prepend_zeros(length, string):
"""
Prepend zeros to the string until the desired length is reached
:param length: the length that the string should have
:param string: the string that we should appends 0's to
:return: A string with zeros appended
"""
return "{}{}".format("0" * (length - ... | f5c56fe7f1dc4c6a65f3c1f93b1257fbe57dea5a | 673,036 |
def plus_haut(points):
""" Trouve le point (xb, yb) le plus en haut à droite, en temps linéaire."""
n = len(points)
xb, yb = points[0]
for j in range(1, n):
xj, yj = points[j]
if (yb < yj) or (yb == yj and xb < xj):
xb, yb = xj, yj
return xb, yb | 4476f1a357c2296642f6a37c922c7f4e7b4c25ba | 673,040 |
import string
def build_link_exp_decay(adj, weight, words_map, words, from_index, to_index, max_dist, stopwords, links_to_stopwords=True, self_links=False):
"""
Builds a link from a given word in the graph to another word at a defined index.
The farther the other word, the smaller the edge between them.
... | 6a810ba96740987751b77cf61acc589e401fef60 | 673,041 |
def try_decode(obj: bytes, encoding="utf-8"):
"""
Try decode given bytes with encoding (default utf-8)
:return: Decoded bytes to string if succeeded, else object itself
"""
try:
rc = obj.decode(encoding=encoding)
except AttributeError:
rc = obj
return rc.strip() | 77919da9204f1574262a95df818c970102977489 | 673,042 |
def apply_parent_validation(clazz, error_prefix=None):
"""
Decorator to automatically invoke parent class validation before applying
custom validation rules. Usage::
class Child(Parent):
@apply_parent_validation(Child, error_prefix="From Child: ")
def validate(data):
... | a8cec4db9bb826024726f8a98ee2ee84bdd28182 | 673,047 |
def mean(mylist):
"""
function to take the mean of a list
Parameters
----------
mylist : list
list of numbers to take a mean
Returns
-------
mean_list : float
The mean of the list.
Examples
--------
>>> mean([1,2,3,4,5,6,7])
4.0
"""
... | 5b3c0796e752c2ac384ea00f97ff14ab7d3e7f2d | 673,052 |
from functools import reduce
def reduce_get(cfg: dict, key: str):
"""
gets value from dictionary based on flat 'key' provided
e.g. instead of dict1["alpha"]["beta"]["gamma"], we do: key = "alpha.beta.gamma"
:param cfg: config dictionary
:param key: flat key e.g. "alpha.beta.gamma"
:return: val... | d2741121bb38abda70e2a733d2afc3d8906e268c | 673,056 |
def traverse(node, order="pre-order", include_terminal=True, acc=None):
"""
Parameters
----------
node: NonTerminal or Terminal
order: str, default "pre-order"
include_terminal: bool, default True
acc: list[T] or None, default None
T -> NonTerminal or Terminal
Returns
------... | 450865dc005be90b28f77378412e3515917077cf | 673,059 |
def safe_open(path):
""" If the file can be opened, returns a file handle; otherwise None."""
try:
return open(path, 'rb')
except (IOError, PermissionError, FileNotFoundError):
return None | 61d5439e438e38f87bfc3936b630d4883bad5454 | 673,062 |
def getAllReachable1Step(original_nodes):
"""
return all node, value pairs reachable from any of the pairs in the original nodes in a single step
:param original_nodes: a set of node, value, complete_path pairs from which we check what they can reach in 1 step
:return: a set of node, value pairs that ca... | 6d6939efbf669b05470c2c27035c90e49650f149 | 673,064 |
def select_zmws(zmws, min_requested_bases):
"""
>>> select_zmws([], 0)
([], 0)
>>> select_zmws([], 10)
([], 0)
>>> select_zmws([('zmw/1', 1), ('zmw/2', 2), ('zmw/3', 5), ('zmw/4', 7), ('zmw/5', 10), ('zmw/6', 15)], 10)
(['zmw/1', 'zmw/2', 'zmw/3', 'zmw/4'], 15)
>>> select_zmws([('zmw/1',... | 106cfba09496a25e2376e92e5747a4e3d13f9f2f | 673,068 |
def preprocess(sample):
"""Preprocess a single sample."""
return sample | b34a59ce5ac2f372940d9ea47fdf8870e63aef06 | 673,069 |
def point_on_rectangle(rect, point, border=False):
"""
Return the point on which ``point`` can be projecten on the
rectangle. ``border = True`` will make sure the point is bound to
the border of the reactangle. Otherwise, if the point is in the
rectangle, it's okay.
>>> point_on_rectangle(Rect... | 761d3cd918b353e18195f8817292b9c2c9ec4f40 | 673,070 |
def for_teuthology(f):
"""
Decorator that adds an "is_for_teuthology" attribute to the wrapped function
"""
f.is_for_teuthology = True
return f | a4fe41f957efe8cf2f5e3bf41428e004f136bfa8 | 673,072 |
import pickle
def loadpfile(path: str) -> list:
"""
Loads whatever object is contained in the pickle file.
Args:
path: file path
Returns:
some object
"""
return pickle.load(open(path, 'rb')) | 7a40b5ebe276ffa8efbaa54f642b3a69ac109d15 | 673,075 |
def single_number(nums):
"""
Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Args:
nums: list[int]
Returns:
int
"... | 96b9146bf93a3704bec638ac5be2c8bbf956387b | 673,077 |
def bin_search(query, data):
""" Query is a coordinate interval. Binary search for the query in sorted data,
which is a list of coordinates. Finishes when an overlapping value of query and
data exists and returns the index in data. """
i = int(round(len(data)/2)) # binary search prep
lower, upper = 0, len(data)... | 355a270b1fb4b2fea75ec699c081b2a3fa064aab | 673,078 |
def _nsec_to_usec_round(nsec: int) -> int:
"""Round nanoseconds to microseconds"""
return (nsec + 500) // 10 ** 3 | c273bea9a4c04478ea3b391682a33fbbbdf5b731 | 673,081 |
def _ord(i):
"""Converts a 1-char byte string to int.
This function is used for python2 and python3 compatibility
that can also handle an integer input.
Args:
i: The 1-char byte string to convert to an int.
Returns:
The byte string value as int or i if the input was already an
... | 5635e7e6dcf58017b0a8170d3afb78a474eb90ad | 673,085 |
def _compute_temp_terminus(temp, temp_grad, ref_hgt,
terminus_hgt, temp_anomaly=0):
"""Computes the (monthly) mean temperature at the glacier terminus,
following section 2.1.2 of Marzeion et. al., 2012. The input temperature
is scaled by the given temperature gradient and the elev... | 155379cdaf8e5aedc5769da20330d752179ffe11 | 673,086 |
def featuretype_filter(feature, featuretype):
"""
Only passes features with the specified *featuretype*
"""
if feature[2] == featuretype:
return True
return False | ccd56ed0f5273af8bfa0365a93d54f8457b13b0b | 673,089 |
def as_latex(ordinal):
"""
Convert the Ordinal object to a LaTeX string.
"""
if isinstance(ordinal, int):
return str(ordinal)
term = r"\omega"
if ordinal.exponent != 1:
term += f"^{{{as_latex(ordinal.exponent)}}}"
if ordinal.copies != 1:
term += rf"\cdot{as_latex(ord... | 6df43f0a1250879f56900bb2d70e2edece3628e3 | 673,090 |
import re
def filter_comments(string):
"""Remove from `string` any Python-style comments ('#' to end of line)."""
comment = re.compile(r'(^|[^\\])#.*')
string = re.sub(comment, '', string)
return string | b4a50d09061b05f8582625a3a0602acb27a97605 | 673,091 |
def apply_ants_transform_to_point(transform, point):
"""
Apply transform to a point
ANTsR function: `applyAntsrTransformToPoint`
Arguments
---------
point : list/tuple
point to which the transform will be applied
Returns
-------
tuple : transformed point
... | 87ebb8c562c3b3c8ed297efac652a452f708f3e3 | 673,095 |
import string
def remove_punctuation(input_string):
"""Remove the punctuations in input string.
Parameters
----------
input_string : string
String to remove punctuations.
Returns
-------
output_string : string
String without punctuations.
"""
out_st... | 61e0e1a0e7921aaa84b7db3f582b43a382fdab18 | 673,097 |
def MigrateUSBPDSpec(spec):
"""Migrate spec from old schema to newest schema.
Args:
spec: An object satisfies USB_PD_SPEC_SCHEMA.
Returns:
An object satisfies USB_PD_SPEC_SCHEMA_V3.
"""
if isinstance(spec, int):
return {
'port': spec
}
if isinstance(spec, (list, tuple)):
return... | 1491f5d956d6ce9fa833322995b49166e2508691 | 673,099 |
def series_circuit_UA(*args):
"""
Calculates the total U*A-value for a series circuit of two or more U*A
values.
Parameters:
-----------
UA : float, int, np.ndarray
U*A value (heat conductivity) in [W/K] for each part of the series
circuit. If given as np.ndarray, all arrays hav... | 354ca1ca4f5f5e706d1c07618896d5a73c2853b9 | 673,102 |
def mesh_dual(mesh, cls=None):
"""Construct the dual of a mesh.
Parameters
----------
mesh : :class:`compas.datastructures.Mesh`
A mesh object.
cls : Type[:class:`compas.datastructures.Mesh`], optional
The type of the dual mesh.
Defaults to the type of the provided mesh obje... | e9ff14953137fe3e8685cdd9d6aab33e96fd5320 | 673,106 |
import requests
import json
def site_catalog(site):
"""
Returns a dictionary of CWMS data paths for a particular site
Arguments:
site -- cwms site name, example TDDO
Returns:
json.loads(r.text) -- dictionary of available site data
"""
url = r'http:... | 229c56cd5d472125695d4a91c95f5966736ea72e | 673,110 |
def split_node_lists(num_jobs, total_node_list=None, ppn=24):
"""
Parse node list and processor list from nodefile contents
Args:
num_jobs (int): number of sub jobs
total_node_list (list of str): the node list of the whole large job
ppn (int): number of procesors per node
Retur... | 9ec3f14b1eedcd8d741be2b38f93791968268c39 | 673,111 |
def undo_keypoint_normalisation(normalised_keypoints, img_wh):
"""
Converts normalised keypoints from [-1, 1] space to pixel space i.e. [0, img_wh]
"""
keypoints = (normalised_keypoints + 1) * (img_wh/2.0)
return keypoints | fc7760b4e1b3318ea73812bdc88b9fb7e87be358 | 673,115 |
def output_aws_credentials(awscreds, awsaccount):
"""
Format the credentials as a string containing the commands to define the ENV variables
"""
aws_access_key_id = awscreds["data"]["access_key"]
aws_secret_access_key = awscreds["data"]["secret_key"]
shellenv_access = "export AWS_ACCESS_KEY_ID=%... | c09c4a26ac9b91c6d2de863c3f37ddca21d21375 | 673,118 |
def get_phase_refr_index(wlen):
"""Get the phase refractive index for ice as a function of wavelength.
See: https://wiki.icecube.wisc.edu/index.php/Refractive_index_of_ice#Numerical_values_for_ice
or eqn 3 in https://arxiv.org/abs/hep-ex/0008001v1
Parameters
----------
wlen
Wavelength ... | 1c8a6000f7c8f9900ed495ae29998bf7e0b656e8 | 673,121 |
from pathlib import Path
def get_github_api_token(tok):
"""
Fetch github personal access token (PAT) for gist api request using POST
Parameters
----------
tok : str
PAT if passed as string, else None and will be fetched
"""
if not tok:
tok_path = Path.home() / ".jupyter_to_... | cbe35a5ef3e5db5bd6538fe30b906eb47946b51f | 673,122 |
def squeeze_axes(shape, axes, skip='XY'):
"""Return shape and axes with single-dimensional entries removed.
Remove unused dimensions unless their axes are listed in 'skip'.
>>> squeeze_axes((5, 1, 2, 1, 1), 'TZYXC')
((5, 2, 1), 'TYX')
"""
if len(shape) != len(axes):
raise ValueError("... | ca359ee31ecf3000d9afc7afd1ebbf779ce528a3 | 673,124 |
def read_padding(fp, size, divisor=2):
"""
Read padding bytes for the given byte size.
:param fp: file-like object
:param divisor: divisor of the byte alignment
:return: read byte size
"""
remainder = size % divisor
if remainder:
return fp.read(divisor - remainder)
return b'... | fdb1e87123125cc3b0e9d1b60b5b7d112bd56235 | 673,125 |
def extractDetails(remoteException):
"""Extract the details of an xml-rpc exception error message"""
try:
details = remoteException.faultString or remoteException.message
details = details.split(":", 2)[-1].replace("'>", "").lstrip()
except AttributeError:
details = str(remoteExcepti... | 5cc9fd0ece9e702843a710a29d03288b61c40cfd | 673,129 |
def fileopen(fun):
""" Open read-only filehandle if first argument is string
This function can be used to decorate functions that expect a filehandle as
the first argument. If the first argument is a string, it is assumed to be
the path to the input file, and the file is opened in read mode.
Args:... | bbe8e4260d88a8ffe05fd98f82f54bedc8bcb99f | 673,130 |
def preprocess_baseline2(segment_df, rush_hour):
"""
Preprocess the segment data considering the weather and the rush hour
Algorithm:
Preprocess segment_df to add a new column of rush hour
split the dataframe with groupby(segment_start, segment_end, weather, rush_hour)
Define the new dataframe
... | b3a3a4ed4096b6c2424023d2adad2fb2a176d71a | 673,131 |
def str_remove(string, index, end_index=None):
"""Remove a substring from an existing string at a certain from-to index range."""
end_index = end_index or (index + 1)
return "%s%s" % (string[:index], string[end_index:]) | b9e2913835bbad96520f20eccead1d40a89b8039 | 673,133 |
def m_coef(h_septum):
"""
Calculates the specific coefficient for calculation the heigth ligth layer of liquid equation.
Parameters
----------
h_septum : float
The heigth of drain septum, [m]
Returns
-------
m_coef : float
The specific coefficient for this equation [dimen... | efc247919fa737bfefb889f2641787a68db89e93 | 673,134 |
def get(conn, uri, access_token=None):
"""
HTTP GET request with an optional authorization header with the access_token
"""
if access_token:
headers = {'authorization': '%s %s' % (access_token['token_type'], access_token['access_token'])}
else:
headers = {}
conn.request('GET', ur... | 3cf381d355652c6d984442e035cba45a8879658c | 673,136 |
def all_true(iterable):
""" Helper that returns true if the iterable is not empty and all its elements evaluate to true. """
items = list(iterable)
return all(items) if items else False | 4a6344abb72393c31883908627529aa6434f44cf | 673,139 |
import unicodedata
import string
import re
def preprocess_names(name, output_sep=' ', firstname_output_letters=1):
"""
Function that outputs a person's name in the format
<last_name><separator><firstname letter(s)> (all lowercase)
>>> preprocess_names("Samuel Eto'o")
'etoo s'
>>> pre... | 8ee4e3a487ef6e1603f8822a14354db621336f76 | 673,140 |
def get_domain_from_fqdn(fqdn):
""" Returns domain name from a fully-qualified domain name
(removes left-most period-delimited value)
"""
if "." in fqdn:
split = fqdn.split(".")
del split[0]
return ".".join(split)
else:
return None | 2a2bd0c67af39dc1949cab1f51fce4593e43d992 | 673,142 |
def GetPartitionsByType(partitions, typename):
"""Given a partition table and type returns the partitions of the type.
Partitions are sorted in num order.
Args:
partitions: List of partitions to search in
typename: The type of partitions to select
Returns:
A list of partitions of the type
"""
... | 58dd5b960f5332fca31a92de9f9a546a550c47ea | 673,144 |
def is_admin(user):
"""
:param user:
:return True, (str): if user is admin
:return False, (str): is user is not admin
"""
if 'isAdmin' in user and user['isAdmin'] is True:
return True, None
return False, 'user is not authorized' | 3bc491d333d59f70c3fe1f1561c4a25c6dbdb54f | 673,149 |
from typing import List
from typing import Any
import collections
def _create_ngrams(tokens: List[Any], n: int) -> collections.Counter:
"""Creates ngrams from the given list of tokens.
Args:
tokens: A list of tokens from which ngrams are created.
n: Number of tokens to use, e.g. 2 for bigrams.
Returns... | 759da5a3179a3805ff84437aff7d52f620bb3bfc | 673,154 |
def split_group(name):
"""Split item name containing ``'/'`` into tuple of group/subname.
Examples:
- an input of ``'foo/bar'`` results in ``('foo', 'bar')``
- an input of ``'foo/bar/baz'`` results in ``('foo/bar', 'baz')``
"""
return tuple(reversed([x[::-1] for x in name[::-1].split("/", 1)]... | 99433ba2fe04bed360c204952b5394c4d22d6162 | 673,155 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.