content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_main(app):
"""
Given the app is up and running
When I make a call to the frontend page
Then I get HTTP 200 OK response
"""
client = app.test_client()
response = client.get("/")
assert response.status_code == 200 | 48,000 |
def update_message_id(message_id, peername):
"""
Update message id for peername in global PEERS_MESSAGE_IDS dict.
Return True iff message_id was updated, else False.
"""
global PEERS_MESSAGE_IDS
if peername not in PEERS_MESSAGE_IDS.keys():
print('[DEBUG] No record of latest messa... | 48,001 |
def quantile_bin_array(data, bins=6):
"""Returns symbolified array with equal-quantile binning.
Parameters
----------
data : array
Data array of shape (time, variables).
bins : int, optional (default: 6)
Number of bins.
Returns
-------
symb_array : array
Conver... | 48,002 |
def make_custom_fields():
"""Create Custom fields
- QR code Image file
- Company Name in Arabic
- Address in Arabic
"""
custom_fields = {
'Sales Invoice': [
dict(
fieldname='qr_code',
label='QR Code',
fieldtype='Attach Image',
read_only=1, no_copy=1, hidden=1
)
],
'Address': [
dict(... | 48,003 |
def wrap_socket(sock: _socket.socket) -> AsyncSocket:
"""
Wraps a standard socket into an async socket
"""
return AsyncSocket(sock) | 48,004 |
def test_uniform_P():
""" This stopped working because SingleContinuousPSpace.compute_density no
longer calls integrate on a DiracDelta but rather just solves directly.
integrate used to call UniformDistribution.expectation which special-cased
subsed out the Min and Max terms that Uniform produces
... | 48,005 |
def _calculate_outer_product_steps(signed_steps, n_steps, dim_x):
"""Calculate array of outer product of steps.
Args:
signed_steps (np.ndarray): Square array with either pos or neg steps returned
by :func:`~estimagic.differentiation.generate_steps.generate_steps` function
n_steps (i... | 48,006 |
def compute_lima_on_off_image(n_on, n_off, a_on, a_off, kernel):
"""Compute Li & Ma significance and flux images for on-off observations.
Parameters
----------
n_on : `~gammapy.maps.WcsNDMap`
Counts image
n_off : `~gammapy.maps.WcsNDMap`
Off counts image
a_on : `~gammapy.maps.Wc... | 48,007 |
def data_preprocess(ex, mode='uniform', z_size=20):
"""
Convert image dtype and scale imge in range [-1,1]
:param z_size:
:param ex:
:param mode:
:return:
"""
image = ex['image']
image = tf.image.convert_image_dtype(image, tf.float32)
image = tf.reshape(image, [-1])
image = i... | 48,008 |
def p2wpkh(pubkey: PubKey, network: str = 'mainnet') -> bytes:
"""Return the p2wpkh (bech32 native) SegWit address."""
network_index = _NETWORKS.index(network)
ec = _CURVES[network_index]
pubkey = to_pubkey_bytes(pubkey, True, ec)
h160 = hash160(pubkey)
return b32address_from_witness(0, h160, ne... | 48,009 |
def generate_output(gruidhitsdict, gemchitsdict, metadata, filename, fevent, nevents, outtype=0):
"""Calls appropiate output function based in outtype.
"""
outfname = generate_outfilename(filename, fevent, nevents)
switch = [_export0, _export1, _export2, _export3, _export4]
switch[outtype-1](gruidhi... | 48,010 |
def is_not_from_subdomain(response, site_dict):
"""
Ensures the response's url isn't from a subdomain.
:param obj response: The scrapy response
:param dict site_dict: The site object from the JSON-File
:return bool: Determines if the response's url is from a subdomain
"""
root_url = re.su... | 48,011 |
def get_affiliation():
"""Return a school/organization affiliation."""
return random.choice(AFFILIATIONS) | 48,012 |
def update_item_feature(train, num_item, user_features, lambda_item, nz_users_indices, robust=False):
"""
Update item feature matrix
:param train: training data, sparse matrix of shape (num_item, num_user)
:param num_item: number of items
:param user_features: factorized user features, dense matrix ... | 48,013 |
def generate_mutation(model, mutation_type):
"""
Generate a model mutation.
Create the mutation class
Parameters:
model (dict): the model dictionary from settings
mutation_type (str): the mutation type (create, delete, update)
Returns:
graphene.Mutation.Field: the mutation field
""... | 48,014 |
def call_and_return_stdout(args: tp.Union[str, tp.List[str]],
timeout: tp.Optional[tp.Union[str, int]] = None,
encoding: tp.Optional[str] = None,
expected_return_code: tp.Optional[int] = None,
**kwargs) -> tp.Uni... | 48,015 |
def p_termlist_multi(p):
"""
termlist : term ',' termlist
"""
p[0] = [p[1], *p[3]] | 48,016 |
def test_add_diagonals_simple():
"""Basis example for _add_diagonals."""
a = np.array([
[1, 2, 3, 4],
[5, 6, 7, 8],
[1, 2, 3, 4]
])
b = np.array([
[1, 2, 3, 4],
[5, 6, 7, 8]
])
expected_output = np.array([
[2, 4, 6, 8],
[10, 12, 14, 16],
... | 48,017 |
def _wf_to_char(string):
"""Wordfast &'XX; escapes -> Char"""
if string:
for code, char in WF_ESCAPE_MAP:
string = string.replace(code, char.encode('utf-8'))
string = string.replace("\\n", "\n").replace("\\t", "\t")
return string | 48,018 |
def cloud_config():
"""
Loads configuration required for running against GCP based environments
This function makes calls to GCP native tools such as Google Secret Manager
and therefore should not be called in situations where these connections are
not possible, e.g running the unit tests locally.
... | 48,019 |
def agg_15_min_load_profile (load_profile_df):
"""
Aggregates 1-Hz load profile by taking average demand over 15-min
increments.
"""
s_in_15min = 15 * 60
# prepare idx slices
start_idxs = np.arange(0, len(load_profile_df), s_in_15min)
end_idxs = np.arange(s_in_15min, len(load_prof... | 48,020 |
def icon(image):
# type (str) -> dict
"""Creates the application folder icon info for main menu items"""
return {"icon": os.path.join(MEDIA_URI, image)} | 48,021 |
def get_gitbuilder_hash(project=None, branch=None, flavor=None,
machine_type=None, distro=None,
distro_version=None):
"""
Find the hash representing the head of the project's repository via
querying a gitbuilder repo.
Will return None in the case of a 404... | 48,022 |
def get_b16_add_conv_config():
"""Returns the ViT-B/16 configuration."""
config = ml_collections.ConfigDict()
config.patches = ml_collections.ConfigDict({'size': (16, 16)})
config.split = 'non-overlap'
config.slide_step = 12
config.hidden_size = 768
config.transformer = ml_collections.Config... | 48,023 |
def real_proto(request) -> programl_pb2.ProgramGraph:
"""A test fixture which enumerates one of 100 "real" protos."""
return request.param | 48,024 |
def flat(arr):
"""Return arr flattened except for last axis."""
shape = arr.shape[:-1]
n_features = arr.shape[-1]
return arr.reshape(np.product(shape), n_features) | 48,025 |
def test():
"""Runs the tests without code coverage"""
tests = unittest.TestLoader().discover("project/tests", pattern="test*.py")
result = unittest.TextTestRunner(verbosity=2).run(tests)
if result.wasSuccessful():
return 0
sys.exit(result) | 48,026 |
def wait_while(f_logic, timeout, warning_timeout=None, warning_text=None, delay_between_attempts=0.5):
"""
Внутренний цик выполняется, пока вычисление `f_logic()` трактуется как `True`.
"""
warning_flag = False
start_time = datetime.now()
while True:
try:
result = f_logic()... | 48,027 |
def acute_lymphocytic_leukemia1():
"""Human Acute Lymphocytic Leukemia dataset (Patient 1).
This dataset was introduced in :cite:`Gawad_2014` and was used in:
* :cite:`B-SCITE` Figure 5.
* :cite:`infSCITE` Figure S16.
The size is n_cells × n_muts = 111 × 20
Returns
-------
:class:`an... | 48,028 |
def extract_module(start_queue, g, locality="top", max_to_crawl=100, max_depth=10):
"""
([rdflib.URI], rdflib.Graph) -> rdflib.Graph
resource (rdflib.URI): resource for which we extract module
g (rdflib.Graph): RDF graph
"""
ontomodule = Graph()
ontomodule.namespace_manager = g.namespace_m... | 48,029 |
def workbook(es_app):
""" Loads a bunch of data (tests/data/workbook-inserts) into the system on first run
(session scope doesn't work). """
WorkbookCache.initialize_if_needed(es_app) | 48,030 |
def test_lyth_ellipsis():
"""
Start the main function, activates the console and hopes that let statement
does not lead to an exception.
"""
with unittest.mock.patch.object(builtins, 'input', send_let):
with unittest.mock.patch('sys.stdout', new_callable=StringIO):
assert main(["... | 48,031 |
def login(servers, *users, config=None):
"""Configure LDAP server and LDAP authenticated users and
try to login and execute a query"""
with ldap_servers(servers):
with ldap_authenticated_users(*users, restart=True, config=config):
for user in users:
if user.get("login", F... | 48,032 |
def test_update(app, combatant):
"""Test update on valid fields."""
combatant.privacy_acceptance.resolve(True)
update_request = UpdateRequest(combatant=combatant)
app.db.session.add(update_request)
app.db.session.commit()
data = dict(
legal_name='Fred McFred',
sca_name='Fred O''... | 48,033 |
def softmax(x):
"""Softmax activation function
Parameters
----------
x : torch.tensor
"""
return torch.exp(x) / torch.sum(torch.exp(x), dim=1).view(-1, 1) | 48,034 |
def comp_raw_bool_eqs(eq1str, eq2str):
""" Will compare two boolean equations to see if they are the same.
The equations can be written using the characters '&', '+' and '!'
for 'and', 'or' and 'not' respectively.
"""
(eqn1, eqn1vars) = OqeFuncUtils.get_vars_bool_eqn(eq1str)
(eqn2, eqn2v... | 48,035 |
def get_integrated_scene(glm_files, start_scene=None):
"""Get an integrated scene.
Given a set of GLM files, get a scene where quantities are summed or
averaged or so.
"""
ms = satpy.MultiScene.from_files(
glm_files,
"glm_l2",
time_threshold=10,
group... | 48,036 |
def _pt_to_test_name(what, pt, view):
"""Helper used to convert Sublime point to a test/bench function name."""
fn_names = []
pat = TEST_PATTERN.format(WHAT=what, **globals())
regions = view.find_all(pat, 0, r'\1', fn_names)
if not regions:
sublime.error_message('Could not find a Rust %s fun... | 48,037 |
def load_log_weights(log_weights_root, iw_mode):
"""Loads the log_weights from the disk. It assumes a file structure of <log_weights_root>/<iw_mode>/*.npy
of mulyiple npy files. This function loads all the weights in a single numpy array, concatenating all npy files.
Finally, it caches the result in a file ... | 48,038 |
def createTrainingSetVisuals():
"""
Using the visualizeTrainingInstance method, this method creates and saves visualizations for *all* training instances.
"""
# Get all training images (by hashnames).
filenames = os.listdir(TRAINING_SET_DIR)
hashes = [os.path.splitext(filename)[0] for filename in filenames if not... | 48,039 |
def pipelines_is_ready():
"""
Used to show the "pipelines is loading..." message
"""
url = f"{API_ENDPOINT}/{STATUS}"
try:
if requests.get(url).status_code < 400:
return True
except Exception as e:
logging.exception(e)
sleep(1) # To avoid spamming a non-exist... | 48,040 |
def invTransect(T, sorted_ring_list, warnifnotunique=True):
"""Finds a transect that ends at T.
In the case there are more than one, if warnifnotunique=True,
user will be warned, but this may slow down transect generation.
IS `warnifnotunique` IMPLEMENTED? Maybe not ...
Returns:
list of tu... | 48,041 |
def gamma_from_RLGC(freq,R,L,G,C):
"""Get propagation constant gamma from RLGC transmission line parameters"""
w=2*np.pi*freq
return cmath.sqrt((R+1j*w*L)*(G+1j*w*C)) | 48,042 |
def get_abs_paths(paths: Optional[List[Union[str, Path]]]) -> List[Union[str, Path]]:
"""Extract the absolute path from the given sources (if any).
:param paths: list of source paths, if empty this functions does nothing.
"""
if paths is None:
return []
paths_abs = []
for path in path... | 48,043 |
async def async_setup_gateway_entry(hass: core.HomeAssistant, entry: config_entries.ConfigEntry) -> bool:
"""Set up the Gateway component from a config entry."""
host = entry.data[CONF_HOST]
euid = entry.data[CONF_TOKEN]
# Connect to gateway
gateway = IT600Gateway(host=host, euid=euid)
try:
... | 48,044 |
def import_from_github(username, repo, commit_hash):
"""Import a GitHub project into the exegesis database. Returns True on
success, False on failure.
"""
url = 'https://api.github.com/repos/{}/{}/git/trees/{}?recursive=1'.format(
username, repo, commit_hash)
headers = {'Accept': 'applicatio... | 48,045 |
def test_logfile_short() -> None:
"""Test logfile parsing."""
params = parse_args(["-lshortname.log"]) # short form
assert params.logfile == "shortname.log" | 48,046 |
def MakeConfigFilenameRelative(absolute_filename):
"""Determine an absolute filename's path relative to the monolith.
Args:
absolute_filename: str
Returns:
str
NB:
looks at MONOLITHIC_CODEBASE_NAME to determine where the monolithic
codebase starts. e.g., if MONOLITHIC_CODEBASE_NAME is 'bar', ... | 48,047 |
def get_checks():
""" Returns a list of Entry """
manager = Manager()
add = manager.add
JOY_DEVICE = '/dev/input/js0'
this_is_a_duckiebot = on_duckiebot()
this_is_a_laptop = on_laptop()
this_is_circle = on_circle()
username = getpass.getuser()
if this_is_a_duckiebot:
... | 48,048 |
def substructure_matching_bonds(mol: dm.Mol, query: dm.Mol, **kwargs):
"""Perform a substructure match using `GetSubstructMatches` but instead
of returning only the atom indices also return the bond indices.
Args:
mol: A molecule.
query: A molecule used as a query to match against.
... | 48,049 |
def remove_element(nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
sz = len(nums)
while sz > 0 and nums[sz - 1] == val:
sz -= 1
i = 0
while i < sz:
if nums[i] == val:
nums[i], nums[sz - 1] = nums[sz - 1], nums[i]
sz -= 1
... | 48,050 |
def drawBoard(board):
"""
Draw the board data structure.
"""
hline = ' ' # initial space for the numbers
# down the left side of the board
for i in range(1, 6):
hline += (' ' * 9) + str(i)
# print the numbers across the top
print(hline)
print(' ' + ('... | 48,051 |
def write_docs(filename, title, docstring):
"""
Writes out documentation to a file.
"""
reflabel = "ref_%s" % filename
title = underline(title, "=")
f = open("%s/%s.rst" % (OUT_DIR, filename), "wt")
f.write(DOC_TEMPLATE % locals()) | 48,052 |
def get_fm_file(file_name):
"""Read facilitymatcher file into dataframe. If not present, generate the file
via script"""
file_meta = set_facilitymatcher_meta(file_name, category='')
df = load_preprocessed_output(file_meta, paths)
if df is None:
log.info('%s not found in %s, writing facility ... | 48,053 |
def call_dot(instr):
"""Call dot, returning stdout and stdout"""
dot = Popen('dot -T png'.split(), stdout=PIPE, stderr=PIPE, stdin=PIPE)
return dot.communicate(instr) | 48,054 |
def add_bank_member_signal(
banks_table: BanksTable,
bank_id: str,
bank_member_id: str,
signal_type: t.Type[SignalType],
signal_value: str,
) -> BankMemberSignal:
"""
Add a bank member signal. Will deduplicate a signal_value + signal_type
tuple before writing to the database.
Callin... | 48,055 |
async def async_migrate_entry(hass, config_entry):
"""Migrate old entry."""
_LOGGER.debug("Migrating from version %s", config_entry.version)
# Flatten configuration but keep old data if user rollbacks HASS
if config_entry.version == 1:
config_entry.data = {**config_entry.data, **config_entry.d... | 48,056 |
def get_flow1_datasets_result_path(create=True):
""" local path for flow1 results file """
path = os.path.join(get_base_path(), 'flow1-datasets-results.json')
if not os.path.isfile(path):
open(path, 'w').close()
return path | 48,057 |
def barre(Liste,a='optionnel',pas='optionnel') :
"""
Liste est une liste de valeurs
Si seulement Liste est renseigné, les valeurs seront réparties en 10 classes.
Si Liste et a sont renseignés, les valeurs seront réparties en a classes.
Si les trois paramètres sont renseignés:
a est le ce... | 48,058 |
def test_norm_context(context, expected_context):
"""
GIVEN context
WHEN _norm_context is called with the context
THEN the expected context is returned.
"""
# pylint: disable=protected-access
returned_context = ref_helper._norm_context(context=context)
assert returned_context == expecte... | 48,059 |
def map_zones(full_system) -> List[Zone]:
"""Map *zones*."""
zones = []
if full_system:
for raw_zone in full_system.get("body", dict()).get("zones", list()):
zone = map_zone(raw_zone)
if zone:
zones.append(zone)
return zones | 48,060 |
def betternn(x, keep_prob):
"""
Builds a network that learns to recognize digits
:param x: input tensor of shape (N_examples, 784) as standard MNIST image is 28x28=7845
:param keep_prob: probability for dropout layer
:return: y - a tensor of shape (N_examples, 10) with
values equal to probabilit... | 48,061 |
def get_valid_scsi_ids(devices, reserved_ids):
"""
Takes a list of dicts devices, and list of ints reserved_ids.
Returns:
- list of ints valid_ids, which are the SCSI ids that are not reserved
- int recommended_id, which is the id that the Web UI should default to recommend
"""
occupied_ids ... | 48,062 |
def check_password_and_delete(target: dict, password) -> dict:
"""
:param target:
:param password:
:return:
"""
if "password" in target:
if md5(str(password).encode()).hexdigest() == target["password"]:
target = dell(target["password"])
Bash().delete({
... | 48,063 |
def search(topic: str) -> None:
"""Searches about the topic on Google"""
link = 'https://www.google.com/search?q={}'.format(topic)
web.open(link) | 48,064 |
def lingodoc_trigger_to_BIO(doc):
"""
:type doc: nlplingo.text.text_theory.Document
"""
ret = []
for sentence in doc.sentences:
token_labels = []
for token_index, token in enumerate(sentence.tokens):
token_labels.append(EventTriggerFeatureGenerator.get_event_type_of_toke... | 48,065 |
def showGUI(taskList, options = {}):
"""
Starts the application in GUI mode
"""
LOGGER.info("Showing GUI")# , options)
options['taskList'] = taskList
app = GUI(options)
app.Show() | 48,066 |
def build_coiled_coil_model():
"""Generates and returns a coiled-coil model."""
model_and_info = build_and_record_model(
request, model_building.HelixType.ALPHA)
return jsonify(model_and_info) | 48,067 |
def main():
""" Set up Q-learning and run """
print("Initiating simulation...")
rospy.init_node('q_learning')
ql_agent = QlearnCartPole()
rospy.on_shutdown(ql_agent.clean_shutdown)
ql_agent.train()
rospy.spin() | 48,068 |
def get_input_fn(config, is_training,
num_cpu_threads=4):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
input_files = []
for input_pattern in config.pretrain_tfrecords.split(","):
input_files.extend(tf.io.gfile.glob(input_pattern))
def input_fn(params):
"""The actu... | 48,069 |
def control_modes_available():
"""API to call the GetCtrlModesCountSrv service to get the list of available modes
in ctrl_pkg (autonomous/manual/calibration).
Returns:
dict: Execution status if the API call was successful, list of available modes
and error reason if call fails.
... | 48,070 |
def reproject_bbox(source_epsg=4326, dest_epsg=None, bbox=None):
"""
Basic function to reproject given coordinate
bounding box (in WGS84).
"""
# checks
# reproject bounding box
l, b, r, t = bbox
return transform_bounds(src_crs=source_epsg,
dst_crs=dest_e... | 48,071 |
def compile_py_files(toc, workpath):
"""
Given a TOC or equivalent list of tuples, generates all the required pyc/pyo files, writing in a local directory
if required, and returns the list of tuples with the updated pathnames.
In the old system using ImpTracker, the generated TOC of "pure" modules alrea... | 48,072 |
def parse_cluster_card_info(soup: BeautifulSoup):
"""
App lists from GET requests follow a redirect to the /cluster page, which
contains different HTML and selectors.
:param soup: A BeautifulSoup object of an app's card
:return: A dictionary of available basic app info
"""
icon = soup.selec... | 48,073 |
def get_joint_occurrence_df(df, row_column, col_column, top_k=10):
"""
Form a DataFrame where:
- index is composed of top_k top values in row_column.
- columns are composed of top_k top values in col_column.
- cell values are the number of times that the index and
column values occur together in... | 48,074 |
def send_message(to, msg, *, from_=None, smtp_cfg={}):
"""
Sends a message.
:param to:
A sequence of recipient email addresses.
:param msg:
`email.mime` message object to send.
:param from_:
The sender address, or none to determine automatically.
"""
host = smtp_cfg.get... | 48,075 |
def get_total_obs_num_samples(obs_length=None,
num_blocks=None,
length_mode='obs_length',
num_antennas=1,
sample_rate=3e9,
block_size=134217728,
... | 48,076 |
def documents_glossary_term(response: Response,
request: Request=Query(None, title=opasConfig.TITLE_REQUEST, description=opasConfig.DESCRIPTION_REQUEST),
term_id: str=Path(..., title="Glossary Term ID or Partial ID", description=opasConfig.DESCRIPTION_GLOSSARYID... | 48,077 |
def test_submit_wrong_key(client):
"""Make sure users cannot submit code with an invalid secret key."""
rv = client.post('/api/submit', data=dict(
problem_id='test',
type='python',
code=(io.BytesIO(b'N=int(input())\nprint(N)\n'), 'code.py'),
username='test_user',
secret_k... | 48,078 |
def test_private_methods(key: bucketstore.S3Key) -> None:
"""This method contains boto internals, so as long as it returns a truthy value, it is good."""
assert key._boto_object | 48,079 |
def compile_dictionary(vargs):
"""
Compile the given dictionary into a MARISA trie,
and save it to file.
:param dict vargs: the command line arguments
"""
if vargs["dictionary"] is None:
print_error("You must specify the path of the input dictionary file.")
if vargs["output"] is... | 48,080 |
def test_album_photos() -> None:
"""
Verify basic parsing of the /album/web/<id> endpoint.
"""
with open(
os.path.join(os.path.dirname(__file__), "data", "album_web.html"),
"r",
encoding="utf-8",
) as f:
assert _parse_album_photos_response(f) == [
Photo(n... | 48,081 |
def number(
x: Scalar,
c: str = 'csl',
w: int = 5,
) -> str:
"""
Return a notation of the number x in context c.
Input:
x (Scalar): number
c (str): context
w (int): width of the output string
Output:
s (str): notation of x
"""
S = 0 if x>=0 else 1 # ... | 48,082 |
def test_create_az_mask_ppi_correctly_finds_azi():
""" Tests whether create_az_mask_ppi correctly indentifies the array element nearest
the specified azimuth value
"""
input_array = np.arange(119, 121)
input_azi = 120
radar_band = "c"
ret_value = create_masks.create_az_mask_ppi(input_a... | 48,083 |
def remove_helm_repo(repos_array):
"""
Execute 'helm repo remove' command on input values
repos_array is an array of strings as:
['stable', 'local', 'nalkinscloud', ...]
:param repos_array: array of strings
:return: return code and value from execution command as dict
"""
status = 0
... | 48,084 |
def unity_inference(env, model,
episodes: int) -> NoReturn:
"""
inference mode. algorithm model will not be train, only used to show agents' behavior
"""
for episode in range(episodes):
model.reset()
ret = env.reset(reset_config={})
while True:
... | 48,085 |
def evaluate_fio(baselines: dict, results: dict, test_name: str, failures: int,
tolerance: int) -> int:
"""
Evaluate the fio test results against the baseline.
Determine if the fio test results meet the expected threshold and display
the outcome with appropriate units.
Parameters
... | 48,086 |
def test_exact_max_start_attempts(tempfiles, caplog, max_start_attempts):
"""
This test asserts that we properly report max_start_attempts.
"""
script = tempfiles.makepyfile(
r"""
# coding=utf-8
import sys
import time
import multiprocessing
def main():
... | 48,087 |
def test_list_identifiers(client, mocker):
"""Test the listIdentifiers verb responds and conforms as expected"""
# Mock the datacite service to ensure the same record data is returned.
mocked_get_metadata_list = mocker.patch('viringo.services.datacite.get_metadata_list')
# Get fake results
result_... | 48,088 |
def f1_3D(x1, x2, x3):
"""
x1 dependant
from example 2.1 in iterative methods
"""
return -0.2*x2 - 0.2*x3 + 0.8 | 48,089 |
def encrypt(message: typing.Union[str, bytes], n: int, e: int) -> bytes:
"""
Encrypt MESSAGE with public key specified by N and E
"""
pub_key = rsa.PublicKey(n, e)
if isinstance(message, str):
message = message.encode("utf-8")
elif isinstance(message, bytes):
pass
else:
... | 48,090 |
def _safe_div(numerator, denominator):
"""Divides two tensors element-wise, returning 0 if the denominator is <= 0.
Args:
numerator: A real `Tensor`.
denominator: A real `Tensor`, with dtype matching `numerator`.
Returns:
0 if `denominator` <= 0, else `numerator` / `denominator`
"""
t ... | 48,091 |
def build_embedding_model():
""" Build model by stacking up a preprocessing layer
and an encoding layer.
Returns
-------
tf.keras.Model
The embedding model, taking a list of strings as input,
and outputting embeddings for each token of the input strings
"""
# Lin... | 48,092 |
def event_date_row(event_names_and_dates):
""" Returns the third row of the attendance csv. This is just a list of event dates.
:param list[(str, datetime)] event_names_and_dates:
A list of names and dates for each event that should appear on the csv
:returns:
the row to be printed
... | 48,093 |
def moving_tajima_d(ac, size, start=0, stop=None, step=None, min_sites=3):
"""Calculate the value of Tajima's D in moving windows of `size` variants.
Parameters
----------
ac : array_like, int, shape (n_variants, n_alleles)
Allele counts array.
size : int
The window size (number of... | 48,094 |
def sample_member(user, name='Attila'):
"""
Create and return a sample tag
:param user:
:param name:
:return:
"""
return Member.objects.create(user=user, name=name) | 48,095 |
def _create_feed(client, customer_id):
"""Creates a page feed with URLs
Args:
client: an initialized GoogleAdsClient instance.
customer_id: a client customer ID str.
Returns:
A FeedDetails instance with information about the newly created feed.
"""
# Retrieve a new feed ope... | 48,096 |
def cal_pj_task_ind(_st_date, _ed_date):
"""
计算产品研发中心资源投入到非产品事务的指标。
:param _st_date: 起始日期
:param _ed_date: 截止日期
:return: 统计指标
"""
global extTask
_pj_info = handler.get_project_info("project_t")
# logging.log(logging.WARN, ">>> cal_pj_task_ind( %s, %s )" % (_st_date, _ed_date))
... | 48,097 |
def retrieve_tensors(logdir, groups=["train", "valid"]):
"""
Grab all tensorboard tensors and put them in one loss dataframe
Parameters
----------
logdir : str
Directory containing summary log of loss for tensorboard
groups : list, optional
groups containing tensors in the summa... | 48,098 |
def get_page_index(obj, amongst_live_pages=True):
"""
Get oage's index (a number) within its siblings.
:param obj:
Wagtail page object
:param amongst_live_pages:
Get index amongst live pages if True or all pages if False.
:return:
Index of a page if found or None if page d... | 48,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.