content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def relpath(path, cwd=None):
""" Find relative path from current directory to path.
Example usage:
>>> from Ska.File import relpath
>>> relpath('/a/b/hello/there', cwd='/a/b/c/d')
'../../hello/there'
>>> relpath('/a/b/c/d/e/hello/there', cwd='/a/b/c/d')
'e/hello/there'
... | 5,293,700 |
def do_set_license_link(parser, token):
"""
Stores the license link to a context variable.
Usage::
{% license_link as [varname] %}
"""
bits = token.contents.split()
if len(bits) != 3:
raise template.TemplateSyntaxError('%s tag requires two arguments' % bits[... | 5,293,701 |
def test_main__PTParserRewriter__1(files, mocker):
"""It skips rewrite of a file without `tal:` in content."""
mocker.spy(PTParserRewriter, 'rewrite_zpt')
main([str(files / 'sane/broken.html'), str(files / 'sane/one.pt')])
# broken.html is not rewritten
assert PTParserRewriter.rewrite_zpt.call_count... | 5,293,702 |
def WriteSecret(name, value, namespace=None, database=None):
"""Writes the secret value."""
collection = _GetCollection(namespace, database)
collection.replace_one({'_id': name},
{'_id': name, 'value': value},
upsert=True) | 5,293,703 |
def testEmptySensitiveVariableFailure(setupSensitiveVariables):
""" Test the check for an empty sensitive variable. """
# Setup
config, variableToWrite, mFile, mPathExists, mMakedirs, mChmod = setupSensitiveVariables
# We just randomly select one of the options in the config. They will all be the same.
... | 5,293,704 |
def test_verify_reference_same_dims(hindcast_hist_obs_1d):
"""Test that verify returns the same dimensionality regardless of reference."""
hindcast = hindcast_hist_obs_1d
metric = "mse"
comparison = "e2o"
dim = "init"
alignment = "same_verif"
actual_no_ref = hindcast.verify(
metric=m... | 5,293,705 |
def bf_get_snapshot_inferred_node_roles():
# type: () -> NodeRolesData
"""Gets suggested definitions and hypothetical assignments of node roles for the active network and snapshot."""
return bf_session.get_node_roles(inferred=True) | 5,293,706 |
def ExtractHelpStrings(docstring):
"""Extracts short help and long help from a docstring.
If the docstring contains a blank line (i.e., a line consisting of zero or
more spaces), everything before the first blank line is taken as the short
help string and everything after it is taken as the long help string. T... | 5,293,707 |
def stocks_to_trade(conditions, prices):
""" Find stocks to trade in """
stocks = []
for stock in conditions:
limit, check = conditions[stock]
# Apply the condition - Use operator module to
# match the string to the condition
price = prices[stock]
ok = eval('%d ... | 5,293,708 |
def test_particle_variable(particle_file):
"""Two particle variables, start_time and location_id"""
with ParticleFile(particle_file) as pf:
assert pf.start_time[0] == np.datetime64("1970-01-01")
assert pf["start_time"][1] == np.datetime64("1970-01-01 01")
assert all(pf.location_id == np.... | 5,293,709 |
def flat_page(path):
"""flat pages rendering"""
page = g.pages.flatpages.get_or_404(path)
# Configure the img link plugin
g.flat_page = page
return render_template('article.html', page=page) | 5,293,710 |
def init_smoothing_wf(fwhm=None, memcalc=MemoryCalculator(), name=None, suffix=None):
"""
Smooths a volume within a mask while correcting for the mask edge
"""
if name is None:
if fwhm is not None:
name = f"smoothing_{int(float(fwhm) * 1e3):d}_wf"
else:
name = "sm... | 5,293,711 |
def assert_equal(actual: Tuple[float, numpy.float64], desired: Tuple[float, float]):
"""
usage.statsmodels: 1
"""
... | 5,293,712 |
def check_similarity_in_list(token_1: str, token_list: array, threshold: int) -> bool:
"""
:param token_1
:param token_list
:param threshold
:return true, if token_1 and at least one token in token_list are equal due to levenshtein distance and a given threshold, otherwise false
"""
for tok... | 5,293,713 |
def sin(val):
""" Qiskit wrapper of sine function
"""
if isinstance(val, Qobj):
return val.sinm()
else:
return np.sin(val) | 5,293,714 |
def toy_data_multitask(n_samples, input_dim, output_dim, random_state=None):
"""Generate data according to Evgeniou, C. A. Micchelli, and M. Pontil.
'Learning multiple tasks with kernel methods.' 2005.
Parameters
----------
"""
rs = check_random_state(random_state)
X = rs.rand(n_samples, ... | 5,293,715 |
def select_all(event):
"""Select all text event in textbox
An event that is bound to the select-all key press.
Selects all text within a text widget.
"""
event.widget.tag_add(SEL, "1.0", END)
event.widget.mark_set(INSERT, "1.0")
event.widget.see(INSERT)
return 'break' | 5,293,716 |
def get_service_type(f):
"""Retrieves service type from function."""
return getattr(f, 'service_type', None) | 5,293,717 |
def tempcsv():
"""Create a temporary CSV file"""
return tempfilename(suffix='.csv') | 5,293,718 |
def func_d2lV(isvegc, edge, saturate):
"""
input:
isvegc : [ncol x nrow] array of vegetation field
output :
d2lV : [ncol x nrow] array, distance to nearest veg cell to the left
= 0 for veg cells
= 1 for bare cells with a veg cell immediately left
"""
ncol = isvegc... | 5,293,719 |
def generate_enum(cls_name, values, imports='') -> str:
"""
Helper function to create C++ enum headers
:param cls_name: the name of the enum
:param values: values to include
:param imports: additional files to import
"""
code = templates.FOUNDATION_ENUM.format(
name=cls_name,
... | 5,293,720 |
def play(player):
"""Play the selected song"""
verbose_output("Play")
player.play() | 5,293,721 |
def main(args):
"""Run through all checks for database."""
presence_stage = PresenceStage(args)
creation_stage = CreationStage(presence_stage)
operations_stage = OperationsStage(creation_stage)
stages = [presence_stage, creation_stage, operations_stage]
for stage in stages:
for check in... | 5,293,722 |
def u(string):
"""
This is a unicode() wrapper since u'string' is a Python3 compiler error.
"""
if is_python3():
return string
return unicode(string, encoding='utf-8', errors='strict') | 5,293,723 |
def test_entry_with_set():
""" Ensure that the serializer can handle a state change event which includes a set. """
state = create_sample_state(
last_updated="",
last_changed="",
attributes=dict({"set_key": set(["a", "b", "c"])}),
)
serializer = get_serializer()
serialized... | 5,293,724 |
def test_load_vault(loaded_token_vault, team_multisig, token, customer, customer_2):
"""We load data correctly."""
assert loaded_token_vault.functions.getState().call() == TokenVaultState.Loading
assert loaded_token_vault.functions.balances(customer).call() == 1000
assert loaded_token_vault.functions.ba... | 5,293,725 |
def downgrade(migrator):
"""Execute globally specified downgrade function."""
globals()[f"downgrade_{METHOD}"](migrator) | 5,293,726 |
def env(ctx, name, home='~'):
"""Run with an anaconda environment"""
return ctx.prefix('source %s/%s/bin/activate %s' % (home, ANACONDA, name)) | 5,293,727 |
def output_file(file_name):
""" adds output file extension, if missing
"""
return _add_extension(file_name, Extension.OUTPUT_LOG) | 5,293,728 |
def get_registry_repository_output(project: Optional[pulumi.Input[Optional[str]]] = None,
region: Optional[pulumi.Input[Optional[str]]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetRegistryRepositoryResult]:
"""
Th... | 5,293,729 |
def plot_all_images(images_path):
"""
plot all passed image by 2 columns
args:
images_path(list of str): list of image path you want to plot
"""
nimage = len(images_path)
ncols = 2
nrows = nimage//ncols if (nimage%ncols==0) else (nimage//ncols) + 1
fig, axes = plt.... | 5,293,730 |
def load_pnasnetlarge(scopes, return_fn=_assign):
"""Converted from the [TF Slim][2]."""
filename = 'pnasnet_large.npz'
weights_path = get_file(
filename, __model_url__ + 'nasnet/' + filename,
cache_subdir='models',
file_hash='a1afc7679b950b643865aa7ea716c901')
values = parse_wei... | 5,293,731 |
def coord_max(t):
"""Multidimensional argmax
Returns coordinates of largest element in tensors of any shape
Args:
t: Tensor to find location of max element within
Returns:
0 or 1-D Tensor of length t.ndims containing coordinates
"""
# Run 1-D argmax on flattened array
idx ... | 5,293,732 |
def test_searcher_format(searcher: Searcher):
"""
The searcher must return data in an specified format
"""
result = searcher.search("Human", max_results=3)
assert isinstance(result, dict)
assert "header" in result.keys()
assert "esearchresult" in result.keys()
jsonschema.validate(result... | 5,293,733 |
def link_config(append=None, **kwargs):
"""link_config."""
_blade_config.update_config('link_config', append, kwargs) | 5,293,734 |
def block_dot(A, B, diagonal=False):
"""
Element wise dot product on block matricies
+------+------+ +------+------+ +-------+-------+
| | | | | | |A11.B11|B12.B12|
| A11 | A12 | | B11 | B12 | | | |
+------+------+ o +------+------| = +-------... | 5,293,735 |
def SSIM(pred, ref):
"""
Compute SSIM between predicted and reference tensors in Tensorflow
Params:
- pred : TensorFlow tensor
Predicted tensor
- ref : TensorFlow tensor
Reference tensor
Outputs:
- ssim : float
SSIM value
... | 5,293,736 |
def test_replace_params(param_id, param_text, prose, result) -> None:
"""Test cases of replacing param in string."""
param_dict = {param_id: param_text}
assert ProfileResolver.Modify._replace_id_with_text(prose, param_dict) == result | 5,293,737 |
def CreatePackagableRoot(target, output_dir, ldpaths, root='/'):
"""Setup a tree from the packages for the specified target
This populates a path with all the files from toolchain packages so that
a tarball can easily be generated from the result.
Args:
target: The target to create a packagable root from
... | 5,293,738 |
def tablename(dxfname):
""" Translate DXF-table-name to attribute-name. ('LAYER' -> 'layers') """
name = dxfname.lower()
return TABLENAMES.get(name, name+'s') | 5,293,739 |
def guessing_game():
"""
Generates random number and checks the user guesses corresponding to it
:return: nothing
"""
# Greet the user with game logo
print(logo)
print('Welcome to the Number Guessing Game!')
# Generate a random number to guess
computer_number = get_number()
pri... | 5,293,740 |
def extra_aaindex(filename):
"""Return AAIndex obj list.
"""
index_list = ['A', 'R', 'N', 'D', 'C', 'Q', 'E', 'G', 'H', 'I',
'L', 'K', 'M', 'F', 'P', 'S', 'T', 'W', 'Y', 'V']
aaindex = []
with open(filename, 'r') as f:
temp_h = ""
lines = f.readlines()
for i... | 5,293,741 |
def make_block(arch_args, in_chs):
"""
Creates a block instance
"""
block_type_code = arch_args['block_type']
out_chs = arch_args.get('out_chs')
if out_chs is None:
out_chs = in_chs
arch_args['name'] = clean_name(arch_args['name'])
block_type_def = NetBuilderConfig.get_block_ty... | 5,293,742 |
def aks_list_table_format(results):
""""Format a list of managed clusters as summary results for display with "-o table"."""
return [_aks_table_format(r) for r in results] | 5,293,743 |
def bank_rank_banker() -> pd.DataFrame:
"""
全球银行排名前 25 家
https://www.thebankerdatabase.com/index.cfm/search/ranking
:return: 全球银行排名前 25 家
:rtype: pandas.DataFrame
"""
url = "https://www.thebankerdatabase.com/index.cfm/search/index.cfm"
headers = {
"accept": "application/json, tex... | 5,293,744 |
def matmul(mat_list):
"""
Compute matrix multiplication of the matrices in mat_list
Arguments:
mat_list: list of numpy arrays, the target matrices
Return:
prod: numpy array, the result
"""
if len(mat_list) <= 1:
prod = mat_list[0]
else:
prod = reduce(np.mat... | 5,293,745 |
def expand_branch(branch):
"""Handles all branch todos (if any), in other words makes it ready.
Implementation of non-recursive DFS."""
if branch.ready:
return
trunk = branch.trunk
stack = list()
def stack_push(branch):
assert not hasattr(branch, 'todo_it'), ("A branch has 't... | 5,293,746 |
def ByteStreamCopyToUTF16Stream(byte_stream, byte_stream_size=None):
"""Reads an UTF-16 formatted stream from a byte stream.
The UTF-16 formatted stream should be terminated by an end-of-string
character (\x00\x00). Otherwise the function reads up to the byte stream size.
Args:
byte_stream: The byte strea... | 5,293,747 |
def compute_error(model_data, reference_data):
"""Returns the summ of the squared differences between model and reference data."""
error = ((model_data - reference_data) ** 2).sum()
return error | 5,293,748 |
def blog_comment():
""" 博客文章评论 """
the_result = do_blog_comment(db, Post, Comment, request.form, request.headers['X-Real-IP'])
return the_result | 5,293,749 |
def pytest_addoption(parser):
"""Add options to the parser."""
parser.addoption("--ci", action="store_true", default=False)
parser.addoption(
"--no-integration-tests",
action="store_true",
default=False,
help="Skip integration tests.",
) | 5,293,750 |
def api(package_name, client, name):
"""Return an API instance."""
module_name = snake_case(name)
package = importlib.import_module(f"{package_name}.api.{module_name}_api")
return {
"api": getattr(package, name + "Api")(client),
"calls": [],
} | 5,293,751 |
def test_ap_wpa2_psk_ext_eapol_retry1c(dev, apdev):
"""WPA2 4-way handshake with EAPOL-Key 1/4 and 2/4 retransmitted and SNonce changing"""
(bssid,ssid,hapd,snonce,pmk,addr,rsne) = eapol_test(apdev[0], dev[0])
msg1 = recv_eapol(hapd)
anonce = msg1['rsn_key_nonce']
msg2 = recv_eapol(hapd)
if an... | 5,293,752 |
def checa_registro_json(registro, caminho_json):
"""
Checa se um <registro> já está no arquivo <caminho_json>.
Parâmetros
----------
registro : dict
Dicionário contendo o registro a ser checado.
Espera-se o formato:
{
'titulo' ... | 5,293,753 |
def train_val_split_images(data, report, dst_dir, phase="train"):
"""Splits the downloaded images into training and validation folders
Parameters
----------
data : pandas DataFrame
Contains the class labels of each image, idetified by its lat lng
report : pandas DataFrame
Contains t... | 5,293,754 |
def handle_recipe(recipe, pkg_path=None):
"""Handle the complete workflow of an autopkg recipe."""
display_verbose("Handling %s" % recipe)
if autopkglib.get_pref('RECIPE_REPO_DIR'):
recipe_repo_dir = autopkglib.get_pref('RECIPE_REPO_DIR')
else:
recipe_repo_dir = os.path.expanduser('~/Library/AutoPkg/Rec... | 5,293,755 |
def temporal_cyclic_transform(datetime_series, periodicity=None):
"""
TODO: VERY UNFINISHED
Replaces all time resolutions above the resolution specified with a fixed value.
This creates a cycle within a datetime series.
Parameters
----------
datetime_series: a pandas series of datetime objec... | 5,293,756 |
def read_json_file(json_path):
""" Read inventory as json file """
tf_inv = {}
try:
with open(json_path) as json_handler:
try:
tf_inv = json.load(json_handler)
except json.decoder.JSONDecodeError:
print(
"Provided terraform ... | 5,293,757 |
def friends_ids(user_id):
"""
https://dev.twitter.com/docs/api/1.1/get/friends/ids
http://docs.tweepy.org/en/latest/api.html#API.friends_ids
"""
for friends_ids_chunk in Cursor(api.friends_ids, user_id=user_id).pages():
for f in friends_ids_chunk: yield f | 5,293,758 |
def from_baseclaim(baseclaim: Baseclaim) -> VictorSolution:
"""Converts a Baseclaim into a VictorSolution.
Args:
baseclaim (Baseclaim): a Baseclaim.
Returns:
solution (VictorSolution): a VictorSolution.
"""
square_above_second = Square(row=baseclaim.second.row - 1, col=baseclaim.se... | 5,293,759 |
def test_render_datasource_new_notebook_with_pandas_Datasource(
empty_data_context,
construct_datasource_new_notebook_assets,
):
"""
What does this test and why?
The DatasourceNewNotebookRenderer should generate a notebook with text based on the datasource we are trying to implement. Here we are tes... | 5,293,760 |
def amsthm_latex(elem: Element, doc: Doc) -> pf.RawBlock | None:
"""Transform amsthm defintion to LaTeX package specifications."""
# check if it is a Div, and the class is an amsthm environment
options: DocOptions = doc._amsthm
if isinstance(elem, pf.Div):
environments: set[str] = options.theore... | 5,293,761 |
def async_run_in_kivy(func=None, clock=None):
"""Decorator that runs the given function in a Kivy context in an
asynchronous manner, waiting (asynchronously) until it's done.
It is primarily useful when kivy and trio are running in different threads.
See :mod:`kivy_trio.context` and the note below for ... | 5,293,762 |
def test_get_next_payment_date(generated_subscription, start_date, frequency, expected):
"""Check that get next payment date works correctly"""
test_subscription = Subscription(
owner=generated_subscription["owner"],
name=generated_subscription["name"],
frequency=frequency,
start... | 5,293,763 |
def he_normal():
""" Returns a weight initializer with a Gaussian distribution whose mean is
zero and standard deviation is :math:`\\sqrt{\\frac{2}{n_i}}`, where
:math:`n_i` is the number inputs to a layer.
See "Delving deep into rectifiers: Surpassing human-level performance on
ImageNet classifica... | 5,293,764 |
def upper_bound(sequences, max_run_time_random_seconds = 1):
""" Finds an upper bound based on some fast approximation algorithms."""
def alphabet_leftmost(sequences):
""" Approximation algorithm by looping through a random permutation on the alphabet """
seqs = copy.deepcopy(sequences)
... | 5,293,765 |
def get_block_source(template_source, block_name):
"""
Given a template's source code, and the name of a defined block tag,
returns the source inside the block tag.
"""
# Find the open block for the given name
match = re.search(NAMED_BLOCK_RE % (block_name,), template_source)
if match is Non... | 5,293,766 |
def test_get_default_site(settings, site_key, throws):
"""Test that get_default_site works as expected"""
authenticated_site = AuthenticatedSiteFactory.create(key="key")
settings.OPEN_DISCUSSIONS_DEFAULT_SITE_KEY = site_key
if not throws:
assert get_default_site() == authenticated_site
else:... | 5,293,767 |
def get_mysql_connection(replica_set_name,
writeable=False,
user_role=None,
replica_set_role=None):
""" Get MySQL connection information. This code also exists in
the wiki and is copied numberous places across the pinterest code base.
... | 5,293,768 |
def dj(_dict):
"""Converts dicts to JSON and safely handles non-serializable items"""
return json.dumps(
_dict,
default=lambda o: 'ERROR: Item not JSON serializable',
sort_keys=True,
indent=3) | 5,293,769 |
def inventree_commit_date(*args, **kwargs):
""" Return InvenTree git commit date string """
return version.inventreeCommitDate() | 5,293,770 |
async def google_signin(
request: Request,
provider: StarletteOAuth2App = Depends(GoogleProviderMarker)
) -> RedirectResponse:
""" Redirect to the login through Google OAuth. """
return await provider.authorize_redirect( # type: ignore[no-any-return]
request=request,
redirect_ur... | 5,293,771 |
def fillna_bfill(array):
"""Backward fills an array.
Args:
array: A 2d numpy array with dimensions (location, time)
Returns:
A numpy array.
"""
_assume_2d(array)
flipped = np.flip(array)
filled = fillna_ffill(flipped)
return np.flip(filled) | 5,293,772 |
def generate_cholesky_factor(n=100, k=20):
"""
Generate a toy banded Cholesky factor
"""
L_band = np.random.uniform(low=0.1, high=1.0, size=(k, n))
L_band[0, :] = np.abs(L_band[0, :])
L_dense = construct_banded_matrix_from_band(k - 1, 0, L_band)
return L_dense | 5,293,773 |
def get_task_status(request):
""" AJAX: Gets the status of a pending background task by hash """
task_hash = request.GET.get("task_hash", "")
if not task_hash:
return {'response': 'bad', 'message': 'Invalid request'}
# Check if completed
if CompletedTask.objects.filter(task_hash=task_hash).... | 5,293,774 |
def convert_to_fortran_bool(boolean):
"""
Converts a Boolean as string to the format defined in the input
:param boolean: either a boolean or a string ('True', 'False', 'F', 'T')
:return: a string (either 't' or 'f')
"""
if isinstance(boolean, bool):
if boolean:
new_string... | 5,293,775 |
def iter_dumps(iterable, width=2):
"""Converts numbers from iterable in the range from -1 to 1 into signed integers 'width' wide. And dumps them into a string or a bytearray."""
if width == 1:
return bytearray(map(lambda x: int(x * 127) & 255, iterable))
elif width == 2:
return bytearray(_se... | 5,293,776 |
def scatterplot(
a,
b=None,
along="x",
area=None,
aspect=None,
color=None,
filename=None,
height=None,
hyperlink=None,
label=None,
margin=50,
marker="o",
mlstyle=None,
mstyle=None,
opacity=1.0,
... | 5,293,777 |
def is_decorated(field_spec):
"""
is this spec a decorated one
:param field_spec: to check
:return: true or false
"""
if 'config' not in field_spec:
return False
config = field_spec.get('config')
return 'prefix' in config or 'suffix' in config or 'quote' in config | 5,293,778 |
def with_any_role_check(
roles: collections_abc.Sequence[typing.Union[hikari.SnowflakeishOr[hikari.Role], int, str]] = [],
*,
error_message: typing.Optional[str] = "You do not have the required roles to use this command!",
halt_execution: bool = False,
) -> collections_abc.Callable[[CommandT], Comm... | 5,293,779 |
def split_path(path):
"""
Normalise S3 path string into bucket and key.
Parameters
----------
path : string
Input path, like `s3://mybucket/path/to/file`
Examples
--------
>>> split_path("s3://mybucket/path/to/file")
['mybucket', 'path/to/file']
"""
if path.startswi... | 5,293,780 |
def test_window_destroy(window_id: int, xsession: XSession):
"""Tests that a window can be destroyed."""
xsession.window_destroy(window=window_id)
allow_xserver_to_sync()
with pytest.raises(RuntimeError):
xsession.get_window_name(window=window_id) | 5,293,781 |
def vj_timeseries(nStep,tau,s,par):
"""Returns time series simulation of squid, figure and csv
DEPENDENCIES
qSQUID()
numpy as np
matplotlib.pyplot as plt
INPUTS
nStep - number of steps to run in time series
tau - step size for time series
s - initial state vector ... | 5,293,782 |
def unixtime2mjd(unixtime):
"""
Converts a UNIX time stamp in Modified Julian Day
Input: time in UNIX seconds
Output: time in MJD (fraction of a day)
"""
# unixtime gives seconds passed since "The Epoch": 1.1.1970 00:00
# MJD at that time was 40587.0
result = 40587.0 + unixtime / (2... | 5,293,783 |
def splitdocfor(path):
"""split the docstring for a path
valid paths are::
./path/to/module.py
./path/to/module.py:SomeClass.method
returns (description, long_description) from the docstring for path
or (None, None) if there isn't a docstring.
Example::
... | 5,293,784 |
def vecdist3(coord1, coord2):
"""Calculate vector between two 3d points."""
#return [i - j for i, j in zip(coord1, coord2)]
# Twice as fast for fixed 3d vectors
vec = [coord2[0] - coord1[0],
coord2[1] - coord1[1],
coord2[2] - coord1[2]]
return (vec[0]*vec[0] + vec[1]*vec[1] + ... | 5,293,785 |
def start():
"""Start application service"""
sudo('start libra') | 5,293,786 |
def test_collect_trace_failures(mock_session_factory, mock_sniffer, status,
side_effect):
"""It should correctly report a timeout."""
expected: Result = {
'url': 'https://google.com', 'protocol': 'h3-Q050',
'page_source': None, 'final_url': None, 'status': status,... | 5,293,787 |
def svn_wc_get_status_editor(*args):
"""
svn_wc_get_status_editor(svn_wc_adm_access_t anchor, char target, apr_hash_t config,
svn_boolean_t recurse, svn_boolean_t get_all,
svn_boolean_t no_ignore, svn_wc_status_func_t status_func,
svn_cancel_func_t cancel_func,
svn_wc_tra... | 5,293,788 |
def get_taxa_set(trees):
"""
""" | 5,293,789 |
def getFORCodes(node, kw):
"""
Helper function for retrieving and organising FOR codes from the CSV file that contains them.
:param node: Node that the returnd values are for.
:param kw: Arguments that are passed to the shema's bind() method.
:return: OrderedDict of FOR codes nested appropriately.
... | 5,293,790 |
def test_vertex_disconnect(create, kindof):
"""Test transition and state vertices disconnection."""
t = create(TransitionItem)
v1 = create(StateItem, UML.State)
v2 = create(StateItem, UML.State)
connect(t, t.head, v1)
connect(t, t.tail, v2)
assert t.subject is not None
assert len(kindo... | 5,293,791 |
def write_to_file_doc(train_acc, train_loss, test_acc, test_loss, epoch, config):
"""
creates if not exist and update sumary csv file of the the training
"""
columns = ['experiment_name', 'epoch', 'train_loss', 'train_accuracy', 'test_loss', "test_accuracy", 'timestamp']
directory = config.summary_d... | 5,293,792 |
def num_active_calls(log, ad):
"""Get the count of current active calls.
Args:
log: Log object.
ad: Android Device Object.
Returns:
Count of current active calls.
"""
calls = ad.droid.telecomCallGetCallIds()
return len(calls) if calls else 0 | 5,293,793 |
def load_rsa(chain, data_path):
"""
func: load rsa fea array from acc file
"""
rsa_vector = {"e": [1, 0], "-": [0, 1], "b": [0, 1]}
rsa_f = os.path.join(data_path, chain, chain+".acc")
rsa_fea_arr = []
f = open(rsa_f, "r")
rsa_str = f.readlines()[-1].strip()
f.close()
for i in rs... | 5,293,794 |
def module_create_from_connection_string(transportType, connectionString, caCertificate=None): # noqa: E501
"""Create a module client from a connection string
# noqa: E501
:param transportType: Transport to use
:type transportType: str
:param connectionString: connection string
:type connect... | 5,293,795 |
def ldns_rdf_new_frm_fp_l(*args):
"""LDNS buffer."""
return _ldns.ldns_rdf_new_frm_fp_l(*args) | 5,293,796 |
def run_experiment(fr: int, to: int) -> (int, int):
"""Run the classical part of Shor's algorithm."""
n = get_odd_non_prime(fr, to)
a = get_coprime(n)
order = classic_order(a, n)
factor1 = math.gcd(a ** (order // 2) + 1, n)
factor2 = math.gcd(a ** (order // 2) - 1, n)
if factor1 == 1 or factor2 == 1:
... | 5,293,797 |
def backward_prop(data, labels, params, forward_prop_func):
"""
Implement the backward propegation gradient computation step for a neural network
Args:
data: A numpy array containing the input
labels: A 2d numpy array containing the labels
params: A dictionary mapping parameter ... | 5,293,798 |
def homepage(js):
"""
Extract an URL for that researcher (if any)
"""
lst = jpath(
'person/researcher-urls/researcher-url', js, default=[])
for url in lst:
val = jpath('url/value', url)
name = jpath('url-name', url)
if name is not None and ('home' in name.lower() or '... | 5,293,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.