content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def replace(ID1,ID2, sensor, starttime=None, project=None):
""" Replace incorrect Sensor data with a neighbour station
It needs:
ID1 ... ID of beacon with broken sensor
ID2 ... ID of neighbour beacon
sensor ... broken sensor
starttime ... time before the sen... | bafd20aca943930d43a4d8e303d9e8867267eb10 | 75,628 |
def matching_upd_j(weights_j, global_weights, sigma_inv_j, global_sigmas,
prior_mean_norm, prior_inv_sigma, popularity_counts, gamma, J):
"""
Computes cost [Equation 8] and solves the linear assignment problem
using hungarian algo
:param weights_j: Jth network weights
:type weight... | 21f4e9a671fba7b3ae8566af63ffe93304b441bc | 75,629 |
def exc(sv, dm, xc_code, **kvargs):
"""
Computes the exchange-correlation energy for a given density matrix
Args:
sv : (System Variables), this must have arrays of coordinates and species, etc
xc_code : is a string must comply with pySCF's convention PZ
"LDA,PZ"
"0.8*LDA+0.2*B88,... | 87f315a980e310c8f2454b31d6640b4c57f1329d | 75,630 |
import io
def read_decimal2(buffer: io.BytesIO, scale: int, offset: int = None) -> float:
"""Retrieve 2 byte (signed float) value from buffer"""
if offset:
buffer.seek(offset)
return float(int.from_bytes(buffer.read(2), byteorder="big", signed=True)) / scale | 3f1a852f837addf77b888cea8795d51c5de799bd | 75,631 |
def request_update(request, article_id):
"""
Processes request from editor to have an entry updated, sends email to registered article owner with update request.
article_id is pk of the article to be updated
"""
article = get_object_or_404(Article, pk=article_id)
transactional_emails.send_updat... | 88d4f53e2b499871342855e8953653a8cb7fdca9 | 75,632 |
def update_name(name, mapping):
""" Update the street name using the mapping dictionary. """
for target_name in mapping:
if name.find(target_name) != -1:
a = name[:name.find(target_name)]
b = mapping[target_name]
c = name[name.find(target_name)+len(target_name):]
... | 8046fc9ef83f262251fac1a3e540a607d7ed39b9 | 75,633 |
import uuid
import re
def create_crontab(title: str = "", text: str = "", interval: str = "") -> str:
"""Parses and interval and creates the notification interval"""
cron = get_crontab()
command = f'osascript -e \'display notification "{text}" with title "{title}"\''
comment = f"mac-os-notifier-id: {... | 070b5c6e72071ab46569534a20b9ca245c419fb4 | 75,634 |
def graph_to_matrix(graph, order=None, weight=None, matrix="adjacency"):
"""
Converts a NetworkX graph into an adjacency matrix.
:param graph: a NetworkX graph
:type graph: NetworkX graphh
:param order: a list or ordered nodes in the NetworkX graph
:type order: Node list
:param weight: re... | 21aaea949f337dc7c980a33c8d1af40802524fb6 | 75,635 |
def index_to_alphabet(input_index: int) -> str:
"""Method to convert integer to A1 notation.
:type input_index: int
:param idx: Cell index to convert.
:rtype: str
:returns: A1 notation of the cell.
"""
try:
assert input_index <= SHEETS_MAX_COLUMN_NUMBER
except AssertionError:
... | ed5e9757a7688d6522f5f601110abc4f857dc150 | 75,636 |
def calcRelURL(toURL, fromURL):
"""
Calculates a relative URL.
"""
fromURL = urlparse(fromURL)
toURL = urlparse(toURL)
if not fromURL.scheme == toURL.scheme: return urlunparse(toURL)
if not fromURL.netloc == toURL.netloc: return urlunparse(toURL)
fromPath = fromURL.path.split("/")
... | d4b29ad85ebbb79384095947d780ce53a032eca1 | 75,637 |
from typing import AsyncGenerator
async def ctx_with_heater_shaker(
mock_hardware: mock.AsyncMock,
mock_module_controller: mock.MagicMock,
enable_heater_shaker_python_api: AsyncGenerator[None, None],
) -> ProtocolContext:
"""Context fixture with a mock heater-shaker."""
mock_module_controller.mode... | a9f957c321e8241c0942945734ff2a1faf6f30ea | 75,638 |
def test_pay_peer(node_factory, bitcoind):
"""If we have a direct channel to the destination we should use that.
This is complicated a bit by not having sufficient capacity, but the
channel_hints can help us there.
l1 -> l2
| ^
v /
l3
"""
l1, l2, l3 = node_factory.get_nodes(3... | 3c4ac0cd0dc9b4cf0ffef47923eb98c4b6f2f435 | 75,639 |
from typing import Any
import textwrap
def get_webdriver() -> Any:
"""get_webdriver() detects an available webdriver and returns it.
:raises ImportError: of Selenium
"""
import selenium.webdriver # pylint: disable=import-error,import-outside-toplevel
logger.info('Trying to open Chrome via WebD... | 64a4f4460f02d03e8bbbda0304ca57d076562cef | 75,640 |
def get_current_user():
"""Returns the current user."""
return users.get_current_user() | 1a84842e290b51d69d265afe10fc921aab8c0b90 | 75,641 |
from typing import Any
def dict_cls(d: dict, cls: Any) -> Any:
"""
Create a dataclass from a dictionary.
"""
field_names = set(f.name for f in fields(cls))
filtered_dict = {k: v for k, v in d.items() if k in field_names}
return cls(**filtered_dict) | de6268c14d6b8d0c4d7b11e8ec8c6e9c96c76eab | 75,642 |
def padding_training_data(x_image, y_label, y_edge, target_height, target_width):
"""Each image has different size, so I need to pad it with zeros to make sure each image has the same size.
Then I can perform random crop, rotation and other augmentation on per batch instead of per image
"""
x_im_pad,... | eda3da6d5a2f126375b7b820e2566a216966f338 | 75,643 |
def eigsy(ctx, A, eigvals_only = False, overwrite_a = False):
"""
This routine solves the (ordinary) eigenvalue problem for a real symmetric
square matrix A. Given A, an orthogonal matrix Q is calculated which
diagonalizes A:
Q' A Q = diag(E) and Q Q' = Q' Q = 1
... | cee3d69518594f61f6088c49d1a4f816f1a7e2ad | 75,644 |
import re
def annotation_version(repo, tag_avail):
"""Generates the string used in Git tag annotations."""
match = re.match("^(.*)-build([0-9]+)$", tag_avail[repo.git()]["build_tag"])
if match is None:
return "%s version %s." % (repo.git(), tag_avail[repo.git()]["build_tag"])
else:
re... | 484eada27b698c2d7a9236d7b86ea6c53050e1e8 | 75,645 |
import math
def _scale_absolute_gap(gap, scale):
"""Convert an absolute gap to a relative gap with the
given scaling factor."""
assert scale > 0
if not math.isinf(gap):
return gap / scale
else:
return gap | 29c1b03e53c66bf7728066ff3503118a266acd3d | 75,646 |
def validate_flow_array(flow, error_string: str = None) -> nd:
"""Checks flow array for validity, ensures the flow is returned with dtype ``float32``
:param flow: Flow array to be checked, should be a numpy array of shape :math:`(H, W, 2)` containing floats
:param error_string: Optional string to be added ... | 1d0421420256afe63aed6f8d90ff20c195a6865a | 75,647 |
def cubic_trajectory_planning(q0, qf, qd0, qdf, m = 100):
"""
Point to Point Cubic Trajectory Planning
...
Parameters
---
q0 : Initial Position (Dof x 1)
qf : Final Position (Dof x 1)
qd0 : Initial Velocity (Dof x 1)
qf0 : Final Velocity (Dof x 1)
m(Optional) : Discrete Time ... | 47fdd736b0a420eeb30caa55396e1ebe0b37ab50 | 75,650 |
def getANSIfgarray_for_ANSIcolor(ANSIcolor):
"""Return array of color codes to be used in composing an SGR escape
sequence. Using array form lets us compose multiple color updates without
putting out additional escapes"""
# We are using "256 color mode" which is available in xterm but not
# necessar... | f8379270fe857d571a5804c9c381ecd37687ac1d | 75,651 |
def get_chooser_data(*args):
"""
get_chooser_data(chooser_caption, n) -> PyObject *
Get the text corresponding to the index N in the chooser data. Use -1
to get the header.
@param chooser_caption (C++: const char *)
@param n (C++: int)
"""
return _ida_kernwin.get_chooser_data(*args) | ded8f78ab035d3dd48e3baa253e368a351627021 | 75,652 |
def twisted_post(url, data=None, **kwargs):
"""
:param url: url to post
:param data: type str, dict like urlencoded
:param kwargs: timeout
:return: Deferred
"""
kwargs.setdefault("method", "POST")
kwargs.setdefault("headers", {"Content-Type": "application/x-www-form-urlencoded"})
kwa... | eacd1d0ef29788107d1e213be6af8dcab3d768c0 | 75,653 |
def create_charset(mime_encoding):
"""Create an appropriate email charset for the given encoding.
Valid options are 'base64' for Base64 encoding, 'qp' for
Quoted-Printable, and 'none' for no encoding, in which case mails will
be sent as 7bit if the content is all ASCII, or 8bit otherwise.
"""
c... | 8628153945530186e4209758dc062e878d3c4f80 | 75,654 |
def tokenize(text):
"""
this function tokenizes text at a very high speed
:param str text: text to be tokenized
:rtype: list[str]
"""
words = WORD.findall(text)
return words | 505924ce8da3e4308d583516ed728c1859e658a9 | 75,656 |
def TStr_PutFExt(*args):
"""
TStr_PutFExt(TStr FNm, TStr FExt) -> TStr
Parameters:
FNm: TStr const &
FExt: TStr const &
"""
return _snap.TStr_PutFExt(*args) | 561e0598199f41602aa02b2424c3515e6c34a1a4 | 75,657 |
def ckr(capsys):
"""Fixture - add an arg named ckr to your test function to automatically get one passed to you."""
return CheckerWrapper(capsys) | 98010429f363245adba9e4a8111eb761148ae561 | 75,659 |
def formatMD(md: str) -> str:
""" Convert Markdown to HTML """
return markdown2.markdown(md, extras=["tables"]) | 1c5d965de6dd3c2d00d78b0853d5a98e1700d862 | 75,660 |
def discretized_mix_logistic_loss(x, l, sum_all=True):
""" log-likelihood for mixture of discretized logistics, assumes the data has been rescaled to [-1,1] interval """
xs = int_shape(
x) # true image (i.e. labels) to regress to, e.g. (B,32,32,3)
ls = int_shape(l) # predicted distribution, e.g. (... | cd651052b7a7e60b118a8ddc5bcc59f833f1de72 | 75,661 |
def _transferred_similarity_loss(reconstructions,
source_images,
weight=1.0,
method='mse',
max_diff=0.4,
name='similarity'):
"""Computes a loss encouragi... | d7e2c6695c1d041a693d3541a5c80dc5c22ee416 | 75,662 |
def generate_episode_by_epsilon_greeedy_policy(simulator, q_func, epsilon):
"""
Generate episodes according to epsilon greedy policy on q_func
"""
state = simulator.reset()
done = False
state_action_pairs = []
while not done:
action = epsilon_greedy_sample(q_func, simulator, epsilon... | 565ab002b98ff9f0bbeb1b718a021f0c89478e89 | 75,663 |
def opkg_lock() -> bool:
"""Returns True if opkg lock is taken. It can be taken by any other process. It doesn't have to be updater.
"""
return _check_exclusive_lock(const.OPKG_LOCK, False) | a4e4c792031fcacf2a3ff63e3bb0b40706f9bbd3 | 75,664 |
import re
def GetTestSubsystemForChange(build_root, change):
"""Get a list of subsystem that a given |change| affects.
If subsystem is specified in the commit message, use that. Otherwise, look in
appropriate COMMIT-QUEUE.ini. If subsystem is not specified anywhere,
'subsystem:default' will be used.
Based... | f7c950e28fc4dd387d724b1693bd786b1bd83d24 | 75,665 |
def run_local(c, param):
"""Run the pipe defined in current directory with parameters"""
spec = get_spec()
return run_spec(c, spec, param) | 1851af8d1b632e83487855d6f4dab22b2b1f0894 | 75,666 |
def rgb2lab(rgb):
"""RGB to lab color space conversion.
Parameters
----------
rgb : array_like
The image in RGB format, in a 3- or 4-D array of shape
``(.., ..,[ ..,] 3)``.
Returns
-------
out : ndarray
The image in Lab format, in a 3- or 4-D array of shape
... | aa66b9ff48704de0869220d7bcf8397770bde350 | 75,667 |
def encode_int(value):
"""Encode an integer type."""
return varint.encode_unsigned(value) | ceb089aa404e40f3c14944896b220aada30db0d1 | 75,668 |
def fit1d_dinput(
dlines=None, dconstraints=None, dconstants=None, dprepare=None,
data=None, lamb=None, mask=None,
domain=None, pos=None, subset=None,
update_domain=None,
same_spectrum=None, nspect=None, same_spectrum_dlamb=None,
focus=None, valid_fraction=None, valid_nsigma=None, focus_half_wid... | 420668a0d8a0c1766a29aa030c8e9783feba570c | 75,669 |
def yolo_label_format(size, box):
"""
Rule to convert anchors to YOLO label format
Expects the box to have (xmin, ymin, xmax, ymax)
:param size: Height and width of the image as a list
:param box: the four corners of the bounding box as a list
:return: YOLO style labels
"""
dw = 1. /... | c958f75ffe3de8462ed25c5eb27bcaa21d52c46c | 75,670 |
def remove(name, **kwargs):
"""
Remove a given security token
Variables:
name => Name of the token to remove
Arguments:
None
Data Block:
None
Result example:
{
"success": true
}
"""
uname = kwargs['user']['uname']
user = STORAGE.user.get(uname, as_ob... | a5da76e19d6bab41273e5a13f7155b2cbe03d8e7 | 75,671 |
def split_vtrace_pg_loss(target_logits, baselines, rewards, trajectories):
"""Computes the split v-trace policy gradient loss.
We compute the policy loss (and therefore update, via autodiff) separately for
the action_type, delay, and arguments. Each of these component losses are
weighted equally.
"""
loss ... | fa77e4f8585ed8e1ced9e3eb886fd49d1052a619 | 75,672 |
def change_tweet_open_status(tweet_id):
"""
Removes an open tweet
PARAMETERS
------------
:param tweet_id: int
posted tweet's tweet id
RETURNS
------------
:return: boolean
True if successful, False otherwise
"""
try:
fdb.child('open_tweets').child(twee... | 76a5d57fda250a2ec40f2da8f200398b04ccb95d | 75,673 |
def upload_dir(app, filename):
""" Returns the upload path for applications.
The end result will be something like:
"uploads/applications/Firefox/icons/firefox.png"
"""
path = ('applications/' + app.name + '/icons/' + filename)
# Note: if the file already exist in the same path, django will... | e188c6c11733e0b88313c65b6be67c8db2fd69a9 | 75,674 |
def calc_K_PT_i_d_t(pv_type, pv_setup, Theta_A_d_t, I_s_i_d_t):
"""太陽電池アレイの温度補正係数 (5)
Args:
pv_type(str): 太陽電池アレイの種類
pv_setup(str): 太陽電池アレイ設置方式
Theta_A_d_t(ndarray): 日付dの時刻tにおける外気温度(℃)
I_s_i_d_t(ndarray): 日付dの時刻tにおける太陽電池アレイiの設置面の単位面積当たりの日射量(W/m2)
Returns:
ndarray: 日付dの時刻tにおける... | 3d87c8b8a0b2eb4a5eafef83c5ce33b9058eb1e1 | 75,675 |
def position_to_class(labels, lateral_partition):
""" Used with hierarchical CNN experiments.
Converts a list of 2D positions into a list of classes, given a lateral partition. Of course,
this assumes the 2D area is a square, and each resulting class will be a sub-square with
side = lateral_partition. I... | cc03a04c28d4f0be457fccbe6dcbd8b1c0cd2fd4 | 75,677 |
def identify_interference(df, sn_ratio_min=10.0, area_min=2000.0):
""" Identify interference in MRM data
Note:
Operates under the following assumptions:
* Interference will dominate transition ratio
* Interference has greater intensity than general noise
Args:
df (p... | 0cf0b485f10e7ce97ab2479a0721e4b683409d4b | 75,678 |
def loop_is_stuck(base_obs1, base_obs2, acme_obs1, acme_obs2, a1, a2):
"""Detect if observations and actions are stuck."""
# If first time step.
if acme_obs1 is None or acme_obs2 is None or a1 is None or a2 is None:
return False, False, False, False
act_stuck = np.all(np.equal(a1, a2))
base_obs_stuck = Tr... | 536315e7ffd8c6bdcf8548e0b4a4b062086b561b | 75,680 |
import itertools
def get_elements_by_attr(xml_node, attribute, value):
"""helper function for xml trees when using minidom"""
def recur_get_element_by_attr(xml_node, attribute, value):
if xml_node.attributes:
test_list = xml_node.attributes.keys()
if attribute in test_list:
... | 8ea494665393cc6c885ad4f611dbf0c3302617b2 | 75,681 |
def calc_assists(data):
"""
Calculate the total traditional and weighted assists for all
players, grouped by player id.
Author: Rasmus Säfvenberg
Parameters
----------
data : pandas.DataFrame
A data frame as retrieved by weighted.get_data()
Returns
-------
weighted... | d01c18e04949eaabbde88aa1d793bcecff47ed03 | 75,682 |
import typing
def function_hstack(data_and_metadata_like_list: typing.Sequence[_DataAndMetadataLike]) -> DataAndMetadata.DataAndMetadata:
"""Stack multiple data_and_metadatas along axis 1.
hstack((a, b, c))
Function is called by passing a tuple of the list of source items, which matches the
form of ... | 55e161f125e053a1528ffefec202150f8ab9b49c | 75,683 |
def run_trials_sync(
benchdir,
benches,
z3time: float,
time: float,
trials: int,
cores: int,
verbose: bool,
logfile,
) -> dict[int, dict]:
"""
Run trials of the given benchmarks and return a dictionary of profiling information.
"""
runs = {}
for i in range(trials):
... | c17d8005ca1d382c3e870248d3336baafacfd0cf | 75,684 |
def is_instance_id(instance):
""" Return True if the user input is an instance ID instead of a name """
if instance[:2] == 'i-':
return True
return False | f4389c340b21c6b5e0f29babe49c556bd4b4c120 | 75,685 |
def cond_set_or_clear_bv32 (f, w, m):
"""
Conditionally set or clear bits.
"""
return If (f == BitVecVal(1, 32), w | m, w & ~m) | 40e13129b990f05b80b22c26e856da72228a7db2 | 75,686 |
import defusedxml.ElementTree as ElemTree
def outlook():
"""
Parses an Autodiscover Request:
https://msdn.microsoft.com/en-us/library/bb204189(v=exchg.150).aspx
and replies with a Autodiscover Response:
https://msdn.microsoft.com/en-us/library/bb204082(v=exchg.150).aspx
https://testconnectiv... | ee253967e972b0c37135c16985155bf4fbffcc4e | 75,687 |
import torch
def div(x1, x2):
"""Elementwise division of two tensors."""
if isinstance(x1, torch.Tensor) and isinstance(x2, torch.Tensor):
return torch.div(x1, x2)
if isinstance(x1, IntervalBoundedTensor) and (isinstance(x2, torch.Tensor) or isinstance(x2, int)):
z = torch.div(x1.val, x2)
... | 25ee690fa1be88640e8958ee23aa7b93ee8d5781 | 75,688 |
from typing import Dict
def get_models_describe(app: str) -> Dict:
"""
get app models describe
:param app:
:return:
"""
ret = {}
for model in Tortoise.apps.get(app).values():
describe = model.describe()
ret[describe.get("name")] = describe
return ret | abfa50fbe29b79a1a45c18b73105726c13454afe | 75,690 |
from typing import Counter
def paths_to_edges_count(paths):
"""Chops a list of paths into its edges, counting each edge visited.
Parameters
----------
paths: list of tuples
list of the paths.
Returns
-------
edges: Counter dictionary
Edge tuples as keys, and counts as val... | 1495d7a5f3d9fa4bc815b13e7875b4ed46423870 | 75,691 |
def start(message):
""" Function responds to any content in private chat with bot owner. """
bot.vk_api.wall.post(message=message.text)
reply = _("Message was sent to your wall in VK.")
return bot.reply_to(message, reply) | 6c3dc956e24da2fca9d9fcb8637331afa440047b | 75,692 |
def readiness() -> tuple[str, int]:
"""A basic healthcheck. Returns 200 to indicate flask is running"""
return 'ready', 200 | de1072809a32583a62229e390ea11f6b21f33b1e | 75,693 |
def name_sep_val(mm, name, sep='=', dtype=float, ipos=1):
"""Read key-value pair such as "name = value"
Args:
mm (mmap): memory map
name (str): name of variable; used to find value line
sep (str, optional): separator, default '='
dtype (type, optional): variable data type, default float
ipos (i... | 4eee14e88ca2a6f43cb1b046de239c6847d57931 | 75,694 |
def get_source_position(obj):
"""Return max x, y value of a SourceProperties or catalog row"""
if isinstance(obj, SourceProperties):
x, y = obj.maxval_xpos.value, obj.maxval_ypos.value
else:
x, y = obj['maxval_xpos'], obj['maxval_ypos']
return x, y | d90d097508be7668a6b34f34b672c9f990c1101b | 75,695 |
def gate_cost(motion, cost: np.ndarray,
tracks: list, detections: list, only_position: bool = False) \
-> np.ndarray:
"""Gate cost matrix
Args:
motion:
cost:
tracks:
detections:
only_position:
Returns: cost matrix
"""
if cost.size:
... | 7c657c5c5d1086873a91d201d4a0bd69d5f8e7ed | 75,696 |
def add_sentence_rule(sentence_rule): # noqa: E501
"""Add a Sentence Rule
# noqa: E501
:param sentence_rule: Sentence Rule to be added
:type sentence_rule: dict | bytes
:rtype: None
"""
if connexion.request.is_json:
values = list(sentence_rule.values())
cols = ','.join(l... | f6bee7251900979436ffe334b98d76712d473923 | 75,697 |
def _create_table(data):
"""Creates a table from the given data."""
table = AsciiTable(data)
table.inner_column_border = False
table.inner_row_border = False
table.outer_border = False
table.inner_heading_row_border = False
table.padding_right = 4
return str(table.table) | e674bd07c15e98e1ab26f9774940ed0b21205629 | 75,698 |
def remove_inactive(batch, live_bus, sim=False):
##### CHANGE ARGS NAMING CONVENTION #####
"""
remove buses from live_bus absent in the new stream batch
sim: stream_batch -> live_bus [FALSE]
live_bus -> active_bus [TRUE]
FUTURE: also remove ones that reaches the last stop
"""
if sim... | 404373b5c3fe607af667bb388ba41737704ae164 | 75,699 |
def binary_search_two_pointers_recur(sorted_nums, target, left, right):
"""Util for binary_search_feast_recur()."""
# Edge case.
if left > right:
return False
# Compare middle number and recursively search left or right part.
mid = left + (right - left) // 2
if sorted_nums[mid] == targ... | 553c6217b29f3507290a9e49cd0ebd6acaccec63 | 75,700 |
def create_content_migration_users(request_ctx, user_id, migration_type, pre_attachment_name=None, pre_attachment_content_type=None, pre_attachment_parent_folder_id=None, pre_attachment_parent_folder_path=None, pre_attachment_folder=None, pre_attachment_on_duplicate=None, settings_file_url=None, settings_source_course_... | d3d9cc5b9822e359dec9b44e73d2679ab708dc2f | 75,701 |
import json
def create_platforms(**args):
"""
Creates platforms means create customers
"""
try:
saved_platforms = []
duplicated_platforms = []
not_processed_customers = []
requested_json = frappe.request.data.decode('utf-8').replace('\0', '')
payload_dict = json.loads(requested_json)
payload_list_data... | ce612843a49d73f983cd1641edc6fe162b200220 | 75,703 |
from typing import Union
from typing import List
from typing import Optional
import warnings
def cat2keys(
key1: Union['Categorical', np.ndarray, List[np.ndarray]],
key2: Union['Categorical', np.ndarray, List[np.ndarray]],
filter: Optional[np.ndarray] = None,
ordered: bool = True,
sort_gb: bool = ... | 97987341372271f6568b62f5ca073f865dd0ca33 | 75,704 |
import re
def positional_length (syl, next_syl):
"""Takes the two sequential syllables and returns the positional length of
the first. Syllables can be created using any tool that separates vowel
clusters. Stop + liquid rules follow the principles that apply in tragedy
(see notes below).
"""
... | e4e4253859f31f1b40c82ed0c0115a0406e4520c | 75,705 |
def _decode_list(vals):
""" List decoder
"""
return [l.decode() if hasattr(l, 'decode') else l for l in vals] | b0018f40628e64132c62095a5d87f84d5b0d7323 | 75,706 |
import json
def Parse(json_string):
"""Constructs a Schema from its JSON descriptor in text form.
Args:
json_string: String representation of the JSON descriptor of the schema.
Returns:
The parsed schema.
Raises:
SchemaParseException: on JSON parsing error,
or if the JSON descriptor is in... | 65059ed7df333d79f14ebb2711b9fb91ce355aa3 | 75,707 |
def split_pdf(update, range):
"""
Answer to the user with the rotated PDF file
or an error message.
:param angle: (str) to rotate the PDF file
:param update: (telegram.update.Update) the update object
:return: (ConversationHandler.END) after send the file or message
"""
if pdf_to_split:
... | 99da4161d90da57ac32c9baf85dddc0dae520a0a | 75,708 |
def test_rescue_failure():
"""Ensures that rescue works for Failure container."""
def factory(inner_value) -> RCR[int, int, str]:
return RCR.from_failure(inner_value * 2)
assert RCR.from_value(5).rescue(
factory,
)(0) == RCR.from_value(5)(0)
assert RCR.from_failure(5).rescue(
... | fbc4da8ec44d9962b3ba2ada1232f56d930af29e | 75,709 |
def one_to_many(unitcol, manycol):
""" Tests that each value in ``manycol`` only is associated with
just a single value in ``unitcol``.
"""
def decorate(func):
@wraps(func)
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
ck.one_to_many(result, unitcol... | 5dc4e6d7587d26973020e3e24adb5106a3bb76ee | 75,710 |
def getBlackListedTags():
"""
We maintain a blacklist of words which we do not want to display as tag in buildbot.
We generate a list of tags by splitting the builder name. We do not want certain words as tag.
For e.g. we don't want '11'as tag for builder iOS-11-Simulator-EWS
"""
tags_blacklist ... | 954b8d3d7359f22ca272ef03cbf69899e747277b | 75,711 |
import random
def gen_nonsingular_matrix(n, p):
"""
Generates an nxn random nonsingular matrix over the finite field Z/pZ.
Works by recursing over the construction of two nxn matrices and returning
their product.
"""
A = np.random.random_integers(0, p, size=(n, n))
T = np.random.random_in... | 1b70ff5e7b8161aa4939b1629d4575ca5e0fc8ef | 75,713 |
from ._common import chemical_properties
def _write_chemp(parameters):
"""Write CHEMP block data."""
# Load data
data = parameters["chemical_properties"]
# Formats
fmt = block_to_format["CHEMP"]
fmt1 = str2format(fmt[1])
fmt2 = str2format(fmt[2])
fmt3 = str2format(fmt[3])
# Reco... | e890179a2092e598e6acbbae25288774632f46da | 75,715 |
import array
def intersect_icurve_icurve(icrv1, icrv2, itol=None):
"""
Find the intersection points of two intersection curves.
:param icrv1:
:param icrv2:
:param itol:
:return:
"""
# Global parameters
if itol is None:
itol = Settings.gtol
# Intersect 3-D curves.
... | 5c35dc831eeacaa87a20d6b749f8907eb6bdc96d | 75,716 |
def extract_class(query):
"""Extract original class object from a SQLAlchemy query.
Args:
query (query): SQLAlchemy query
Returns:
class: base class use when setting up the SQL query
"""
first_expression = query.column_descriptions[0]['expr']
try:
# query returns subset of columns as tuples
... | 48bfec4301c752c68bda613334dcb7dfc17f3f15 | 75,718 |
def json():
"""
Render the dashboard template on the /dashboard route
"""
try:
return str(simple_receive().decode('utf-8'))
except ConnectionError:
return '', 502 | 1eb81a8b2ed06332b57f661582082e7edc6147ed | 75,719 |
def get_timeinrois_stats(data, rois, fps=None, returndf=False, check_inroi=True):
"""
Quantify number of times the animal enters a roi, cumulative number of frames spend there, cumulative time in seconds
spent in the roi and average velocity while in the roi.
In which roi the mouse is at a given frame i... | 130f1e2af9acb344775f108a5c0a91840d604aa7 | 75,720 |
def get_restore_user(domain, couch_user, as_user_obj):
"""
This will retrieve the restore_user from the couch_user or the as_user_obj
if specified
:param domain: Domain of restore
:param couch_user: The couch user attempting authentication
:param as_user_obj: The user that the couch_user is atte... | 09ad1783236860779064f2929bb91c05915cdd6e | 75,721 |
def determine_seat_position(boarding_pass: str) -> tuple[int, int]:
"""Calculate seat row and column from the boarding pass."""
seat_row = find_seat_position(boarding_pass[:7], "F", "B") - 1
seat_column = find_seat_position(boarding_pass[7:], "L", "R") - 1
return seat_row, seat_column | 122ca00d36103457c2bc3874cebeb524a77262ab | 75,722 |
def handle_pr_events(iterable, who=None):
"""Report pull request changes and comments."""
lines = []
unused = iterable
actions = defaultdict(list)
# Pull Requests
events, unused = partition_type('PullRequestEvent', unused)
for event in sorted(events, key=lambda event: event.created_at):
... | 1df402ebefd85e316f37a108697fe1c094405a36 | 75,723 |
def authorization_end(request, radius_username, authorization_id):
"""
End an authorization from the specified user.
Required user level: Manager
Returns true when successful. Returns false when the authorization was already ended.
radius_username -- Username to search for.
identifier ... | 1460b09b0224f4c6316668a457028042f9e7dd26 | 75,724 |
import re
def membership_holders(token_address):
"""
会員権_保有者一覧取得
:param token_address: トークンアドレス
"""
logger.info(f'[{current_identity._get_current_object()}] api/membership/holders')
# API実行ユーザの取得
# LocalProxy (current_identity) のままSQLAlchemyに渡すとエラーになるためプロキシ先オブジェクトを取得する
user_id = curre... | 7e890087cc8783618e811457a6eb547db81d5e7c | 75,726 |
from espnet.optimizer.pytorch import OPTIMIZER_FACTORY_DICT
from espnet.optimizer.chainer import OPTIMIZER_FACTORY_DICT
def dynamic_import_optimizer(name: str, backend: str) -> OptimizerFactoryInterface:
"""Import optimizer class dynamically.
Args:
name (str): alias name or dynamic import syntax `mod... | b75363ec600c76a6ba5874f975e8b47daa805171 | 75,727 |
def _caps_to_camel_case(row):
"""Convert CAPITAL TERMS to Camel Case
Args:
row (dict): Row of data to evaluate.
Returns:
_row (dict): Modified row.
"""
_row = deepcopy(row)
for k, v in row.items():
if type(v) is str:
_row[k] = _caps_to_camel_case_by_value(v)
... | 193f08f0bb09c9ab8e1390979402c23f5bb7ee2c | 75,730 |
def can_manage_email_dashboard(handler):
"""Decorator to check whether user can access email dashboard.
Args:
handler: function. The function to be decorated.
Returns:
function. The newly decorated function that now checks if the user has
permission to access the email dashboard.
... | b998cd5373e1a40ad8115a02763835a2309f1549 | 75,731 |
import json
def get_sflow(brname):
"""
If Bridge brname doesn't have an sflow record, return None.
"""
response = {}
try:
con = dbclient.connect()
except dbclient.DatabaseError as e:
response["ret"] = e.ret
response["msg"] = e.msg
return json.dumps(response)
... | 184350dadabd126905bfe5556e9b04666288de75 | 75,732 |
def read_data_sets(directory, value, dtype=tf.float32):
"""
Load data from HDF5 files.
Inputs:
-- directory: file name
-- value: array name in the file
-- dtype: DataSet's data type
Output:
-- data_sets: loaded DataSet
"""
with h5py.File(directory, 'r') as readfile:
ima... | 3785a4342e0d936231777f0d2b84acee0b45e8d6 | 75,733 |
def capitalize_column_names(dataframe):
"""Capitalize column names of the model's input dataframe.
Keep column names consistent with the dataframe used for
training the model."""
dataframe.columns = [x.upper() for x in dataframe.columns]
cols = []
for col in dataframe.columns:
if col.en... | 52486a58b72099ebd73c38876604743a386905fe | 75,734 |
def full_coverage(urls, segment):
"""Returns True if the list of URLS completely covers a GPS interval
The URL list is presumed to be contiguous, so this just checks that
the first URL (by GPS timestamp) and the last URL can form a segment
that overlaps that given.
"""
if not urls:
retu... | f382cace54c8748ad017a4074f82d3e9651f31bc | 75,735 |
def grid_2d(shape, name="grid_2d"):
""" creates a tensor with a grid 2d coordinates
Args:
shape (`Tensor`): an Tensor of tf.int32 with a 2D shape for the grid
name (`str`): grid_2d op name
Returns:
grid_coordinates (`Tensor`): 2D tensor with grid coordinates
"""
shape ... | 488b34015bdf2536d58362d9f77425fe32c69c5c | 75,736 |
def factory_parametrised_RNN(input_dim=1, output_dim=1, num_layers=1, bidirectional=False, input_time_series_len=1,
output_time_series_len=1, nb_output_consider=1, hidden_size=150, dropout=0.,
*, rnn_class, Parent):
"""
GRU and LSTM are very close in ter... | 5f32cc932b401c7c8d90b0c823bd6e9c8195b0cc | 75,737 |
def get_vectors(model, corpus_size, vectors_size, vectors_type):
"""
Get vectors from trained doc2vec model
:param doc2vec_model: Trained Doc2Vec model
:param corpus_size: Size of the data
:param vectors_size: Size of the embedding vectors:wq
:param vectors_type: Training or Testing vectors
... | 4ca2a5962362234159f71d090689cdbf415d0e24 | 75,738 |
def PhoneNumberFactory():
"""Create a phone number for a person in the address book."""
def create_phone_number(person, set_as_default=False, **kw):
return icemac.addressbook.testing.create(
person.__parent__, person,
icemac.addressbook.interfaces.IPhoneNumber,
set_as... | f6ddfd453ce1f77332237308e112cc32f480ce2c | 75,739 |
def dim_in_bnd_vec(X, dim, a, b):
"""Dimension between bounds indicator function for 2-dimensional X"""
n = X.shape[0]
res = np.zeros(n, dtype=np.int64)
for i in range(n):
res[i] = dim_in_bnd(X[i, :], dim, a, b)
return res | 0e36cf640bb0c084e527d6f82e7e7509c0c8a8d7 | 75,741 |
def extract(element, items, section=None):
"""Extract data from an XML element.
:sig:
(
Element,
Sequence[Mapping[str, Any]],
Optional[str]
) -> Mapping[str, Any]
:param element: Element to extract the data from.
:param items: Descriptions for extract... | 2519e5f51defb806bf62c4a5baf55170092491ad | 75,742 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.