content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_k_best_and_worst_performing(val_metrics_csv: Path, test_metrics_csv: Path, k: int,
prediction_target: str = MetricsDict.DEFAULT_HUE_KEY) -> Optional[Results]:
"""
Get the top "k" best predictions (i.e. correct classifications where the model was the most certain) and ... | 5,316,300 |
def cli(env, identifier, domain, userfile, tag, hostname, userdata,
public_speed, private_speed):
"""Edit a virtual server's details."""
if userdata and userfile:
raise exceptions.ArgumentError(
'[-u | --userdata] not allowed with [-F | --userfile]')
data = {}
if userdata:... | 5,316,301 |
def flow_experiment_from_csv(filename):
"""
Initialise a flow experiment from a formatted .csv file.
Parameters
----------
filename: str
Name of a formatted configuration file.
Returns
-------
experiment: Classes.FlowExperiment
"""
with open(filename, "r", encoding="ut... | 5,316,302 |
def ls():
"""
Lists all files in the current directory.
"""
list_of_files = [obj for obj in os.listdir(pwd())]
for item in list_of_files:
if os.path.isdir(pwd() + "/" + item):
index_of_item = list_of_files.index(item)
list_of_files[index_of_item] = list_of_files[... | 5,316,303 |
def _validate_label_map(label_map):
"""
检查生成的label_map是否有效
:param label_map: 用于检查的StringIntLabelMap数据
:raise
ValueError: 如果label_map无效
"""
for item in label_map.item:
if item.id < 0:
raise ValueError("标签文件中的ID应≥0")
if item.id == 0:
if item.name.low... | 5,316,304 |
def _linear_predictor_typecheck(x, coeffs):
"""Check that x is a one-dimensional vector of the right shape.
This is a temporary hackaround until I actually implement bulk predict."""
if type(x) == ndarray:
if x.ndim == 1:
if x.shape == coeffs.shape:
pass
else:... | 5,316,305 |
def save_article(conn, article):
"""
Create a new task
:param conn:
:param task:
:return:
"""
sql = ''' INSERT INTO articleNumber(number,date)
VALUES(?,?) '''
cur = conn.cursor()
cur.execute(sql, article)
conn.commit()
cur.close() | 5,316,306 |
def get_int(value, allow_sign=False):
"""Convert a value to an integer.
Args:
value: String value to convert.
allow_sign: If True, negative values are allowed.
Return:
int(value) if possible.
"""
try:
# rstrip needed when 0. is passed via [count]
int_val = in... | 5,316,307 |
def main():
"""Inference demo for GFPGAN (for users).
"""
parser = argparse.ArgumentParser()
parser.add_argument(
'-i',
'--input',
type=str,
default='inputs/whole_imgs',
help='Input image or folder. Default: inputs/whole_imgs')
parser.add_argument('-o', '--out... | 5,316,308 |
def calculate_weights(
performance: Union['xr.DataArray', None],
independence: Union['xr.DataArray', None],
performance_sigma: Union[float, None],
independence_sigma: Union[float, None]) -> 'xr.DataArray':
"""Calculate normalized weights for each model N.
Parameters
--------... | 5,316,309 |
def validate_state(state):
"""
State validation rule.
Property: LifecyclePolicy.State
"""
VALID_STATES = ("ENABLED", "DISABLED")
if state not in VALID_STATES:
raise ValueError("State must be one of : %s" % ", ".join(VALID_STATES))
return state | 5,316,310 |
def load_variable_config(project_config):
"""Extract the variable configuration out of the project configuration.
Args:
project_config (dict-like): Project configuration.
Returns:
dict: Variable dictionary with name: [levels] (single level will have a list containing None.)
"""
# ... | 5,316,311 |
def send_message(socket, message, message_type, mycroft_id, mycroft_name, recipient="all"):
"""
Args: TYPE and Message and WHO FOR (Needed if not intercom"""
if message_type is not "intercom" and recipient is None:
# Check that when there is a message, it has a specified recipient
raise Valu... | 5,316,312 |
def absolute_simulations_distance_for_tables(
simulation_dfs: Union[List[pd.DataFrame], pd.DataFrame],
gt_simulation_dfs: Union[List[pd.DataFrame], pd.DataFrame]):
"""Compute absolute normalized distance between simulations.
Parameters
----------
simulation_dfs: PEtab simulation tables ... | 5,316,313 |
def _experiment_fn(run_config, hparams):
"""Outputs `Experiment` object given `output_dir`.
Args:
run_config: `EstimatorConfig` object fo run configuration.
hparams: `HParams` object that contains hyperparameters.
Returns:
`Experiment` object
"""
estimator = learn.Estimator(
... | 5,316,314 |
def cross_op_torch(r):
"""
Return the cross operator as a matrix
i.e. for input vector r \in \R^3
output rX s.t. rX.dot(v) = np.cross(r, v)
where rX \in \R^{3 X 3}
"""
if len(r.shape) > 1:
rX = torch.zeros(r.shape[0], 3, 3).to(r)
rX[..., 0, 1] = -r[..., 2]
rX[..., 0, 2] = r[..., 1]
... | 5,316,315 |
def main(arguments) -> None:
""" Main function for pira framework. Used to invoke the various components. """
show_pira_invoc_info(arguments)
invoc_cfg = process_args_for_invoc(arguments)
use_extra_p, extrap_config = process_args_for_extrap(arguments)
home_dir = U.get_cwd()
U.set_home_dir(home_dir)
U.m... | 5,316,316 |
def test_zmq_api_environment_open_close_2(re_manager): # noqa F811
"""
Test for `environment_open` and `environment_close` methods.
Opening/closing the environment while it is being opened/closed.
Opening the environment that already exists.
Closing the environment that does not exist.
"""
... | 5,316,317 |
def copytree_hardlink(source, dest):
"""Recursively copy a directory ala shutils.copytree, but hardlink files instead of copying.
Parameters
----------
source : str
Path to source directory
dest : str
Path to destination directory
Warnings
--------
Available on UNIX sys... | 5,316,318 |
def apply_internal(user_id, job_id, resume, comment):
"""
Basic logic for applying to internal job postings.
Arguments:
`user_id`: ID of the user applying
`job_id`: ID of the job a user is applying for
`resume`: Handy tool for applying to jobs
"""
if not user_id:
return {"status... | 5,316,319 |
def check_acls(user, obj, acl_type):
"""Check ACLs."""
if acl_type == 'moz_contact':
try:
return user.email in obj.addon.get_mozilla_contacts()
except AttributeError:
return user.email in obj.thread.addon.get_mozilla_contacts()
if acl_type == 'admin':
return a... | 5,316,320 |
def variable_labels():
"""Dictionaries that contain Variables objects."""
_phi = r'$\phi$'
_eta = r'$\eta$'
_T = r'$_\text{T}$ [GeV]'
_mass = 'Mass [GeV]'
variables = {}
variables['ljet_C2'] = Variable(binning=hist1d(10, 0., 0.6), label=r'Large-R Jet C$_2^{\beta\text{=1}}$')
v... | 5,316,321 |
async def test_groups_same_prefix(channel_layer):
"""
Tests group_send with multiple channels with same channel prefix
"""
channel_layer = RedisChannelLayer(hosts=TEST_HOSTS)
channel_name1 = await channel_layer.new_channel(prefix="test-gr-chan")
channel_name2 = await channel_layer.new_channel(pr... | 5,316,322 |
def _calcDistance(fiberMatrix1, fiberMatrix2):
""" *INTERNAL FUNCTION*
Computes average Euclidean distance
INPUT:
fiberMatrix1 - 3D matrix containing fiber spatial infomration
fiberMatrix2 - 3D matrix containing fiber spatial information for
comparison
OUTPUT:
... | 5,316,323 |
def energize (grid, row=None, col=None):
"""Energizes octopus `grid` by increasing energy levels by one.
If `row` and `col` are given, only the octopus at that grid position
is energized. Otherwise all octopuses are energized.
"""
if row is not None and col is not None:
grid[row][col] += 1... | 5,316,324 |
def test_create_env_def_file_wdl():
"""testing create_env_def_file with wdl option and no input Env variable"""
envfilename = 'someenvfile'
runjson_dict = {'Job': {'App': {'language': 'wdl',
'wdl_url': 'someurl',
'main_wdl': 'somewdl',... | 5,316,325 |
def mock_step_mutating_run(context):
"""Mock a step's run_step by setting a context value False."""
context['dynamic_run_expression'] = False | 5,316,326 |
def find_suppliers(client, framework, supplier_ids=None, map_impl=map, dry_run=False):
"""Return supplier details for suppliers with framework interest
:param client: data api client
:type client: dmapiclient.DataAPIClient
:param dict framework: framework
:param supplier_ids: list of supplier IDs t... | 5,316,327 |
def filter_topology(model: Dict[str, str], operator: str, value: str,
component: str):
"""Check whether model should be included according to the user input. The
model should be added if the its topology is consistent with the components
requested by the user (number of controller or com... | 5,316,328 |
def getAuctionPrice(the_auction: models.DutchAuction, bid: Transaction[BidParameter, TezlandDutchAuctionsStorage]):
"""Returns current price in mutez.
More or less pasted from dutch auction contract."""
granularity = int(bid.storage.granularity)
op_now = bid.data.timestamp
# return start price if ... | 5,316,329 |
def __all_paths_between_acceptance_states(Dfa):
"""Generates for each front acceptance state a copy of the complete
graph which can be reached inside 'Dfa' starting from it until the next
acceptance state.
RETURNS: List of DFAs containing a tail for each found acceptance states.
"""
def _get_br... | 5,316,330 |
def hello():
"""
An op definition. This example op outputs a single string.
For more hints about writing Dagster ops, see our documentation overview on Ops:
https://docs.dagster.io/concepts/ops-jobs-graphs/ops
"""
return "Hello, Dagster!" | 5,316,331 |
def vtk_clean_polydata(surface):
"""
Clean surface by merging
duplicate points, and/or
removing unused points
and/or removing degenerate cells.
Args:
surface (vtkPolyData): Surface model.
Returns:
cleanSurface (vtkPolyData): Cleaned surface model.
"""
# Clean surfac... | 5,316,332 |
def custom_exception_handler(exc, context):
"""
A custom exception handler that makes sure errors are returned with a fixed format.
Django, django-rest-framework, and the jwt framework all throw exceptions in slightly
different ways. This has to be caught and each type of exception has to be converted
... | 5,316,333 |
def fetch_svc(k8s_host, **kwargs):
"""
Fetch named service definition from Kubernetes (output: dict)
"""
pass_headers = {}
if 'k8s_api_headers' in kwargs:
headers = kwargs.pop('k8s_api_headers')
pass_headers.update(headers)
namespace = kwargs['namespace']
service_name = kwargs[... | 5,316,334 |
def printPrices(setOrder, shops):
""" gets the prices of the packs by looping each pack and storing on the the table """
# create window
window = Tk()
today = date.today()
window.title(today.strftime("%d/%m") + " Pokemon Card Prices")
labelRow = 1
labelColumn = 1
# header
for shop ... | 5,316,335 |
def save_cifar10(db):
"""Save CIFAR-10 to HDF5 dataset.
Parameters
----------
db : h5py.File
file object for HDF5 dataset.
"""
folder_name = "cifar-10-batches-py"
data = load_cifar_batch(folder_name, "test_batch")
cifar10_ds = db.create_dataset("CIFAR10", (10000, 32, 32, 3),
... | 5,316,336 |
def mentionable():
"""
:return: boolean
True, if there is something mentionable to notify about
False, if not
"""
# need to be implemented
return False | 5,316,337 |
def main():
""" Dual UKF for Discrete time systems
This function test the dual UKF algorithm.
Two UKF algorithms are run simultaneously.
The first algorithm is for updating the weights.
These updates weights are used in the next UKF algorithm to update the states.
The updated states are then fe... | 5,316,338 |
def update_local_job_details( key, status ):
""" Updates local job details of 'local job details file'. """
ljdf_t = read_local_job_details(".", "local_job_details.json")
ljdf_t[ key ] = status
with open("local_job_details.json", 'w') as outfile:
json.dump(ljdf_t, outfile, indent=2)
out... | 5,316,339 |
def cmp_ver(a, b):
"""Compare versions in the form 'a.b.c'
"""
for (i, j) in zip(split_ver(a), split_ver(b)):
if i != j:
return i - j
return 0 | 5,316,340 |
def update_table_policy(new_policy, client, table_ref, table_id):
"""
Updates the BigQuery table with the new private IAM policy
"""
try:
client.set_iam_policy(table_ref, new_policy)
logging.info(f"IAM policy successfully updated on BigQuery Table: {table_id}.")
except:
logg... | 5,316,341 |
def findFileTypes(wpath, type ='*.txt', verbose=False):
""" to find all the files in wpath and below with file names matching fname
"""
alist=sorted(os.walk(wpath))
if verbose:
print(' getting file list')
listPath = []
listFile = []
fileName = []
for (dirpath,dirnames,filenames)... | 5,316,342 |
def _parse_args(argv=None):
"""Parse command-line args."""
def _positive_int(value):
"""Define a positive integer ArgumentParser type."""
value = int(value)
if value <= 0:
raise argparse.ArgumentTypeError(
"Value must be positive, {} was passed.".format(value... | 5,316,343 |
def send_message(message):
"""
Send messages to server\n
*Caution* "stop" message will stop the server
"""
sock = connect()
try:
# Send data
#message = b'This is the message. It will be repeated.'
#print('sending {!r}'.format(message))
print('sending ' + mes... | 5,316,344 |
def delete_buckets(buckets) -> list:
"""Deletes all buckets from a list
Args:
buckets (list): A list of s3 buckets
Returns:
A list of terminated buckets
"""
terminated_buckets = []
for bucket in buckets:
bucket_name = bucket["Name"]
if helpers.check_in_whitelist... | 5,316,345 |
def _find_widget_refs_by_state(widget, state):
"""Find references to other widgets in a widget's state"""
# Copy keys to allow changes to state during iteration:
keys = tuple(state.keys())
for key in keys:
value = getattr(widget, key)
# Trivial case: Direct references to other widgets:
... | 5,316,346 |
def box_fusion(
bounding_boxes,
confidence_score,
labels,
mode='wbf',
image_size=None,
weights=None,
iou_threshold=0.5):
"""
bounding boxes:
list of boxes of same image [[box1, box2,...],[...]] if ensemble many models
list of boxes of sing... | 5,316,347 |
def get_worker_class(global_conf, message):
"""Returns class of worker needed to do message's work"""
worker_type = 'worker-%s' % (message.body['worker_type'])
if worker_type not in global_conf:
raise RuntimeError("Invalid worker type '%s'" % (worker_type))
conf = global_conf[worker_type]
im... | 5,316,348 |
def add_site_data(apps, schema_editor):
"""Add or change site data.
Add a new Site instance with the information we want for our site, or,
if it already exists, alter the domain name for the existing site instance.
"""
Site = apps.get_model('sites', 'Site') # Get the historical Site model
new_... | 5,316,349 |
def is_valid_widget(widget):
"""
Checks if a widget is a valid in the backend
:param widget: QWidget
:return: bool, True if the widget still has a C++ object, False otherwise
"""
if widget is None:
return False
# Added try because Houdini does not includes Shiboken library by defau... | 5,316,350 |
def get_builtin_configs() -> Dict[str, ClientConfig]:
"""
Return a cached mapping of preconfigured clients.
"""
path = os.path.join(os.path.dirname(__file__), "builtin_clients.yml")
with open(path, "r", encoding="utf-8") as fdata:
configs = yaml.safe_load(fdata)
return {
config_n... | 5,316,351 |
def isConsistant(spectrum,kmer):
"""Checks whether a given kmer is consistent with a given spectrum or not.
INPUT :
spectrum: array-like. The spectrum required to check the given kmer against.
kmer: string. The given kmer required to check its consistency.
OUTPUT:
.: bool. The consist... | 5,316,352 |
def validate_java_file(java_file):
"""Validates a java file.
Args:
java_file_path: the path to the java file.
Returns:
a list of errors.
"""
file_status, java_file_path = java_file
with open(java_file_path, "r") as fp:
contents = fp.read()
if not contents:
return ["[ERROR] Errors exist in " + java_fi... | 5,316,353 |
def convertVoltage(raw_voltage):
""" Ground is 1
1.8 is 4095
"""
converted_voltage = (raw_voltage/4095)*1.8
return "%.3f" % converted_voltage | 5,316,354 |
def fast_ica(image, components):
"""Reconstruct an image from Fast ICA compression using specific number of components to use
Args:
image: PIL Image, Numpy array or path of 3D image
components: Number of components used for reconstruction
Returns:
Reconstructed image
Example:
... | 5,316,355 |
def test_forgot_password_case_insensitive(email, exists):
"""Test that CustomEmailResetSerializer is case insensitive"""
user = UserFactory.create(email=EMAIL) if exists else None
serializer = CustomSendEmailResetSerializer(data={"email": email})
assert serializer.is_valid() is True
assert serializ... | 5,316,356 |
def solve_nr(
f: Callable[[float], float],
df: Callable[[float], float],
estimate: float,
eps: Optional[float]=1.0e-6,
max_num_iter=100,
throw_if_failed_converge=True,
return_vector=False) -> Union[Tuple[float, int], Iterable[float]]:
"""
Solves f(x) = 0 using Newton-Raphson method
:param f: function ... | 5,316,357 |
def get_data(source):
"""fungsi ambil data pegawai, jadwal, judul, liburan"""
with open(source, 'r') as srce:
return json.load(srce) | 5,316,358 |
def load_testsets_by_path(path):
""" load testcases from file path
@param path: path could be in several type
- absolute/relative file path
- absolute/relative folder path
- list/set container with file(s) and/or folder(s)
@return testcase sets list, each testset is corresponding to ... | 5,316,359 |
def unpack_request(data):
"""Take a buffer and return a pair of the RequestHeader and app data"""
start = MSG_TYPE_SIZE + REQUEST_HEADER_SIZE
return (unpack_request_header(data), data[start:]) | 5,316,360 |
def pivot_timeseries(events, pivot_keys, static_keys=None):
"""Pivot sequence of events with sequences as data to single sequence
For example a sequence of 5 events with 100 frames of 2D data per datum
will turn into a sequence of 500 events which each have a single frame.
Any keys not in ``pivot_keys... | 5,316,361 |
def basic_pl_stats(degree_sequence):
"""
:param degree sequence of individual nodes
"""
results = Fit(degree_sequence,discrete=True)
return (results.alpha,results.sigma) | 5,316,362 |
def merge_config_dictionaries(*dicts):
"""
Merges n dictionaries of configuration data
:param list<dicts>:
:return dict:
"""
res_dict = {}
if isinstance(dicts, list):
if len(dicts) == 1 and isinstance(dicts[0], dict):
return dicts[0]
else:
for diction... | 5,316,363 |
def test_GraphBatcher_max_node_count_limit_handler_skip():
"""Test that graph is included when larger than max node count."""
big_graph = random_graph_tuple_generator.CreateRandomGraphTuple(node_count=10)
batcher = graph_batcher.GraphBatcher(
MockIterator([big_graph]),
max_node_count=5,
max_node_coun... | 5,316,364 |
def op_catalog_size() -> int:
"""
Return number of entries in the operational-data catalog
@return: integer
"""
return sum(len(entries) for entries in _op_catalog.values()) | 5,316,365 |
def remove(socket):
"""Remove the specified containers
:<json list container_ids: required, a list of container_id
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
{
"id": "9c91d06cb165e829e8e0ad5d5b5484c47d4596af04122489e... | 5,316,366 |
def worker_recv_export_job(request):
"""Worker进程(集群节点)请求接受给定ID(taskSettingId)的导出任务"""
try:
datas = json.loads(request.body.decode())
taskSettingId = int(datas["params"]["taskSettingId"])
# Worker进程可以有多个,为了防止并发请求导致job更新不及时被两个Worker消费,这里需要这样处理
updateRows = PlExportJob.objects.filte... | 5,316,367 |
def add_host_log_history(
host_id, exception_when_existing=False,
filename=None, user=None, session=None, **kwargs
):
"""add a host log history."""
host = _get_host(host_id, session=session)
return utils.add_db_object(
session, models.HostLogHistory, exception_when_existing,
host.id,... | 5,316,368 |
def process_schools(schools_data, url):
"""
Calculate number of wheelchair-accessible and total stops for each school.
type: str
:param: schools_data: path to the school data json file
:type: str
:param: url: currently, this value is https://api-v3.mbta.com/stops
"""
if not os.path.exis... | 5,316,369 |
def load_fiveplates_priority(platerun, filling_scheme):
"""
"""
priority_file = paths.fiveplates_priority(platerun, filling_scheme)
if priority_file.exists():
pass
else:
raise FileNotFoundError(os.fspath(priority_file))
priority_table = Table.read(os.fspath(priority_file),
... | 5,316,370 |
def get_main_window():
"""Return the tkinter root window that Porcupine is using."""
if _root is None:
raise RuntimeError("Porcupine is not running")
return _root | 5,316,371 |
def test_load_bmrb():
"""Test the loading of the BMRB table."""
resnum_col = 1
atom_col = 3
shift_col = 4
observed_dic = load_bmrbm(TEST_BMRB_TABLE, resnum_col, atom_col, shift_col)
expected_dic = {
1: {
"C": 170.52,
"CA": 54.4,
"CB": 33.4599,
... | 5,316,372 |
def calculate_cluster_spatial_enrichment(all_data, dist_mats, fovs=None,
bootstrap_num=1000, dist_lim=100):
"""Spatial enrichment analysis based on cell phenotypes to find significant interactions between different
cell types, looking for both positive and negative enric... | 5,316,373 |
def epoch(dt):
"""
Returns the epoch timestamp of a timezone-aware datetime object.
"""
return calendar.timegm(dt.astimezone(pytz.utc).timetuple()) | 5,316,374 |
def main():
"""Implements the main method running this smoke test."""
defaults = {
'TEST_STACK': str(OpenStackSmokeTestScenario.DEFAULT_TEST_ID),
'TEST_APP': 'openstack-smoketest' + OpenStackSmokeTestScenario.DEFAULT_TEST_ID
}
return citest.base.TestRunner.main(
parser_inits=[OpenStackSm... | 5,316,375 |
def is_pandas_series(value):
"""
Check if an object is a Pandas DataFrame
:param value:
:return:
"""
return isinstance(value, pd.Series) | 5,316,376 |
def main():
""" Define and parse command line arguments.
"""
# Create the top-level parser.
parser = argparse.ArgumentParser()
parser.add_argument('-t', '--process_count',
help='number of worker processes to use',
type=int,
cho... | 5,316,377 |
def _create_logrun(directory):
"""Creates log directory with run file to start s6 logger."""
fs.mkdir_safe(os.path.join(directory, 'log'))
utils.create_script(os.path.join(directory, 'log', 'run'),
'logger.run') | 5,316,378 |
def setup_database(app):
"""Creates the database tables on initial startup"""
with app.app_context():
if not is_db_inited():
populate_db()
if not app.config["TESTING"] and app.config["RUNMODE"] == "DEVELOPMENT":
dev_populate_db() | 5,316,379 |
def test_telegraf_migrate_not_empty(tmp_path):
"""
Migration moves legacy files.
"""
file_contents = b'1234'
src = tmp_path / 'src'
dst = tmp_path / 'dst'
src.mkdir()
file = src / 'file'
file.write_bytes(file_contents)
assert cli.migrate_containers(src, dst) is True
assert no... | 5,316,380 |
def download_file(unittest_adapter, output_dir):
"""
This function tests that the file pointed to by url is downloaded
successfully to the local space. The url is in the message, which is an
attribute in the object adapter. This object is created with message file
as a global object before this func... | 5,316,381 |
def copy_visibility(vis: Union[Visibility, BlockVisibility], zero=False) -> Union[
Visibility, BlockVisibility]:
"""Copy a visibility
Performs a deepcopy of the data array
:param vis: Visibility or BlockVisibility
:returns: Visibility or BlockVisibility
"""
assert isinstance(vis, Visibilit... | 5,316,382 |
def set_produce_compilation_cache(enabled: bool) -> dict:
"""Forces compilation cache to be generated for every subresource script.
Parameters
----------
enabled: bool
**Experimental**
"""
return {"method": "Page.setProduceCompilationCache", "params": {"enabled": enabled}} | 5,316,383 |
def get_args(strInput=None):
"""
Collect arguments from command-line, or from strInput if given (only used for debugging)
"""
parser = argparse.ArgumentParser(description="This program allows you to run the randomoverlaps3.py script against "
"multiple v... | 5,316,384 |
def raw_input(prompt=None): # real signature unknown; restored from __doc__
"""
raw_input([prompt]) -> string
Read a string from standard input. The trailing newline is stripped.
If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
On Unix, GNU readline is used if enabled... | 5,316,385 |
def get_checksum32(oqparam):
"""
Build an unsigned 32 bit integer from the input files of the calculation
"""
# NB: using adler32 & 0xffffffff is the documented way to get a checksum
# which is the same between Python 2 and Python 3
checksum = 0
for key in sorted(oqparam.inputs):
fna... | 5,316,386 |
def create_future(*, loop):
""" Helper for `create a new future`_ with backward compatibility for Python 3.4
.. _create a new future: https://goo.gl/YrzGQ6
"""
try:
return loop.create_future()
except AttributeError:
return asyncio.Future(loop=loop) | 5,316,387 |
def log_sum_exp(mat, axis=0):
"""
Computes the log-sum-exp of a matrix with a numerically stable scheme,
in the user-defined summation dimension: exp is never applied
to a number >= 0, and in each summation row, there is at least
one "exp(0)" to stabilize the sum.
For instance, if dim = 1 and m... | 5,316,388 |
def msd(n_x, yr, min_support):
"""Compute the Mean Squared Difference similarity between all pairs of
users (or items).
Only **common** users (or items) are taken into account. The Mean Squared
Difference is defined as:
.. math ::
\\text{msd}(u, v) = \\frac{1}{|I_{uv}|} \cdot
\\sum... | 5,316,389 |
def create_parser():
""" Parse command line arguments """
parser = argparse.ArgumentParser(
description="Zeus Z80 assembler files converter")
parser.add_argument(
'-v', '--verbose', help="Increase output verbosity",
action='store_true')
subparsers = parser.add_subparsers(help="A... | 5,316,390 |
def wrap_deepmind(env,
episode_life=True,
resize=True,
grayscale=True,
width=84,
height=84,
scale=False,
clip_rewards=True,
frame_stack=True,
stack=4):
""... | 5,316,391 |
def run_3d(name):
"""Run 3D analysis for one source."""
logging.info(f"run3d: {name}")
mode = "3d"
config_file = f"config{mode}.yaml"
target_config_file = f"targets.yaml"
model_file = f"model{mode}_{name}.yaml"
outdir = f"results/{name}"
config = target_config3d(config_file, target_con... | 5,316,392 |
def install_environment():
"""
Install prerequisites to an empty Raspberry PI.
"""
if not exists(CONFIG["arpi_key_name"]) and \
not exists(CONFIG["arpi_key_name"] + ".pub"):
generate_SSH_key(CONFIG["arpi_key_name"], CONFIG["arpi_password"])
dhparam_file = "arpi_dhparam.pem"
if no... | 5,316,393 |
def get_repository_output(arn: Optional[pulumi.Input[str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetRepositoryResult]:
"""
The resource schema to create a CodeArtifact repository.
:param str arn: The ARN of the repository.
"""
... | 5,316,394 |
def annotate_intersection(sv, elements, filetype='gtf'):
"""
Parameters
----------
sv : pbt.BedTool
SV breakpoints and CNV intervals
gencode : pbt.BedTool
Gencode annotations
"""
# Number of fields in SV bedtool
N_BED_FIELDS = 6
# Check intersection with gene bounda... | 5,316,395 |
def install_tracer(env):
"""A program for analysing results from Bayesian MCMC programs such as BEAST & MrBayes.
http://tree.bio.ed.ac.uk/software/tracer/
"""
version = "1.5"
install_dir = os.path.join(env.system_install, "bioinf")
final_exe = os.path.join(env.system_install, "bin", "tracer")
... | 5,316,396 |
def test_get_exams_by_idAdmission(client):
"""Teste get /exams/idAdmission - Valida status_code 200"""
access_token = get_access(client)
idAdmission = '5'
response = client.get('/exams/' + idAdmission, headers=make_headers(access_token))
data = json.loads(response.data)
# TODO: Add consu... | 5,316,397 |
def analyzeGHP(ghp):
"""Analyze this libLF.GitHubProject
Returns:
(testsPassed, libLF.RegexUsage[])
"""
dynoRegexFileName = getRegexOutputFileName()
libLF.log("{}/{} will use dyno regex file {}".format(ghp.owner, ghp.name, dynoRegexFileName))
libLF.log("Untarring")
untarDir = unpackTarball(ghp)
... | 5,316,398 |
def convert(name):
"""
Converts camelCase strings to snake_case ones.
:param name
"""
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() | 5,316,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.