content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def to_inport_xml(table, variables, project):
"""
Generate NMFS/FIS InPort XML Format document for DWSupport table
Document represents an Entity Insert if no table
inport_entity_id is available. If an inport_entity_id is available
the document will represent an Entity Update.
per: https://inpor... | ff954673f63643baf3254b649e5653d1ee5f467d | 3,614,500 |
def PolsDeath(t):
"""Number of policies: Death override"""
return (PolsIF_Beg1(t) * asmp.BaseMortRate(AttAge(t))
* asmp.MortFactor(t) * MortRateFactor(t)) | 4bc7b09f78c071fea8cf26e620987b5bc0af23d9 | 3,614,501 |
import utool as ut
def unflat_vecmap(func, unflat_items, vectorized=False, **kwargs):
"""unflat map for vectorized functions"""
# First flatten the list, and remember the original dimensions
flat_items, reverse_list = ut.invertible_flatten2(unflat_items)
# Then preform the lookup / implicit mapping
... | e056887fd0ba31490814d8dc056ff692dcf8ddd7 | 3,614,502 |
def hrs_process(image_name, ampsec=[], oscansec=[], trimsec=[],
masterbias=None, error=False, bad_pixel_mask=None, flip=False,
rdnoise=None, oscan_median=True, oscan_model=None):
"""Processing required for HRS observations. If the images have multiple
amps, then this will pro... | 8357ae5a55bdeb6fd5da47214397274468a75be7 | 3,614,503 |
def label_allocation_method(data):
"""Add ``allocation method`` attribute to each dataset with the chosen allocation function."""
for ds in data:
ds['allocation method'] = choose_allocation_method(ds)
detailed.info({
'ds': ds,
'message': ds['allocation method'],
... | bf8bfe8aac9060f95c25799c3b7b8208dc0f35f4 | 3,614,504 |
def get_event(event_id):
"""
Get event by event_id
"""
for ec in (ActiveEvent, ArchivedEvent, FailedEvent):
e = ec.objects.filter(id=event_id).first()
if e:
return e
return None | 5d72d18287ee29b44587b6a822f74fc93138a1d0 | 3,614,505 |
def testFloat(val):
"""
Test value for float.
Used to detect use of variables, strings and none types, which cannot be checked.
"""
try:
return type(float(val)) == float
except Exception:
return False | 19f3eac980b4489b7d14b1f994002a887f063ac7 | 3,614,506 |
def _mpl_sp_kw_split(kwargs):
"""
Process keyword arguments supplied to a matplotlib plot function.
Returns
--------
:class:`tuple` ( :class:`dict`, :class:`dict` )
"""
sctr_kwargs = scatterkwargs(kwargs)
# c kwarg is first priority, if it isn't present, use the color arg
if sctr_kw... | 9797163f6ee2cf620552fef5bdca3d902d53f8fb | 3,614,507 |
import subprocess
import errno
import re
def disassemble_shcbin(binfile, objdumpcmd):
"""Extract a disassembly dump of a compiled shellcode binary file
Return a list of (bytes, instruction) tuples
"""
# Disassemble the .shcode code section
cmd = [objdumpcmd, '-d', '-j', '.shcode', binfile]
try... | 3411340910324e7cbeedba6f68c7024bc462f4f6 | 3,614,508 |
import re
def get_videos_page_url(url):
"""
Get a valid videos page URL from a YouTube channel/user URL. See
`Understand Your Channel URLs`_.
Args:
url (str): URL for a YouTube channel or user. The end of the URL may
contain extra parameters or a subpath to a different page on the... | 5fe32971c7b043e2bf39fa58c13014d7b980774c | 3,614,509 |
def Xception65(params):
"""
Construct Xception network modified in DeepLabv3+
"""
return Xception(params) | d5e98b25c8e2de2aa469451d2152a41b09791f03 | 3,614,510 |
def generate_domain_csv(request):
"""
Generate a CSV file of the Domain information
:param request: The request for this CSV.
:type request: :class:`django.http.HttpRequest`
:returns: :class:`django.http.HttpResponse`
"""
response = csv_export(request,Domain)
return response | 9d8a079dce5e267db5c23dab078e8481ee13fcbb | 3,614,511 |
import select
def truthy(iterable):
"""Returns a iterable with only the truthy values.
Example::
truthy((0, 1, 2, False, None, True)) -> (1, 2, True)
:param iterable:
Iterable sequence.
:returns:
Iterable with truthy values.
"""
return select(bool, iterable) | b0ad155e0f53e02661abd7a96e524aa58b9b3f48 | 3,614,512 |
import fnmatch
def get_file_list_match(file_list, match_string):
"""Get filenames containing the given match_string."""
match_list = []
for fid in file_list:
fid = str(fid) # MW: To also allow fid to be of type pathlib.Path
if fnmatch(fid, match_string):
match_list.append(fid... | 88d728583517213e401a4cb2cc8186b80eeebb5e | 3,614,513 |
def alpha(S,T,P=0):
"""Compute thermal expansion coefficient
Usage: alpha(S, T, [P])
Input:
S = Salinity, [PSS-78]
T = Temperature, [�C]
P = Pressure, [dbar]
P is optional, with a default value = zero
Output:
Thermal expansion coefficient, [1/K]
"""
... | cd1aedb1eef3ae43c5d0ffd2d28738fb6ffe3c47 | 3,614,514 |
from typing import Dict
from typing import Optional
import logging
def iterate_value_v_pi(
agent: MdpAgent,
environment: ModelBasedMdpEnvironment,
theta: float,
evaluation_iterations_per_improvement: int,
update_in_place: bool
) -> Dict[MdpState, float]:
"""
Run dynamic... | 8ebb94ab8f38900c467b40806bd17ebec25d3ca1 | 3,614,515 |
import logging
def get_first_oembed_response(oembed_urls, max_width=None, max_height=None):
"""Fetches an OEmbed response from a list of OEmbed URLs. The URLs will be
tried in turn until one returns successfully.
:param oembed_urls: an iterable of OEmbed URLs.
:param max_width: (optional) the maximu... | a83f1289dfac0a6a03daf07d49a69fdfdda3128d | 3,614,516 |
def display():
"""Build and render the status page."""
build_key = current_app.bert_e.settings.build_key
output_mode = request.args.get('output')
if output_mode is None:
output_mode = 'html'
current_job = current_app.bert_e.status.get('current job', None)
merged_prs = current_app.bert_e... | 296bcfe3bc3c2724388ccf86453afa518a352b11 | 3,614,517 |
import os
import json
def load_genre(metadata_path):
"""Load beatport_key genre data from a file
Args:
metadata_path (str): path to metadata annotation file
Returns:
(dict): with the list of strings with genres ['genres'] and list of strings with sub-genres ['sub_genres']
"""
if me... | a0c80a37360ddaa0390ad496cc2408e71df59df1 | 3,614,518 |
def transaction(callback, retry=None, entity_group=None, **ctx_options):
"""Run a callback in a transaction.
Args:
callback: A function or tasklet to be called.
retry: Optional retry count (keyword only; default set by
ndb.context.Context.transaction()).
entity_group: Optional root key to use as ... | b7275cd32833ca97dd6f00bdfbdef3b31370d5fe | 3,614,519 |
def _run_mailbox_simulator(address):
"""Runs the AWS SES mailbox-simulator see:
docs.aws.amazon.com/ses/latest/DeveloperGuide/mailbox-simulator.html
"""
options['recipients'] = [address]
return send_email(**options) | 8f0064d98674c72734192c9b95f1de9a0f86c3af | 3,614,520 |
def outliers(input):
"""
Extract index and values of outliers in input
Works with NaN values
:param input: vector data (signal)
:return: index, (whisker inf, sup)
"""
Quart = np.nanpercentile(input, [25, 75]) # 1er et 3ème quartile
IQuart = Quart[1] - Quart[0] # interquartil... | 6118b2f829d070f54da4de9a43f95181b8db56c8 | 3,614,521 |
import re
import regex
def credits_in_subject(line, creditsInMatch):
"""
Parse string of type "x credits in/at/of subject"
Attributes
---------
line: str
pre-requisite string
creditMatch: str
used in regex expression to find if "x credits in/at/of subject" pattern is matched
... | af08eef1fde70bea540e57f17ce924edad40ef31 | 3,614,522 |
def choose_backup(backup_list, recovery_target_time):
""" pick up the latest backup file starting before time recovery_target_time"""
match_timestamp = match = None
for backup in backup_list:
last_modified = parse(backup['last_modified'])
if last_modified < recovery_target_time:
... | 1c2609033b92f1b03fa0da568232d8a14e320076 | 3,614,523 |
def get_reverse(sequence):
"""Reverse orientation of `sequence`.
Returns a string with `sequence` in the reverse order.
If `sequence` is empty, an empty string is returned.
"""
#Convert all rna_sequence to upper case:
sequence=sequence.upper()
#reverse rna sequence:
rna_rev_list=sequen... | a3816b66ad6e6f8a1bb963bc13bf4c656b3d9c79 | 3,614,524 |
import os
def is_gnome():
"""
Check if current DE is GNOME or not.
On Ubuntu 20.04, $XDG_CURRENT_DESKTOP = ubuntu:GNOME
On Fedora 34, $XDG_CURRENT_DESKTOP = GNOME
Hence we do the detection by looking for the word "gnome"
"""
return "gnome" in os.environ["XDG_CURRENT_DESKTOP"].lower() | 730e1b4468194cd15a716eed0aad4e72812cfb70 | 3,614,525 |
async def async_unload_entry(
hass: core.HomeAssistant, entry: config_entries.ConfigEntry
):
"""Unload a config entry."""
if entry.data[CONF_KEY] is not None:
platforms = GATEWAY_PLATFORMS
else:
platforms = GATEWAY_PLATFORMS_NO_KEY
unload_ok = await hass.config_entries.async_unload_... | c765f95a9b8b7501f6a086f090198469c8e73a6f | 3,614,526 |
import torch
def nll_catogrical(preds, target, add_const=False):
"""compute the loglikelihood of discrete variables"""
total_loss = 0
for node_size in range(preds.size(1)):
total_loss += -(
torch.log(preds[:, node_size, target[:, node_size].long()])
* target[:, node_size]
... | 2343e2adff44c89e73c35cacdcc55180b8029611 | 3,614,527 |
def robustfit(
X, y, weight_function="bisquare", tune=None, rcond=1, tol=0.001, maxit=50
):
"""
Multiple linear regression via iteratively reweighted least squares.
Parameters
----------
X : ndarray (n, p)
MLR model with `p` parameters (independent variables) at `n` times
y : ndarra... | f58646f99fadba53785ca275e568b1071527e009 | 3,614,528 |
def to_xhr_response(request, non_xhr_result, form):
"""
Return an XHR response for the given ``form``, or ``non_xhr_result``.
If the given ``request`` is an XMLHttpRequest then return an XHR form
submission response for the given form (contains only the ``<form>``
element as an HTML snippet, not th... | e32c94ecb3a5ce12c81ea312647b8bf527007bfc | 3,614,529 |
def tail_vertical(vehicle, wing, rudder_fraction=0.25):
""" Calculate the weight of the vertical fin of an aircraft without the weight of
the rudder and then calculate the weight of the rudder
Assumptions:
Vertical tail weight is the weight of the vertical fin without the rudder weight.
... | c3d516aa1d38d7062e0d2c7e5508822d41067934 | 3,614,530 |
def concat_recarrays(arr):
""" Concatenate two or more record arrays.
This increases the string field size to accommodate strings in all
the arrays, converting to a new dtype where necessary. The
original input arrays are not changed.
Parameters
----------
arr : sequence of Numpy record/st... | b11b9770f4a85dd526efa356a823926708aaa593 | 3,614,531 |
from typing import List
from pathlib import Path
def get_config_files(
path: str,
) -> List[ConfigFile]:
"""
:param path: relative path to directory with files
:return:
"""
config_files: List[ConfigFile] = []
abs_path: Path = Path(path)
files: List[Path] = [abs_path.joinpath(f) for f ... | 6a38bf525664d0c432511ff240e5d90cc75af9ad | 3,614,532 |
def seasonStats(personId,type = 'gameLog',group = 'hitting'):
"""Returns a player's season/career stats and wether it's hitting or pitching or fielding
fix and improve this later"""
#playerInfo = get('people', {'personIds':personId})
teamStats = get('person',{ 'ver':'v1' , 'personId':personId,'h... | e86321480523657fed952660843393160a4b1b15 | 3,614,533 |
def ensemble_address():
"""Zookeeper ensemble address
:return:
"""
zk_port = __pillar__['zookeeper']['port']
return '{0}:{1}'.format(':{0},'.format(zk_port).join(hosts()), zk_port) | 39b4ff2b1c46ad964cdd0a61168870dd902b5873 | 3,614,534 |
def STEL_methods(CASRN):
"""Return all methods available to obtain STEL for the desired chemical.
Parameters
----------
CASRN : str
CASRN, [-]
Returns
-------
methods : list[str]
Methods which can be used to obtain STEL with the given inputs.
See Also
--------
... | c92e7b5c836bb788c83b24a006fc2ee0d06f2795 | 3,614,535 |
def optional(converter):
"""
A converter that allows an attribute to be optional. An optional attribute
is one which can be set to ``None``.
:param callable converter: the converter that is used for non-``None``
values.
.. versionadded:: 17.1.0
"""
def optional_converter(val):
... | 128042c7a95bb91c665ab6ac0f6771e4a72632ed | 3,614,536 |
import pickle
def get_challenge_by_channel_id(database, challenge_channel_id):
"""
Fetch a Challenge object in the database with a given channel ID
Return the matching Challenge object if found, or None otherwise.
"""
ctfs = pickle.load(open(database, "rb"))
for ctf in ctfs:
for challe... | 9ae3fc3519b61c6e9a1abceb20b8882e2e29ca48 | 3,614,537 |
def get_action(action):
"""Get action according to the action."""
return {
'create': create_issue,
'list': list_issues
}.get(action, create_issue) | 6358bced9840cc681bf16bbc5277a718e161041f | 3,614,538 |
def combine_orderings(ordering_1, ordering_2):
"""
Function to combine two orderings.
Example 1:
ordering_1 = ((7,2), 'X')
ordering_2 = ((6,5),)
combined_ordering = ((7,2),(6,5))
Example 2:
ordering_1 = ((7,2), 'X', 'X')
ordering_2 = ((6,5), 'X')
combined_ordering = ((7,2),(6,5... | c5faed01c387a6c958dfed324da5bfa1bb2b06bd | 3,614,539 |
def are_counts_even(env):
""" From dcicutils - to be ported over in this form at some point. """
try:
totals = get_metadata('/counts', ff_env=env)['db_es_total'].split()
except Exception:
# if we cant get counts page assume its False
return False, {}
# example value of split tot... | 91d9809c88963733f1b47011d2344bf8909c9821 | 3,614,540 |
def whoami_fn(request):
"""
Test-route to validate token and nickname from headers.
:return: welcome-dict
"""
nickname = request.validated["user"].nickname
return {
"status": "ok",
"nickname": nickname,
"message": "Hello " + nickname + ", nice to meet you."
} | c8d23a20a6d4f56832e45739ffb81d3aca398bed | 3,614,541 |
def sort_points_on_line(point_list):
""" Sorts points by distance on a line, taking the
two first points as the reference direction. """
point_list = [Coord(p[0], p[1]) for p in point_list]
p0 = point_list[0]
dx = point_list[1][0] - point_list[0][0]
dy = point_list[1][1] - point_list[0][1]
p... | f0ff26ecf040ce9292a4862db575350082555edf | 3,614,542 |
import json
def save_tracks(input_tracks, out_filename):
"""Saves smoothed tracks to the specified file.
:param input_tracks: List of input tracks
:param out_filename: File to save tracks
"""
def _convert_track(input_track):
"""Converts event from internal representation to dict format
... | 884d2e1906f53c4dc66f21536d7e666920016ccf | 3,614,543 |
def new(**kwargs):
"""Return a new instance of a BLAKE2s hash object.
:Keywords:
data : byte string
The very first chunk of the message to hash.
It is equivalent to an early call to `BLAKE2s_Hash.update()`.
digest_bytes : integer
The size of the digest, in bytes (1 to 32).
... | 6b4ac2d58dd501d3759610531808cbe2bd26c846 | 3,614,544 |
def DTKN(token, wsL='', wsR=r'\s*'):
"""Syntactic Sugar for 'Series(Whitespace(wsL), DropText(token), Whitespace(wsR))'"""
return withWS(lambda: Drop(Text(token)), wsL, wsR) | b4b2877ee17667195efb8872800bdbf37630f4e6 | 3,614,545 |
def remove_ngram(sentence, ngram_to_remove, n):
"""Removes all occurrences of an n-gram from a sentence.
:param sentence: The sentence.
:param ngram_to_remove: The n-gram that will be removed from the sentence.
:param n: The n in n-gram.
"""
# If the number of words in the sentence is < than th... | 1f4ef092d7b831a6b355df8aa6fae774cf6e68ea | 3,614,546 |
def prepare_new_session():
"""
Prepares a new session for managing a user's interactions.
:return: Session ID as a string
"""
return session.create_new_session() | 551a1760cc086c501ec20be4cc5ad69d75df89d5 | 3,614,547 |
def verificar(palavra, entrada):
"""
Confere se as tentativas do usuário estão corretas conforme a palavra sorteada.
Se não estiver, retorna à função principal e continua a iteração.
Entrada: palavra, entrada (string, input/string).
Saída: bool.
"""
return palavra == entrada | b1de59f316d3ba63c73979f2e5cc9584a20e291f | 3,614,548 |
def centeredMoment(moments, order):
"""
Compute a single moment of a specific order about the mean (centered)
given moments about the origin (raw).
:param moments: (list) First 'order' raw moments
:param order: (int) The order of the moment to calculate
"""
moment_c = 0 # first centered mo... | 5b0abd5e2212e833f1ae28bd834c11ab6f328c4f | 3,614,549 |
def signal_periodic_impulse(period, phase):
"""Signal generator for periodic pulses
Parameters
----------
period : SignalUserTemplate
singal or constant describing the period in samples at which the pulses are generated
phase : SignalUserTemplate
singal or constant describing the p... | 27a0ca7736f6a5d4aa2a9404713cb0940f33bbac | 3,614,550 |
def qstr(s, validate=True):
"""Return a quoted string after escaping '\' and '"' characters.
When validate is set to True (default), the string must consist only of
7-bit ASCII characters excluding NULL, CR, and LF.
"""
if validate:
s.encode('ascii')
if '\0' in s or '\r' in s or '\n' in s:
raise ValueError... | 2805c2aff61294cafe6719e9a8bd93082d9603df | 3,614,551 |
import random
def random_permutation(iterable, r = None):
"""random_product(iterable, r = None) -> tuple
Arguments:
iterable: An iterable.
r(int): Size of the permutation. If :const:`None` select all elements in
`iterable`.
Returns:
A random element from ``itertools.permutat... | 7e84d33b62786d08443dc5ea2c66ff65ced3070c | 3,614,552 |
def stringToAscii(sequence):
"""sequence is a sequence of characters.
Return the string with the hex representation for each character"""
return "".join("%02x" % ord(c) for c in sequence).upper() | 19f0c5a057c6176cee7e0f6e7ac5e8834ea0d650 | 3,614,553 |
def get_version():
"""
Returns a PEP 386-compliant version number from VERSION.
"""
assert len(VERSION) == 5
assert VERSION[3] in ('alpha', 'beta', 'rc', 'final')
# Now build the two parts of the version number:
# main = X.Y[.Z]
# sub = .devN - for pre-alpha releases
# | {a|b|c... | 1d839b91ef001e6322f0b3273300718de62bd9d9 | 3,614,554 |
def fit_HH_x_single_layer(
damping_data_in_pct,
*,
use_scipy=True,
pop_size=800,
n_gen=100,
lower_bound_power=-4,
upper_bound_power=6,
eta=0.1,
seed=0,
show_fig=False,
verbose=False,
suppress_warnings=True,
parallel=... | 9cc9c869fe2bbb66a6aacfb8452a4c6fcc92f24e | 3,614,555 |
from typing import Tuple
import struct
def get_int(dgram: bytes, start_index: int) -> Tuple[int, int]:
"""Get a 32-bit big-endian two's complement integer from the datagram.
Args:
dgram: A datagram packet.
start_index: An index where the integer starts in the datagram.
Returns:
A tuple... | ee21315063ef7badd4620cd61bf412e57707c0a3 | 3,614,556 |
def language_to_flag(code):
"""Generates css flag class for the language code"""
if code.lower() == 'en':
return 'flag-icon flag-icon-us'
return 'flag-icon flag-icon-' + code.lower() | 8d81d1e1cdac675a6bdf94bb22ac6f45993338db | 3,614,557 |
from typing import Optional
def get_file_id_of_media(message: 'Ubot .Message') -> Optional[str]:
""" get file_id """
file_ = message.audio or message.animation or message.photo \
or message.sticker or message.voice or message.video_note \
or message.video or message.document
if file_:
... | 72f46950bd5d1f52a57e8ec1fad6d7b0162c7e08 | 3,614,558 |
def parse(filepath:str, cpp_args:list):
"""
Parse c source file by pycparser, and return AST object.
"""
ast = parse_file(filepath, use_cpp=True,
cpp_path='gcc',
cpp_args=cpp_args)
return ast | 14b20d0236d8fe5dcff99b53ebcac8bf6cfd0e63 | 3,614,559 |
def make_polynomial_regression_data(n_data=100, degree=2, coefficients=None,
coefficient_scale=3.0, noise=0.1, x_range=(-1.0, 1.0), random_seed=None):
"""
It generates artificial data for linear regression
:param int n_data: Number of generated data
:param int degree: Degree of polynomial
:para... | 5e866f23353a1c74fa3c08db45f635a6f2cfa093 | 3,614,560 |
from typing import List
def add_percentage_value(l:int, to:List[list]) -> List[list]:
"""
counter.most_commonしたtaxonomyリストに割合を追加する
:param sids:
:param sto:
:return:
"""
for d in to:
d.append(d[2]/l)
return to | 0744c47d0d616e3a4fef85bc341ae0ed98bb0695 | 3,614,561 |
def gru(inputs,targets,hprev):
"""
inputs and targets are both lists of integers.
hprev is Hx1 array of initial hidden state
returns the loss, gradients on model params and last hidden state
"""
x,r,i,h,h_hat,y,p = {},{},{},{},{},{},{}
#copy the hprev to last element of hs dict
h[-1] = ... | bfc27a1527e7240382c58886bd458e6abc4cef9b | 3,614,562 |
import collections
import re
def parse_cmu(cmufh):
"""Parses an incoming file handle as a CMU pronouncing dictionary file.
(Most end-users of this module won't need to call this function explicitly,
as it's called internally by the :func:`init_cmu` function.)
:param cmufh: a filehandle with CMUdict-... | 6229bf41bb3a11ffaf1f5f45dfd55d6e051b0e45 | 3,614,563 |
def GetNextElement(op):
"""Returns the next material or shader after `op`."""
if not op:
return
if op.IsInstanceOf(c4d.Mmaterial) and op.GetFirstShader():
return op.GetFirstShader()
elif op.GetDown():
return op.GetDown()
while (not op.GetNext()) and op.GetUp():
op ... | ac075dd38bebc01770c65c03db003e2f3b8f0bb9 | 3,614,564 |
from typing import Any
import yaml
def cli(
cls: str,
description: str,
default: list[str],
) -> dict[str, Any]:
"""Create CLI that loads kwargs from config files
Parameters
----------
cls: str
Class to be constructed from configuration parameters.
This is only used as a :... | 6e7e23b56e50dc33a26448d5750fd3b2c3ea1098 | 3,614,565 |
def truncate_patch_version(version):
"""Return just the major and minor versions from `version`."""
split_version = version.split(".")
return "{}.{}".format(split_version[0], split_version[1]) | d4eb7f23aeab17f862b13109315a417039eb6897 | 3,614,566 |
def CGz(Omega, k, l, m, f, N2, w=0):
"""
Vertical Group Speed (includes vertical flow but is 0 by default)
"""
K2 = k**2 + l**2 + m**2
return (-1*(k**2 + l**2) * m * (N2 - f**2)) / (K2**2 * Omega) | f20f80dcfca91048f1c47d0ca1270b81ae56819f | 3,614,567 |
def AUT_SetSearchArea(dCenterHz, dCenterV, dRangeHz, dRangeV, bEnabled=1):
"""
[GeoCom **p62**]
Define the position and dimensions and activates the PowerSearch window.
:returns: [error, RC, parameters]
* error=0 and RC=0 if the request is successful
* error=1 if not
:rtype: list
"""... | 48f1c283209ceb03cb9372db2503a4361ce0e32d | 3,614,568 |
from typing import Tuple
def generalized_advantage_estimate(
rewards: Tensor,
old_values: Tensor,
new_values: Tensor,
dones: Tensor,
gamma: float = 0.99,
gae_lambda: float = 0.95,
dtype: str = "torch",
) -> Tuple[Tensor, Tensor]:
"""
Generalized advantage estimate of a trajectory: ... | ab75b0ef183812bb6daf7ea30c66873ff57c32dc | 3,614,569 |
async def is_lover(self, author, fetch=False, resp=None):
"""Checks if the user is Lover on my server."""
return await check_if_role(self, author, fetch, resp, config["LOVER_ROLE"]) | 1309b3c2b38b747f9a270a3f1b416f6824df50e8 | 3,614,570 |
import pathos
from functools import partial
from itertools import repeat
from typing import Sequence
from typing import Dict
from typing import Set
from typing import Tuple
import gc
def estimate_aps_onnx(onnx: str, X_c = None, X_d = None, data = None, C: Sequence = None, D: Sequence = None, L: Dict[int, Set] = None,... | a7c4720b8761db02fd16302bcdea82ced194a3c7 | 3,614,571 |
from typing import Tuple
def _get_membership(max_radius_a, radis_a, radius_b, len_a, u, epsilon) -> Tuple[np.ndarray, np.ndarray]:
"""
Calculates the membership and noise values based on pre-computed radius values
:return:
-[0] membership values for class "a"
-[1] noise values for class "a"
"... | d6c11cc7cb516ac0919f3513784001f62375c3c3 | 3,614,572 |
def davis_sponge_h_timescale(X, Y):
"""Produce the sponge timescale file used by Davis et al. (2014)."""
sponge_h_timescale = np.zeros(X.shape, dtype=np.float64)
sponge_h_timescale[Y<480e3] = 1/(1.*30.*86400.) # six month relaxation time
plt.figure()
plt.pcolormesh(X,Y,sponge_h_timescale*86400.*30.... | 0550ff707db5c6f870a2c495c2785e9e5bd9ed30 | 3,614,573 |
def get_key_value_list(lines):
"""
Split lines at the first space.
:param lines: lines from trackhub file
:return: [(name, value)] where name is before first space and value is after first space
"""
result = []
for line in lines:
line = line.strip()
if line:
parts... | aa2d1c3b100c963a50c05cfaf684df5bbed612bd | 3,614,574 |
def sendEmail_thru_mailjet_api(From, To, Cc, Bcc, Subject, text_body, html_body, attachments=[], caller_area={}):
"""
sendEmail_thru_mailjet_api
"""
_process_name = 'sendEmail_thru_mailjet_api'
_process_entity = 'email'
_process_action = 'send_email'
_process_msgID = f'process:[{_process_nam... | d8d76afbde5c9b9595df5f3938a58973962291d0 | 3,614,575 |
def one_hot_encode(label, label_values):
"""
Convert a segmentation image label array to one-hot format
by replacing each pixel value with a vector of length num_classes
# Arguments
label: The 2D array segmentation image label
label_values
# Returns
A 2D array with t... | 6acd5a0cfc6dfc755e256c369806106042ffee6c | 3,614,576 |
def nmea0183_readout_handler():
"""
Reads all available NMEA0183 sentences through serial connection.
"""
ret = {}
# Read lines from serial connection
lines = conn.read_lines()
if not lines:
log.warn("No NMEA0183 sentences available")
return ret
# Parse NMEA sentences... | fc3240091c49110dad9d29e3699108b7efa4771f | 3,614,577 |
import argparse
def main():
"""Run an experiment in the cloud."""
logs.initialize()
parser = argparse.ArgumentParser(
description='Begin an experiment that evaluates fuzzers on one or '
'more benchmarks.')
all_benchmarks = benchmark_utils.get_all_benchmarks()
all_fuzzers = fuzzer... | 15ff1c152a5c0d94bd6bae519f645191222b1a3b | 3,614,578 |
def summarize_results(result,task):
"""
creates a summary of the result as dict
"""
summary={
#'Csc':data['pairwise_contact_matrix'],
#'Cpop':data['population_contact_matrix'],
#'Xmean':data['prior_shape_model'],
'n':result.n,
'd':result.d,
... | dca60dcbef0bb747d288f60bcbef6b6531c2094e | 3,614,579 |
def omw_stats():
"""
statistics about wordnet as a big graph
"""
### get language
selected_lang = int(_get_cookie('selected_lang', 1))
### get hypernym graph
hypernym_dict=fetch_graph()
G = nx.DiGraph(hypernym_dict, name='OMW')
info = nx.info(G).splitlines()
cycles = list(... | dbd419538ef3b0a3e43eb9c5215ef1c5805ac05e | 3,614,580 |
def get_data_field(thing_description, data_field_list):
"""Get the field specified by 'data_field_list' from each thing description
Args:
data_field_list(list): list of str that specified the hierarchical field names
For example, if the parameter value is ['foo', 'bar', 'foobar'], then this... | f0ef0a46fbcafa993e01f59349c1283b51bbd393 | 3,614,581 |
import numpy as np
def get_anchor_labels(anchors, coords, config):
"""
Generates the anchor labels for tranining the PPN.
Returns y_conf, y_reg.
anchors
The list of anchor coordinates generated from get_anchors().
coords
The list of ground truth point coordinates.
config
... | c12e25dc672f48d7bd98255dd8a84c2ec4310a1d | 3,614,582 |
def cliview_conf_mos(cookie, in_additional_methods, in_commit, in_configs, in_hierarchical=YesOrNo.FALSE):
""" Auto-generated UCSC XML API Method. """
method = ExternalMethod("CliviewConfMos")
method.cookie = cookie
method.in_additional_methods = in_additional_methods
method.in_commit = in_commit
... | 51479daeb687e39bf3e142157f188fd8cdb42044 | 3,614,583 |
def limpieza_texto(texto, lista_palabras=[], lista_expresiones=[],
ubicacion_archivo=None, n_min=0, quitar_numeros=True,
quitar_acentos=False, tokenizador=None, momento_stopwords='ambos'):
"""Limpieza completa de texto. Esta función hace una limpieza exhaustiva del texto de ent... | 9d5da91bc01abcdc538d5b6074bf418fd6f00a21 | 3,614,584 |
def get_speed_formatted_str(speed):
""" Returns the speed with always two whole numbers and two decimal value.
Example: 03.45
Args:
speed (float): The actual speed of the car
Returns:
str: The text format of the speed
"""
speed_str = "{:0.2f}".format(round(speed, 2))
return s... | c05d20f568950f8236f9e46e90387e3a71090589 | 3,614,585 |
import jinja2
def _from_string_with_informative_exceptions(env: jinja2.Environment, text: str) -> jinja2.Template:
"""
Parse the jinja2 template raising more informative exceptions if there are any.
:param env: global jinja2 environment
:param text: text of the template
:return: parsed template
... | f623d59079f12371bf4abf8c62b7800b85e9ce28 | 3,614,586 |
def _make_trace_requests(parity_hosts, blocks):
"""
Make requests to get trace by the same parameters as in _make_requests
"""
def request(block_number):
return {
"jsonrpc": "2.0",
"id": "trace_{}".format(block_number),
"method": "trace_block",
"pa... | a992995c85a4e5cbead5669b61833f170fee051c | 3,614,587 |
def ccw(A, B, C):
"""
Check if a point C is counter-clockwise to AB.
"""
return (C[1] - A[1])*(B[0]-A[0]) > (B[1]-A[1])*(C[0]-A[0]) | c1afb4e510be6a85ad7de1aa924917e37b227dbe | 3,614,588 |
from unittest.mock import call
import logging
def stack_remove(name: str):
"""Removes a stack. Due to limitations of the Docker SDK this calls the actual Docker CLI."""
proc = call(["docker", "stack", "rm", name])
if proc.returncode is not 0:
logging.error("`docker stack remove` exited with non-ze... | 9ad76d789b9d749119826688902acb08752eeabc | 3,614,589 |
def inverted_dummy_template_operations(wires):
"""The expected inverted operations for the dummy template."""
ops = []
for wire in reversed(wires):
ops.append(qml.RY(1, wires=[wire]))
ops.append(qml.RX(-1, wires=[wire]))
return ops | b07992a887d3e4fa6635ed0ad37f3476e685edc7 | 3,614,590 |
def AsQuotedString(input_string):
"""Convert |input_string| into a quoted string."""
subs = [
('\n', '\\n'),
('\t', '\\t'),
("'", "\\'")
]
# Go through each substitution and replace any occurrences.
output_string = input_string
for before, after in subs:
output_string = output_string.... | edf344cae423e13a6cfc04e960674c954b5eb7ee | 3,614,591 |
from typing import List
def certificate_chain_from_printcert(printcert: str) -> List[Certificate]:
"""
This function parses the output of 'keytool -printcert' and creates a list of Certificate objects.
The input to this function is the output of keytool_printcert
:param printcert: the string output o... | a11ea3f923b5d6f8a6fd14623a458db5d4868b90 | 3,614,592 |
from operator import mul
def accumulating_product_acc(items):
"""Calculate the accumulating product of a list.
Uses itertools.accumulate.
Arguments:
items {[list]} -- List of numbers.
Returns:
[list] -- List of accumulating products.
"""
return list(accumulate(items, func=m... | 70702faae627aa98ceedf77292b4ca2d1b3dcfab | 3,614,593 |
from typing import Counter
def check_cardinality(df, cat_cols, threshold=8):
"""
Check categorical cardinality
Checks the cardinality of categorical features of a given dataset. Returns
two dictionaries, one for features with low cardinality and another for
features with high cardinality. The low... | 5b33a39c1da007de46ca409c8fb531b3b3600a7b | 3,614,594 |
from sys import path
import os
import fnmatch
def _treelist(root, child, exclude, include):
"""
Recursive function that does the actual work of `treelist`.
"""
src_dir = root
if child:
src_dir = path.join(src_dir, child)
files = []
for filename in os.listdir(src_dir):
... | b2354ec9018872caf06cbfe75c425dcf837334cd | 3,614,595 |
def draw_grid(data, img_width, img_height, tile_size):
"""Draw a white grid on an original image labelled version, depending on
its tile splitting, *i.e.* draw vertical and horizontal lines each
`tile_size` pixels.
Parameters
----------
data : numpy.array
Labelled version of an image
... | 3f524941831af538bb5e19d62806e4ff0ed31dd1 | 3,614,596 |
def get_application_serializer(instance, **kwargs):
"""
Returns an instantiated serializer based on the instance class type. Custom
serializers can be defined per application type. This function will return the one
that is set else it will return the default one.
:param instance: The instance where... | 90032bc7347c4ac7151f0f1fd5e3061d441fcaeb | 3,614,597 |
def create_snapshot(_user_id):
"""Creates a new FAQ snapshot.
@param _user_id: author's identifier
@return: 201: a new_uuid as a flask/response object \
with application/json mimetype.
@raise 400: misunderstood request
"""
# Store new snapshot
id = snapshot_service.create_snapshot(_user_... | a66bed354bad56bb1453d5a3da46a0963e59fcd0 | 3,614,598 |
def flow_duration(ds):
"""Compute the flow duration for a given dataset"""
# NOTE: This exists in prms_objfcn.py
# See http://pubs.usgs.gov/sir/2008/5126/section3.html
# for the approach used to compute the flow duration
# We only want valid values, sort the values in descending order
... | dc0c85fc50434d23efebf51c470ce48c30490ec4 | 3,614,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.