content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def required_download(delta, E, I, EAF, w_o):
""" Returns the required download for stability. """
term1 = 1.16 - 4.76 * (E * I * w_o / delta) ** 0.5 / EAF
term2 = ((delta * w_o) / (E * I)) ** 0.5
return term1 * EAF * term2 | 60aa9773b96b9c839dc96338d65b4aa51424f1e0 | 635,600 |
def find_samples(df, sample_size, existing):
"""
Sample anime in df that have a link on /r/AnimeThemes
:param df: dataframe to sample from
:param sample_size: amount of samples to return
:param existing: dict with downloadable links
:return: list of samples
"""
result = []
count = 0... | 96a05972cbba5e9ef5bd628013b68a88a265ba17 | 635,601 |
def formatsWritersField(writers_list):
""" Formats Writers field for Web app template. """
film_writers=""
if writers_list != None:
for writer in writers_list:
if len(writers_list) == 1 or writer == writers_list[-2]:
film_writers = writer
elif writer != w... | 6088f8bed1b754d1769c694f4671252bf9ffadf8 | 635,602 |
def compute_exact_score(predictions, target_lists):
"""Computes the Exact score (accuracy) of the predictions.
Exact score is defined as the percentage of predictions that match at least
one of the targets.
Args:
predictions: List of predictions.
target_lists: List of targets (1 or mor... | 8b4c80670413cee6cc232eca4740692981755f99 | 635,603 |
def bits2val(bits):
"""For a given enumeratable bits, compute the corresponding decimal integer."""
# We assume bits are given in high to low order. For example,
# the bits [1, 1, 0] will produce the value 6.
return sum(v * (1 << (len(bits)-i-1)) for i, v in enumerate(bits)) | 52471c014418e8cfcee09ecb9c37cd13f883857c | 635,604 |
def clamp_value(n, minimum, maximum):
"""
Clamp a value between a min and max
:param n:
:param minimum:
:param maximum:
:return:
"""
return max(minimum, min(n, maximum)) | 7edcf25454f0cd5989ed1a77ae877d2d9c783020 | 635,605 |
def boundary_conditions(cells, cell_data, phy_lin, nodes_array, bc_x, bc_y):
"""Impose nodal point boundary conditions as required by SolidsPy
Parameters
----------
cell : dictionary
Dictionary created by meshio with cells information.
cell_data: dictionary
Dictionar... | 573e892ff48e30cb3a18469a153f445be1aceedc | 635,606 |
def registrar(obj, store=lambda func, *args: ((name, func) for name in args)):
"""Returns a function decorator that registers the decorated function
in a dictionary-like object 'obj' before returning the function, unmodified.
The 'store' argument should be a callable object that describes how the
funct... | ce78f1241181164113943ab79663ab98f7ef5d6d | 635,607 |
def impute_missing_data(ts):
""" Encodes missing data in time series as
blanks for efficiency when reading files.
Uses Pandas library modules. """
print("\nIMPUTE MISSING DATA running...\n")
# fills NaN values with 0s
ts.fillna(0)
return ts | 51a8458df79ab8e477376e4ee0d08f0650d5ba35 | 635,608 |
import os
def findFrameIndices(rex, grp, searchDir):
"""
Takes a compiled regular expression and a search directory.
Checks each entry of the directory, if a match is found,
the frame number is extracted according to the group named `grp`
"""
files = os.listdir(searchDir)
frame_indices = ... | 6ecd03d3ae0173601bf03f37bef3df94c3ebc305 | 635,609 |
import numpy
def torsional_sampling_ranges(tors_names):
""" sampling ranges for torsional dihedrals
"""
# sym_nums = torsional_symmetry_numbers(zma, tors_names,
# frm_bnd_key=None, brk_bnd_key=None)
# return tuple((0, 2*numpy.pi/sym_num) for sym_num in sym_nums)
# originally restricted range b... | 326f7f3af39671f1f52ec99de06620b064f31d97 | 635,610 |
from typing import Tuple
from typing import Dict
from typing import List
import shutil
def gnu_params() -> Tuple[Dict[str, str], List[str]]:
"""
GNU compilers e.g. GCC, Gfortran
"""
compilers = {'FC': 'gfortran',
'CC': 'gcc',
'CXX': 'g++'}
if not shutil.which(com... | 137f2fe627d1cb0cbd4d43e976c46e38a327fa10 | 635,611 |
def string2index(sentences, vocab):
"""Convert string to its corresponding index
i.e. A -> 0, B -> 1 ... for vocab [A,B,...]
Args:
sentences (np.array of String): list of String to convert.
shape = [num_samples, length]
vocab (list of String): list of vocabulary
Returns:
index (np.array of In... | c0c02dacd312f541e97bcdb330b11562227835c2 | 635,612 |
def line_options(strokeColor='black', fillColor='black', strokeWidth=1):
"""Map from RLD line option names"""
return dict(edgecolor=strokeColor, facecolor=fillColor, linewidth=strokeWidth) | 729389fbf144d91936cbc8c00297cd6ef9c02ba2 | 635,614 |
def _remove_type_bracket_block_from_args_str(args_str: str) -> str:
"""
Remove type annotation block bracket from arguments string.
Parameters
----------
args_str : str
The target arguments string.
e.g., 'dict_val: Dict[str, int] == {}'
Returns
-------
result_str : str
... | d4dcc2f2968c543161ef08cb76cf2baa56058648 | 635,615 |
def parse_country_code(country_code):
"""
Parse country code from URL to determine origin.
:param country_code: country code from URL
:return: parsed country code
"""
cc = str(country_code).lower()
if cc.lower() == 'edu' or cc.lower() == 'com' or cc.lower() == 'org' or cc.lower() == 'gov':
... | 01b9a1e319dc9d08455e69a638154b0c2e8493ee | 635,616 |
def concatenacao(a,b):
""" A função organiza strings de uma forma particular;
str, str -> str """
return a + b + b + a | 05a6e98be0a676d67994695b337aa4c00e23ab30 | 635,617 |
def _wrap(text, width):
"""Break text into lines of specific width."""
lines = []
pos = 0
while pos < len(text):
lines.append(text[pos:pos + width])
pos += width
return lines | 3288dfb868996906357b235b9add27b34678bcc4 | 635,618 |
def chromosome_check(all_sample):
"""
chromosome_check(AllSamples) -> list
:return: list of chromosome found in all samples
"""
return all_sample.chr_list | f4a0841746a5e649ec93d1dd9ecb88cbb175944c | 635,619 |
def unify_walk(bv, o, U):
"""
The unification succeed iff BV.value == other_object
"""
if bv.value == o:
return U
else:
return False | 73d43898cf5d5ae9649a7b8c58ecf617ff16c6ca | 635,620 |
def slice_notation(adjusting_function):
"""
Decorator that returns replacement function using a slice object to determine correct dict (normal or inverse) and
key or raises an exception.
"""
def directed_adjustment(self, key, value=None):
if isinstance(key, slice): # problem: can't use slic... | 22f7efeea5acd53641aa9740cb2e90a17557475e | 635,621 |
import os
import re
def ls(path, exts=None, pattern_incl=None, pattern_excl=None,
ignore_dot_underscore=True):
""" Lists the directory and returns it sorted. Only the files with
extensions in `ext` are kept. The output should match the output of Linux
command "ls". It wrapps os.listdir() which is n... | 78e9c801d1859cbe5da0ee2addc72f7797e70a36 | 635,622 |
def format_auto_pi_set(pi_set):
"""
Parameters
----------
pi_set Pi set in the automatic buckingham DataTable format
Returns Pi set in the Simple Buckingham format
-------
"""
spt = pi_set.split('|')
f_pi_set = ""
for ps in spt:
ps = ps.strip()
ps = ps.replace('... | 23bccd41334e5394ac2ef3833889cd92dbecc50a | 635,623 |
import math
def round_aspect(number, key):
"""(code taken from PIL)"""
return max(min(math.floor(number), math.ceil(number), key=key), 1) | cf91569e0ccdf61ddeac26192333232e23d48f83 | 635,624 |
def rename_nfa_states(nfa: dict, suffix: str):
""" Side effect on input! Renames all the states of the NFA
adding a **suffix**.
It is an utility function to be used to avoid automata to have
states with names in common.
Avoid suffix that can lead to special name like "as", "and",...
:param di... | 4f4ceeeb3298cb2e04c3c832cd9328502371ccfd | 635,625 |
def virtual_machine_name_to_container_name(virtual_machine_name, module_name):
"""
virtual machine name to container name
Args:
module_name: select module name
virtual_machine_name: virtual machine name
Returns:
string(container name)
"""
return "{0}_{1}".format(virtual... | 087d8a96199585dd0bf548129225e1bc1dee68d1 | 635,626 |
def join_matrixes(matrix_1, matrix_2, matrix_2_offset):
""" Copy matrix 2 onto matrix 1 based on the passed in x, y offset coordinate """
offset_x, offset_y = matrix_2_offset
for cy, row in enumerate(matrix_2):
for cx, val in enumerate(row):
matrix_1[cy + offset_y - 1][cx + offset_x] += ... | 5186863471187d3b595786d995552fdb66c62b02 | 635,627 |
def merge_envelopes(envelopes, extent_type='intersection'):
"""Return the extent of a list of envelopes.
Return the extent of the union or intersection of a list of envelopes
:param envelopes: list of envelopes or raster filenames (also mixed)
:type envelopes: list, tuple, iterator
:param extent_t... | 90304f0ea88e735a9a995cb7125928545312cac0 | 635,628 |
import random
def generate_ascending_array(power):
"""Generate an array of integers sorted in ascending order."""
A = []
for k in range((2**power)+1):
A.append(random.randint(-1000000, 1000000))
return sorted(A) | b989e2b9f50a93347ba0c0147c2bb36d6bafa049 | 635,629 |
import string
def format_output(rc, time):
"""
Formats the output that is used in sending the message to the client,
depending on the return code of the command.
"""
template = string.Template("""
${greeting}!\n
I have finished executing your job. Its return code is `$rc`, which
$comment.\n
Your command to... | 091613f5c3b07b822d61b184def02d42abc01a11 | 635,630 |
def elem_to_dict(elem, ns, key_map, value_map={}):
"""Convert an XML etree.Element to a desired dictionary
as specified by the key map and value map.
Args:
elem (etree.Element): An ancestor element
of the tags specified in the key map.
ns (string): The namespace to use
... | fc5c894bba1d374679db23e6cfa176a598c18fdc | 635,631 |
def list_to_string(in_list, conjunction):
"""Simple helper for formatting lists contaings strings as strings.
This is intended for simple lists that contain strings. Input will
not be checked.
:param in_list: List to be converted to a string.
:param conjunction: String - conjunction to be used (e.... | 192b9a01fc7f861ec21e54647097f1a53ce6bc7c | 635,632 |
def to_bio2(tags):
"""
Convert the original tag sequence to BIO2 format. If the input is already in BIO2 format,
the original input is returned.
Args:
tags: a list of tags in either BIO or BIO2 format
Returns:
new_tags: a list of tags in BIO2 format
"""
new_tags = []
... | c0430d7f04c9a7b3e7399c35c26c4cee2a430c76 | 635,633 |
def send_etag():
"""Decorator to specify that in data returned, '_plugit_etag' shouldn't be send back as data but in etag header"""
def real_decorator(function):
function.pi_api_send_etag = True
return function
return real_decorator | 3d5aaa061614781884aba8a591675a8e8792a5f5 | 635,634 |
def cmdline_for_pid(pid):
"""Get the commandline arguments list for a given pid.
Potentially returns None if the process doesn't exist anymore."""
try:
with open('/proc/%s/cmdline' % pid, 'rb') as f:
return f.read().split(b'\0')
except EnvironmentError:
# process already ter... | 9e4085fafc13d78fd3b4ca3b459be48251fc871d | 635,635 |
from typing import OrderedDict
def effectiveBandwidth_dict(xmlroot):
"""Get an ordered dictionary with the xml tags for the image bands as keys
and the effectiveBandwidth as values. We will assume that the order of the bands
in the xml file is the same as the order of the bands in the tif image. This
... | 1eea505e52208568aa06ee1d4dec6ffbb2ec9a65 | 635,636 |
def execute_request(service, property_uri, request):
"""Executes a searchAnalytics.query request.
Args:
service: The webmasters service to use when executing the query.
property_uri: The site or app URI to request data for.
request: The request to be executed.
Returns:
An array of response rows.... | a40ca88b1a60e2da01ff237c95db0cb08cb57bab | 635,637 |
def get_daily_percent_increase(current_rate, increase):
"""Get the daily percentage increase of emails by the new subscription."""
percent_change = (increase / current_rate) * 100
return percent_change | 93f7b92d5bba6f190b40ca6cc1fdf59f964ed374 | 635,638 |
def get_text_title(root):
"""extract text title from NAF"""
target = root.find('nafHeader/fileDesc')
title = target.get('title')
return title | 47efa32e1a2d5809c6cbf8f518c4d1da8e6583b8 | 635,639 |
import os
def check_location_exists(path, file_type):
"""
:param path: absolute path to directory / file you want to check
:param file_type: string: 'source' or 'dest'.
:return: prints status to command line
"""
if file_type != 'source' and file_type != 'dest':
raise ValueError('Speci... | 83c0636da56094e787d697feae75a40628f9dce3 | 635,640 |
def get_natoms(lines):
"""Get the number of atoms from a file like TRAJECTORY."""
istep = lines[0].split()[0]
natoms=0
for line in lines:
new_i = line.split()[0]
if new_i != istep:
return natoms
else:
natoms+=1 | df3b4eb4beb725b711d0e939235b5c4279f936bc | 635,641 |
def lowest(t1,t2):
"""Find consistent lowest of two tuples/lists"""
compare_len = min(len(t1), len(t2))
for i in range(0,compare_len):
if t1[i] < t2[i]:
return t1
elif t1[i] > t2[i]:
return t2
# if here, identical to compare_len; just pick one
return t1 | 4ab3a910e438c5a9849d3eb13f64904c51d0c801 | 635,642 |
import argparse
def get_args():
"""Get arguments from command line and config file."""
parser = argparse.ArgumentParser(description='CosmoFlow training')
parser.add_argument('config', type=str, nargs='?',
help='Configuration file')
parser.add_argument('--output-dir', type=str, ... | 5b28576080d436a3077fa2ca1849270380eaba14 | 635,643 |
import os
import csv
def get_names():
"""
returns a two dimensional list of rows from a csv
file containing the most popular names from 1980
:return: list of rows in csv of names
"""
PATH = os.path.join(os.path.dirname(__file__), "names.csv")
with open(PATH, "r") as file:
reader = ... | 55613b4c4bcf3aa0653b253636f91ae7d3f2b697 | 635,645 |
def custom_admin_notification(session, notification_type, message, task_id=None):
"""
Function for implementing custom admin notifications.
notifications are stored in session and show to user when user refreshes page.
A valid session object must be passed to this function with notification type and me... | 6ab3b478c5109a821fc64201c9468e3d8d132cff | 635,646 |
def calculate_product(alist):
""" Returns the product of a list of numbers. """
product = 1
for fact in alist:
product *= fact
return product | 7abcc1287703bed8cd499738d6afaba9c35199f4 | 635,647 |
def get_accuracy(predictions: list, targets: list):
"""
Here, t can be a list of acceptable labels, instead of just one label. This is
helpful if an evaluation dataset has fewer classes than a model was trained with.
For example, say we want an nli model trained with contraditction, entailment,
neut... | b4a29137340ff6e44ff121311122d9b2f4dd00b8 | 635,648 |
def create_matrices(i, cohort, exp):
"""
Returns train and test features and labels matrices
"""
# Splits cohort according to cutoff (= data_ends - test_label_span - test_span), train: strictly before cutoff, test: after cutoff
train = cohort.loc[cohort['datetime_opened'] < exp['temporal_deltas']['c... | bd581728a0f42bd146b7d9cd17baccf50bd4fea0 | 635,649 |
def mao_like(r1, a, b):
""" Input: a [GPa] and b [1] "mao-like" form parameters (floats)
Return: "mao-like" function with a and b parameters fixed
Descr.: produce function similar to doi:10.1063/1.325277"""
la_0 = 694.24 # nm
return (a / b) * (((r1 / la_0) ** b)... | e31984b31db84c2b3ab4227aca285039eabc736d | 635,650 |
import os
def base_dir(context):
""" Hack for getting the base_dir for uWSGI config. settings.BASE_DIR returns '' in latex templates when using uWSGI """
return '{}'.format(os.getcwd()) | 9be356fa14c8f4688f9b62d8f27ac96642b431e2 | 635,651 |
def get_best_snp(snp_list):
"""
This function choses the best SNP from the tested list by the max values
:param snp_list: list of SNPs with log-likelihood values
:return: name of the best SNP anf its loading value
"""
if len(snp_list) == 0:
return None, 0, 0
# Get the best SNP
sn... | d6c154fa7347c9eb146b4df6da4d2ad23283402e | 635,652 |
def check_null_field(event, field, default):
"""
Check for field in event and assign a default value
:param event:
:param field:
:param default:
"""
return event.get(field) \
if event.get(field) is not None and event[field] is not None \
else default | 77f091af0bed40da5a8b54a4bab09e2c13ca3ad1 | 635,653 |
def get_snapshot_year(ing_year, active_years):
"""
Returns the smallest year greater than ing year
"""
return min([y for y in active_years if ing_year <= y]) | e413183d4bec59c3a5f766213ee703c46716dd24 | 635,655 |
import uuid
import random
def gen_id():
"""Generates a unique but deterministic id if `smarts.core.seed` has set the core seed."""
id_ = uuid.UUID(int=random.getrandbits(128))
return str(id_)[:8] | a3a966625ae5ab6fdfff6b0f8ffffccd560674bf | 635,656 |
def init_state_collection(state, dict_, key):
"""Initialize a collection attribute and return the collection adapter."""
attr = state.manager[key].impl
user_data = attr.initialize(state, dict_)
return attr.get_collection(state, dict_, user_data) | 57a24a449a4bc7e50169ece36acad58b2f7c5a15 | 635,657 |
def check_config(config, warnings, errors):
"""Checks the config for consistency, returns (config, warnings, errors)"""
if 'server' not in config:
errors.append("No server specified.")
if 'user' not in config:
errors.append("No username specified.")
if ('keyfilename' in config) ^ ('certf... | 3c55f734f72bab7b89d42393a2cc19c9c302fd61 | 635,658 |
def uf_external(request):
"""
Provides IP of the uf server and management port based on pytest-args(splunk_type)
"""
uf_info = {
"uf_host": request.config.getoption("splunk_uf_host"),
"uf_port": request.config.getoption("splunk_uf_port"),
"uf_username": request.config.getoption("... | 23ab040d96fb6b8e787ac874c909cafec76d0ad7 | 635,659 |
import base64
def _payout_address_belongs_to_current_wallet(payout_address, all_wallets, machine_auth):
"""Determines whether payout_address belongs to the current wallet on the user's computer.
Args:
payout_address (str): The payout address that the user has specified.
all_wallets (list): Li... | f0e24e21e52ec455c1a3d67d10ea19cfafcbdaee | 635,660 |
import os
def load_public_key(filepath):
"""
load RSA public key in pem format
"""
if not os.path.exists(filepath):
raise ValueError("Public key file not found")
with open(filepath, "rb") as key_file:
public_key = key_file.read()
return public_key | 3cc6f47d40e6bc3d449b14e7c28f71279c30d3de | 635,661 |
def _get_pgh_obj_pk_col(history_model):
"""
Returns the column name of the PK field tracked by the history model
"""
return history_model._meta.get_field(
'pgh_obj'
).related_model._meta.pk.column | 8ff914a7c0142973b58b48b22d9c7429682d69de | 635,662 |
import os
def curdir():
"""
返回当前目录
:return: 当前目录
"""
return os.curdir | 86648379ab657e2b34e4c2bea13a9201de41aa41 | 635,665 |
def small_motif_find(s):
"""processes IUPACcondensed glycan sequence (string) without splitting it into glycowords"""
b = s.split('(')
b = [k.split(')') for k in b]
b = [item for sublist in b for item in sublist]
b = [k.strip('[') for k in b]
b = [k.strip(']') for k in b]
b = [k.replace('[', '') for k in ... | 639fc2a5abd6daed1f5a7627ede07563f001c8d3 | 635,666 |
def table_class_validator(x):
"""
Property: Table.TableClass
"""
valid_table_classes = ["STANDARD", "STANDARD_INFREQUENT_ACCESS"]
if x not in valid_table_classes:
raise ValueError(
"Table class must be one of: %s" % ", ".join(valid_table_classes)
)
return x | a0390cf7821feb847fba8c940ead1370d9fb3673 | 635,667 |
def _parse_query(query):
"""extract key-value pairs from a url query string
for example
"collection=23&someoption&format=json"
-> {"collection": "23", "someoption": None, "format": "json"}
"""
parts = [p.split("=") for p in query.split("&")]
result = {}
for p in parts:
if len... | 7d390f86bc7e74f4016396f066b5aab8afa72f72 | 635,668 |
async def get_modification_stats(db, index_id):
"""
Get the number of modified otus and the number of changes made for a specific index.
:param db: the application database client
:type db: :class:`~motor.motor_asyncio.AsyncIOMotorClient`
:param index_id: the id of the index to return counts for
... | cbeadb2e7d194b57a9b47e664f3d1cbdbe412bf7 | 635,669 |
def _get_sockets(bots):
"""Connects and gathers sockets for all chatrooms"""
sockets = {}
#sockets[sys.stdin] = 'stdio'
for bot in bots:
bot.connect()
sockets[bot.client.Connection._sock] = bot
return sockets | b9548126c9caa791b4a65a58a352e0171ced5d9a | 635,670 |
import random
def create_fake_url():
"""
Generate fake valid URL for VDR and technicalSpecifications
randomize size, font and background color for image.
Example: https://dummyimage.com/700x400/964f96/363636
"""
base = 'https://dummyimage.com'
background_color = ''.join([random.choice('012... | f37349594942f4542c282408b214b1050657a7cc | 635,671 |
import os
def NormalizePath(path):
"""Normalize path for use with os.path.commonprefix.
On windows, this makes sure that the drive letters are always in the
same case."""
abs_path = os.path.abspath(path)
drive, rest = os.path.splitdrive(abs_path)
return os.path.join(drive.lower(), rest) | 8a98492931864ff1dc450eec97c9fc6cb6cb6c07 | 635,672 |
def _check_is_max_context(doc_spans, cur_span_index, position):
"""Check if this is the 'max context' doc span for the token."""
best_score = None
best_span_index = None
for (span_index, doc_span) in enumerate(doc_spans):
end = doc_span["start"] + doc_span["length"] - 1
if position < doc... | ea6c19d67bca3cc6adbcea4ecb6c7c9fe005f886 | 635,673 |
def should_show(name, pruning_params):
"""Whether to show the layer's distribution or not."""
in_whitelist = not pruning_params.white_list or any(
e in name for e in pruning_params.white_list)
in_blacklist = any(e in name for e in pruning_params.black_list)
if pruning_params.white_list and not i... | ced5ed604e75ed7f32267a3f703ddcf2828e546d | 635,674 |
def featurePropertiesOutput(feat):
""" generates a string for features properties """
info = feat.getInfo()
properties = info['properties']
theid = info.get('id')
if theid:
stdout = '<h3>ID {}</h3></br>'.format(theid)
else:
stdout = '<h3>Feature has no ID</h3></br>'
if prope... | e1318f176f6056757a68bcacb0ee0fe64935e18e | 635,675 |
from datetime import datetime
def strip_time(dt: datetime) -> datetime:
"""
Strip a given datetime object of hours, minutes, seconds, ms
* `dt` - date time object to strip
"""
return dt.replace(hour=0, minute=0, second=0, microsecond=0) | 2f98a3bda9d3ebe015c1043405e36fd5c4ee9692 | 635,676 |
def test_case_is_success(test):
"""Determine if the the test expects a successful parse"""
if "results" not in test:
return True
for result in test["results"]:
if "error" in result:
return False
return True | fee43364a8a11ed42564b07533a2500b69c60894 | 635,677 |
import re
def is_leap_year(year: str) -> bool:
"""
All the years that are perfectly divisible by 4 are called as Leap
years except the century years. This checks for that.
:param year : str
a four digit string of numbers
:return bool
"""
assert len(year) == 4, "year must be a str... | 7c606203fbf700da5c6c01204acd5c53c636d10d | 635,678 |
def part_2_fuel(pos, list_):
"""gives the fuel amount for a specific position according to rules of part 2"""
fuel = [(abs(pos - i)*(abs(pos-i)+1))/2 for i in list_]
return sum(fuel) | 95c24df030e8a2eb93bb281a8aef424c1cf6197d | 635,680 |
def preprocess_nxgraph(graph):
"""
:param graph:
:return: idx2node:索引转系节点、node2idx:节点转索引
e.t.([1, 2, 3, 4], {1: 0, 2: 1, 3: 2, 4: 3})
"""
node2idx = {}
idx2node = []
node_size = 0
for node in graph.nodes():
node2idx[node] = node_size
idx2node.append(node)
nod... | 3d9c8de95328de6c2239296c05f349770bb39015 | 635,681 |
def minNbIndif(instance):
""" Returns the minimum number of indifference classes over the orders of the instance.
:param instance: The instance.
:type instance: preflibtools.instance.preflibinstance.PreflibInstance
:return: The minimum number of indifference classes of the instance.
:rtype: int
"""
return ... | b349402f71c7e52a1a925cd8e67d75851f98d686 | 635,682 |
def segments_intersect_or_coincide(a, b, c, d):
"""Return True if segments intersect or coincide"""
def overlapping():
if ((c.x < a.x < d.x) or (c.x < b.x < d.x) or
(c.y < a.y < d.y) or (c.y < b.y < d.y) or
(c in (a, b)) or (d in (a, b))):
return True
... | c2e5e9cef5fa2da10f7c3c61fa43c3664ac7c5e0 | 635,684 |
def hello():
"""Return a friendly HTTP greeting."""
return '''
<html>
<head>
<title>BlackFriday Drones!</title>
<style>
/* http://meyerweb.com/eric/tools/css/reset/
v2.0 | 20110126
License: none (public domain)
*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pr... | 877f64c7ef587a644279f88f071823db74c574e6 | 635,685 |
def is_variable(x):
"""
Checks if the provided expression x is a variable, i.e., a string that
starts with ?.
>>> is_variable('?x')
True
>>> is_variable('x')
False
"""
return isinstance(x, str) and len(x) > 0 and x[0] == "?" | 6eca19d849bfc318f96b54980e1c63d2f8845850 | 635,687 |
def ozip(*optionals):
"""Zip optional values. Return None if one value or the other is None."""
return None if any(x is None for x in optionals) else tuple(optionals) | 1b71b721244d2e922c86848564461600671645b1 | 635,688 |
def check_fizz(number: int) -> str:
"""If a integer is divisible by three function outputs fizz
Args:
number (int): integer to check if divisible by three
Returns:
str: returns fizz if divisible by three, else continues
Examples:
>>> check_fizz(3)
'fizz'
>>> ch... | 35026ef713b0fa3849f0954b7e5df75a8fa72222 | 635,689 |
def tune_step_size_random_walk(step_size, acc_rate):
"""Keep acceptance rate within 25% - 40% acceptance."""
if acc_rate < 0.001:
step_size *= 0.1
elif acc_rate < 0.05:
step_size *= 0.5
elif acc_rate < 0.25:
step_size *= 0.9
elif acc_rate > 0.95:
step_size *= 10.0
... | 90940c41fa7af995cbc660d004bf4a523a8b68b2 | 635,690 |
import os
def check_path_exists(s):
"""Check that path to file exists."""
if s is None or s == 'None':
return None
if os.path.exists(s):
return s
else:
raise FileNotFoundError(f'{s} does not exist.') | 7dbf27e947bbdafd70fda22a534db9e0e649bab8 | 635,691 |
def add_lower(line):
"""Returns if the upper case string is different from the lower case line
Param:
line (unicode)
Returns:
False if they are the same
Lowered string if they are not
"""
line_lower = line.lower()
if line != line_lower:
return line_lower
else... | 440bcb97cf3af831856b9eab2580e7c7cc407294 | 635,692 |
def encode_labels(label: str, label2id: dict, other_class: int) -> int:
""" Encodes labels with corresponding labels id. If relation is unknown, returns special id for unknown relations"""
return label2id.get(label, other_class) | 137c38d41333f6d6cdf403890a63ad90d85ee63f | 635,693 |
import re
from typing import Counter
def sort_oligos(parser, tfunc):
"""
Stores oligos by person ID and oligo ID in a nested dictionary structure
using counts of bases for each base position in each oligo by means of
a Counter object.
{{[]}}
"""
TAGLEN = 28
badcharpattern... | aa6b4a3be7bb800ed04414b6489b99a4a503cc16 | 635,694 |
def build_args(parser):
"""Build arguments."""
# File
parser.add_argument("--train_file", type=str, required=True)
parser.add_argument("--valid_file", type=str, required=True)
parser.add_argument("--model_file", type=str, default="model.pt")
parser.add_argument("--resume", action="store_true")
... | caeaafd2f95962b0821933c2879ac3f00b46b0aa | 635,695 |
import torch
def check_device(device):
"""Check torch device validity."""
if isinstance(device, str):
device = torch.device(device)
if not isinstance(device, torch.device):
raise TypeError("Specify device as torch.device or as string : 'cpu','cuda',...")
if device.type != 'cpu':
... | aef225b71748fe4823b59d85feec84975baae097 | 635,696 |
import getpass
def secure_input(prompt: str) -> str:
"""Get secure input without showing it in the command line.
Args:
prompt (str): The prompt asking the user to input.
Returns:
str: The secure input.
"""
return getpass.getpass(prompt + ' ') | b02befc04196873e793d17820a4d5a010c400d86 | 635,697 |
import pandas
def pqr_to_dict(pqr_file):
"""Convert PQR to dictionary.
Args:
pqr_file: file object for PQR.
Returns:
DataFrame with PQR information.
"""
pqr = []
for line in pqr_file:
row_dict = {}
line = " ".join([line[:6], line[6:]])
words = line.st... | 5f830695c2e315ed5ece219f29c67ec38a4106ed | 635,698 |
def SplitLines( contents ):
"""Return a list of each of the lines in the byte string |contents|.
Behavior is equivalent to str.splitlines with the following exceptions:
- empty strings are returned as [ '' ];
- a trailing newline is not ignored (i.e. SplitLines( '\n' )
returns [ '', '' ], not [ '' ] ).""... | 550fa8e48f8672378fa863c69d1f1696135bdfc5 | 635,699 |
import os
def find_recursive_wfile():
"""
Used to search for `.workflow` files in $PWD and
then recursively in sub directories.
Returns:
list: List of path of workflow files.
"""
wfile_list = list()
for root, _, files in os.walk('.'):
for file in files:
if file... | 335153f23df68e16655f46490731a9fec4b350f4 | 635,700 |
def scan_for_benchmark_versions(bmkdir):
"""Scan subdirectories of a benchmark Directory 'bmkdir' to find
benchmark versions. Return a sequence containing all benchmark
version names."""
srcdir = bmkdir.getChildByName('src')
srcdir.scan()
return srcdir.getScannedChildren() | f6e262e6032e9b413ca47faf02f61a3f16fb1a80 | 635,701 |
def get_lattice(lattice, alat, rescale = False):
"""
Compute the lattice vectors. If rescale = True the vectors are expressed in units
of the lattice constant.
Args:
lattice (:py:class:`array`) : array with the lattice vectors. The i-th
row represents the i-th lattice vectors in car... | 791dd282b5d7f829c21d11999aa86ecf182f528a | 635,702 |
def A(u, dfs_data):
"""The adjacency function."""
return dfs_data['adj'][u] | 447b6ef6ad75fa2054c2291ccc0467107b9bf745 | 635,703 |
import pickle
import tkinter
def SaveVar(var, master=None, value=None, name=None, filename='data.pkl'):
"""Save tkinter variable data in a pickle file and load the
same value when the program is executed next time.
#### If the content of the file changes, it might not load correct values \
to t... | d12100db3eba1ed45a48574e194249b3c087849e | 635,704 |
from typing import BinaryIO
def is_real_file(the_input: BinaryIO) -> bool:
"""
Determine if the file-like object is associated with an actual file.
This is mainly to consider suitability for establishment of a numpy.memmap.
Parameters
----------
the_input : BinaryIO
Returns
-------
... | 04427b6f801bbfad083adecd9117df67c20535ac | 635,705 |
def int2bytes(n):
"""PKCS#1 integer to bytes conversion, as used by RSA"""
string = ""
while n > 0:
string = "%s%s" % (chr(n & 0xFF), string)
n /= 256
return string | 7ddd1e93f08b88cbbb11ab0dd938f974a5b72013 | 635,707 |
def jumlah_deret_geometri(utama: int, rasio_umum: int, jumlah: int) -> int:
"""
Menghitung jumlah deret geometri
>>> jumlah_deret_geometri(1, 2, 10)
1023.0
>>> jumlah_deret_geometri(1, 10, 5)
11111.0
>>> jumlah_deret_geometri(0, 2, 10)
0.0
"""
if rasio_umum == 1:
# Rumus ... | 314228d51f4f08bcb6e77a93de55f4b714615e40 | 635,708 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.