content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def dump_yaml_and_check_difference(obj, filename, sort_keys=False):
"""Dump object to a yaml file, and check if the file content is different
from the original.
Args:
obj (any): The python object to be dumped.
filename (str): YAML filename to dump the object to.
sort_keys (str); Sor... | 47a271a34b0a1774188a725eddf0d6698f76e04c | 3,643,324 |
from re import T
from typing import Optional
def get_data(
db: Redis[bytes],
store: StorageEngine,
source: Artefact[T],
carry_error: Optional[hash_t] = None,
do_resolve_link: bool = True,
) -> Result[T]:
"""Retrieve data corresponding to an artefact."""
stream = get_stream(db, store, sourc... | 1bb07e01ae151f985fcd30e8cca0da1b11213459 | 3,643,325 |
def record_edit(request, pk):
"""拜访记录修改"""
user = request.session.get('user_id')
record = get_object_or_404(Record, pk=pk, user=user, is_valid=True)
if request.method == 'POST':
form = RecordForm(data=request.POST, instance=record)
if form.is_valid():
form.save()
... | d2d610e53641962e913849b4b643f38898b72a3f | 3,643,326 |
def remove_body_footer(raw):
"""
Remove a specific body footer starting with the delimiter : -=-=-=-=-=-=-=-=-=-=-=-
"""
body = raw[MELUSINE_COLS[0]]
return body.replace(r'-=-=-=-=.*?$', '') | 60161b06fe80fd526f66c796657bd9a77cc1bfb9 | 3,643,327 |
def get_strategy_name():
"""Return strategy module name."""
return 'store_type' | bbf1ed9f43f492561ee5c595061f74bea0f5e464 | 3,643,328 |
def pyccel_to_sympy(expr, symbol_map, used_names):
"""
Convert a pyccel expression to a sympy expression saving any pyccel objects
converted to sympy symbols in a dictionary to allow the reverse conversion
to be carried out later
Parameters
----------
expr : PyccelAstNode
... | 1800a41d1d06fbbfd212b3b7b48ddc9f4ae07508 | 3,643,329 |
from pathlib import Path
def get_lockfile_path(repo_name: str) -> Path:
"""Get a lockfile to lock a git repo."""
if not _lockfile_path.is_dir():
_lockfile_path.mkdir()
return _lockfile_path / f"{repo_name}_lock_file.lock" | 5f043b6976921d487054d5c9171c91eb6def19ee | 3,643,330 |
def path_to_graph(hypernym_list, initialnoun):
"""Make a hypernym chain into a graph.
:param hypernym_list: list of hypernyms for a word as obtained from wordnet
:type hypernym_list: [str]
:param initialnoun: the initial noun (we need this to mark it as leaf in the tree)
:type initialnoun: str
... | e80f90490e6376403d511f37a4703a7b867d2738 | 3,643,331 |
def make_3d_grid():
"""Generate a 3d grid of evenly spaced points"""
return np.mgrid[0:21, 0:21, 0:5] | 0eccd9b2320ed28f0d08d40c9d59c22e77b607f4 | 3,643,332 |
def rho(flag, F, K, t, r, sigma):
"""Returns the Black rho of an option.
:param flag: 'c' or 'p' for call or put.
:type flag: str
:param F: underlying futures price
:type F: float
:param K: strike price
:type K: float
:param t: time to expiration in years
:type t: float
:pa... | 62bd0fdfe76319261c89bfa33b02b57fcdafb8df | 3,643,333 |
async def novel_series(id: int, endpoint: PixivEndpoints = Depends(request_client)):
"""
## Name: `novel_series`
> 获取小说系列的信息
---
### Required:
- ***int*** **`id`**
- Description: 小说系列ID
"""
return await endpoint.novel_series(id=id) | 94859a313c823d3fdcf055390473b116ea1229e0 | 3,643,334 |
def to_raw(
y: np.ndarray,
low: np.ndarray,
high: np.ndarray,
eps: float = 1e-4
) -> np.ndarray:
"""Scale the input y in [-1, 1] to [low, high]"""
# Warn the user if the arguments are out of bounds, this shouldn't happend.""""
if not (np.all(y >= -np.ones_like(y) - eps) and np.all(y <= np.o... | 61e916f9f46582fc6b9c135ac53fff3a3939d710 | 3,643,335 |
def etched_lines(image):
"""
Filters the given image to a representation that is similar to a drawing being preprocessed with an Adaptive Gaussian
Threshold
"""
block_size = 61
c = 41
blur = 7
max_value = 255
# image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
img_blur = cv2.Gauss... | 33858c8ee50cd6977f81cc64f55967ecd8849369 | 3,643,336 |
def get_last_position(fit, warmup=False):
"""Parse last position from fit object
Parameters
----------
fit : StanFit4Model
warmup : bool
If True, returns the last warmup position, when warmup has been done.
Otherwise function returns the first sample position.
Returns
-----... | 28ec10c4f90ac786053334f593ffd3ade27b1fc5 | 3,643,337 |
def find_fast_route(objective, init, alpha=1, threshold=1e-3, max_iters=1e3):
"""
Optimizes FastRoute objective using Newton’s method optimizer to
find a fast route between the starting point and finish point.
Arguments:
objective : an initialized FastRoute object with preset start and finis... | ab0d8364a7aab80a735b2b468a45abb5e30b396b | 3,643,338 |
def check_tx_success(result):
"""
Checks if function :meth:`UcanServer.write_can_msg_ex` successfully wrote all CAN message(s).
:param ReturnCode result: Error code of the function.
:return: True if CAN message(s) was(were) written successfully, otherwise False.
:rtype: bool
"""
return resu... | 815293aafa42b7323414e1cb96d6d150ef16bb48 | 3,643,341 |
from typing import Iterable
from typing import Optional
def cache_contains_keys(connection: 'Connection', cache_info: CacheInfo, keys: Iterable,
query_id: Optional[int] = None) -> 'APIResult':
"""
Returns a value indicating whether all given keys are present in cache.
:param conne... | 48fffa703d7cd120d0faa898e7e94355ec663a84 | 3,643,342 |
def discount_cumsum_trun(x, discount, length):
"""
compute discounted cumulative sums of vectors.
truncate x in length array
:param x:
vector x,
[x0,
x1,
x2,
x3,
x4]
:param length:
vector length,
[3,
2]
:return:
... | 589ac22b19705a7881f91cffe78bed5accafc661 | 3,643,343 |
def get_canonical(flop):
"""
Returns the canonical version of the given flop.
Canonical flops are sorted. The first suit is 'c' and, if applicable,
the second is 'd' and the third is 'h'.
Args:
flop (tuple): three pokertools.Card objects
Returns
A tuple of three pokertools.Car... | 4a797c27e8c32dff18412128d2823a1592c2468e | 3,643,344 |
import importlib
def _version(lib_name):
"""
Returns the version of a package.
If version cannot be determined returns "available"
"""
lib = importlib.import_module(lib_name)
if hasattr(lib, "__version__"):
return lib.__version__
else:
return "available" | cec49d2de66d2fc3a7ed3c89259711bdf40bbe8e | 3,643,346 |
def DeltaDeltaP(y, treatment, left_mask):
"""Absolute difference between ATEs of two groups."""
return np.abs(
ATE(y[left_mask], treatment[left_mask])
- ATE(y[~left_mask], treatment[~left_mask])
) | cd7816d2aa02cfb72dccf364cc73e07d596cc6ec | 3,643,347 |
def start(isdsAppliance, serverID='directoryserver', check_mode=False, force=False):
"""
Restart the specified appliance server
"""
if force is True or _check(isdsAppliance, serverID, action='start') is True:
if check_mode is True:
return isdsAppliance.create_return_object(changed=True... | b59941eafff24d9389f91edaa38de7b35eb48660 | 3,643,348 |
def get_dates_keyboard(dates):
"""
Метод получения клавиатуры дат
"""
buttons = []
for date in dates:
button = InlineKeyboardButton(
text=date['entry_date'],
callback_data=date_callback.new(date_str=date['entry_date'], entry_date=date['entry_date'])
)
... | 41a87c64e603d6b19921c3a960743d3d27f2e373 | 3,643,351 |
def merge_synset(wn, synsets, reason, lexfile, ssid=None, change_list=None):
"""Create a new synset merging all the facts from other synsets"""
pos = synsets[0].part_of_speech.value
if not ssid:
ssid = new_id(wn, pos, synsets[0].definitions[0].text)
ss = Synset(ssid, "in",
PartOf... | d1d7af2a83d6b7deb506fb69c7cbdb2770735f4f | 3,643,355 |
def clean_all(record):
""" A really messy function to make sure that the citeproc data
are indeed in the citeproc format. Basically a long list of if/...
conditions to catch all errors I have noticed.
"""
record = clean_fields(record)
for arrayed in ['ISSN']:
if arrayed in record:
... | 28ba59e808e88058c5745c444f1e58cd564c726d | 3,643,357 |
def _create_model() -> Model:
"""Setup code: Load a program minimally"""
model = Model(initial_program, [], load=False)
engine = ApproximateEngine(model, 1, geometric_mean)
model.set_engine(engine)
return model | 71fa7c000e6ed0cd8ad14bb0be3bb617337e7631 | 3,643,358 |
def candidate_elimination(trainingset):
"""Computes the version space containig all hypothesis
from H that are consistent with the examples in the training set"""
G = set()#set of maximally general h in H
S = set()#set of maximally specific h in H
G.add(("?","?","?","?","?","?"))
S.add(("0","0",... | b368cea3b058cc667c41725b0fa6a6b4a51f418b | 3,643,359 |
from pathlib import Path
def mkdir(path_str):
"""
Method to create a new directory or directories recursively.
"""
return Path(path_str).mkdir(parents=True, exist_ok=True) | 1621fd5f4d74b739de0b17933c1804faabf44a2f | 3,643,360 |
def get_image_with_projected_bbox3d(img, proj_bbox3d_pts=[], width=0, color=Color.White):
"""
Draw the outline of a 3D bbox on the image.
Input:
proj_bbox3d_pts: (8,2) array of projected vertices
"""
v = proj_bbox3d_pts
if proj_bbox3d_pts != []:
draw = ImageDraw.Draw(img)
for k in range(0,4):
... | 2ec900c055635adbc6619f8e786e52bd820c6930 | 3,643,361 |
def process_spectrogram_params(fs, nfft, frequency_range, window_start, datawin_size):
""" Helper function to create frequency vector and window indices
Arguments:
fs (float): sampling frequency in Hz -- required
nfft (int): length of signal to calculate fft on -- required
... | 0e8563051a5ee4b48f7e635126ed4e6639e47bdd | 3,643,362 |
from typing import Union
def Hellwig2022_to_XYZ(
specification: CAM_Specification_Hellwig2022,
XYZ_w: ArrayLike,
L_A: FloatingOrArrayLike,
Y_b: FloatingOrArrayLike,
surround: Union[
InductionFactors_CIECAM02, InductionFactors_Hellwig2022
] = VIEWING_CONDITIONS_HELLWIG2022["Average"],
... | ef5f05f32f6871eaa67bb554a23595cedf2a97b1 | 3,643,363 |
def build_exec_file_name(graph: str,
strt: str,
nagts: int,
exec_id: int,
soc_name: str = None):
"""Builds the execution file name of id `exec_id` for the given patrolling
scenario `{graph, nagts, strt}` .
A... | 143731bee19ad8e4b925f07d5449baff83994059 | 3,643,364 |
def set_ticks(ax, tick_locs, tick_labels=None, axis='y'):
"""Sets ticks at standard numerical locations"""
if tick_labels is None:
tick_labels = tick_locs
ax_transformer = AxTransformer()
ax_transformer.fit(ax, axis=axis)
getattr(ax, f'set_{axis}ticks')(ax_transformer.transform(tick_locs))
... | 690179bcb2d2ca4f3b1e5b8cb03f68627168b73a | 3,643,365 |
from typing import List
import re
def extract_discovery(value:str) -> List[dict]:
"""处理show discovery/show onu discovered得到的信息
Args:
value (str): show discovery/show onu discovered命令返回的字符串
Returns:
List[dict]: 包含字典的列表
"""
# ================================================... | 6107d194d10e6b7c1c6e33f7151214152e5bff7d | 3,643,366 |
def dict_to_networkx(data):
"""
Convert data into networkx graph
Args:
data: data in dictionary type
Returns: networkx graph
"""
data_checker(data)
G = nx.Graph(data)
return G | 0a3c670d3bad87bb18212dc6d2e47ac5a1ccc413 | 3,643,367 |
import urllib
def to_url_slug(string):
"""Transforms string into URL-safe slug."""
slug = urllib.parse.quote_plus(string)
return slug | 0976e3d1568f793fa946be9fa67b40cc82e6f4f5 | 3,643,368 |
def is_wrapping(wrapper):
"""Determines if the given callable is a wrapper for another callable"""
return hasattr(wrapper, __WRAPPED) | 16dcff38253424f6b93cee2a887aa7d91afd4f44 | 3,643,369 |
from conekt.models.relationships.sequence_go import SequenceGOAssociation
from typing import Sequence
def sequence_view(sequence_id):
"""
Get a sequence based on the ID and show the details for this sequence
:param sequence_id: ID of the sequence
"""
current_sequence = Sequence.query.get_or_404(... | c9493376b8df2b9dc7585d8b380e54ce4d20f473 | 3,643,370 |
def horner(n,c,x0):
"""
Parameters
----------
n : integer
degree of the polynomial.
c : float
coefficients of the polynomial.
x0 : float
where we are evaluating the polynomial.
Returns
-------
y : float
the value of the function evaluated at x0.... | adf3f3772d12d5bed0158045ad480cee8454cb5c | 3,643,371 |
import gzip
def _compression_safe_opener(fname):
"""Determine whether to use *open* or *gzip.open* to read
the input file, depending on whether or not the file is compressed.
"""
f = gzip.open(fname, "r")
try:
f.read(1)
opener = gzip.open
except IOError:
opener = open
... | 4c44da2ae15c63ccd6467e6e893a3c590c20a7e9 | 3,643,373 |
from typing import List
import json
def read_payload(payload: str) -> OneOf[Issue, List[FileReport]]:
"""Transform an eslint payload to a list of `FileReport` instances.
Args:
payload: The raw payload from eslint.
Returns:
A `OneOf` containing an `Issue` or a list of `FileReport` instanc... | 809e4db54cb8d4c737d9eea7f77f1a1846f24589 | 3,643,375 |
from typing import Iterable
from typing import Any
from typing import Iterator
import itertools
def prepend(
iterable: Iterable[Any],
value: Any,
*,
times: int = 1,
) -> Iterator[Any]:
"""Return an iterator with a specified value prepended.
Arguments:
iterable: the ite... | 659bc3616238f5e40865505c006c1369f20e33d3 | 3,643,377 |
from skimage.transform import warp
def apply_transform(transform, source, target,
fill_value=None, propagate_mask=False):
"""Applies the transformation ``transform`` to ``source``.
The output image will have the same shape as ``target``.
Args:
transform: A scikit-image ``Simi... | 97843939a6e03389d8c4741a04cea77ac7e1e0c4 | 3,643,378 |
def _with_extension(base: str, extension: str) -> str:
"""
Adds an extension to a base name
"""
if "sus" in base:
return f"{extension}{base}"
else:
return f"{base}{extension}" | 5a1253763808127f296c3bcb04c07562346dea2d | 3,643,379 |
def putin_rfid_no_order_api():
"""
无订单的情况下入库, 自动创建订单(类型为生产入库), 订单行入库
post req: withlock
{
lines: [{line_id:~, qty, location, lpn='', sku,
rfid_list[rfid1, rfid2, rfid3...],
rfid_details[{rfid1, weight, gross_weight, qty_inner}, {rfid2}, {rfid3}...}],
}...]
... | 6637fba766e86bc25dae733d7ddc102114e79e27 | 3,643,380 |
def GuessLanguage(filename):
""" Attempts to Guess Langauge of `filename`. Essentially, we do a
filename.rsplit('.', 1), and a lookup into a dictionary of extensions."""
try:
(_, extension) = filename.rsplit('.', 1)
except ValueError:
raise ValueError("Could not guess language as '%s' does not have an \... | 3cd1289ab3140256dfbeb3718f30a3ac3ffca6f2 | 3,643,381 |
import numpy
def extract_data_size(series, *names):
"""
Determines series data size from the first available property, which
provides direct values as list, tuple or NumPy array.
Args:
series: perrot.Series
Series from which to extract data size.
names: (str,)... | 39d503b359318d9dc118481baa7f99a43b926711 | 3,643,382 |
def uintToQuint (v, length=2):
""" Turn any integer into a proquint with fixed length """
assert 0 <= v < 2**(length*16)
return '-'.join (reversed ([u16ToQuint ((v>>(x*16))&0xffff) for x in range (length)])) | 96f707ed527e1063d055ab1b6d1f8a17308ed772 | 3,643,383 |
import hashlib
import base64
def alphanumeric_hash(s: str, size=5):
"""Short alphanumeric string derived from hash of given string"""
hash_object = hashlib.md5(s.encode('ascii'))
s = base64.b32encode(hash_object.digest())
result = s[:size].decode('ascii').lower()
return result | 915159aa2242eedfe8dcba682ae4bcf4fdebc3c4 | 3,643,384 |
def fake_execute_default_reply_handler(*ignore_args, **ignore_kwargs):
"""A reply handler for commands that haven't been added to the reply list.
Returns empty strings for stdout and stderr.
"""
return '', '' | e73bd970030c4f78aebf2913b1540fc1b370d906 | 3,643,385 |
from typing import List
from pathlib import Path
def require(section: str = "install") -> List[str]:
""" Requirements txt parser. """
require_txt = Path(".").parent / "requirements.txt"
if not Path(require_txt).is_file():
return []
requires = defaultdict(list) # type: Dict[str, List[str]]
... | efda45491798e5b7b66e0f2d6a4ac7b9fc3324d0 | 3,643,386 |
def string_in_list_of_dicts(key, search_value, list_of_dicts):
"""
Returns True if search_value is list of dictionaries at specified key.
Case insensitive and without leading or trailing whitespaces.
:return: True if found, else False
"""
for item in list_of_dicts:
if equals(item[key], s... | a761e3b44efc6e584c8f9045be307837daad49c4 | 3,643,388 |
import itertools
import pandas
def get_data(station_id, elements=None, update=True, as_dataframe=False):
"""Retrieves data for a given station.
Parameters
----------
station_id : str
Station ID to retrieve data for.
elements : ``None``, str, or list of str
If specified, limits th... | 7eaa0d152a8f76fa7bfc4109fb4e0a5c3d90e318 | 3,643,389 |
def Find_Peaks(profile, scale, **kwargs):
"""
Pulls out the peaks from a radial profile
Inputs:
profile : dictionary, contains intensity profile and pixel scale of
diffraction pattern
calibration : dictionary, contains camera parameters to scale data
... | 3d5cf4a5d559d54aa061d4abd9a02efb96c03d05 | 3,643,390 |
def empty_items(item_list, total):
"""
Returns a list of null objects. Useful when you want to always show n
results and you have a list of < n.
"""
list_length = len(item_list)
expected_total = int(total)
if list_length != expected_total:
return range(0, expected_total-list_length)
... | 12848fe61457b2d138a2fcd074fb6ec6d09cbaf5 | 3,643,391 |
import struct
def _read_string(fp):
"""Read the next sigproc-format string in the file.
Parameters
----------
fp : file
file object to read from.
Returns
-------
str
read value from the file
"""
strlen = struct.unpack("I", fp.read(struct.calcsize("I")))[0]
ret... | 346a65e6be15f593c91dde34cb45c53cb5731877 | 3,643,392 |
def add_optional_parameters(detail_json, detail, rating, rating_n, popularity, current_popularity, time_spent, detailFromGoogle={}):
"""
check for optional return parameters and add them to the result json
:param detail_json:
:param detail:
:param rating:
:param rating_n:
:param popularity:
... | 176fab2255f9302c945cb29ac5f9513da368a57e | 3,643,393 |
def build_get_string_with_null_request(
**kwargs # type: Any
):
# type: (...) -> HttpRequest
"""Get string dictionary value {"0": "foo", "1": null, "2": "foo2"}.
See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder
into your code flow.
:return: Retur... | 976b20770b74b4cf8504f673e66aec94fbf55c2b | 3,643,394 |
def get_db_url(db_host, db_name, db_user, db_pass):
"""
Helper function for creating the "pyodbc" connection string.
@see /etc/freetds.conf
@see http://docs.sqlalchemy.org/en/latest/dialects/mssql.html
@see https://code.google.com/p/pyodbc/wiki/ConnectionStrings
"""
params = parse.quote(
... | f0ed18ac321fcc9e93b038dc2f3905af52191c7b | 3,643,395 |
import torch
def boxes_iou3d_cpu(boxes_a, boxes_b, box_mode='wlh', rect=False, need_bev=False):
"""
Input (torch):
boxes_a: (N, 7) [x, y, z, h, w, l, ry], torch tensor with type float32
boxes_b: (M, 7) [x, y, z, h, w, l, ry], torch tensor with type float32
rect: True/False means boxes ... | e3b40e2c4c35a7f423739791cc9268ecd22cdf42 | 3,643,396 |
def make_attrstring(attr):
"""Returns an attribute string in the form key="val" """
attrstring = ' '.join(['%s="%s"' % (k, v) for k, v in attr.items()])
return '%s%s' % (' ' if attrstring != '' else '', attrstring) | fbaf2b763b4b1f4399c45c3a19698d0602f0b224 | 3,643,397 |
import requests
from bs4 import BeautifulSoup
from datetime import datetime
def depreciated_get_paste(paste_tup):
"""
This takes a tuple consisting of href from a paste link and a name that identify a pastebin paste.
It scrapes the page for the pastes content.
:param paste_tup: (string, string)
:... | 6f3620354827998eade57b989c503be4f093b6d8 | 3,643,399 |
from typing import List
from typing import Dict
def delete_nodes_list(
nodes: List[str],
credentials: HTTPBasicCredentials = Depends(
check_credentials
), # pylint: disable=unused-argument
) -> Dict[str, str]:
"""Deletes a list of nodes (that are discoverables with lldp) to the db.
Exple... | 1b7d4e25e67f1a0d2a5eec23b12b1ca87242a066 | 3,643,400 |
def index():
"""
Application Home page
"""
module_name = settings.modules[c].get("name_nice")
response.title = module_name
return {"module_name": module_name,
} | 527aa4b19eff87bb5c6fde6c0578ced5e876f59b | 3,643,401 |
def is_CW_in_extension(G):
"""
Returns True if G is 'CW in expansion', otherwise it returns False.
G: directed graph of type 'networkx.DiGraph'
EXAMPLE
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
G=nx.DiGraph()
e_list = [(0,1),(0,2),(0,3),(0,4),(1,2),(1,3),(1,4)]
G.add_edges_fro... | 3a1af65be274d23de16cdc15253185a0bbeda0ec | 3,643,403 |
from typing import Callable
from typing import Iterable
from typing import List
def get_index_where(condition: Callable[..., bool], iterable: Iterable) -> List[int]:
"""Return index values where `condition` is `True`."""
return [idx for idx, item in enumerate(iterable) if condition(item)] | 6f99086730dfc2ab1f87df90632bc637fc6f2b93 | 3,643,404 |
def geom_crossbar(mapping=None, *, data=None, stat=None, position=None, show_legend=None, sampling=None, tooltips=None,
fatten=None,
**other_args):
"""
Display bars with horizontal median line.
Parameters
----------
mapping : `FeatureSpec`
Set of aestheti... | 27f1faf1dea99b033e9ac5ab4dbc52ea2865934c | 3,643,405 |
from typing import Union
def chess_to_coordinate(pos: str) -> Union[Coordinate, Move]:
"""
Arguments:
"""
if len(pos) == 2:
return Coordinate(int(pos[1]) - 1, file_dict[pos[0]])
else:
if len(pos) == 5:
if pos[4] == 'n':
return Move(Coordinate(... | f55e8c4d349419a5477d5fc3c5390d133b89cdf7 | 3,643,406 |
def get_db_session():
"""
Get the db session from g.
If not exist, create a session and return.
:return:
"""
session = get_g_cache('_flaskz_db_session')
if session is None:
session = DBSession()
set_g_cache('_flaskz_db_session', session)
return session | 1254a99c3c1dd3fe71f1a9099b9937df46754c33 | 3,643,407 |
def make_tril_scale(
loc=None,
scale_tril=None,
scale_diag=None,
scale_identity_multiplier=None,
shape_hint=None,
validate_args=False,
assert_positive=False,
name=None):
"""Creates a LinOp representing a lower triangular matrix.
Args:
loc: Floating-point `Tensor`. This is used f... | 137a0ac84e7b2fab71f1630ae1bd1b0b24fe8879 | 3,643,408 |
def remove_punctuation(word):
"""Remove all punctuation from the word (unicode). Note that the `translate`
method is used, and we assume unicode inputs. The str method has a different
`translate` method, so if you end up working with strings, you may want to
revisit this method.
"""
return word.... | 46476b6e4480a2f067c2370fd378778b452a1a3e | 3,643,409 |
def prepare_filter_weights_slice_conv_2d(weights):
"""Change dimension order of 2d filter weights to the one used in fdeep"""
assert len(weights.shape) == 4
return np.moveaxis(weights, [0, 1, 2, 3], [1, 2, 0, 3]).flatten() | 2b6ca65d68d4407ac0a7744efe01a90dc5423870 | 3,643,410 |
async def hello(request):
"""Hello page containing sarafan node metadata.
`version` contains sarafan node version.
`content_service_id` — contains service_id of content node
:param request:
:return:
"""
return web.json_response(await request.app['sarafan'].hello()) | 4a8b82a525082a03009d087a18042574e19c1796 | 3,643,411 |
import yaml
def load_capabilities(
base: str = "docassemble.ALWeaver", minimum_version="1.5", include_playground=False
):
"""
Load and return a dictionary containing all advertised capabilities matching
the specified minimum version, and optionally include capabilities that were
advertised from a ... | 3bb12fdbf4fc4340a042f0685a4917a7b1c1ed85 | 3,643,413 |
def build_graph(
config,
train_input_fn, test_input_fn, model_preprocess_fn, model):
"""Builds the training graph.
Args:
config: Training configuration.
train_input_fn: Callable returning the training data as a nest of tensors.
test_input_fn: Callable returning the test data as a nest of tensor... | 4eff7555b2383db0870d5e63467e2d68a3336ece | 3,643,414 |
import functools
import traceback
import time
def execli_deco():
""" This is a decorating function to excecute a client side Earth Engine
function and retry as many times as needed.
Parameters can be set by modifing module's variables `_execli_trace`,
`_execli_times` and `_execli_wait`
:Example:
... | c245cd30f372e6d00895f42ba26936f2fb92c257 | 3,643,415 |
import uuid
def lstm_with_backend_selection(inputs, init_h, init_c, kernel,
recurrent_kernel, bias, mask, time_major,
go_backwards, sequence_lengths,
zero_output_for_mask):
"""Call the LSTM with optimized backend kernel ... | 4c45709265de5385399a7b9bff0aeb4e9a4d7b17 | 3,643,416 |
def _build_stack_from_3d(recipe, input_folder, fov=0, nb_r=1, nb_c=1):
"""Load and stack 3-d tensors.
Parameters
----------
recipe : dict
Map the images according to their field of view, their round,
their channel and their spatial dimensions. Only contain the keys
'fov', 'r', '... | 6cb4e567324cb3404d6e373b3f9a00d3ccdd51ef | 3,643,417 |
def view_menu(request):
"""Admin user view all the reservations."""
menus = Menu.objects.all()
return render(request,
"super/view_menu.html",
{'menus': menus}) | 7b8244a315f2da0794a80f71cf73517e81f614e0 | 3,643,418 |
def _get_hdfs_dirs_by_date(physical_table_name, date):
"""
根据日期获取指定日期的hdfs上数据目录列表
:param physical_table_name: 物理表名称
:param date: 日期
:return: hdfs上的数据目录列表
"""
return [f"{physical_table_name}/{date[0:4]}/{date[4:6]}/{date[6:8]}/{hour}" for hour in DAY_HOURS] | 6581f81ebcf9051ccf97ade02fc80eeba46e0e78 | 3,643,419 |
import json
def indeed_jobs(request, category_id):
"""
Load Indeed jobs via ajax.
"""
if request.is_ajax() and request.method == 'POST':
per_page = 10
page = 1
html = []
if category_id == '0':
all_jobs = IndeedJob.objects.all()
else:
al... | 12cf21f9ecad672e78715ef9687ad2e69d5ea963 | 3,643,420 |
def iinsertion_sort(arr, order=ASCENDING):
"""Iterative implementation of insertion sort.
:param arr: input list
:param order: sorting order i.e "asc" or "desc"
:return: list sorted in the order defined
"""
operator = SORTING_OPERATORS.get(order.lower(), GREATER_THAN)
for i in range(1, len(... | 8698fbb500bfad3cb2e6964112d46ef8151c1e89 | 3,643,421 |
def actor_files_paths():
"""
Returns the file paths that are bundled with the actor. (Path to the content of the actor's file directory).
"""
return current_actor().actor_files_paths | 2ec9505eceb2da78aee668ff044e565374aa3a1c | 3,643,422 |
import struct
def parse_table(data: bytes, fields: list) -> dict:
"""Return a Python dictionary created from the bytes *data* of
an ISIS cube table (presumably extracted via read_table_data()),
and described by the *fields* list and *records*.
Please be aware that this does not perform masking of the... | 3727a37d619c77c6789e1d11479ecfd67b814766 | 3,643,423 |
import scipy
def gridtilts(shape, thismask, slit_cen, coeff2, func2d, spec_order, spat_order, pad_spec=30, pad_spat = 5, method='interp'):
"""
Parameters
----------
tilt_fit_dict: dict
Tilt fit dictioary produced by fit_tilts
Returns
-------
piximg: ndarray, float
Image in... | 55dd6ddd065e4f4bfefdc30bef27dc6e6541190b | 3,643,424 |
import functools
def exp_t(u, t):
"""Compute exp_t for `u`."""
def _internal_exp_t(u, t):
return tf.nn.relu(1.0 + (1.0 - t) * u) ** (1.0 / (1.0 - t))
return tf.cond(
tf.math.equal(t, 1.0), lambda: tf.math.exp(u),
functools.partial(_internal_exp_t, u, t)) | 27fe729ea55bc8933d6ccd41c5ae96657b4426ad | 3,643,425 |
def max_matching(G, method="ilp"):
"""Return a largest matching in *G*.
Parameters
----------
G : NetworkX graph
An undirected graph.
method: string
The method to use for finding the maximum matching. Use
'ilp' for integer linear program or 'bf' for brute force.
Def... | 34407865678e46d7d042fa94852b66ebc22787d6 | 3,643,426 |
def hasEdgeFlux(source, edgeDistance=1):
"""hasEdgeFlux
Determine whether or not a source has flux within `edgeDistance`
of the edge.
Parameters
----------
source : `scarlet.Component`
The source to check for edge flux
edgeDistance : int
The distance from the edge of the im... | 2fd924c20cb89b3728ef3a24f92b89eb0b136fe5 | 3,643,427 |
def biswas_robustness(data_scikit, data_mm):
"""
summary stats on consensus peaks
"""
CV = find_CV(th=0.0001, ca=0.5, sd=1)
CV_th001 = find_CV(th=0.001, ca=0.5, sd=1)
CV_th01 = find_CV(th=0.01, ca=0.5, sd=1)
CV_th00001 = find_CV(th=0.00001, ca=0.5, sd=1)
CV_sd15 = find_CV(th=0.0001, ca=... | 70ecee0baa60a5b06c785dd172bc9d0719840903 | 3,643,428 |
def get_click_offset(df):
"""
df[session_key] return a set of session_key
df[session_key].nunique() return the size of session_key set (int)
df.groupby(session_key).size() return the size of each session_id
df.groupby(session_key).size().cumsum() retunn cumulative sum
"""
offsets = np.zeros(... | c8caed25899f71549a9333e64452f8eed9cf1029 | 3,643,429 |
def delete_enrichment():
"""
Controller to delete all existing GO enrichments
:return: Redirect to admin main screen
"""
CoexpressionCluster.delete_enrichment()
flash('Successfully removed GO enrichment for co-expression clusters', 'success')
return redirect(url_for('admin.controls.index')... | 9cface0783929581f3e6076f43a461ef815c0d2b | 3,643,430 |
from typing import Sequence
def argmax(sequence: Sequence) -> int:
"""Find the argmax of a sequence."""
return max(range(len(sequence)), key=lambda i: sequence[i]) | 58cc1d0e952a7f15ff3fca721f43c4c658c41de1 | 3,643,432 |
def read_data_from_device(device, location):
""" Reads text data from device and returns it as output
Args:
location ('str'): Path to the text file
Raises:
FileNotFoundError: File Does not Exist
Returns:
Data ('str'): Text data read from the device
"""... | f6895d25f9f9e68ec33bb2d8f693999a7e3a2812 | 3,643,433 |
from typing import Dict
def postman_parser(postman_info: dict,
environment_vars: Dict = None) -> APITest:
"""
Get a parser collection, in JSON input format, and parser it
:param postman_info: JSON parsed info from Postman
:type postman_info: dict
:param environment_vars: varia... | 1e3c351c3b7ee37d438edeb9e64e70d67b45e1b9 | 3,643,435 |
def allOPT2 (routes, dists, maxtime=float("inf")):
"""
A simpler way to make the 2-OPT optimization on all
the provided routes.
:param routes: The routes to optimize.
:param dists: The matrix of distances.
:param maxtime: The maximum time the optimization can go on.
:return: The optimised ... | ec7a2e337371cf806b7fa32661185b7400e774a0 | 3,643,436 |
def getScoreByName(name):
"""
This function will search for the name and
will, if found, return the scores
"""
for idx, val in enumerate(names):
if val == name:
return scores[idx] | 77074b360c2e35ae30053e1b00b3270166f27ada | 3,643,437 |
def count_dict(dict_):
"""
Count how many levels the dict has
"""
if not isinstance(dict_, dict):
raise Dict_Exception("dict_ must be a dict")
return max(count_dict(v) if isinstance(v, dict) else 0 for v in dict_.values()) + 1 | b608469d67f050b366cb5b97a7d686bdf8347616 | 3,643,438 |
def __draw_tick_labels(scales, chart_height, chart_width):
"""Draws the numbers in both axes."""
axis_values = [0, 0.25, 0.5, 0.75, 1]
axis_df = pd.DataFrame({"main_axis_values": axis_values, "aux_axis_position": 0})
x_tick_labels = (
alt.Chart(axis_df)
.mark_text(
yOffset... | 85107e3255953af667e43374927299a5a55b6809 | 3,643,439 |
def thread_profile(D,P,inset,internal=True,base_pad=0.1):
"""ISO thread profile"""
H = P*np.sqrt(3)/2
Dm = D - 2*5*H/8
Dp = D - 2*3*H/8
if internal:
return np.array([
(-P/2,D/2+H/8+base_pad+inset),
(-P/2,D/2+H/8+inset),
(-P/8,Dm/2+inset),
(P/8,... | abea6e4f234f4176a385b3abc2ca6f1de0c93a1b | 3,643,442 |
def get_service(hass, config, discovery_info=None):
"""Get the HipChat notification service."""
return HipchatNotificationService(
config[CONF_TOKEN],
config[CONF_ROOM],
config[CONF_COLOR],
config[CONF_NOTIFY],
config[CONF_FORMAT],
config[CONF_HOST]) | 1d6b7e5d53084bd91de307a162c4710aac84be24 | 3,643,444 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.