content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Optional
def offset(xs: Optional[ColumnSize] = None,
sm: Optional[ColumnSize] = None,
md: Optional[ColumnSize] = None,
lg: Optional[ColumnSize] = None,
xl: Optional[ColumnSize] = None) -> Optional[str]:
"""
Arguments:
xs: Offset (in column... | 7b2cc1c96deda1cdbea02e44415c98ef3ba1a34d | 3,635,167 |
def play_sound(data):
"""
Parameters
----------
data: dict
Returns
-------
"""
if 'sound_name' in data:
clientUtils.sound(data.get('sound_name'))
return ""
return "Je ne trouve pas le son demandé" | 3206d44682581458d62ebda2c90597d10aff9fab | 3,635,168 |
async def async_setup(hass, config):
"""Start the Fortigate component."""
conf = config[DOMAIN]
host = conf[CONF_HOST]
user = conf[CONF_USERNAME]
api_key = conf[CONF_API_KEY]
devices = conf[CONF_DEVICES]
is_success = await async_setup_fortigate(hass, config, host, user, api_key, devices)
... | 0ed909bc2e18a242131bee458a4d7b0082576fb4 | 3,635,169 |
import select
from operator import and_
def get_snapshot_usages_project(meta, project_id):
"""Return the snapshot resource usages of a project"""
snapshots_t = Table('snapshots', meta, autoload=True)
snapshots_q = select(columns=[snapshots_t.c.id,
snapshots_t.c.volume_s... | 8185cd670d595f07d739d9c9e9e52b23eace432c | 3,635,170 |
import contextlib
def compute_patch_embeddings(
samples,
model,
patches_field,
embeddings_field=None,
force_square=False,
alpha=None,
handle_missing="skip",
batch_size=None,
num_workers=None,
skip_failures=True,
):
"""Computes embeddings for the image patches defined by ``p... | 371d4ae24e1e451b0e9970b78d43c4b8791d0e3c | 3,635,171 |
def getRetRange( rets, naLower, naUpper, naExpected = "False", s_type = "long"):
"""
@summary Returns the range of possible returns with upper and lower bounds on the portfolio participation
@param rets: Expected returns
@param naLower: List of lower percentages by stock
@param naUpper: List of uppe... | 7e51851ab82d9da6ff670ef52b09464190e8ee3c | 3,635,173 |
def landing():
"""
Landing page - either shows login/sign-up or redirects to dashboard
"""
if g.uid:
return redirect("/dashboard")
else:
return render_template("landing.html", menu_item="login") | 4ca27c76ca76bd762dc24ba2fa6a64cc06b355d3 | 3,635,174 |
def pi_estimator(iterations: int):
"""An implementation of the Monte Carlo method used to find pi.
1. Draw a 2x2 square centred at (0,0).
2. Inscribe a circle within the square.
3. For each iteration, place a dot anywhere in the square.
3.1 Record the number of dots within the circle.
4. After a... | 65475038c3655ea9e093b82b64eb1086f81a1ba8 | 3,635,175 |
from typing import Optional
from typing import Sequence
def get_projects(filters: Optional[Sequence[pulumi.InputType['GetProjectsFilterArgs']]] = None,
sorts: Optional[Sequence[pulumi.InputType['GetProjectsSortArgs']]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> Awaitable... | fa282a9420eb30633c4f354963343d46d77d4c2f | 3,635,176 |
def get_market_impact(
portfolio_name,
start_date,
end_date,
denominator="reference_equity",
model_id=DEFAULT_MODEL_ID,
):
"""Get market impact for each daily change of a portfolio in terms of dollars and percent of a denominator, either reference_equity or gmv.
Note that this ignores change... | fa74d8aad26bd4bb759a115cfc51a8fbc21b9353 | 3,635,177 |
def importH5(name, df):
"""
"""
f = h5py.File(name,'r')
data = f.get(df)
data = np.array(data)
oldShape = data.shape
data = np.swapaxes(data, 1, 2)
print 'convert shape %s to %s' % (oldShape, data.shape)
return data | 4c6f14fec8497f965c2b14a153bd2f6f21f429c7 | 3,635,178 |
def svc_longi_u_polar(vr,vpsi,vz,gamma_l=-1,R=1,m=0,ntheta=180,polar_out=False):
""" Raw function, not intended to be exported.
Induced velocity from a skewed semi infinite cylinder of longitudinal vorticity.
Takes polar coordinates as inputs, returns velocity either in Cartesian (default) or polar.
Th... | c4d1713ef08c4672bfefba0e11d2daca121032f4 | 3,635,179 |
import requests
import json
import logging
def _unremediate_email_o365_EWS(emails):
"""Remediates the given emails specified by a list of tuples of (message-id, recipient email address)."""
assert emails
assert all([len(e) == 2 for e in emails])
result = [] # tuple(message_id, recipient, result_code,... | 15c4b07b0f45d0792f9632cdf3312f8ab6025e44 | 3,635,180 |
def filenames_per_batch (gen):
""" arg = name of the data generator (datagen.flow_from_dataframe) """
img_paths_per_batch=[]
batches_per_epoch = gen.samples // gen.batch_size + (gen.samples % gen.batch_size > 0)
for i in range(batches_per_epoch):
batch = next(gen)
current_inde... | 23ea9dfbbfe64fc51796af22c83a470847c9f698 | 3,635,182 |
def coarsemask_head_generator(params):
"""Generator function for ShapeMask coarse mask head architecture."""
head_params = params.shapemask_head
return heads.ShapemaskCoarsemaskHead(
head_params.num_classes,
head_params.num_downsample_channels,
head_params.mask_crop_size,
head_params.use_c... | 6dea83780e2b0169f71401ca3577d9c4383280f0 | 3,635,183 |
def ethtype_to_int_priv_pubv(priv, pubv):
"""
将 priv 和 pubv 转换为 weidentity 支持的格式(十进制)
:param priv: type: bytes
:param pubv: type: hex
:return: priv int, pubv int
"""
private_key = int.from_bytes(priv, byteorder='big', signed=False)
public_key = eval(pubv)
return {"priv": str(private... | 763a284015029a43257061818634b50d69417de5 | 3,635,184 |
import time
def solver(I, a, L, Nx, F, T, theta=0.5, u_L=0, u_R=0,
user_action=None):
"""
Solve the diffusion equation u_t = a*u_xx on (0,L) with
boundary conditions u(0,t) = u_L and u(L,t) = u_R,
for t in (0,T]. Initial condition: u(x,0) = I(x).
Method: (implicit) theta-rule in time.
... | 99da0c06fcbbc36515b6b4aee23b4b3b4eff0032 | 3,635,186 |
def create_clean_df_from_cloud_json(js):
""" Given a json downloaded on the cloud from get_datasource_data or get_location_data, returns a corrected df"""
df = json_to_df(js)
df_data = set_timestamp_df_index(df)
for col in df_data.columns:
if col[:6] == 'values':
df_data[col] = __pd.... | cdad4f51dd3014a05e9c1e5f5068d344220bccd5 | 3,635,187 |
def tfidf_corpus(docs=CORPUS):
""" Count the words in a corpus and return a TfidfVectorizer() as well as all the TFIDF vecgtors for the corpus
Args:
docs (iterable of strs): a sequence of documents (strings)
Returns:
(TfidfVectorizer, tfidf_vectors)
"""
vectorizer = TfidfVectorizer()
... | 401b9e0ed9321e7a20f9efeb303b5c8f51b70a75 | 3,635,188 |
def svn_utf_cstring_from_utf8_string(*args):
"""svn_utf_cstring_from_utf8_string(svn_string_t const * src, apr_pool_t pool) -> svn_error_t"""
return _core.svn_utf_cstring_from_utf8_string(*args) | 63be2c2624a66d7221845e8c0546f58c5f2f952a | 3,635,189 |
def squint(t, r, orbit, attitude, side, angle=0.0, dem=None, **kw):
"""Find squint angle given imaging time and range to target.
"""
assert orbit.reference_epoch == attitude.reference_epoch
p, v = orbit.interpolate(t)
R = attitude.interpolate(t).to_rotation_matrix()
axis = R[:,1]
# In NISAR ... | 0172b4f525e5738740eb0c948b650bf3c1abbb11 | 3,635,190 |
def get_cmfgenNoRot_atmosphere(metallicity=0, temperature=30000, gravity=4.14):
"""
metallicity = [M/H] (def = 0)
temperature = Kelvin (def = 30000)
gravity = log gravity (def = 4.14)
"""
sp = pysynphot.Icat('cmfgenF15_noRot', temperature, metallicity, gravity)
# Do some error checking
... | a188661f24083b4ab29f83559dac6011eee4d7aa | 3,635,191 |
def _SanitizeDoc(doc, leader):
"""Cleanup the doc string in several ways:
* Convert None to empty string
* Replace new line chars with doxygen comments
* Strip leading white space per line
"""
if doc is None:
return ''
return leader.join([line.lstrip() for line in doc.spli... | 7ca6f17296c9b23c05239092e28c8d6b4df7c725 | 3,635,192 |
import json
import yaml
def load_file(file_path: str):
"""Loads a file using a serializer which guesses based on the file extension"""
if file_path.lower().endswith('.json'):
with open(file_path) as input_file:
return json.load(input_file)
elif file_path.lower().endswith('.yaml') or fi... | 1b9c3278bd40a23e142590952d95876401c5f99b | 3,635,193 |
import json
def list_assets(event, context):
"""
Get a list of assets of the given type.
Query string parameters
-----------------------
asset_type (required):
The type of asset to get. Allowed values are found in the
``asset_map`` dict.
"""
query_params = event.get('query... | e0cf59d2ee275dc9c6610f30daacc91a9042723a | 3,635,194 |
def pop_execute_query_kwargs(keyword_arguments):
""" pop the optional execute query arguments from arbitrary kwargs;
return non-None query kwargs in a dict
"""
query_kwargs = {}
for key in ('transaction', 'isolate', 'pool'):
val = keyword_arguments.pop(key, None)
if val is not No... | d4ae2df3158660f62e21153d943922692f633b76 | 3,635,195 |
import time
import json
def decompress(target_file):
"""This is the decompression section"""
# extract binary string from a file
start_decompress = float(time.process_time()) # start measure time in this line to check processing time
binary_file_name = target_file
filename = target_file
wit... | 0491bdcb3b4555b42705b2a3a02fe3bf98ca6bb6 | 3,635,196 |
def resize(img, new_shape, interpolation=1):
"""
img: [H, W, D, C] or [H, W, D]
new_shape: [H, W, D]
"""
type = 1
if type == 0:
new_img = skt.resize(img, new_shape, order=interpolation, mode='constant', cval=0, clip=True, anti_aliasing=False)
else:
shp = tuple(np.array(new_s... | 5754f8e61cca50927fc7ad65d4f3122c1718bcc1 | 3,635,197 |
import logging
def get_oneview_client(session_id=None, is_service_root=False):
"""Establishes a OneView connection to be used in the module
Establishes a OV connection if one does not exists.
If one exists, do a single OV access to check if its sill
valid. If not tries to establish a new ... | eeb5c80bbced6deb6188878ff646ef0a7a54a184 | 3,635,198 |
def SegmentByPeaks(data, peaks, weights=None):
"""Average the values of the probes within each segment.
Parameters
----------
data : array
the probe array values
peaks : array
Positions of copy number breakpoints in the original array
Source: SegmentByPeaks.R
"""
segs =... | 97acb45c320d4da9a3094188239a6442cafe48b1 | 3,635,199 |
def get_cnt_sw(g_sc, g_sa, g_wn, g_wc, g_wo, g_wvi, pr_sc, pr_sa, pr_wn, pr_wc, pr_wo, pr_wvi, mode):
""" usalbe only when g_wc was used to find pr_wv
"""
cnt_sc = get_cnt_sc(g_sc, pr_sc)
cnt_sa = get_cnt_sa(g_sa, pr_sa)
cnt_wn = get_cnt_wn(g_wn, pr_wn)
cnt_wc = get_cnt_wc(g_wc, pr_wc)
cnt_w... | 069632779f353e28f23a0687e11d00761c8dea19 | 3,635,200 |
def _get_memcache_client():
"""Return memcache client if it's enabled, otherwise return None"""
if not cache_utils.has_memcache():
return None
return cache_utils.get_cache_manager().cache_object.memcache_client | c781bf4d638fc4b094fc0d64943b9305e0ec18b8 | 3,635,201 |
def get_long_description(readme_file='README.md'):
"""Returns the long description of the package.
@return str -- Long description
"""
return "".join(open(readme_file, 'r').readlines()[2:]) | 604c57fce1f9b8c32df4b64dc9df4fe61120d680 | 3,635,202 |
import requests
def extract_dem(
bounds,
out_raster="dem.tif"
):
"""Get 25m DEM for area of interest from BC WCS, write to GeoTIFF
"""
bbox = ",".join([str(b) for b in bounds])
# build request
payload = {
"service": "WCS",
"version": "1.0.0",
"request": "GetCoverage... | 9ff9349df9e3cd129a12111f2f45f151bd2851d0 | 3,635,203 |
def G1DListGetEdgesComposite(mom, dad):
""" Get the edges and the merge between the edges of two G1DList individuals
:param mom: the mom G1DList individual
:param dad: the dad G1DList individual
:rtype: a tuple (mom edges, dad edges, merge)
"""
mom_edges = G1DListGetEdges(mom)
dad_edges = G1DListG... | c61ffa657dfaf3daecfbc66d4166aa57efb6141b | 3,635,204 |
def entropy_approximate(signal, delay=1, dimension=2, tolerance="default", corrected=False, **kwargs):
"""Approximate entropy (ApEn)
Python implementations of the approximate entropy (ApEn) and its corrected version (cApEn).
Approximate entropy is a technique used to quantify the amount of regularity and t... | 5e39f5aa4e571e3e8d452c79b3742520af2644bc | 3,635,205 |
from typing import Tuple
def ir_typeref_to_type(
schema: s_schema.Schema,
typeref: irast.TypeRef,
) -> Tuple[s_schema.Schema, s_types.Type]:
"""Return a schema type for a given IR TypeRef.
This is the reverse of :func:`~type_to_typeref`.
Args:
schema:
A schema instance. The r... | 71ce2deae8caa5a177e0d8ad7df60ce1ba1b1be6 | 3,635,206 |
def get_releases_query(session: db.Session, current_user: UserType, show_legacy=False):
"""Returns the query necessary to fetch a list of releases
If a user is passed, then the releases will be tagged `is_mine` if in that user's collection.
"""
if current_user.is_anonymous():
query = session.qu... | 56732a67eb909f89afe01f6189c516d06bccf518 | 3,635,207 |
def get_total_supply(endpoint=_default_endpoint, timeout=_default_timeout) -> int:
"""
Get total number of pre-mined tokens
Parameters
----------
endpoint: :obj:`str`, optional
Endpoint to send request to
timeout: :obj:`int`, optional
Timeout in seconds
Returnss
-------... | f235be169273a638f042ab661fc88744a0b029ae | 3,635,208 |
def _is_css(filename):
"""
Checks whether a file is CSS waveform data (header) or not.
:type filename: str
:param filename: CSS file to be checked.
:rtype: bool
:return: ``True`` if a CSS waveform header file.
"""
# Fixed file format.
# Tests:
# - the length of each line (283 c... | 57d7b1fdbc244a7d17c905b5f5b5a2aa653f6e13 | 3,635,209 |
def extract_versions():
"""
Extracts version values from the main matplotlib __init__.py and
returns them as a dictionary.
"""
with open('lib/matplotlib/__init__.py') as fd:
for line in fd.readlines():
if (line.startswith('__version__numpy__')):
exec(line.strip())... | b54733ffdae76206400e7203f792e3b809cf6c30 | 3,635,210 |
def make_df(raw_data, add_annotations = True):
"""
Basic preprocessing of data:
* Turn dictionry into a pandas dataframe
* Add annotator column to DF -- stored as string
* Name columns according to body part, etc
"""
df = []
labels = []
seqs = []
for seq_id in raw_data['sequences... | cfc893b3616c879e734cabfd8a2dc420aec095d7 | 3,635,212 |
def cyclic_tdma(lower_diagonal, main_diagonal, upper_diagonal, right_hand_side):
"""The thomas algorithm (TDMA) solution for tri-diagonal matrix inversion with the sherman morison formula applied
Parameters
----------
lower_diagonal: np.ndarray
The lower diagonal of the matrix length n, the fir... | a1fd869d181caad075a14bae061c8ee217ef185f | 3,635,213 |
def lico2_ocp_Ramadass2004(sto):
"""
Lithium Cobalt Oxide (LiCO2) Open Circuit Potential (OCP) as a a function of the
stochiometry. The fit is taken from Ramadass 2004. Stretch is considered the
overhang area negative electrode / area positive electrode, in Ramadass 2002.
References
----------
... | 2c0902e1d1cdec9ac7626038e34092933665bf84 | 3,635,214 |
import doctest
def doctestobj(*args, **kwargs):
"""
Wrapper for doctest.run_docstring_examples that works in maya gui.
"""
return doctest.run_docstring_examples(*args, **kwargs) | 1efccd1a887636bbcf80e762f12934e7d03efe28 | 3,635,215 |
def _return_model_names_for_plots():
"""Returns models to be used for testing plots. Needs
- 1 model that has prediction interval ("theta")
- 1 model that does not have prediction interval ("lr_cds_dt")
- 1 model that has in-sample forecasts ("theta")
- 1 model that does not have in-... | bd180134c5c74f4d1782384bc8e3b13abff8b125 | 3,635,216 |
def _convert_input_type_range(img):
"""Convert the type and range of the input image.
It converts the input image to np.float16 type and range of [0, 1].
It is mainly used for pre-processing the input image in colorspace
convertion functions such as rgb2ycbcr and ycbcr2rgb.
Args:
img (Asce... | 990516e2cb069b9afd4388c6fbb8f1f333893dc9 | 3,635,217 |
from pathlib import Path
def collect_derivatives(derivatives_dir, subject_id, std_spaces, freesurfer,
spec=None, patterns=None):
"""Gather existing derivatives and compose a cache."""
if spec is None or patterns is None:
_spec, _patterns = tuple(
loads(Path(pkgrf('a... | f33353c4c67d847b94f4d8467c6721ecc7dc71fa | 3,635,218 |
def aten_meshgrid(mapper, graph, node):
""" 构造对每个张量做扩充操作的PaddleLayer。
TorchScript示例:
%out.39 : int = aten::mshgrid(%input.1)
参数含义:
%out.39 (Tensor): 输出,扩充后的结果。
%input.1 (Tensor): 输入。
"""
scope_name = mapper.normalize_scope_name(node)
output_name = mapper._get_outputs... | e260855ca6732f9d846cc492c949197e93e9551a | 3,635,219 |
def bearing_example():
"""This function returns an instance of a simple bearing.
The purpose is to make available a simple model
so that doctest can be written using it.
Parameters
----------
Returns
-------
An instance of a bearing object.
Examples
--------
>>> bearing = ... | f4d8e71b0b13aa17f9ad08208e8082ef5827a70c | 3,635,220 |
def create_data():
"""Create some random exponential data"""
#np.random.seed(18)
pure = np.array(sorted([np.random.exponential() for i in range(10)]))
noise = np.random.normal(0,1, pure.shape)
signal = pure + noise
return signal | 613231436fe0faca177106cf80abe5d475510469 | 3,635,222 |
def fetch_accidents(data_home=None):
"""Fetch and return the accidents dataset (Frequent Itemset Mining)
Traffic accident data, anonymized.
see: http://fimi.uantwerpen.be/data/accidents.pdf
==================== ==============
Nb of items 468
Nb of transactions ... | 612a7c67fc5b81297ec7ca37d38e0267d23fed36 | 3,635,223 |
def align_nodes(nodenet_uid, nodespace):
""" Automatically align the nodes in the given nodespace """
return runtime.align_nodes(nodenet_uid, nodespace) | aa9fd5f22d8433d0b15e9b826dba9d4c6fa1b590 | 3,635,224 |
def cindex(y_true: np.array, scores: np.array) -> float:
"""AI is creating summary for cindex
Args:
y_true (np.array): An array of actual values of target
scores (np.array): An array of predicted score of target
Returns:
[float]: Returns C-Index score
"""
return lifelines.u... | e69bc4f2e3b391c4049b6b60936a64bcfff9f27d | 3,635,225 |
def match_tones(
left, right, eps=2000., shift_from_right=0.,
match_col='fr',
join_type='inner'):
"""Return a table with tones matched.
This function makes use the ``stilts`` utility.
Parameters
----------
left: astropy.Table
The left model params table.
right: ... | 0be28ac4727b721f4b8847b6e3bc92fbea95de55 | 3,635,226 |
from typing import Tuple
from typing import Optional
from typing import List
from typing import cast
def verify(
symbol_table: intermediate.SymbolTable,
) -> Tuple[Optional[VerifiedIntermediateSymbolTable], Optional[List[Error]]]:
"""Verify that C# code can be generated from the ``symbol_table``."""
error... | c7af0f196cb59022f89f8097f17e98a913fb7615 | 3,635,228 |
import time
def find_workflow_component_figures(page):
""" Returns workflow component figure elements in `page`. """
time.sleep(0.5) # Pause for stable display.
root = page.root or page.browser
return root.find_elements_by_class_name('WorkflowComponentFigure') | 1a56a0a348803394c69478e3443cbe8c6cb0ce9c | 3,635,229 |
def select_best_features(tx, selected_features, rho_exp, w, number_of_select):
"""Selects features by the highest value of the weights
Parameters
----------
tx : np.ndarray
Original features
selected_features : [(int, int)]
Best features from previous iteration
rho_exp : np.nda... | bef855b3685116cec90cfc51194e00d5cee4d3af | 3,635,230 |
def make_pol_lookup(codes):
"""
Returns a lookup table from a list of polarization codes
"""
codes = unique(codes)
codes.sort()
lookup = {}
for code in codes:
if code == 'X' or code == 'XX' or code == 'H':
lookup[code] = -5
elif code == 'Y' or code == 'YY' or code == 'V' or code == 'E':
... | f5c4aece195ff436af8855a5296e1be493c92737 | 3,635,231 |
def _calc_best_estimator_optuna_univariate(
X,
y,
estimator,
measure_of_accuracy,
estimator_params,
verbose,
test_size,
random_state,
eval_metric,
number_of_trials,
sampler,
pruner,
with_stratified,
):
"""Function for calculating best estimator
Parameters
... | 35cbc2458455d7153a1b17c91576c2629baf2ab3 | 3,635,232 |
def get_users_info_async(future_session: "FuturesSession", connection, name_begins,
abbreviation_begins, offset=0, limit=-1, fields=None):
"""Get information for a set of users asynchronously.
Args:
future_session: Future Session object to call MicroStrategy REST
Se... | f2679de38822a12abb2e0e65d102de7876304ccd | 3,635,233 |
def site_link_url(request, siteobj):
"""returns a site urls form already given keys"""
return '%s://%s%s/site/%s' % (
presettings.DYNAMIC_LINK_SCHEMA_PROTO,
request.META.get('HTTP_HOST'),
presettings.DYNAMIC_LINK_URL,
siteobj.link_key
) | c0a29c6ac0157e7ac7fae506ea9f87960c03a92e | 3,635,235 |
def get_arguments():
""" All cli arguments. """
p = ap.ArgumentParser()
p.add_argument('mode', type=str, choices=['train', 'predict'])
# files
p.add_argument('--train-file', type=str)
p.add_argument('--dev-file', type=str)
p.add_argument('--test-file', type=str)
p.add_argument('--model-... | e1d426856fcb7fba3e8bf56200748a7354b09797 | 3,635,236 |
import configparser
def get_headers(path='.credentials/key.conf'):
"""Get the authentication key header for all requests"""
config = configparser.ConfigParser()
config.read(path)
headers = {
'Ocp-Apim-Subscription-Key': config['default']['primary']
}
return headers | d40c1b6246efb728040adc47b6180f50aa4dc3e8 | 3,635,237 |
def Sdif(M0, dM0M1, alpha):
"""
:math:`S(\\alpha)`, as defined in the paper, computed using `M0`,
`M0 - M1`, and `alpha`.
Parameters
----------
M0 : ndarray or matrix
A symmetric indefinite matrix to be shrunk.
dM0M1 : ndarray or matrix
M0 - M1, where M1 is a positive defini... | 6463cb04d7dcfaad93358c7db38f4674a51654b2 | 3,635,238 |
def add_entry(entries, folders, collections, session):
"""Add vault entry
Args: entries - list of dicts
folders - dict of folder objects
collections - dict of collections objects
session - bytes
Returns: None or entry (Item)
"""
folder = select_folder(folders)
col... | 7eab6d0b1df5c713c96a2b70dd874345faf28b3f | 3,635,240 |
def _get_node_by_name(graph_def: rewrite.GraphDef,
node_name: str) -> rewrite.NodeDef:
"""Return a node from a graph that matches the provided name"""
matches = [node for node in graph_def.node if node.name == node_name]
return matches[0] if len(matches) > 0 else None | 8e893b4d51a1fba861f7659ec7edaf8bd794e114 | 3,635,242 |
import requests
def shorten_link(url: str) -> tuple:
"""
Method to shorten a given url using the shrtco.de API
@Parameters
url:str url to be shortened
@Returns
(errorcode:int,result:str)
errorcode: int indicating whether operation succeeded ... | c8acbcb1641d8344ced55e5bd820f0084fc01164 | 3,635,243 |
from typing import Dict
def get_sanitized_bot_name(dict: Dict[str, int], name: str) -> str:
"""
Cut off at 31 characters and handle duplicates.
:param dict: Holds the list of names for duplicates
:param name: The name that is being sanitized
:return: A sanitized version of the name
"""
# ... | 42d432610602b15b1206f0ce1bc007fdaef6b23f | 3,635,244 |
def eval_nmt_bleu(model,dataset,vectorizer,args):
"""
Evaluates the trained model on the test set using the bleu_score method
from NLTK.
Parameters
----------
model : NMTModel
Trained NMT model.
dataset : Dataset
Dataset with Source/Target sentences.
vectorizer : object
... | e26bb0ab39cf7af704a32e8ed36d7df44a799f55 | 3,635,245 |
import yaml
def load_up_the_tests(folder):
"""reads the files from the samples directory and parametrizes the test"""
tests = []
for i in folder:
if not i.path.endswith('.yml'):
continue
with open(i, 'r') as f:
out = yaml.load(f.read(), Loader=yaml.BaseLoader)
... | 5361f7805452471cf65385ddb1901709d69245a7 | 3,635,246 |
from .algorithms.dpll import dpll_satisfiable
from .algorithms.dpll2 import dpll_satisfiable
def satisfiable(expr, algorithm='dpll2', all_models=False):
"""
Check satisfiability of a propositional sentence.
Returns a model when it succeeds.
Returns {true: true} for trivially true expressions.
On ... | 03cfa14bfa2f7812263f7ca5be98e583e7a3136c | 3,635,247 |
def dist_create_samples(net_file, K=Inf, nproc=None, U=0.0, S=0.0, V=0.0, max_iter=Inf, T=Inf, discard=False,
variance=False,
input_vars=DEFAULT_INPUTS, output_vars=DEFAULT_OUTPUTS, dual_vars=DEFAULT_DUALS,
sampler='sample_polytope_cprnd', sampler_... | a012c019374b45e9a657b15f602b2cbc4b9cbc31 | 3,635,248 |
import re
def get_valid_filename(s):
"""
Returns the given string converted to a string that can be used for a clean
filename. Specifically, leading and trailing spaces are removed; other
spaces are converted to underscores; slashes and colons are converted to
dashes; and anything that is not a un... | 7be8b5080d79b44b167fe2b1cf03108b1a36b169 | 3,635,249 |
import re
def clean_text(text, remove_stopwords = True):
"""
remove artifacts, unneccessary words etc
"""
## regex method - remove '\n'
cleantext = re.sub(r"\\n", " ", text)
## remove '\BA'
cleantext = re.sub(r"\\BA", " ", cleantext)
## remove '\'
... | f7ee64e905b22d62d039e94251347aa126588f09 | 3,635,250 |
def initialise_empty_cells():
"""Initialise empty dictionary of cells for the grid."""
cells = {(x, y): False for x in range(CELL_WIDTH) for y in range(CELL_HEIGHT)}
return cells | eed3b50adefa7c5bf8dff9875ee26f23217e54e5 | 3,635,251 |
def query_left(tree, index):
"""Returns sum of values between 1-index inclusive.
Args:
tree: BIT
index: Last index to include to the sum
Returns:
Sum of values up to given index
"""
res = 0
while index:
res += tree[index]
index -= (index & -index)
... | e293194c86ad1c53a005be290ba61ef2fff097c8 | 3,635,252 |
def deleteCategory(category_name):
""" This endpoint will show category delete confirmation by GET request
and will delet the category by POST request."""
session = DBSession()
category = session.query(Category).filter_by(name=category_name).one()
if request.method == 'POST' and login_session['user... | cf1ef2e0363347125cc270b5c07751da5a5467f8 | 3,635,253 |
def apply_box_deltas_graph(boxes, deltas, Size=24):
"""Applies the given deltas to the given boxes.
boxes: [N, (z1, y1, x1, z2, y2, x2)] boxes to update
deltas: [N, (dz, dy, dx)] refinements to apply
"""
# center_z, center_y, center_x are the (normalized) coordinates of the centers
center_z... | 9a9c6a8c40f53d0956533a55815e65a2fa94eaf1 | 3,635,255 |
def calculate_number_of_peaks_gottschalk_80_rule(peak_to_measure, spread):
"""
Calculate number of peaks optimal for SOBP optimization
on given spread using Gottschalk 80% rule.
"""
width = peak_to_measure.width_at(val=0.80)
n_of_optimal_peaks = int(np.ceil(spread // width))
return n_of_opti... | 2204222a3df6ebe4bebb62f5e4c53311cadaaa77 | 3,635,256 |
def maxsum(sequence):
"""Return maximum sum."""
maxsofar, maxendinghere = 0, 0
for x in sequence:
# invariant: ``maxendinghere`` and ``maxsofar`` are accurate for ``x[0..i-1]``
maxendinghere = max(maxendinghere + x, 0)
maxsofar = max(maxsofar, maxendinghere)
return maxsofar | 884d8b5dd20a0a35ff79c64bc6151b0d8ae7f5a0 | 3,635,257 |
import torch
def matrix_from_angles(rot):
"""
Create a rotation matrix from a triplet of rotation angles.
Args:
rot: a tf.Tensor of shape [..., 3], where the last dimension is the rotation angles, along x, y, and z.
Returns:
A tf.tensor of shape [..., 3, 3], where the last two d... | 2108cf7d59d5f641ef7a9813f32cae7a33b00322 | 3,635,258 |
def get_fov_stats(mrcnn, low_confidence, discordant,
extreme, artifacts,
roi_mask= None, keep_thresh = 0.5,
fov_dims= (256,256), shift_step= 128):
"""
Gets potential FOVs along with their associated
statistics.
Args:
* mrcnn [m, n, 4] - pos... | 767a101900ebdf68e8fbf3fedac8bfaa58b27c15 | 3,635,260 |
import torch
def negative_sampling_loss(pos_dot, neg_dot, size_average=True, reduce=True):
"""
:param pos_dot: The first tensor of SKipGram's output: (#mini_batches)
:param neg_dot: The second tensor of SKipGram's output: (#mini_batches, #negatives)
:param size_average:
:param reduce:
:return:... | 18f05e138010b98ef8abaec35dd37030b08ecfcb | 3,635,261 |
def _has_externally_shared_axis(ax1: "matplotlib.axes", compare_axis: "str") -> bool:
"""
Return whether an axis is externally shared.
Parameters
----------
ax1 : matplotlib.axes
Axis to query.
compare_axis : str
`"x"` or `"y"` according to whether the X-axis or Y-axis is being
... | 6f71975e62ba763e2fece42e4d3d760e12f5ddc5 | 3,635,262 |
def network_size(graph, n1, degrees_of_separation=None):
""" Determines the nodes within the range given by
a degree of separation
:param graph: Graph
:param n1: start node
:param degrees_of_separation: integer
:return: set of nodes within given range
"""
if not isinstance(graph, (BasicG... | f62095abe184d818d25451b38430eaa331a71654 | 3,635,263 |
def get_conserved_sequences(cur):
"""docstring for get_conserved_sequences"""
cur.execute("SELECT sureselect_probe_counts.'sureselect.seq', \
sureselect_probe_counts.cnt, \
sureselect_probe_counts.data_source, \
cons.cons \
FROM sureselect_probe_counts, cons \
WHERE sures... | e518d22b7ac2ba072c75a76f72114009eed6ce7c | 3,635,264 |
from typing import Any
def delete_empty_keys(data: Any):
"""Build dictionary copy sans empty fields"""
# Remove empty field from dict
# https://stackoverflow.com/questions/5844672/delete-an-element-from-a-dictionary#5844700
dic = data.dict()
# if isinstance(data, BaseModel):
# dic = **data... | db190b021bb00ae3870e205bc27bf28dd09e29c3 | 3,635,265 |
def find_language(article_content):
"""Given an article's xml content as string, returns the article's language"""
if article_content.Language is None:
return None
return article_content.Language.string | 4a228779992b156d01bc25501677556a5c9b7d39 | 3,635,267 |
def create_problem_from_type_base(problem):
"""
Creates OptProblem from type-base problem.
Parameters
----------
problem : Object
"""
p = OptProblem()
# Init attributes
p.phi = problem.phi
p.gphi = problem.gphi
p.Hphi = problem.Hphi
p.A = problem.A
p.b = problem.b
... | c631e3f27d49b288e85e6043a81f658f65f962e2 | 3,635,269 |
import re
def geturls(str1):
"""returns the URIs in a string"""
URLPAT = 'https?:[\w/\.:;+\-~\%#\$?=&,()]+|www\.[\w/\.:;+\-~\%#\$?=&,()]+|' +\
'ftp:[\w/\.:;+\-~\%#?=&,]+'
return re.findall(URLPAT, str1) | 3d127a3c4250d7b013d9198e21cfb87f7909de8d | 3,635,270 |
import requests
def get_list(imid: str) -> requests.Response:
""" Return the requests.Response containing
the list of images for a given image-net.org
collection ID.
"""
imlist = requests.get(LIST_URL.format(imid=imid))
return imlist | da63e021e594eff6ee672e3aa234522a3d23e34d | 3,635,271 |
def minimum(x1, x2):
"""Element-wise minimum of input variables.
Args:
x1 (~chainer.Variable): Input variables to be compared.
x2 (~chainer.Variable): Input variables to be compared.
Returns:
~chainer.Variable: Output variable.
"""
return Minimum().apply((x1, x2))[0] | b511edb9c13abf3a0df5dad48d1fffcf1d96c82a | 3,635,272 |
import torch
def train(train_dataset : dict, validation_dataset : dict, batch_size : int = 16,
num_epochs : int = 5000, allow_cuda : bool = True,
use_shuffle : bool = True, save_criterion : callable = None,
stop_criterion : callable = None, save_on_finish : bool = True) -> dict:
"""
... | db0b50be37fe1dd96bffa1c934d5a68d3ac5198e | 3,635,274 |
def reduce_to(n):
"""processor to reduce list"""
def reduce(list):
if len(list) < n:
return n
else:
return list[0:n]
return reduce | b9a1fb6091ef9801957c6cc64cab5485091d6801 | 3,635,275 |
def render(renderer_name, value, request=None, package=None):
""" Using the renderer ``renderer_name`` (a template
or a static renderer), render the value (or set of values) present
in ``value``. Return the result of the renderer's ``__call__``
method (usually a string or Unicode).
If the ``rendere... | 84e172cbb476f12ad6f7e801fa5b995fa2dedc20 | 3,635,276 |
def validate(number):
"""Check if the number provided is a valid NCF."""
number = compact(number)
if len(number) == 13:
if number[0] != 'E' or not isdigits(number[1:]):
raise InvalidFormat()
if number[1:3] not in _ecf_document_types:
raise InvalidComponent()
elif ... | f9d2f738b020fc49bbecb0a6be9805dd4243121a | 3,635,278 |
def upsampling_d1_batch_normal_act_subpixel(input_tensor,
residual_tensor,
filter_size,
layer_number,
active_function=tf.nn.relu,
... | 12b016e6e0e6d44bf396ccbbd9b4f9c870ea7bbf | 3,635,279 |
def search_ws(sheet, search_term, distance=20, warnings=True, origin=[0,0],
exact = False):
""" Searches through an excel sheet for a specified term.
The function searches along the bottom left to top right diagonals.
The function starts at the "origin" and only looks for values below or to
... | 3228ee48960b255cf042252ca0b5ac2f69c0d259 | 3,635,280 |
def obs_all_table_target_pairs_one_hot(agent_id: int, factory: Factory) -> np.ndarray:
"""One-hot encoding for each table target, NOT summed together; length: number of tables x number of nodes"""
num_nodes = len(factory.nodes)
num_tables = len(factory.tables)
table_target_pair = np.zeros(num_nodes * nu... | dc021799fa09e0bf37dac27908996e471b23223d | 3,635,282 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.