content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def normalization(data, dmin=0, dmax=1, save_centering=False):
"""
Normalization in [a, b] interval or with saving centering
x` = (b - a) * (xi - min(x)) / (max(x) - min(x)) + a
Args:
data (np.ndarray): data for normalization
dmin (float): left interval
dmax (float): right interval
save_centering (bool): if... | 5,311,800 |
def relpath(path: str, start: str = os.curdir) -> str:
"""Return a relative version of a path"""
try:
return os.path.relpath(path, start)
except ValueError:
return path | 5,311,801 |
def normalize_adjacency_matrix(adjacency_matrix):
"""
Helper function for denoise_predictions.
Arguments:
adjacency_matrix: A matrix of size h * w,
https://en.wikipedia.org/wiki/Adjacency_matrix
For this type of normalization, should be symmetric - i.e. from an... | 5,311,802 |
def dl_parse_bsd_lo(link_packet):
"""parse bsd loopback packet"""
if len(link_packet) < 4:
return None, None
# first 4 bytes are packet size which always less then 256, may be LE or BE
if six.byte2int(link_packet) == 0 and six.indexbytes(link_packet, 1) == 0:
prot, = struct.unpack(b'>I',... | 5,311,803 |
def test_all_current_members_by_given_party_id():
"""all_current_members_by_given_party_id works as expected
"""
for i in set([x["PartyOrganisationId"] for x in niaopendata.all_current_members()]):
r = niaopendata.all_current_members_by_given_party_id(i)
_check_valid_list_response(r)
for... | 5,311,804 |
def energycalc(spcode0, climatezone, dbh_orig, height, azimuth, distance, vintage, shade_reduction, lu_conversion_shade, lu_conversion_climate, eqpt_cooling_potential, eqpt_heating_potential):
"""Calculates avoided emissions values given tree and building relationship data.
Args:
spcode0 - species cod... | 5,311,805 |
def _create_scene_object(token: str, object_type: TrackedObjectType) -> Agent:
"""
:param token: a unique instance token
:param object_type: agent type.
:return: a random Agent
"""
scene = SceneObject.make_random(token, object_type)
return Agent(
tracked_object_type=object_type,
... | 5,311,806 |
def conv3x3_group(in_planes, out_planes, groups=1, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, groups=groups, stride=stride,
padding=1, bias=False) | 5,311,807 |
def test_esn_prediction_multiple():
"""
The window size is not a multiple of the
total future.
"""
with pytest.raises(AssertionError):
pred = esn_prediction(X_in, params_broke)
return | 5,311,808 |
def named(name):
"""Change the name of something (via a decorator)."""
def decorator(obj):
obj.__name__ = name
return obj
return decorator | 5,311,809 |
def split_repo_and_dir(repo):
"""
Split the input string
org-name/repo-name/subdir-name/more/sub/dirs
(where '/subdir-name/more/sub/dirs' is optional) into
org-name/repo-name
and
subdir-name/more/sub/dirs
The second part might be the empty string if no subdir-name was given.
"""
parts = repo.s... | 5,311,810 |
def plot_2(config, plot_data, fig_path):
"""Plot eigenvalues of GGN and Hessian."""
# Extract results
G_evals = plot_data["G_evals"]
H_evals = plot_data["H_evals"]
if not len(G_evals) == len(config["decimal_checkpoints"]):
print("Not enough results were found. Skipping this config.")
... | 5,311,811 |
def save_upload_file_tmp(upload_file: UploadFile):
"""Saves recieved dat and returns directory"""
try:
suffix = Path(upload_file.filename).suffix
direc = mkdtemp(dir="dat")
with NamedTemporaryFile(
delete=False, suffix=suffix, dir=os.path.abspath(direc)
) as tmp:
... | 5,311,812 |
def test_suite():
""" Run the suite of tests for code in this module (this file).
"""
test(sum_of_squares([2, 3, 4]) == 29)
test(sum_of_squares([]) == 0)
test(sum_of_squares([2, -3, 4]) == 29) | 5,311,813 |
def loadUZHMensa(baseDate, uzhConnectionInfo, db):
""" Loads all meals for all days of the given uzh connection info. <br>
Stores the resulting mensa in the mensaMapping object."""
name = uzhConnectionInfo["mensa"]
mensaCollection = db["mensas"]
if mensaCollection.count_documents({"name": name}, ... | 5,311,814 |
def hits_recorded(pitcher_id=None):
"""Get the number of hits recorded by each historical pitcher. If pitcherId is specified, only that pitcher is returned.
`pitcher_id` is a single string UUID or list of string UUIDs.
Returns dictionary {pitcher_id: count}"""
params = {}
if pitcher_id:
par... | 5,311,815 |
def calculateOnlineVariance(data):
"""
Returns the variance of the given list.
:param data: A list of numbers to be measured (ie. the window)
:returns: The variance of the data.
"""
n, mean, M2 = 0, 0, 0
for x in data:
n = n + 1
delta = x - mean
mean = mean + delta/n
M2 = M2 + delta*(x-... | 5,311,816 |
def clamp(x, xmin, xmax):
"""Constrain a value to lie between two further values, element-wise.
The returned value is computed as `min(max(x, xmin), xmax)`.
The arguments can be scalars or :class:`~taichi.Matrix`,
as long as they can be broadcasted to a common shape.
Args:
x (:mod:`~taichi... | 5,311,817 |
def log(message, log_class, log_level):
"""Log information to the console.
If you are angry about having to use Enums instead of typing the classes and levels in, look up how any logging facility works.
Arguments:
message -- the relevant information to be logged
log_class -- the category of informa... | 5,311,818 |
def anim_curve_exists(attr_curve_name):
"""
"""
anim_curve = get_anim_curve(attr_curve_name)
if not anim_curve:
return True
else:
return False | 5,311,819 |
def create_string(item):
"""Create strings for tests."""
return WEBEX_TEAMS_TEST_STRING_TEMPLATE.substitute(
prefix=WEBEX_TEAMS_TEST_STRING_PREFIX,
item=item,
datetime=str(datetime.datetime.now())
) | 5,311,820 |
def test_atomic_ncname_length_1_nistxml_sv_iv_atomic_ncname_length_2_3(mode, save_output, output_format):
"""
Type atomic/NCName is restricted by facet length with value 61.
"""
assert_bindings(
schema="nistData/atomic/NCName/Schema+Instance/NISTSchema-SV-IV-atomic-NCName-length-2.xsd",
... | 5,311,821 |
def save_image_with_legends_and_labels(save_path: str, image: np.ndarray, legends: List[Rectangle],
labels: List[str]) -> (plt.Figure, plt.Axes):
"""
Saves the given image with the given legends rects and labels
Args:
save_path: the path to the folder to save ... | 5,311,822 |
def test_rename_tab_dialog(ui_no_refs_config_fixture, qtbot, mocker):
""" Test, that rename dialog change the name """
from pytestqt.plugin import _qapp_instance
main_gui = main_window.MainWindow(_qapp_instance)
main_gui.show()
main_gui.load(ui_no_refs_config_fixture)
qtbot.addWidget(main_gui)... | 5,311,823 |
def test_stsf_on_unit_test_data():
"""Test of SupervisedTimeSeriesForest on unit test data."""
# load unit test data
X_train, y_train = load_unit_test(split="train", return_X_y=True)
X_test, y_test = load_unit_test(split="test", return_X_y=True)
indices = np.random.RandomState(0).choice(len(y_train)... | 5,311,824 |
def nod_uploadkey(private, own=False, date=None):
"""Generate the key for the next News of the Day entry.
>>> nod_uploadkey("USK@foo,moo,goo/WebOfTrust/0", own=False, date=datetime.datetime(2010,1,1))
'SSK@foo,moo,goo/nod-shared-2010-01-01'
>>> nod_uploadkey("USK@foo,moo,goo/WebOfTrust/0", own=True, da... | 5,311,825 |
def is_struct(struct):
""" Checks if the message is a data structure or an rpc
request/response"""
return (not struct.name.endswith("Request") and
not struct.name.endswith("Response")) | 5,311,826 |
def tcp_nodelay(transport, value):
"""
Sets or removes tcp nodelay socket option to the given transport's socket if applicable.
Parameters
----------
transport : `Any`
Asynchronous transport implementation.
value : `bool`
Value to set tcp nodelay to.
"""
socket = tra... | 5,311,827 |
def relative_round(value, relative_digits):
"""Rounds to a given relative precision"""
if isinstance(value, tuple):
return tuple((relative_round(x, relative_digits) for x in value))
if value == 0 or isinstance(value, str) or np.isnan(value) or np.isinf(value):
return value
value_preci... | 5,311,828 |
def wind_stress(expts=[]):
"""
Plot zonally averaged wind stress.
Parameters
----------
expts : str or list of str
Experiment name(s).
"""
if not isinstance(expts, list):
expts = [expts]
# computing
results = []
for expt in tqdm_notebook(expts, leave=False, des... | 5,311,829 |
def get_pypi_proxy():
"""Returns a RPC ServerProxy object pointing to the PyPI RPC
URL.
:rtype: xmlrpclib.ServerProxy
:return: the RPC ServerProxy to PyPI repository.
"""
return xmlrpc.client.ServerProxy(PYPI_XMLRPC) | 5,311,830 |
def replace_labels(code):
"""
Replaces free labels in `code` with integers, and accordingly any label call / branch.
For example, code:
('BRANCH', 'L0')
('LABEL', '2+')
('1+',)
('EXIT',)
('LABEL', 'L0')
returns:
('BRANCH', 1)
('LABEL', 0)
... | 5,311,831 |
def read_tarfile_csv(path: Union[str, Path], inner_path: str, sep: str = "\t", **kwargs):
"""Read an inner CSV file from a tar archive.
:param path: The path to the tar archive
:param inner_path: The path inside the tar archive to the dataframe
:param sep: The separator in the dataframe. Overrides Pand... | 5,311,832 |
def hasReturnType(matcher):
"""Match a function/method with a specified return type
>>> from glud import *
>>> config = '''
... class X {};
... X u();
... int v();
... '''
>>> m = functionDecl(hasReturnType(builtinType()))
>>> for c in walk(m, parse_string(config).cursor):
... ... | 5,311,833 |
def main():
""" Parse arguments, load key from disk and call either in_toto_record_start
or in_toto_record_stop. """
parser = argparse.ArgumentParser(
description="Starts or stops link metadata recording")
subparsers = parser.add_subparsers(dest="command")
subparser_start = subparsers.add_parser('star... | 5,311,834 |
def setup_aws_creds(user, private_key, ip):
"""AWS 크레덴셜 설치."""
cmds = [
'mkdir -p ~/.aws',
'cd ~/.aws',
'echo [default] > credentials',
'echo [default] > config'
]
ak, sk, dr = get_aws_config()
cmd = 'echo "aws_access_key_id = {}" >> credentials'.format(ak)
cmds.... | 5,311,835 |
def calc_path(filename):
"""Calculate a filepath based off of current file"""
logger.info("calc_path filename: %s", filename)
if filename is None:
return None
filepath = Path(filename)
if not filepath.is_absolute():
filepath = Path(__file__, "..", filepath)
return filepath.resolv... | 5,311,836 |
def get_hash_command():
"""
Get hash reputation and classification.
"""
# Init main vars
headers = ['Hash', 'Rank', 'ClassificationSource', 'Classification']
# Get arguments
hash_ = demisto.args().get('hash')
type_ = get_hash_type(hash_)
if type_ == 'Unknown':
return_error('E... | 5,311,837 |
def get_enum_map(mri, name):
""" Returns enum value to name and name to enum value map.
@param mri mri instance
@param name name of enum """
ret = {}
tdm = mri.engine.tdm
n = len(name) + 1
roles = tdm.getByHierarchicalName(name)
constants = roles.getConstants()
for c... | 5,311,838 |
def CreateWebsList(AssetInfo, TimePause, TimesFetch):
""" Get web pages """
AssetTickers = list(AssetInfo.keys())
# Create a linked list for every asset
WebsLists = dict()
for s in AssetTickers:
WebsLists[s] = WebLinkedList.WebList()
# Start crawling
for t in range(TimesFetch):
... | 5,311,839 |
def spatial_filter(x, y, z, dx, dy, sigma=3.0):
"""
des: outlier filtering within the defined spatial region (dx * dy).
arg:
x, y: coord_x and coord_y (m)
z: value
dx, dy: resolution in x (m) and y (m)
n_sigma: cut-off value
thres: max absolute value of data
retu... | 5,311,840 |
def save_jit(output_name, run, model):
""" Export trained model with JIT
Args:
output_name (string): output filename
model (ResNet): neural net to generate predictions
run (int): cycle count
"""
model = model.eval()
model.train(False)
example = torch.rand(1, 3, 128, 128).cud... | 5,311,841 |
def _log_add(x, y):
"""
Add x and y in log space.
"""
if x == -np.inf:
return y
if y == -np.inf:
return x
return np.max([x, y]) + np.log1p(np.exp(-abs(x - y))) | 5,311,842 |
def test_get_access_level_from_id(app):
""" Check members' access level according to the database. """
with app.app_context():
db = get_db()
cursor = db.cursor()
assert utils.get_access_level_from_id(1, cursor) == 255
assert utils.get_access_level_from_id(2, cursor) == 190 | 5,311,843 |
def query_by_name(first, last, jurisdictions=None, timeout=None):
"""Query jurisdictions with an inmate name.
:param first_name: Inmate first name to search.
:type first_name: str
:param last_name: Inmate last name to search.
:type last_name: str
:param jurisdictions: List of jurisdictions to... | 5,311,844 |
def test_basic(ray_start_with_dashboard):
"""Dashboard test that starts a Ray cluster with a dashboard server running,
then hits the dashboard API and asserts that it receives sensible data."""
assert (wait_until_server_available(ray_start_with_dashboard["webui_url"])
is True)
address_info =... | 5,311,845 |
def get_os_info(values=None):
"""Get operating system info.
This is designed to work with Raspbian / Raspberry Pi OS
Args:
values (list): List of values to print.
Supported values are:
'PRETTY_NAME',
'NAME',
'VERSION_ID',
... | 5,311,846 |
def arc_length_3point(A, B, C):
""" Returns length of arc defined by 3 points, A, B and C; B is the point in between """
### Meticulously transcribed from
# https://develop.openfoam.com/Development/openfoam/-/blob/master/src/mesh/blockMesh/blockEdges/arcEdge/arcEdge.C
p1 = np.asarray(A)
p2 = np.asa... | 5,311,847 |
def test_mapping_parse(content):
"""Content that can be parsed to a mapping"""
stream = StringIO(initial_value=content)
Mapping.load(stream) | 5,311,848 |
def format_checker(fmt: str, fmt_list: list = GRAPH_FORMATS) -> None:
"""Check formats."""
if fmt not in fmt_list:
raise ValueError(
f'The selected sep {fmt} is not valid. Please ensure you use one of the following formats: '
f'{fmt_list}'
) | 5,311,849 |
def connect_bucket(cfg):
""" TODO: do we really need this? """
return (
cfg.bucket,
boto3.client('s3')
) | 5,311,850 |
def dsymv(alpha, A, X, beta, Y, Uplo=CblasLower):
"""
returns y'
This function computes the matrix-vector product and
sum \M{y' = S{alpha} A x + S{beta} y} for the symmetric matrix A. Since the
matrix A is symmetric only its upper half or lower half need to be
stored. When Uplo is CblasUpper th... | 5,311,851 |
def doctest_dump():
"""Test that profiling can save the stats in a file.
Create a temporary file
>>> import tempfile
>>> tf = tempfile.mkstemp()
Now create some stats in that file
>>> @profilehooks.profile(filename=tf[1])
... def f():
... pass
>>> run_... | 5,311,852 |
def view_categories(request):
"""View category posts view"""
categories = Category.objects.all()
ret_dict = {
'categories': categories,
'view_rss': 'rss/categories.xml',
'current_nav': 'categories',
}
ret_dict = __append_common_vars(request, ret_dict)
return render(requ... | 5,311,853 |
def test_python_functions():
"""
This is useful to ensure nothing has changed
"""
assert quint(1) == 1
assert quint(2) == 32
assert double(2) == 4
assert triple(2) == 6
assert triple_naive(5) == 15
assert triple_mul(6) == 18
assert unit(2) == 1
assert parent(2) == 243 | 5,311,854 |
def zfill_to_collection_size(index: int, collection_size: int) -> str:
"""
Prepends amount of zeroes required for indexes to be string-sortable in terms of given collection size.
Examples:
for 10 items prepends up to 1 zero: 1 -> "01", 10 -> "10"
for 100 items prepends up to 2 zeroes: 7 -> "... | 5,311,855 |
def parse_fname_meta(file):
"""
Takes a file name and separates out any/all metadata of interest
(Serial ID, Source, NN Tags)
Decisions to be made: How strict to be on naming?
This should be in the config file...
FOR NOW: Only Impose 3 Rules:
* UNTIL FIRST "_" is Serial ID (Expect but do... | 5,311,856 |
def print_usage():
"""Prints the usage message"""
print "Censor a document\n"
print "Use: python censor.py x NUM_DOCS s t p heuristic flag\n"
print "Arguments:"
print "\tif Greedy, x = index of the target document to censor (0 <= x < NUM_DOCS)\n\tif KillNodes, x = percentage of nodes to be shut down... | 5,311,857 |
def _make_grid_spec(storage) -> GridSpec:
"""Make a grid spec based on a storage spec."""
assert 'tile_size' in storage
crs = CRS(storage['crs'])
return GridSpec(crs=crs,
tile_size=[storage['tile_size'][dim] for dim in crs.dimensions],
resolution=[storage['resolu... | 5,311,858 |
async def edit_group_information(
group_id, query: UpdateGroupQuery, db: Session = Depends(get_db)
) -> None:
"""
Update group details.
**Potential error codes in response:**
* `601`: if the group does not exist,
* `250`: if an unknown error occurred.
"""
try:
await environ.env.... | 5,311,859 |
def gaussian_2d_cylind(shape, center, resolution, scale, sigma=1, min_range_rho=0):
"""Generate gaussian map.
Args:
shape (list[int]): Shape of the map. [y, x]
sigma (float): Sigma to generate gaussian map.
Defaults to 1.
Returns:
np.ndarray: Generated gaussian map. [rh... | 5,311,860 |
async def create_specific_guid(guid: str, data: GuidIn):
"""
Create a record w/ a guid specified in the path.
Also cleans up expired records & caches the new record.
Raises an exception if you try to overwrite an existing record.
"""
try:
guid = validate_guid(guid)
except ValueErro... | 5,311,861 |
def partition(predicate, values):
"""
Splits the values into two sets, based on the return value of the function
(True/False). e.g.:
>>> partition(lambda x: x > 3, range(5))
[0, 1, 2, 3], [4]
"""
results = ([], [])
for item in values:
results[predicate(item)].append(item... | 5,311,862 |
def get_colors(color='ALL'):
""" get color palette as a dictionary """
if color == 'ALL':
return color_dict['palette']
return color_dict['palette'][color] | 5,311,863 |
def avoid_line_too_long(pretty_html_text):
"""
detect any line with more than 998 characters
"""
lines = pretty_html_text.split('\n')
new_lines = []
for line in lines:
line_length = len(line)
if line_length >= 998:
# Cut the line in several parts of 900 characters
... | 5,311,864 |
def tmul_(a: T.Scalar, x: T.FloatTensor) -> T.FloatTensor:
"""
Elementwise multiplication of tensor x by scalar a.
Notes:
Modifes x in place
Args:
x: A tensor.
a: scalar.
Returns:
tensor: Elementwise a * x.
"""
x.mul_(a) | 5,311,865 |
def stringify_tags(tags, human_readable=False):
"""
格式化 Beancount 标签列表
"""
if human_readable:
if len(tags) == 0:
return _('无')
return ', '.join(f'#{t}' for t in tags)
return ' '.join(f'#{t}' for t in tags) | 5,311,866 |
def is_friday():
"""判断是否是周五"""
return datetime.date.today().weekday() == 4 | 5,311,867 |
def _parse_exclude_images_commands(commands, experiments, reflections):
"""Parse a list of list of command line options.
e.g. commands = [['1:101:200'], ['0:201:300']]
or commands = [[101:200]] allowable for a single experiment.
builds and returns a list of tuples (exp_id, (start, stop))
"""
... | 5,311,868 |
def test_kql_connect_kql_exceptions(get_ipython):
"""Check loaded true."""
get_ipython.return_value = _MockIPython()
kql_driver = KqlDriver()
with pytest.raises(MsticpyKqlConnectionError) as mp_ex:
kql_driver.connect(connection_str="la://connection+KqlErrorUnk")
check.is_in("Kql response er... | 5,311,869 |
def thomson_spec_series(eleckineng, photeng, T, as_pairs=False):
""" Thomson ICS spectrum of secondary photons by series method.
Parameters
----------
eleckineng : ndarray
Incoming electron kinetic energy.
photeng : ndarray
Outgoing photon energy.
T : float
CMB tempera... | 5,311,870 |
def voxel_grid_sampling(coords: np.ndarray, voxel_size: float) -> np.ndarray:
"""Voxel grid sampling
Args:
coords: coords (N, C)
voxel_size: voxel grid size
Returns:
samples: sample coords (M, C)
"""
N, C = coords.shape
# get voxel indices.
indices_float = coor... | 5,311,871 |
def rosnode_listnodes(namespace=None, list_uri=False, list_all=False):
"""
Print list of all ROS nodes to screen.
@param namespace: namespace to scope list to
@type namespace: str
@param list_uri: print uris of nodes instead of names
@type list_uri: bool
@param list_all: print node names ... | 5,311,872 |
def compute_skewness(data):
""" Skewness of the data (per channel).
Parameters
----------
data : ndarray, shape (n_channels, n_times)
Returns
-------
output : ndarray, shape (n_channels,)
"""
ndim = data.ndim
return stats.skew(data, axis=ndim - 1) | 5,311,873 |
def piconget(pid, mnpicon, picndir, piconslug, hxclr1, hxclr2, mangle=None,
colrful=False, brite=False):
""" Function for fetching and manipulating picons """
if direxists(picndir):
urlbase = "http://images.pluto.tv/channels/"
if mnpicon:
urlend = 'solidLogoPNG.png'
... | 5,311,874 |
def rfft(x, n=None, axis=-1, norm=None, overwrite_x=False, *, plan=None):
"""Compute the one-dimensional FFT for real input.
The returned array contains the positive frequency components of the
corresponding :func:`fft`, up to and including the Nyquist frequency.
Args:
x (cupy.ndarray): Array ... | 5,311,875 |
def copy_from_table_row(row, clobber=False):
"""Perform a single copy operation using information from a single row of a copy_table.
Args:
param1 (type): The first parameter.
param2 (type): The second parameter.
Returns:
Path: destination path returned by respective copy function.
... | 5,311,876 |
def mustache(template, partials=None, **kwargs):
"""Usage:
{{ mustache('path/to/whatever.mustache', key=value, key1=value1.. keyn=valuen) }}
or, with partials
{{ mustache('path/to/whatever.mustache', partials={'partial_name': 'path/to/partial.mustache'}, \
key1=value1... | 5,311,877 |
def enable_v2_dtype_behavior():
"""Enable the V2 dtype behavior for Keras layers.
By default, the V2 dtype behavior is enabled in TensorFlow 2.
When enabled, the dtype of Keras layers defaults to floatx (which is typically
float32) instead of None. In addition, layers will automatically cast
floating-point ... | 5,311,878 |
def from_protos(
proto_list: List[american_option_pb2.AmericanEquityOption],
american_option_config: "AmericanOptionConfig" = None
) -> Dict[str, Any]:
"""Creates a dictionary of preprocessed swap data."""
prepare_fras = {}
for am_option_proto in proto_list:
short_position = am_option_proto.short_... | 5,311,879 |
def proxy_capture(self, link_guid, user_agent=''):
"""
start warcprox process. Warcprox is a MITM proxy server and needs to be running
before, during and after phantomjs gets a screenshot.
Create an image from the supplied URL, write it to disk and update our asset model with the path.
The heavy l... | 5,311,880 |
def create_operator(key, value, context):
"""
Create operator instance along with its arguments
Args:
key:
operator name
value:
operator arguments
context (Dict):
Python dictionary holding all imported modules
Returns:
Tasrif pipeline... | 5,311,881 |
def get_combined_segmentation_points(ts, loc_df, time_query, filters_in_df, filter_methods):
"""
We can have mixed filters in a particular time range for multiple reasons.
a) user switches phones from one platform to another
b) user signs in simultaneously to phones on both platforms
case (b) is not... | 5,311,882 |
def is_experiment(names):
"""[Check names follows experiment rules]
Args:
names ([str]): [names founds in the path]
Returns:
[type]: [True or false ]
"""
regexps = get_regular_expressions(os.path.join(dir_rules, 'experiment_rules.json'))
conditions = []
if type(names) == s... | 5,311,883 |
def est_positif_non_nul(valeur: any):
"""Indique si la valeur fournie est un entier positif non nul."""
if valeur is not None:
if isinstance(valeur, int):
return valeur > 0
if isinstance(valeur, float) and valeur.is_integer():
return valeur > 0
return False | 5,311,884 |
def cmd_issuer_hash(cert):
"""Returns hash of certificate issuer.
"""
return cert.get_issuer().hash() | 5,311,885 |
def linearly_enhancing_details(alphas, numOfScales=2, window_scale=3):
"""
:param alphas: the high frequency component of the image calculated with Shearlet transformation.
i * j * (kl) array, where i, j are equal to the height and width of the original image, kl is
... | 5,311,886 |
def strip_c(buf, dia):
"""This is the ugliest python function I've ever written and I'm ashamed
that it exists. Can you tell that it's an almost line for line translation
of a C program? The two embedded functions were macros.
"""
pos = bytes(buf, 'ascii', errors='replace')
single_q = double_q =... | 5,311,887 |
def map_bool(to_bool) -> bool:
"""Maps value to boolean from a string.
Parameters
----------
to_bool: str
Value to be converted to boolean.
Returns
-------
mapped_bool: bool
Boolean value converted from string.
Example
-------
>>> boolean_string = "True" # can ... | 5,311,888 |
def _format_koff_text(properties, timeunit):
"""Format text for koff plot. """
tu = "ns" if timeunit == "ns" else r"$\mu$s"
text = "{:18s} = {:.3f} {:2s}$^{{-1}} $\n".format("$k_{{off1}}$", properties["ks"][0], tu)
text += "{:18s} = {:.3f} {:2s}$^{{-1}} $\n".format("$k_{{off2}}$", properties["ks"][1], t... | 5,311,889 |
def hello():
"""Print "Hello World" and return None"""
print("Hello World") | 5,311,890 |
def make_volume_svmbir(
fn, *, path=".", center_offset=None, T=0.1, p=1.1, sharpness=4.0, snr_db=20.0, max_iterations=500
):
"""
Performs reconstruction using ``svmbir`` algorithm. The data is loaded from a single
HDF5 file. The results are saved to the same file.
Parameters
----------
... | 5,311,891 |
def annotate_heatmap(im, data=None, valfmt="{x:.2f}",
textcolors=("black", "white"),
threshold=None, **textkw):
"""
A function to annotate a heatmap.
Parameters
----------
im
The AxesImage to be labeled.
data
Data used to annotate. If No... | 5,311,892 |
def fmt_val(val, shorten=True):
"""Format a value for inclusion in an
informative text string.
"""
val = repr(val)
max = 50
if shorten:
if len(val) > max:
close = val[-1]
val = val[0:max-4] + "..."
if close in (">", "'", '"', ']', '}', ')'):
... | 5,311,893 |
def start_nodes(aliases: List[str] = [],
ssh_config_file: str = DEFAULT_CHAOS_SSH_CONFIG_FILE) -> bool:
"""
Start indy-node service on a list of nodes.
:param aliases: A list of nodes. Required.
:type aliases: List[str]
:param ssh_config_file: The relative or absolute path to the SS... | 5,311,894 |
def get_rms_radius(ts):
"""
Calculate the RMS radius at the different iterations of the timeseries.
"""
r = []
for iteration in ts.iterations:
x, w = ts.get_particle( ['x', 'w'], iteration=iteration )
r.append( np.sqrt( np.average( x**2, weights=w ) ) )
return( 1.e-6*np.array(r) ... | 5,311,895 |
def encode_function_data(function=None, *args):
"""Encodes the function call so we can work with an initializer.
Args:
initializer ([brownie.network.contract.ContractTx], optional):
The initializer function we want to call. Example: `box.store`.
Defaults to None.
args (Any, opt... | 5,311,896 |
def analyzeTarget(obj, targetPath):
"""
This function is used (more during the development cycle than in the
runtime application) to analyze the difference between the vertex positions of
a mesh object and those recorded in a file on disk.
The result is a representation of each vertex displa... | 5,311,897 |
def generate_ranklist(data, rerank_lists):
"""
Create a reranked lists based on the data and rerank documents ids.
Args:
data: (Raw_data) the dataset that contains the raw data
rerank_lists: (list<list<int>>) a list of rerank list in which each
el... | 5,311,898 |
def is_merge_brances_has_written(from_branch, to_branch, merge_msg="auto merge"):
"""
returns True, if merge is successful and it has modified some untracked_files
return False, if there is nothing to merge
"""
for line in git("merge", from_branch, to_branch, "-m", merge_msg, _iter=True, _tty_out=F... | 5,311,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.