content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import math
import random
def naive_scheduler(task_qs, max_workers, old_worker_map, to_die_list, logger):
""" Return two items (as one tuple) dict kill_list :: KILL [(worker_type, num_kill), ...]
dict create_list :: CREATE [(worker_type, num_create), ...]
In this s... | 801bfbf3dc9071b1e1f202f63452634e562edb14 | 3,655,100 |
def run(ceph_cluster, **kwargs) -> int:
"""
Method that executes the external test suite.
Args:
ceph_cluster The storage cluster participating in the test.
kwargs The supported keys are
config contains the test configuration
Returns:
0 - Suc... | a8107c35049d2edcb5d8f4f844e287ea7fcd1c81 | 3,655,101 |
import requests
import urllib
from bs4 import BeautifulSoup
def search_item(search_term, next=False, page=0, board=0):
"""function to search and return comments"""
if next == False:
page = requests.get("https://www.nairaland.com/search?q=" + urllib.parse.quote_plus(str(search_term)) + "&board="+str(b... | 7e2a72c9df82f204ac852b1c3028c6de8906594b | 3,655,102 |
def is_valid_action(state, x, y, direction):
"""
Checks if moving the piece at given x, y coordinates in the given direction is valid, given the current state.
:param state: the current state
:param x: the x coordinate of the piece
:param y: the y coordinate of the piece
:param direction: the d... | 9be9d6a16d6ec3f766ee7f91c08d3ced7d5ff6b8 | 3,655,103 |
def range_(minimum, maximum):
"""
A validator that raises a :exc:`ValueError` if the initializer is called
with a value that does not belong in the [minimum, maximum] range. The
check is performed using ``minimum <= value and value <= maximum``
"""
return _RangeValidator(minimum, maximum) | 27dc9c9c814371eb03b25f99be874e39d48c1a52 | 3,655,104 |
def sigmoid_prime(z):
"""Helper function for backpropagation"""
return sigmoid(z) * (1 - sigmoid(z)) | 13541050982152668cdcec728f3a913298f2aad8 | 3,655,105 |
def register_widget_util(ui_name, some_type, gen_widgets, apply_with_params):
"""
ui_name: the name of this utility in the UI
some_type: this utility will appear in the sidebar whenever your view function
returns a value of type ``some_type``
gen_widgets(val): a function that takes the report valu... | 25273753e0e31472cc44ef3527200e9dfa797de2 | 3,655,106 |
from datetime import datetime
def _CreateSamplePostsubmitReport(manifest=None,
builder='linux-code-coverage',
modifier_id=0):
"""Returns a sample PostsubmitReport for testing purpose.
Note: only use this method if the exact values don't matter.
... | 5c7bccda2648f4d8d26725e983a567d5b011dbb6 | 3,655,107 |
import os
def create_doc_term_matrix():
"""
Load document-term matrix from disk into memory
"""
df = None
if os.path.isfile(DOCTERM_PICKLE):
print('Saved dataframe found! Loading saved document-term matrix...')
df = pd.read_pickle(DOCTERM_PICKLE)
else:
print('Could not find saved document-term matrix, l... | 3583dafc056397766e6c2491d4395cb35eb8ef84 | 3,655,108 |
import typing
def _fetch_measurement_stats_arrays(
ssc_s: typing.List[_NIScopeSSC],
scalar_measurements: typing.List[niscope.ScalarMeasurement],
):
"""
private function for fetching statics for selected functions.
Obtains a waveform measurement and returns the measurement value. This
method ma... | 4acad87bc9b0cd682725ea5edcade10d996653a1 | 3,655,109 |
def nativeMouseY(self):
"""
TOWRITE
:rtype: qreal
"""
scene = self.activeScene() # QGraphicsScene*
if scene:
qDebug("mouseY: %.50f" % -scene.property("SCENE_MOUSE_POINT").y()) # .toPointF().y())
if scene:
return -scene.property("SCENE_MOUSE_POINT").y() # .toPointF().y()
... | dc0d4c1f0ff4ab1611ee68a35fd5dfb254a31566 | 3,655,110 |
def generate_repository_dependencies_folder_label_from_key( repository_name, repository_owner, changeset_revision, key ):
"""Return a repository dependency label based on the repository dependency key."""
if key_is_current_repositorys_key( repository_name, repository_owner, changeset_revision, key ):
la... | 5654b29354b07f9742ef1cdf20c313ecbcfec02f | 3,655,111 |
def weighted_characteristic_path_length(matrix):
"""Calculate the characteristic path length for weighted graphs."""
n_nodes = len(matrix)
min_distances = weighted_shortest_path(matrix)
sum_vector = np.empty(n_nodes)
for i in range(n_nodes):
# calculate the inner sum
sum_vector[i] = (1/(n_nodes-1)) *... | ff171ad9bf7a6968ebf9d41dd5c508bb8b39b16a | 3,655,112 |
import threading
import sqlite3
def execute_timeout(cnx, command, **kwargs):
"""Perform Sqlite3 command to be interrupted if running too long.
If the given command is a string, it is executed as SQL.
If the command is a callable, call it with the cnx and any given
keyword arguments.
Raises SystemE... | 57b0cc43fc5e9790a0cada0ca9fdd075e652bf41 | 3,655,113 |
def mean_IoU(threshold=0.5, center_crop=0, get_batch_mean=True):
"""
- y_true is a 3D array. Each channel represents the ground truth BINARY channel
- y_pred is a 3D array. Each channel represents the predicted BINARY channel
"""
def _f(y_true, y_pred):
y_true = fix_input(y_true)
y_... | 0c9ee55b694e11615bd6ab023ce1f43354b986b1 | 3,655,114 |
import csv
def ConvertCSVStringToList(csv_string):
"""Helper to convert a csv string to a list."""
reader = csv.reader([csv_string])
return list(reader)[0] | fa244d2a1c8c50b2b097883f964f1b5bb7ccf393 | 3,655,115 |
def get_section_range_pairs(orig_section, new_pdf):
"""Return MatchingSection for a section."""
other_section = new_pdf.find_corresponding_section(orig_section)
if not other_section:
print("Skipping section {} - no match in the other doc!".format(
orig_section.title))
return None... | ff1ef7bedcc0a1264a8cd191267d35a75c302eac | 3,655,116 |
import sqlite3
from typing import Any
import logging
def atomic_transaction(conn: sqlite3.Connection,
sql: str, *args: Any) -> sqlite3.Cursor:
"""Perform an **atomic** transaction.
The transaction is committed if there are no exceptions else the
transaction is rolled back.
Args... | 9748a6e315521278c4dc60df891081dcd77c98b9 | 3,655,117 |
def convert_to_tensor(narray, device):
"""Convert numpy to tensor."""
return tf.convert_to_tensor(narray, tf.float32) | 699f4cbdad83bc72525d237549420e67d0d464f8 | 3,655,118 |
import logging
def get_config_origin(c):
"""Return appropriate configuration origin
Parameters
----------
c: Configuration
configuration to be examined
Returns
-------
origin: str
origin of configuration (e.g. "Local", "Random", etc.)
"""
if not c.origin:
... | a52be755fe37f128c0e629fecfe3307d3bb69fff | 3,655,119 |
def get_instance_ip() -> str:
"""
For a given identifier for a deployment (env var of IDENTIFIER), find the cluster
that was deployed, find the tasks within the cluster (there should only be one),
find the network interfaces on that task, and return the public IP of the instance
:returns: str The pu... | 6b52f6c385e2d96e500458397465f67550a0deeb | 3,655,120 |
def is_hign_level_admin():
"""超级管理员"""
return is_admin() and request.user.level == 1 | 7faa7872f556307b67afd1e5604c104aa6aa242d | 3,655,121 |
def object_metadata(save_path):
"""Retrieves information about the objects in a checkpoint.
Example usage:
```python
object_graph = tf.contrib.checkpoint.object_metadata(
tf.train.latest_checkpoint(checkpoint_directory))
ckpt_variable_names = set()
for node in object_graph.nodes:
for attribute i... | 8a01cc2a60298a466921c81144bfbd9c4e43aa97 | 3,655,122 |
async def login(_request: Request, _user: User) -> response.HTTPResponse:
"""
Login redirect
"""
return redirect(app.url_for("pages.portfolios")) | 375452df081f619db9c887359b6bb0217aa8e802 | 3,655,123 |
def delete_source(source_uuid: SourceId, database: Database):
"""Delete a source."""
data_model = latest_datamodel(database)
reports = latest_reports(database)
data = SourceData(data_model, reports, source_uuid)
delta_description = (
f"{{user}} deleted the source '{data.source_name}' from me... | f160a8304df54a20026155f1afb763c0077d05a9 | 3,655,124 |
def find_object_with_matching_attr(iterable, attr_name, value):
"""
Finds the first item in an iterable that has an attribute with the given name and value. Returns
None otherwise.
Returns:
Matching item or None
"""
for item in iterable:
try:
if getattr(item, attr_na... | e37b7620bf484ce887e6a75f31592951ed93ac74 | 3,655,125 |
def send_message(token, message: str) -> str:
"""
A function that notifies LINENotify of the character string given as an argument
:param message:
A string to be notified
:param token:
LineNotify Access Token
:return response:
server response (thats like 200 etc...)
"""
... | 995abdc61398d9e977323e18f3a3e008fbaa1f3b | 3,655,126 |
def _fix(node):
"""Fix the naive construction of the adjont.
See `fixes.py` for details.
This function also returns the result of reaching definitions analysis so
that `split` mode can use this to carry over the state from primal to
adjoint.
Args:
node: A module with the primal and adjoint function d... | 27c6836366afc033e12fea254d9cf13a902d1ee7 | 3,655,127 |
def greyscale(state):
"""
Preprocess state (210, 160, 3) image into
a (80, 80, 1) image in grey scale
"""
state = np.reshape(state, [210, 160, 3]).astype(np.float32)
# grey scale
state = state[:, :, 0] * 0.299 + state[:, :, 1] * 0.587 + state[:, :, 2] * 0.114
# karpathy
state = sta... | 446651be7573eb1352a84e48780b908b0383e0ca | 3,655,128 |
def functional_common_information(dist, rvs=None, crvs=None, rv_mode=None):
"""
Compute the functional common information, F, of `dist`. It is the entropy
of the smallest random variable W such that all the variables in `rvs` are
rendered independent conditioned on W, and W is a function of `rvs`.
... | cbeef4f042fc5a28d4d909419c1991c0501c0522 | 3,655,129 |
def kubernetes_client() -> BatchV1Api:
"""
returns a kubernetes client
"""
config.load_config()
return BatchV1Api() | 6323d5074f1af02f52eb99b62f7109793908c549 | 3,655,130 |
import types
def admin_only(func):
"""[TODO summary of func]
args:
[TODO insert arguments]
returns:
[TODO insert returns]
"""
def isadmin(invoker, chatadmins):
adminids = []
for admin in chatadmins:
adminids.append(admin.user.id)
return invoker.i... | 4e3cd62e8045b052e556b233d1a7e73adf473bfc | 3,655,131 |
def create_simple():
"""Create an instance of the `Simple` class."""
return Simple() | 98180d64e264c7842596c8f74ce28574459d2648 | 3,655,132 |
def contains_rep_info(line):
"""
Checks does that line contains link to the github repo (pretty simple 'algorithm' at the moment)
:param line: string from aa readme file
:return: true if it has link to the github repository
:type line:string
:rtype: boolean
"""
return True if line.find(... | 335e10a654510a4eda7d28d8df71030f31f98ff1 | 3,655,133 |
def GetAtomPairFingerprintAsBitVect(mol):
""" Returns the Atom-pair fingerprint for a molecule as
a SparseBitVect. Note that this doesn't match the standard
definition of atom pairs, which uses counts of the
pairs, not just their presence.
**Arguments**:
- mol: a molecule
**Returns**: a SparseBitVect... | 9a63aa57f25d9a856d5628ec53bab0378e8088d1 | 3,655,134 |
import sqlite3
def get_registrations_by_player_id(db_cursor: sqlite3.Cursor, player_id: int) -> list[registration.Registration]:
"""
Get a list of registrations by player id.
:param db_cursor: database object to interact with database
:param player_id: player id
:return: a list of registrations
... | 3e87d0f7379ac7657f85225be95dd6c1d7697300 | 3,655,135 |
import sys
def main(argv=None, from_checkout=False):
"""Top-level script function to create a new Zope instance."""
if argv is None:
argv = sys.argv
try:
options = parse_args(argv, from_checkout)
except SystemExit as e:
if e.code:
return 2
else:
... | b1141e580bb281b976f580f3958c3101cfea552e | 3,655,136 |
from re import L
def run_sim(alpha,db,m,DELTA,game,game_constants,i):
"""run a single simulation and save interaction data for each clone"""
rates = (DEATH_RATE,DEATH_RATE/db)
rand = np.random.RandomState()
data = [get_areas_and_fitnesses(tissue,DELTA,game,game_constants)
for tissue in... | 2201a836ff8c3da4c289908e561558c52206256b | 3,655,137 |
def IMDB(*args, **kwargs):
""" Defines IMDB datasets.
The labels includes:
- 0 : Negative
- 1 : Positive
Create sentiment analysis dataset: IMDB
Separately returns the training and test dataset
Arguments:
root: Directory where the datasets are saved. Default: "... | 4bb55c88fc108fce350dc3c29a2ac4497ab205b1 | 3,655,138 |
from typing import List
def load_multiples(image_file_list: List, method: str='mean', stretch: bool=True, **kwargs) -> ImageLike:
"""Combine multiple image files into one superimposed image.
Parameters
----------
image_file_list : list
A list of the files to be superimposed.
method : {'me... | f61f51c89f3318d17f2223640e34573282280e4a | 3,655,139 |
def select_seeds(
img: np.ndarray, clust_result: np.ndarray, FN: int = 500,
TN: int = 700, n_clust_object: int = 2
):
"""
Sample seeds from the fluid and retina regions acording to the procedure
described in Rashno et al. 2017
Args:
img (np.ndarray): Image from where to sample the seeds.... | afdfe7654b53b5269f42c6c74d07265623839d75 | 3,655,140 |
def common(list1, list2):
"""
This function is passed two lists and returns a new list containing
those elements that appear in both of the lists passed in.
"""
common_list = []
temp_list = list1.copy()
temp_list.extend(list2)
temp_list = list(set(temp_list))
temp_list.sort()
for... | 021605a2aad6c939155a9a35b8845992870100f0 | 3,655,141 |
def create_combobox(root, values, **kwargs):
"""Creates and Grids A Combobox"""
box = ttk.Combobox(root, values=values, **kwargs)
box.set(values[0])
return box | 7406dca6ab99d9130a09a6cb25220c1e40148cc0 | 3,655,142 |
from datetime import datetime
import logging
import sys
def configure_logging_console(logger_type):
"""
Configure logger
:param logger_type: The type to write logger and setup on the modules of App
:return _imoporter_log:
"""
_date_name = datetime.now().strftime('%Y-%m-%dT%H%M')
_import... | 412e0c491af07ebff0f9b7a851635017e047a216 | 3,655,143 |
def chi_x2(samples,df):
"""
Compute the central chi-squared statistics for set of chi-squared
distributed samples.
Parameters:
- - - - -
samples : chi-square random variables
df : degrees of freedom
"""
return chi2.pdf(samples,df) | 5700803396e78c7a5658c05ff1b7bd7ae3bd6722 | 3,655,144 |
def integrate(
pc2i,
eos,
initial_frac=DEFAULT_INITIAL_FRAC,
rtol=DEFAULT_RTOL,
):
"""integrate the TOV equations with central pressure "pc2i" and equation of state described by energy density "eps/c2" and pressure "p/c2"
expects eos = (logenthalpy, pressurec2, energy_density... | 5934da344fc6927d397dccc7c2a730436e1106d5 | 3,655,145 |
import oci.exceptions
def add_ingress_port_to_security_lists(**kwargs):
"""Checks if the given ingress port already is a security list,
if not it gets added.
Args:
**kwargs: Optional parameters
Keyword Args:
security_lists (list): A list of security_lists.
port (int): The por... | 0fd1cdc05ea3c035c5424f2e179d2655e4b84bd4 | 3,655,146 |
def describe_cluster_instances(stack_name, node_type):
"""Return the cluster instances optionally filtered by tag."""
instances = _describe_cluster_instances(stack_name, filter_by_node_type=str(node_type))
if not instances:
# Support for cluster that do not have aws-parallelcluster-node-type tag
... | cdb09b0dd15b6c549895280dc79ea4ccb122a3d9 | 3,655,147 |
import os
def region_root(data_dir):
"""Returns the path of test regions."""
return os.path.join(data_dir, 'regions') | a49385b4cdb550e88b5016783c09b4f9dbebd216 | 3,655,148 |
def list_statistics_keys():
"""ListStatistics definition"""
return ["list", "counts"] | 39521910b4dbde3fc6c9836460c73945561be731 | 3,655,149 |
def forecast_handler(req, req_body, res, res_body, zip):
"""Handles forecast requests"""
return True | a2e35eaad472cfd52dead476d18d18ee2bcd3f6f | 3,655,150 |
def _configure_output(args):
"""
Configures the output. Loads templates and applies the specified formatter if any.
If none of these configurations are specified, it will return the default output
which is to print each value to standard out.
"""
writer = _get_writer(args)
if args.template:... | 69a279a63f858ef1124533720179eea9b7c3589a | 3,655,151 |
def refToMastoidsNP(data, M1, M2):
"""
"""
mastoidsMean = np.mean([M1, M2], axis=0)
mastoidsMean = mastoidsMean.reshape(mastoidsMean.shape[0], 1)
newData = data - mastoidsMean
return newData | 15f50718fb1ea0d7b0fc2961a3a9b8d1baa98636 | 3,655,152 |
from typing import Dict
from typing import Callable
from typing import Any
def override_kwargs(
kwargs: Dict[str, str],
func: Callable[..., Any],
filter: Callable[..., Any] = lambda _: True,
) -> Dict[str, str]:
"""Override the kwargs of a function given a function to apply and an optional filter.
... | 31c689a1e2df1e5168f784011fbac6cf4a86bf13 | 3,655,153 |
def prepare_for_revival(bucket, obj_prefix):
"""
Makes a manifest for reviving any deleted objects in the bucket. A deleted
object is one that has a delete marker as its latest version.
:param bucket: The bucket that contains the stanzas.
:param obj_prefix: The prefix of the uploaded stanzas.
:... | 879182e354d94f1c24cddd233e7c004939c4d0c0 | 3,655,154 |
import ast
import json
import os
def make_drive_resource() -> Resource:
"""
Authenticates and returns a google drive resource.
"""
google_oauth_creds = ast.literal_eval(
credstash.getSecret("IA_PIPELINE_GLOBAL_GOOGLE_SHEETS_API_KEY")
)
with open("key.json", "w") as fp:
json.du... | 7cf2d67791d63f6d3995dce3702775fad1f52a45 | 3,655,155 |
def make_subparser(sub, command_name, help, command_func=None, details=None, **kwargs):
"""
Create the "sub-parser" for our command-line parser.
This facilitates having multiple "commands" for a single script,
for example "norm_yaml", "make_rest", etc.
"""
if command_func is None:
comma... | acd2467c78f2ff477a5f0412cf48cbef19882f2c | 3,655,156 |
import os
def _get_static_settings():
"""Configuration required for Galaxy static middleware.
Returns dictionary of the settings necessary for a galaxy App
to be wrapped in the static middleware.
This mainly consists of the filesystem locations of url-mapped
static resources.
"""
static_... | cc4cc77d2bac7b2ca2718135f0ecfd31d5ce7f1e | 3,655,157 |
def application():
""" Flask application fixture. """
def _view():
return 'OK', 200
application = Flask('test-application')
application.testing = True
application.add_url_rule('/', 'page', view_func=_view)
return application | bd9168a66cb8db8c7a2b816f1521d5633fbdcbf8 | 3,655,158 |
def get_qe_specific_fp_run_inputs(
configure, code_pw, code_wannier90, code_pw2wannier90,
get_repeated_pw_input, get_metadata_singlecore
):
"""
Creates the InSb inputs for the QE fp_run workflow. For the
higher-level workflows (fp_tb, optimize_*), these are passed
in the 'fp_run' namespace.
... | b0f8fd6536a237ade55139ef0ec6daaad8c0fb08 | 3,655,159 |
def _get_cohort_representation(cohort, course):
"""
Returns a JSON representation of a cohort.
"""
group_id, partition_id = cohorts.get_group_info_for_cohort(cohort)
assignment_type = cohorts.get_assignment_type(cohort)
return {
'name': cohort.name,
'id': cohort.id,
'user... | aaa2c7b9c53e3a49ebc97e738077a0f6873d0559 | 3,655,160 |
import json
def config_string(cfg_dict):
""" Pretty-print cfg_dict with one-line queries """
upper_level = ["queries", "show_attributes", "priority", "gtf", "bed", "prefix", "outdir", "threads", "output_by_query"]
query_level = ["feature", "feature_anchor", "distance", "strand", "relative_location", "filter_attr... | c6533512b6f87fea1726573c0588bbd3ddd54e41 | 3,655,161 |
def area_km2_per_grid(infra_dataset, df_store):
"""Total area in km2 per assettype per grid, given in geographic coordinates
Arguments:
*infra_dataset* : a shapely object with WGS-84 coordinates
*df_store* : (empty) geopandas dataframe containing coordinates per grid for each grid
R... | 3d4b516429235f6b20a56801b0ef98e3fd80306d | 3,655,162 |
from click.testing import CliRunner
def cli_runner(script_info):
"""Create a CLI runner for testing a CLI command.
Scope: module
.. code-block:: python
def test_cmd(cli_runner):
result = cli_runner(mycmd)
assert result.exit_code == 0
"""
def cli_invoke(command, ... | 3593354dd190bcc36f2099a92bad247c9f7c7cf1 | 3,655,163 |
def sgf_to_gamestate(sgf_string):
"""
Creates a GameState object from the first game in the given collection
"""
# Don't Repeat Yourself; parsing handled by sgf_iter_states
for (gs, move, player) in sgf_iter_states(sgf_string, True):
pass
# gs has been updated in-place to the final s... | 1c1a6274769abb654d51dc02d0b3182e7a9fd1f6 | 3,655,164 |
def get_titlebar_text():
"""Return (style, text) tuples for startup."""
return [
("class:title", "Hello World!"),
("class:title", " (Press <Exit> to quit.)"),
] | 947b94f2e85d7a172f5c0ba84db0ec78045a0f6c | 3,655,165 |
import json
def image_fnames_captions(captions_file, images_dir, partition):
"""
Loads annotations file and return lists with each image's path and caption
Arguments:
partition: string
either 'train' or 'val'
Returns:
all_captions: list of strings
list with ea... | f592decefaded079fca92091ad795d67150b4ca8 | 3,655,166 |
def build_menu(
buttons: list,
columns: int = 3,
header_button=None,
footer_button=None,
resize_keyboard: bool = True
):
"""Хелпер для удобного построения меню."""
menu = [buttons[i:i + columns] for i in range(0, len(buttons), columns)]
if header_button:
menu.... | d375a7af5f5e45e4b08520561c70d8c2664af4ef | 3,655,167 |
def pandas_dataframe_to_unit_arrays(df, column_units=None):
"""Attach units to data in pandas dataframes and return united arrays.
Parameters
----------
df : `pandas.DataFrame`
Data in pandas dataframe.
column_units : dict
Dictionary of units to attach to columns of the dataframe. ... | 41aff3bd785139f4d99d677e09def2764448acf2 | 3,655,168 |
from typing import Any
def is_empty(value: Any) -> bool:
"""
empty means given value is one of none, zero length string, empty list, empty dict
"""
if value is None:
return True
elif isinstance(value, str):
return len(value) == 0
elif isinstance(value, list):
return len(value) == 0
elif isinstance(value,... | fd4c68dd5f0369e0836ab775d73424360bad9219 | 3,655,169 |
import os
def get_worksheets (path, **kwargs):
"""
Gets all available worksheets within a xlsx-file and returns a list
:param path: Path to excel file
:type path: str
:return: Returns a list with all worksheets within the excel-file
:rtype: list
"""
if not os.path.isabs(path):
... | 17b2f72cbda1c2abfb190d9592d3f7c7520ccc83 | 3,655,170 |
import caffe_parser
import numpy as np
def read_caffe_mean(caffe_mean_file):
"""
Reads caffe formatted mean file
:param caffe_mean_file: path to caffe mean file, presumably with 'binaryproto' suffix
:return: mean image, converted from BGR to RGB format
"""
mean_blob = caffe_parser.caffe_pb2.B... | 6835bf429f3caca6308db450bb18e9254ff2b9a0 | 3,655,171 |
def estimate_pauli_sum(pauli_terms,
basis_transform_dict,
program,
variance_bound,
quantum_resource,
commutation_check=True,
symmetrize=True,
rand_samples=16):... | 8dc63069229cf83164196c1ca2e29d20c5be2756 | 3,655,172 |
def GetQuasiSequenceOrderp(ProteinSequence, maxlag=30, weight=0.1, distancematrix={}):
"""
###############################################################################
Computing quasi-sequence-order descriptors for a given protein.
[1]:Kuo-Chen Chou. Prediction of Protein Subcellar Locations by
... | f59c60826e2dc40db6827ac263423cf69c338d89 | 3,655,173 |
def check(lst: list, search_element: int) -> bool:
"""Check if the list contains the search_element."""
return any([True for i in lst if i == search_element]) | 15f35ceff44e9fde28f577663e79a2216ffce148 | 3,655,174 |
def halfcube(random_start=0,random_end=32,halfwidth0=1,pow=-1):
"""
Produce a halfcube with given dimension and decaying power
:param random_start: decay starting parameter
:param random_end: decay ending parameter
:param halfwidth0: base halfwidth
:param pow: decaying power
:return: A (rand... | eb3acfe76abf2ba2ddec73973a875ad7509cd265 | 3,655,175 |
def valid_passphrase(module, **kwargs):
"""Tests whether the given passphrase is valid for the specified device.
Return: <boolean> <error>"""
for req in ["device", "passphrase"]:
if req not in kwargs or kwargs[req] is None:
errmsg = "valid_passphrase: {0} is a required parameter".format... | c6355a4c75b8973372b5d01817fa59569746ed6c | 3,655,176 |
def contract_address(deploy_hash_base16: str, fn_store_id: int) -> bytes:
"""
Should match what the EE does (new_function_address)
//32 bytes for deploy hash + 4 bytes ID
blake2b256( [0;32] ++ [0;4] )
deploy_hash ++ fn_store_id
"""
def hash(data: bytes) -> bytes:
h = blake2... | 0623209f88a59c1a2cbe8460603f920ff66575f1 | 3,655,177 |
import json
def dump_js_escaped_json(obj, cls=EdxJSONEncoder):
"""
JSON dumps and escapes objects that are safe to be embedded in JavaScript.
Use this for anything but strings (e.g. dicts, tuples, lists, bools, and
numbers). For strings, use js_escaped_string.
The output of this method is also ... | eba36fbf101c0779fe5756fa6fbfe8f0d2c5686c | 3,655,178 |
from typing import NamedTuple
def RawTuple(num_fields, name_prefix='field'):
"""
Creates a tuple of `num_field` untyped scalars.
"""
assert isinstance(num_fields, int)
assert num_fields >= 0
return NamedTuple(name_prefix, *([np.void] * num_fields)) | 3287a827099098e1550141e9e99321f75a9317f6 | 3,655,179 |
def pose2mat(R, p):
""" convert pose to transformation matrix """
p0 = p.ravel()
H = np.block([
[R, p0[:, np.newaxis]],
[np.zeros(3), 1]
])
return H | 626cbfcf5c188d4379f60b0e2d7b399aece67e8c | 3,655,180 |
def _fill_missing_values(df=None):
"""replace missing values with NaN"""
# fills in rows where lake refroze in same season
df['WINTER'].replace(to_replace='"', method='ffill', inplace=True)
# use nan as the missing value
for headr in ['DAYS', 'OPENED', 'CLOSED']:
df[headr].replace(to_replac... | b86bfdac06d6e22c47d7b905d9cb7b5feba40fdb | 3,655,181 |
def csi_prelu(data, alpha, axis, out_dtype, q_params, layer_name=""):
"""Quantized activation relu.
Parameters
----------
data : relay.Expr
The quantized input data.
alpha : relay.Expr
The quantized alpha.
out_dtype : str
Specifies the output data type for mixed precisi... | 8e8e3c09ae7c3cb3b89f1229cfb83836682e5bc8 | 3,655,182 |
def json(filename):
"""Returns the parsed contents of the given JSON fixture file."""
content = contents(filename)
return json_.loads(content) | fc66afdfe1a04ac8ef65272e55283de98c145f8c | 3,655,183 |
def _parse_assayData(assayData, assay):
"""Parse Rpy2 assayData (Environment object)
assayData: Rpy2 Environment object.
assay: An assay name indicating the data to be loaded.
Return a parsed expression dataframe (Pandas).
"""
pandas2ri.activate()
mat = assayData[assay] # rpy2 expression ... | aea2e5fe25eaf563fdd7ed981d7486fdf39098b4 | 3,655,184 |
def method_list():
""" list of available electronic structure methods
"""
return theory.METHOD_LST | d1ad84bc709db1973f83e5a743bf4aed21f98652 | 3,655,185 |
def readReadQualities(fastqfile):
"""
Reads a .fastqfile and calculates a defined readscore
input: fastq file
output: fastq dictionary key = readid; value = qualstr
@type fastqfile: string
@param fastqfile: path to fastq file
@rtype: dictionary
@return: dictionary containin... | 8af9c0fc0c2d8f3a4d2f93ef81489098cb572643 | 3,655,186 |
from typing import Optional
from typing import Any
from typing import Dict
async def default_field_resolver(
parent: Optional[Any],
args: Dict[str, Any],
ctx: Optional[Any],
info: "ResolveInfo",
) -> Any:
"""
Default callable to use as resolver for field which doesn't implement a
custom on... | d0458cc10a968c359c9165ac59be60ece0270c41 | 3,655,187 |
from typing import List
from typing import Dict
def revision_list_to_str(diffs: List[Dict]) -> str:
"""Convert list of diff ids to a comma separated list, prefixed with "D"."""
return ', '.join([diff_to_str(d['id']) for d in diffs]) | fbaa4473daf1e4b52d089c801f2db46aa7485972 | 3,655,188 |
from typing import Optional
from pathlib import Path
import time
def get_path_of_latest_file() -> Optional[Path]:
"""Gets the path of the latest produced file that contains weight information"""
path = Path(storage_folder)
latest_file = None
time_stamp_latest = -1
for entry in path.iterdir():
... | a72308c4b3852429d6959552cc90779a4ee03dc5 | 3,655,189 |
def index():
"""
A function than returns the home page when called upon
"""
#get all available news sources
news_sources = get_sources()
#get all news articles available
everything = get_everything()
print(everything)
# title = 'Home - Find all the current news at your convinien... | 4cf1eacaa550ce1ffd0ed954b60a7c7adf1702a6 | 3,655,190 |
import base64
import logging
import traceback
import sys
def parse_secret_from_literal(literal):
"""Parse a literal string, into a secret dict.
:param literal: String containg a key and a value. (e.g. 'KEY=VALUE')
:returns secret: Dictionary in the format suitable for sending
via http request.
""... | de1bc56d0e2d314fd56b8d58604fdd693362bda1 | 3,655,191 |
def blur(img):
"""
:param img: SimpleImage, the input image
:return: the processed image which is blurred
the function calculate the every position and its neighbors' pixel color and then average then
set it as the new pixel's RGB
"""
sum_red = 0
sum_blue = 0
sum_green = 0
neigh... | a4b9e98e97b7d4a27b76b8151fa91493b58fc4a6 | 3,655,192 |
def delete_project_api_document_annotations_url(document_id: int, annotation_id: int) -> str:
"""
Delete the annotation of a document.
:param document_id: ID of the document as integer
:param annotation_id: ID of the annotation as integer
:return: URL to delete annotation of a document
"""
... | 470a9bb602c4a9327839f811f818e469747e6758 | 3,655,193 |
import subprocess
def subprocess_call_wrapper(lst, stdin=None):
"""Wrapper around the subprocess.call functions."""
print_debug('About to run "%s"' % ' '.join(lst))
try:
ret = subprocess.call(lst, stdin=stdin)
except (OSError, IOError):
ret = 127 # an error code
except IndexError:... | 144723c065e0e194be2d8e3f424fbfaa47259ec7 | 3,655,194 |
def GetHomeFunctorViaPose():
""" Deprecated.
Returns a function that will move the robot to the home position when called.
"""
js_home = GetPlanToHomeService()
req = ServoToPoseRequest()
pose_home = GetHomePoseKDL()
req.target = pm.toMsg(pose_home)
open_gripper = GetOpenGripperService()... | 7160f326c1aa0249da16dbfbf6fd740774284a4a | 3,655,195 |
import requests
def getAveragePlatPrice(item_name):
"""
Get the current average price of the item on the Warframe marketplace.
Args:
item_name (str): The name of the item.
Returns:
float: the average platinum market price of the item.
"""
avg_price = -1
item_name = clean... | 221abd20125df49f40cfe246869a321943c5afbc | 3,655,196 |
def mode_strength(n, kr, sphere_type='rigid'):
"""Mode strength b_n(kr) for an incident plane wave on sphere.
Parameters
----------
n : int
Degree.
kr : array_like
kr vector, product of wavenumber k and radius r_0.
sphere_type : 'rigid' or 'open'
Returns
-------
b_n... | 888981e34d444934e1c4b3d25c3042deabbe5005 | 3,655,197 |
from pathlib import Path
def data_dir(test_dir: Path) -> Path:
"""
Create a directory for storing the mock data set.
"""
_data_dir = test_dir / 'data'
_data_dir.mkdir(exist_ok=True)
return _data_dir | 3b204816252a2c87698197a416a4e2de218f639d | 3,655,198 |
import multiprocessing
def get_runtime_brief():
""" A digest version of get_runtime to be used more frequently """
return {"cpu_count": multiprocessing.cpu_count()} | 9dbb54c476d303bae401d52ce76197e094ee5d71 | 3,655,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.