content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def poor_cond_toep(n):
"""
:param n: size of output
:returns: the top row of a randomly scaled PSDT matrix whose
:math:`L^2` condition number scales exponentially with `n`
"""
top = np.arange(n)[::-1] * (np.random.rand() + 1e-3)
while smallest_eig(top) < 0:
top[0] *= 2
... | f9645e50ade7aa76e694242fd61a4eb1bae8a443 | 3,599,000 |
from datetime import date, timedelta
from numpy import ndarray, matrix, generic
from pandas import DataFrame, Series, Index
from spyder.pil_patch import Image
def get_supported_types():
"""
Return a dictionnary containing types lists supported by the
namespace browser.
Note:
If you update this li... | 51e577fbfbe97f5fc945fb906399a8ab7a5e188c | 3,599,001 |
def view_mempool():
"""insert new transaction to mempool"""
return mempool.transactions | a8dbb0fd7b50a6f89c895c641aadc854e195643b | 3,599,002 |
def calculate_profile_input_for_cluster_analysis_from_ERA5(p_profile, t_profile, td_profile, q_profile,
u_profile, v_profile, h_profile, surface_p):
"""
takes data from ERA5 for only one time stamp for all pressure levels from 250 to 1000 hPa
:param... | dd1f15c3b62ad5e6b9706b59c55fcb220340b9a0 | 3,599,003 |
def components_graph(geo, stereo=True):
""" Generate a list of molecular graphs where each element is a graph that
consists of fully connected (bonded) atoms. Stereochemistry is included
if requested.
:param geo: molecular geometry
:type geo: automol geometry data structure
:... | e1fbee2042601620f342578725d2eb35fc6bc7bf | 3,599,004 |
from pathlib import Path
import json
def get_configured_hosts():
"""Look into the user preferences to enumerate the remote ssh hosts
that were configured for use with dallinger.
"""
hosts_dir = Path(APPDIRS.user_data_dir) / "hosts"
res = {}
if not hosts_dir.is_dir():
return res
for... | 49a7c8b4aa7ad34ad82bc5df5c196de957495fa1 | 3,599,005 |
import numpy
def readValidationImages():
""" Reads in all images in the validation directories
Creates a numpy array containing the pixel data of all the images in the directories of validation images. Assumes that the subdirectories "PosVal" and "NegVal" exit in the working directory
Args: None
... | b110d5e20091fd09b6ef9c3cd7ca540933e3451a | 3,599,006 |
from typing import Optional
from typing import List
import math
import random
def sample_from_range(range_max: int,
sample_ratio: float,
max_samples: int,
preselected: Optional[List[int]]) -> List[int]:
"""
Given a range of numbers in 0..range_... | 8be7b5ded3b6f3b54da57027a5d7629a9bf5dc9f | 3,599,007 |
import regex
import traceback
def data_masking(instance, db_name, sql, sql_result):
"""脱敏数据"""
try:
keywords_count = {}
# 解析查询语句,判断UNION需要单独处理
p = sqlparse.parse(sql)[0]
for token in p.tokens:
if token.ttype is Keyword and token.value.upper() in ['UNION', 'UNION ALL... | b92df933e5681cf729a213dd7bc92eda5962c80d | 3,599,008 |
from typing import List
def filter_single_group(
molecules: pd.DataFrame, groups: List[str], exclude: bool) -> pd.DataFrame:
"""Check that the molecule has a single functional group."""
# First filter the molecules that have the target functional groups
molecules = filter_by_functional_group(molec... | 31fb07a77282c317f577ca2c0c8c935887af5894 | 3,599,009 |
def occ(s1,s2):
"""occ (s1, s2) - returns the number of times that s2 occurs in s1"""
count = 0
start = 0
while True:
search = s1.find(s2,start)
if search == -1:
break
else:
count +=1
start = search+1
return count | 4f107e5552d794e9e82a8a6b19ec63992034e9f7 | 3,599,010 |
import functools
import operator
def prod(x):
"""Equivalent of sum but with multiplication."""
# http://stackoverflow.com/a/595396/1088938
return functools.reduce(operator.mul, x, 1) | 31f4defa3401d6dcf05f8ec70c32650f000a1852 | 3,599,011 |
def compare_dfs(old_df, new_df, on):
"""
Function to compare two DataFrames with nans and return a dict with rows that have changed (diff), rows that exist in new_df but not in old_df (new), and rows that exist in old_df but not in new_df (remove).
Both DataFrame must have the same columns.
Parameters... | 705f19b9b48827dca3baf4e31e6396f706d9136c | 3,599,012 |
def indent(text, prefix=" "):
"""
Add a prefix to every line in a string.
"""
return "\n".join(prefix+line for line in text.splitlines()) | e83cc0b14c5b8c304f6e41bf145b06b1de451e8c | 3,599,013 |
def load(fname):
"""Return a `BDD` loaded from DDDMP file `fname`.
If no `.orderedvarnames` appear in the file,
then `.suppvarnames` and `.permids` are used instead.
In the second case, the variable levels contains blanks.
To avoid blanks, the levels are re-indexed here.
This has no effect if `... | d81ff16bb356f00df3e795991657772ee71ca2d5 | 3,599,014 |
def get_iterator(ip, value, community_string, is_oid=False):
"""
Get pysnmp iterator
Args:
ip: The device's IP address
value: MIB id or SNMP OID
community_string: The community string for the network. Usually 'public' or 'private'
is_oid: boolean if t... | f1fcfdb3aa772efd7448c1dec3506aa14d205731 | 3,599,015 |
from typing import Tuple
from typing import Dict
from typing import Union
def _get_event_description(
elem: etree.Element,
) -> Tuple[str, Dict[str, Union[str, int]]]:
"""Returns the full description of a single XML Event in the DFL format.
Parameters
----------
elem: lxml.etree.Element
l... | 8e1af0808d570f6ce1949b8035dcb316f12c6a70 | 3,599,016 |
def deserialize(fmt, stream_or_string, **options):
"""
Deserialize a stream or a string.
"""
d = get_deserializer(fmt)
return d(stream_or_string, **options) | f14c8b42f2be5a2c3301cbe1ca7bf70fe22ddc73 | 3,599,017 |
import logging
def read_nitfile(path: str):
""" read and parse the "nit" (config) file and return as a dict """
logging.info(f"opening nit file {path}")
nit = {}
with open(path) as fp:
for line in fp.readlines():
if '#' in line:
line, comment = line.split('#', max... | 831453ee9e0bc6b4c58969ffad10cd385754fdc0 | 3,599,018 |
import sys
def extract_comparison_attributes_and_print_multinomial(model_h2o, h2o_model_test_metrics, family_type, end_test_str,
compare_att_str=["", "", "", "", "", "", ""],
h2o_att_str=["", "", "", "", ""... | d15af3edfce0ae316fd9ae53d4fbaf7cc9e15f94 | 3,599,019 |
def get_resblock(model, layer_name):
"""
model is a class resnet
e.g. layer_name is "layer1.0.relu2"
"""
obj_name, b_idx, act_name = layer_name.split(".")
b_idx = int(b_idx)
block = getattr(model, obj_name)[b_idx]
return block | a4ae6c65df336b3dd36b53e9dd348a76b4a47b89 | 3,599,020 |
def compute_rolling_mean(df, window=30):
"""Return rolling mean of given values, using specified window size."""
df['SMA_{}'.format(str(window))] = df['Price'].rolling(window=window, center=False).mean()
return df | 36048112a720e0bdd66d2dfeeac6fb5cab62fa46 | 3,599,021 |
def fix_link_header(headers):
"""Replace the GitLab URL in the Link header."""
if 'Link' in headers:
headers['Link'] = headers['Link'].replace(
app.config['GITLAB_URL'], app.config['HOST_NAME']
)
return headers | d11d1cde6a474084a208d82d31f68d3b0b3eb44b | 3,599,022 |
import os
import tarfile
def make_archive(name, repo, ref, destdir):
"""Makes an archive of a repository in the given destdir.
:param text name: Name to give the archive. For instance foo. The file
that is created will be called foo.tar.gz.
:param text repo: Repository to clone.
:param text ref... | 29292b085bb0c138616035c4493cac994b4270b9 | 3,599,023 |
def insert(linked_list, value):
"""Metoda insert() vlozi na konec seznamu linked_list (za prvek last)
novy uzel s hodnotou value. Vraci nove vlozeny objekt.
"""
n = Node()
n.value = value
n.prev = linked_list.last
if linked_list.first is None:
linked_list.first = n
else:
... | 82da5a2180e83d6dd66e0125ecde456bb53e6aaa | 3,599,024 |
import torch
def compute_loss(leo, metadata, train_stats, transformers, mode="meta_train"):
""" Performs meta optimization across tasks
returns the meta validation loss across tasks
Args:
metadata(dict): dictionary containing training data
train_stats(ob... | ef299d9c4de41c9c97bea37f2606418e0aaeacec | 3,599,025 |
def GetAcceleratorFlag():
"""Gets the --accelerator flag."""
help_text = """\
Manage the configuration of the type and number of accelerator cards attached.
*count*::: The number of pieces of the accelerator to attach to the allocation.
*type*::: The specific type (e.g. nvidia-tesla-k80 for nVidia Tesla K80) of
a... | b501f4fc87dea568575494a246cbc9f6f5ba940c | 3,599,026 |
def _format_A_constraints(A, n_x, sparse_lhs=False):
"""Format the left hand side of the constraints to a 2D array
Parameters
----------
A : 2D array
2D array such that ``A @ x`` gives the values of the upper-bound
(in)equality constraints at ``x``.
n_x : int
The number of v... | 0f5f6ce6163fde35254d9bfdb6a8f3ccad7914b8 | 3,599,027 |
def argsort(x, topn=None, reverse=False):
"""Get indices of the `topn` smallest elements in array `x`.
Parameters
----------
x : array_like
Array to sort.
topn : int, optional
Number of indices of the smallest(greatest) elements to be returned if given,
otherwise - indices o... | 6fcd896d3bbf296f818e2dcd993f75583ba880de | 3,599,028 |
def preprocess_image(image_path: str) -> np.ndarray:
"""
Pre-processing steps:
* Load the input image in grayscale mode (1 channel),
* resize it to 224x224 pixels for the VGG19 CNN model,
* transform it to an array format,
* normalise the pixel intensities.
:param image_path:... | 2b674415e6b096381a3b3c918be46f6a86545de7 | 3,599,029 |
from typing import Sequence
def is_planar_face(face: Sequence[Vec3], abs_tol=1e-9) -> bool:
""" Returns ``True`` if sequence of vectors is a planar face.
Args:
face: sequence of :class:`~ezdxf.math.Vec3` objects
abs_tol: tolerance for normals check
"""
if len(face) < 3:
ret... | a50dcf37bec0e1c8a7a210195676ef5bdf6aff21 | 3,599,030 |
import platform
import os
def GetAllPlatformConfigs(build_args):
"""
Return a map of directory name to GN args for the current platform.
"""
result = {}
# Merged args without validation.
args = GetMergedArgs(build_args)
create_debug = True
# Don't create debug directories for asan builds.
if GetA... | 25ff377a5e02788058fcd36168ee1b656b28c766 | 3,599,031 |
def is_campaign_config_file(file_name):
"""
Check if the given file is a CampaignConfig
:param file_name: string
:param file_name: File to check
:rtype: boolean
:return: If the file is a campaign config or not
"""
status = False
try:
# MUST BE xml file
if file_nam... | 57c9314af84ea1835fb16db54ce53d9997541254 | 3,599,032 |
def dice_coefficient(prediction, ground_truth, smooth=1.0):
"""
Function to calculate the dice coefficient.
:param prediction: the logits (before softmax)
:param ground_truth: the segmentation ground truth
:param smooth: Smoothing coefficient.
:return: the dice coefficient.
"""
y_true_f... | 629d083edaa386bb6527ed498c5f4f76cd8efaa7 | 3,599,033 |
def bilinear_interpolate(data, x, y, nan_boundaries=False):
"""
Author: Michael Denbina (source: Kapok library)
Function to perform bilinear interpolation on the input array data, at
the image coordinates given by input arguments x and y.
Arguments
data (array): 2D array containing raster ... | 5a059a31d135c3947894aa80d3b8c3d097ae5337 | 3,599,034 |
def get_data(col='close'):
""" Returns a 3 x n_step array """
msft = pd.read_csv('data/msft.csv', usecols=[col])
aapl = pd.read_csv('data/aapl.csv', usecols=[col])
ibm = pd.read_csv('data/ibm.csv', usecols=[col])
# recent price are at top; reverse it
return np.array([msft[col].values[::-1],
... | 7bc9d759b2037cdb45db8da619d8cfab05f7ec0f | 3,599,035 |
def GetCommentsForParams(func):
"""Gets the comments for the params.
Args:
func: The function.
param: The parameter.
Returns:
a (string, dict) pair. The string is the comments minus the param parts.
The dict is a dict of param names to comments.
"""
collecting_key = None
param_comments = {}... | c81cc9ff3b8fb6da57c257d7a8b536cafa22bad2 | 3,599,036 |
def FindClientNode(mothership):
"""Search the mothership for the client node."""
nodes = mothership.Nodes()
assert len(nodes) == 2
if nodes[0].IsAppNode():
return nodes[0]
else:
assert nodes[1].IsAppNode()
return nodes[1] | 06ac3bcde5571ca425d47885ad5839f2aa32ca0d | 3,599,037 |
def index_max_maxunpooling(prev_indexes,X,pool_size,stride):
"""Function that return the indexes of maximum values of maxpooling
operation.
Args:
prev_indexes: Python list with tuples of indexes in the form
(batch, frame, height, width, channels).
X: Input of the max... | 80f0c1ad85a97c576608912af3d46c6a1300a654 | 3,599,038 |
import textwrap
def to_flatimage(pathfile, to="(-3,0,0)", width=8, height=8, name="temp"):
"""
Adds a flat image to the canvas.
"""
text = rf"""
\node[canvas is xy plane at z=0] ({name}) at {to}{{
\includegraphics[width={width}cm,height={height}cm]{{{pathfile}}}
}};
"""... | 61906516d85ba3311506067ad4ec81b32786f1b9 | 3,599,039 |
def CalculateMSE(xs_, mu):
"""
计算均方误差
xs_: 所有样本均值
mu: 总体均值
"""
return sum([(x - mu) ** 2 for x in xs_]) / len(xs_) | 45e90b003e05d54fdfa13c82b1f1332d0e68082a | 3,599,040 |
def load_hw10_starfit():
"""
Set up data for fitting
"""
hw10 = rd.load_hw10(as_number=True)
columns_to_use = np.array([isinstance(col, (int, np.integer)) for col in hw10.columns])
hw10logN = np.log10(hw10[hw10.columns[columns_to_use]])
return hw10, hw10logN | ff7387a8d1030f477469b7f335fa8d8ef9a07786 | 3,599,041 |
def is_init_authorised(context, bushfire_id):
"""
Usage::
{% if is_init_authorised %}
...
{% endif %}
or
{% for bushfire in object_list %}
{% is_init_authorised bushfire.id as init_authorised %}
<tr>
<td>{{ bushfire.id }}</td>
... | 377a4bfeffd8dc04751ad6264b3348845f638e69 | 3,599,042 |
def is_email(email: str):
"""Returns wether the given string is an email address or not"""
return EMAIL_REGEX.fullmatch(str(email)) is not None | a0a90a5a04f065058cee18f9479553aca2eec2e7 | 3,599,043 |
def gaussian_noise(images, bounds):
"""
adding gaussian noise to images. Different noise for each image.
:param images: RGB matrix of two input images. Nois on mask is useless
:param bounds: min and max of the gaussian noise
:return: RGB matrix with gaussian Noise
"""
noisy_images = images.c... | 8c6128534caa7ebaa8f817d0b8c70e72be19c2cd | 3,599,044 |
def voronoi(frame, data, f, parameters=None, call_num=None):
"""
Voronoi draws the voronoi network that surrounds each particle
Notes
-----
The voronoi cells must previously have been calculated in postprocessing.
See "voronoi" in postprocessing.
Parameters
----------
cmap_t... | 85cf9db42a82de3abae48131fb9df41151dde40b | 3,599,045 |
def computeVisSamples(vislm, k, r, theta, phi):
"""The reverse function to computeVislm, compute the visibilities for give set of (r, theta, phi) from vislm coefficients, Eq. 9 pf Carozzi 2015
vislm: complex array, spherical wave harmonics visibility coefficients computed from computeVislm()
k: [N, 1] float... | 138b080d5ebece92af457d8b4c86e51473b4e1ae | 3,599,046 |
def _get_primary_status(row):
"""Get package primary status."""
try:
return row.find('div', {'class': 'pack_h3'}).string
except AttributeError:
return None | 1df5b66e9e16e17b8c5f3fc019a587a4320cf6d0 | 3,599,047 |
def calc_n_g(df_schedule, week):
"""Calculate list of games i.e. Ng
Each row has home_id, away_id, home_total_points, away_total_points
:param df_schedule: data frame with each matchup
:param week: current matchup period id
:return: list of games with team ids and scores for home/away
"""
df_scores = (
... | 1029840d28617d5de60fa499e8e6a9ae40b4ddea | 3,599,048 |
def is_string(s):
"""
Portable function to answer whether a variable is a string.
Parameters
----------
s : object
An object that is potentially a string
Returns
-------
isstring : bool
A boolean decision on whether ``s`` is a string or not
"""
return isinstance... | ed59a1b3a80f6695c971c49ff3b7936aa048523f | 3,599,049 |
from os.path import dirname
def default_install_dir():
"""Return the default install directory. Assumes this file lives in
a 'site-packages' directory.
Returns
-------
:class:`str`
The path to the install directory.
"""
return dirname(dirname(dirname(dirname(dirname(__file__))))) | 238ec1d309f6697978ef97198cc21b205e2dd6cb | 3,599,050 |
def flatten_nested_list(list_in, drop_dupes=False):
"""Function to take a nested list and flatten into a 1d list."""
is_nested=True if type(list_in[0]) ==type(['v','d']) else False
if is_nested is True:
list_out=[];
if drop_dupes is True:
for list_i in list_in:
... | d3580ea22458ef794bdef280cec650f1521fda04 | 3,599,051 |
def computeIchimokuCloud(candleSet):
""" compute current values of Ichimoku Cloud lines """
conversionLine = (max([x["High"] for i,x in candleSet.iloc[-9:].iterrows()]) + min([y["Low"] for i,y in candleSet.iloc[-9:].iterrows()]))/2
baseLine = (max([x["High"] for i,x in candleSet.iloc[-26:].iterrows(... | 781df8f002a7fc3f5f7b3dd854a123bb3f21c142 | 3,599,052 |
def update_subfield_snippet(context,
code,
subfield,
value):
"""
Replaces a new value in a subfield snippet for a MARC field
:param context: Context
:param code: Field code
:param subfield: MARC subfield, if numeric... | 67ddf74faef5295028d27725534e05c888fba36a | 3,599,053 |
from typing import Sequence
from typing import Optional
def setup_minimal_example(
num_companies: int = _num_companies,
num_markets: int = _num_markets,
market_company_connections: np.ndarray = _market_company_connections,
market_capacities: np.ndarray = _market_capacities,
step_sizes: Sequence[fl... | 712f5b811767e37979670be001f4caf39aa18d04 | 3,599,054 |
import json
def follow(request, username,
template_name='relationships/relationship_add_confirm.html',
success_template_name='relationships/relationship_add_success.html',
mimetype='text/html'):
"""
Allows a user to follow another user.
Templates: ``relationships... | a2baf9c1aebdda46c4879db66d3e269d13fa3c18 | 3,599,055 |
from typing import Any
from typing import Optional
def _strat_has_unitary_from_has_unitary(val: Any) -> Optional[bool]:
"""Attempts to infer a value's unitary-ness via its _has_unitary_ method."""
if hasattr(val, '_has_unitary_'):
result = val._has_unitary_()
if result is NotImplemented:
... | 96965cfec5f5c3c29ea641c95f20a2d4b1f3b859 | 3,599,056 |
import os
import tarfile
def dir_to_tar(src_path, dst_path, dst_name=None):
"""
将目录打包为tar.gz文件
:param src_path: 被打包目录
:param dst_path: tar文件存放目录
:param dst_name: tar文件名
:return: tar.gz生成路径
"""
if not os.path.exists(src_path):
return ""
if not dst_name or "" == dst_name:
... | 8b5c031a4e80e43a13ca97fd4ab93e4e72ba8f9c | 3,599,057 |
def write_keyvalue_toxlsx(worksheet, row, key, value):
"""Write a dictionary to excel sheet."""
if type(value).__name__ == 'dict':
worksheet.write(row, 0, key)
row += 1
for dictkey, dictvalue in value.items():
row = write_keyvalue_toxlsx(worksheet, row, dictkey, dictvalue)
... | c89111a35b182824664624c9b41358a15351f91d | 3,599,058 |
def swap_index_values(series: pd.Series) -> pd.Series:
"""Swap index and values in series.
Examples:
>>> s = pd.Series({'a': 1, 'b': 2})
>>> s.name = 'val'
>>> s.index.name = 'char'
>>> swap_index_values(s)
val
1 a
2 b
Name: char, dtype: obj... | 3849fd2c21bdd0782391f0030947fdcf3fca2251 | 3,599,059 |
def BFS(map_dict, start, end, verbose):
"""
BFS algorithm to find the shortest path between the start and end points
on the map, following the map given by map_dict
If an invalid end location is given then it will return the longest possible
path and its length.
Returns the length of t... | f6770fe8cd5f6c4ebffce2a78992c76cfbb5bd31 | 3,599,060 |
from config import get_config
import socket
def get_hostname(config=None):
"""
Get the canonical host name this agent should identify as. This is
the authoritative source of the host name for the agent.
Tries, in order:
* agent config (config.cfg, "hostname:")
* 'hostname -f' (on unix)
... | 5b5eff2b65b382689586e0ed6b5e71594054f9e9 | 3,599,061 |
import requests
import os
def ok_refresh():
"""Proxy for front-end to perform refreshes on OAuth tokens"""
refresh_token = request.args.get('refresh_token')
if not refresh_token:
return jsonify(success=False), 400
r = requests.post('https://okpy.org/oauth/token', data={
'refresh_token'... | 3449366a3d0c6de2d5b52c870961b5372c35803d | 3,599,062 |
def ir_swap_price(
pay_leg_coupon_rates,
receive_leg_coupon_rates,
pay_leg_notional,
receive_leg_notional,
pay_leg_daycount_fractions,
receive_leg_daycount_fractions,
pay_leg_discount_factors,
receive_leg_discount_factors,
dtype=None,
name=None):
"""Computes prices of a batch o... | 7c19f71c061992f17bf344ed69eaa45e01a81623 | 3,599,063 |
def construct_timeseries_cds(report):
"""Construct two standardized Bokeh CDS for the timeseries and scatter
plot functions. One with timeseries data for all observations,
aggregates, and forecasts in the report, and the other with
associated metadata sharing a common `pair_index` key.
Parameters
... | adeb72708a6c68c8f97a5e9006c5ff9f97029b58 | 3,599,064 |
from functools import reduce
def pipeline(source, functions):
"""Apply an array of functions to a source iterable"""
return reduce(lambda x, y: y(x), functions, source) | c79977ce46a6be15fc428530d94f8c4878a68ede | 3,599,065 |
def compare_proj4(original, new):
"""compare proj4 strings"""
def to_dict(proj4_str):
"""convert to dictionary"""
proj4_split = proj4_str.strip().split(" ")
proj4_dict = dict()
for elem in proj4_split:
elem_split = elem.strip().split("=")
try:
... | c7fba2e9f9257414e681d5aa28d55bada02ef61e | 3,599,066 |
import requests
def cube_instance(connection, cube_id, body={}, offset=0, limit=1000, verbose=False):
"""
Create a new instance of a specific cube. This in-memory instance can be used by other requests.
Args:
connection: MicroStrategy REST API connection object.
cube_id (str): Unique ID o... | 512962af29851c87bd278088aa69d0b9db967707 | 3,599,067 |
from typing import Union
from typing import Dict
from pathlib import Path
import uuid
import json
def transform_code_cell( # noqa: C901 (flake8 too complex)
cell: NotebookNode,
plot_data_folder: Union[PathLike, str],
filename: Union[PathLike, str],
) -> Dict[str, Union[str, bool]]:
"""Transform the g... | be342d62ac7febbcb08fb7a15d7270ce4b3b5945 | 3,599,068 |
from pathlib import Path
def read_commit(wkspc_dir) -> str:
"""
read and return the value
in the commit file
:param wkspc_dir: jenkins workspace dicrectory
:return: commit tag value
"""
commit = 'false'
# confirm branch directory exists
vol_dir = '/'.join(['/volumes', PurePath(wk... | f547fd7619241549060f0156012e5ca89ceb42e0 | 3,599,069 |
def findAllTabs():
"""
Returns:
list
"""
tabModules = []
for m in findAllModules():
mod = __import__("DLS.widget.%s" % m, '', '', [m])
if hasattr(mod, 'TAB') and mod.ENABLE:
reload(mod)
tabModules.append(mod)
tabModules.sort(key=lambda m... | 135db0c90b62ffa70490b715a4bd354b7e08123f | 3,599,070 |
def timestamp_to_unix(x):
"""
parse timestamp to unix numeric
x: datetime
return: numeric unix representation of x
"""
x_unix = dt.datetime.timestamp(x)
return x_unix.__round__() | dffc31473afe23cea193721ea59108966d57c829 | 3,599,071 |
def dataset_task(func):
"""
Decorate tasks with a real DataladStore object and Celery options.
"""
@app.task
@wraps(func)
def dataset_task_decorator(*args, **kwargs):
annex_path = args[0]
return func(DataladStore(annex_path), *args[1:], **kwargs)
return dataset_task_decorator | 321599059f2ad0260847aa5e4de753ade266ffce | 3,599,072 |
def get_entity_description(es, schema, entity_id):
"""Get the descriptions to the required entity by id.
Args:
es: featuretools.EntitySet, the entity set that includes all patients' health records.
schema: dict, the schema of the entities.
entity_id: string, the identifier of the requir... | 1608c3677e9035581176f8ea11d8c806a63a11d3 | 3,599,073 |
def pf_encode(index):
"""pf: Turn off light."""
return MessageEncode(f"09pf{index_to_housecode(index)}00", None) | d47774d9d1f6fe209aa6d794ef171f4c89dfb950 | 3,599,074 |
import json
def check_order_accepted_for_execution(request):
"""
Check if order is accepted for execution
:param request: request from "Check order accepted for execution" Dialogflow intent
:return: Json with response if order is accepted for execution
"""
language = request.data['queryResult'... | de87275b8cd5c23338af9fb5114c634825c778a4 | 3,599,075 |
import torch
def project_pose(x, camera=None, **kwargs):
"""
Args
x: 3xN points in world coordinates
R: 3x3 Camera rotation matrix
T: 3x1 Camera translation parameters
f: 2 Camera focal length
c: 2x1 Camera center
k: 3x1 Camera radial distortion coefficients
... | f407828feb3caf9812e41a79da90c8486b096c89 | 3,599,076 |
def update_letter_view(puzzle: str, view: str, position: int, guess: str) -> str:
"""Return the updated view based on whether the guess matches position in puzzle
>>> update_letter_view('apple', 'a^^le', 2, 'p')
p
>>> update_letter_view('banana', 'ba^a^a', 0, 'b')
b
>>> update_letter_view('bitt... | b7c534acdbc57c04e1f7ee6a83fc94ff2734948a | 3,599,077 |
def combine_kernels(dist_matrices_arg, gamma=None,
is_sim_l=None, weights_l=None, libsvm_fmt=False):
""" Returns a kernel matrix that is the sum of the kernel matrices for the
different distances in dist_matrices_arg
is_sim_l: list of booleans,
stating if the distance matr... | a185f3769538788a001f71970a228fb8c33f9c6f | 3,599,078 |
def put(url, body=None, **kwargs):
"""put performs a HTTP PUT request."""
return request('PUT', url=url, body=body, **kwargs) | a2783c88e8c5f542748713fd721ce91b4595549a | 3,599,079 |
from .attribute import Attribute
from .node import Node
def MapyaObject(mayaObjectName, typedNodes=True):
"""
from maya object name return mapya object instance
mayaObjectName: node or attribute name
# TODO: support lists, ...
"""
if '.' in mayaObjectName:
return Attribute(mayaObjectNa... | c5abadfb51aab6e97938049b2c9da99464b23d8a | 3,599,080 |
def get_instances(cpu, memory):
"""
Return a list of instances that fulfill the requirements (CPU and RAM)
"""
cpu = int(cpu)
memory = int(memory)
instances = []
for instance, resource in INSTANCE_TYPES.iteritems():
if resource[0] >= cpu and resource[1] >= memory:
instan... | 546e6b1251f797187323f0b42cb25e824095ab44 | 3,599,081 |
def getPartCharFunc2_Python(partDHisto, key, paramProd, rArray, drPrime, delta):
"""
Calculates inter-atom contributions to the EPDDF for a partial distance histogram.
@param partDHisto Partial distance histogram.
@param key string Representing pair of particle species.
@param paramProd Parameter d... | e6cc5c65c0c5210df78ef9287c7214c3dd9f4d98 | 3,599,082 |
def bboxes_sort(scores, bboxes, top_k=20, scope=None):
"""Sort bounding boxes by decreasing order and keep only the top_k.
If inputs are dictionnaries, assume every key is a different class.
Assume a batch-type input.
Args:
scores: Batch x N Tensor/Dictionary containing float scores.
bboxes... | bd7c82cbb296858a121b622182cdd9b0f1591aec | 3,599,083 |
def build_nodes(graph):
"""Gather function metadata for graph nodes"""
acc = {}
for k, v in graph.iteritems():
if callable(v):
acc[k] = util.fninfo(v)
else:
acc[k] = v
return acc | e22a945c4bf1d55bc53d5f17f909460168c27d02 | 3,599,084 |
from sys import flags
def offline_oracle_q(paths, critic_qs, h):
"""
This offers the results the oracle would have in oracle_q, but in an
offline manner. critic_qs should be a single tensor of all the critic
values at the corresponding state and action along each trajectory,
concatenated along the... | 725523c4e1b0dd1b522af713659ef3570ce51cee | 3,599,085 |
def _get_deployment_group_manager(groups, revision_id):
"""Retrieves the deployment group manager"""
return DeploymentGroupManager(groups, _get_node_lookup(revision_id)) | 7d816befb2e6689482ee5acae825b0f5015775cf | 3,599,086 |
import os
def prepare_dataset(opt):
"""
Prepare PyTorch dataset objects used for training 2D-to-3D deep network
Args
opt: experiment options
Returns
train_dataset: training dataset as PyTorch dataset object
eval_dataset: evaluation dataset as PyTorch dataset object
... | 915cd35205fb45964719135306d3ae77d73e2ea4 | 3,599,087 |
def add_cert(domain, is_bad=False):
"""
Returns:
True if successfully added cert + add id
False if not successful and None
"""
crt_results = crtsh.get_results(domain)
if not crt_results:
return False, -1
crt_id = Certs.add_cert(
crt_results.get('caid'),
... | de3bfae28640781d849708f70d3fdd20bc89f146 | 3,599,088 |
def dbscan(
df,
ignored_cols=(
'timestamp',
'machine_status',
),
index_col='timestamp',
engine=pd,
**args,
):
"""
Apply sklearn DBSCAN over a dataframe. First
data is normalized with the zscore function.
-------
Paramaters
-------
- df: pandas Dataf... | 81a88b37c2ddb562fea74bb7010e652200c2fd38 | 3,599,089 |
def geneactiv_acc_data(open_csv):
"""
Function to collect GENEActiv data and return dataframe with Linux time-
series index column and x, y, z value columns
Parameters
----------
df : pandas dataframe
dataframe for which to organize data
Returns
-------
new_df : pandas data... | 10ac2f8e3aebf0e4ed70b4ab652ec67e3561d87f | 3,599,090 |
import tempfile
def download_xbrl(path: str, rcept_no: str, reprt_code: str = None) -> str:
""" XBRL 파일 다운로드
Parameters
----------
path: str
Download Path
rcept_no: str
접수번호
reprt_code: str, optinal
1분기보고서 : 11013 반기보고서 : 11012 3분기보고서 : 11014 사업보고서 : 11011
Returns... | 5fe9884473f6e7e56c608944cd5e93fb2ce72fe6 | 3,599,091 |
def geocode_to_gdf(query, which_result=None, buffer_dist=None):
"""
Geocode a query or queries to a GeoDataFrame with the Nominatim geocoder.
Geometry column contains place boundaries if they exist in OpenStreetMap.
Query can be a string or dict, or a list of strings/dicts to send to the
geocoder. ... | 9b883c908aca92957776e9a0eafa53c1fa2d313e | 3,599,092 |
def CMMCore_getDeviceLibraries():
"""CMMCore_getDeviceLibraries() -> StrVector"""
return _MMCorePy.CMMCore_getDeviceLibraries() | ce925ec5cbf78020e9da339feb910bd16428b555 | 3,599,093 |
def multiplex(*brules):
""" Multiplex many branching rules into one """
def multiplex_brl(expr):
seen = set([])
for brl in brules:
for nexpr in brl(expr):
if nexpr not in seen:
seen.add(nexpr)
yield nexpr
return multiplex_br... | 5245b4eb68a7ae00bc15f9b8071a225d33376781 | 3,599,094 |
import SimpleITK as sitk
def relabel_component(label_image:napari.types.LabelsData, minimumObjectSize:int=15, viewer: napari.Viewer = None) -> napari.types.LabelsData:
"""
See Also
--------
..[0] http://insightsoftwareconsortium.github.io/SimpleITK-Notebooks/Python_html/35_Segmentation_Shape_Analysis.... | aeff92ec1110300ab001cb6de80e2cecc0245c54 | 3,599,095 |
import importlib
def load_class(full_class_string):
"""
Dynamically load a class from a string
"""
class_data = full_class_string.split(".")
module_path = ".".join(class_data[:-1])
class_str = class_data[-1]
module = importlib.import_module(module_path)
return getattr(module, class_s... | 31113a7299c83c80bf00b9cb4bb13e0b01cb67e2 | 3,599,096 |
def is_network_or_minor_error_or_client(exception: Exception) -> bool:
"""Checks if the exception is a network issue or an :py:class:`ApiException` minor error or a client error
:param exception: The exception to be checked
:return: True if the exception is an :py:class:`ApiException` with status 500, 401,... | 8816be54d4ab6a647bfaa13c717cdc70e29a01ff | 3,599,097 |
def problem62(exponent, threshold_count):
"""Problem 62 - Cubic permutations"""
for i in exponent_number_generator(3):
key = "".join(sorted(str(i)))
# Initial Add
if key not in permutation_count_dict:
permutation_count_dict[key] = (i, 0)
# Update
cur_tuple ... | 2fc4f461642afec4ddb19858b7451409cfdf104a | 3,599,098 |
def intersects(feature, dataset):
"""
Returns True if vector feature and raster bounding boxes intersect.
"""
feature_left, feature_bottom, feature_right, feature_top = rasterio.features.bounds(feature)
raster_left, raster_bottom, raster_right, raster_top = dataset.bounds
intersect_bottom = fe... | b3e418d395158cfb57a96b4a655c32258c3f0736 | 3,599,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.