content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def hasattrs(object, *names):
"""
Takes in an object and a variable length amount of named attributes,
and checks to see if the object has each property. If any of the
attributes are missing, this returns false.
:param object: an object that may or may not contain the listed attributes
:param n... | 44,700 |
def pano_stretch_image(pano_img, kx, ky, kz):
"""
Note that this is the inverse mapping, which refers to Equation 3 in HorizonNet paper (the coordinate system in
the paper is different from here, xz needs to be swapped)
:param pano_img: a panorama image, shape must be [h,w,c]
:param kx: stretching a... | 44,701 |
def main():
"""Exercise create_bucket() method"""
# Assign these values before running the program
bucket_name_in_default_region = 'BUCKET_NAME'
bucket_name_in_specified_region = 'BUCKET_NAME'
region = 'us-west-2'
# Set up logging
logging.basicConfig(level=logging.DEBUG,
... | 44,702 |
def blue_process(infile, masterbias=None, error=False, rdnoise=None, oscan_correct=False):
"""Process a blue frame
"""
# check to make sure it is a blue file
ccd = ccdproc.CCDData.read(infile, unit=u.adu)
try:
namps = ccd.header['CCDAMPS']
except KeyError:
namps = ccd.header['CCD... | 44,703 |
def _rand_sparse(m, n, density, format='csr'):
"""Helper function for sprand, sprandn"""
nnz = max(min(int(m*n*density), m*n), 0)
row = np.random.random_integers(low=0, high=m-1, size=nnz)
col = np.random.random_integers(low=0, high=n-1, size=nnz)
data = np.ones(nnz, dtype=float)
# duplicate ... | 44,704 |
def purge_temp(directory):
"""Delete any temporary files."""
shutil.rmtree(directory) | 44,705 |
def return_filepath_or_absent(acl_id):
""" Forms a file path from the acl id, checks if it is present in the input directory,
and returns either the full file path or None (NaN)"""
filepath = '{}/{}.txt'.format(acl_filepath, acl_id)
if os.path.exists(filepath):
return filepath
else:
... | 44,706 |
def draw_loading_screen(dis: display) -> None:
"""Draw loading screen."""
msg1 = "Welcome to Hungry Geese!!!"
msg2 = "Please press any key to start."
msg3 = "You will play the white character, you can control it"
msg4 = "using the direction keys. After each input, the NPCs"
msg5 = "will take a ... | 44,707 |
def STD(cpu_context: ProcessorContext, instruction: Instruction):
""" Set Direction Flag """
cpu_context.registers.df = 1 | 44,708 |
def setup_fonts(fonts_path):
"""Copy fonts."""
os.makedirs(fonts_path, exist_ok=True)
copy_tree(os.path.join(WHERE_AM_I, 'fonts'), fonts_path) | 44,709 |
def main():
"""Entry point."""
print("Creating idlist.csv")
with open("idlist.csv", "w") as basefile:
writer = csv.writer(basefile)
writer.writerow(["ID", "Name"])
count = 0
for appid, name in idreader():
writer.writerow([appid, name])
count += 1
p... | 44,710 |
def antialiasing(scene, win, multi_samples=8, max_peels=4,
occlusion_ratio=0.0):
"""Enable anti-aliasing and ordered transparency.
Parameters
----------
scene : Scene
win : Window
Provided by ShowManager.window attribute.
multi_samples : int
Number of samples fo... | 44,711 |
def _generate_trace(distance):
"""
生成轨迹
:param distance:
:return:
"""
# 初速度
v = 0
# 位移/轨迹列表,列表内的一个元素代表0.02s的位移
tracks_list = []
# 当前的位移
current = 0
while current < distance - 3:
# 加速度越小,单位时间的位移越小,模拟的轨迹就越多越详细
a = random.randint(10000, 12000) # 加速运动
... | 44,712 |
def update_nt_uid_acc(cachepath, uid, accession):
"""Update nt UID GenBank accession."""
# Path must be string, not PosixPath, in Py3.6
conn = sqlite3.connect(str(cachepath))
results = []
with conn:
cur = conn.cursor()
cur.execute(SQL_UPDATE_UID_ACC, (accession, uid))
results... | 44,713 |
def bool_env(env_val):
""" check for boolean values """
if env_val:
if env_val in TRUE_LIST:
return True
if env_val in FALSE_LIST:
return False
# print("Return:%s" % env_val)
return env_val
else:
if env_val in FALSE_LIST:
return Fa... | 44,714 |
def try_parse_json(json_):
"""Converts the string representation of JSON to JSON.
:param str json_: JSON in str representation.
:rtype: :class:`dict` if converted successfully, otherwise False.
"""
if not json_:
return False
try:
return json.loads(json_)
except ValueError:
... | 44,715 |
def svn_ra_get_file(*args):
"""
svn_ra_get_file(svn_ra_session_t session, char path, svn_revnum_t revision,
svn_stream_t stream, apr_pool_t pool) -> svn_error_t
"""
return _ra.svn_ra_get_file(*args) | 44,716 |
def version_microservices(full=True):
"""
Display Zoomdata microservice packages version.
CLI Example:
full : True
Return full version. If set False, return only short version (X.Y.Z).
.. code-block:: bash
salt '*' zoomdata.version_microservices
"""
ms_version = ''
ms... | 44,717 |
def permissions(file):
"""
Returns the permissions for a given file.
"""
octal = {'0': 'no permission', '1': 'execute', '2': 'write', '3': 'write and execute', '4': 'read', '5': 'read and execute', '6': 'read and write', '7': 'read, write and execute'}
permissions = {}
correct_path = get_correct... | 44,718 |
def gatk_variant_recalibrator(job,
mode,
vcf,
ref_fasta, ref_fai, ref_dict,
annotations,
hapmap=None, omni=None, phase=None, dbsnp=None, mills=None,
... | 44,719 |
def generate_times(fnames, sat_id, freq='1S'):
"""Construct list of times for simulated instruments
Parameters
----------
fnames : (list)
List of filenames. Currently, only the first is used. Does not
support multi-file days as of yet.
sat_id : (str or NoneType)
Instrument... | 44,720 |
def test_subtract_two_numbers():
"""Tests if subtraction of two numbers behaves as expected"""
calculator = SimpleCalculator()
result = calculator.sub(10, 3)
assert result == 7, "Subtract 3 from 10 should be 7" | 44,721 |
def run_get_config_info(
config_paths: submanager.models.config.ConfigPaths | None = None,
*,
endpoints: bool = False,
verbose: bool = True,
) -> None:
"""Print basic information about the current configuration."""
vprint = submanager.utils.output.VerbosePrinter(enable=verbose)
if config_pat... | 44,722 |
def test_sequence_compilation5(root_with_template):
"""Test compiling a template : issue in template_vars.
"""
template = root_with_template.items[0]
template.template_vars = {'b': '*1'}
res, miss, errors = root_with_template.compile_sequence(False)
assert not res
assert '1_b' in errors | 44,723 |
def KGCOVID19(
directed = False, preprocess = "auto", load_nodes = True, load_node_types = True,
load_edge_weights = True, auto_enable_tradeoffs = True,
sort_tmp_dir = None, verbose = 2, cache = True, cache_path = None,
cache_sys_var = "GRAPH_CACHE_DIR", version = "current", **kwargs
) -> Graph:
"""... | 44,724 |
def log(*args, **kwargs):
"""
用 log 代替 print
:param args:
:param kwargs:
:return: 在前面多了标识符
"""
print('log', *args, **kwargs) | 44,725 |
def validate_get_response(context):
"""Validate put response."""
json_data = context.response.json()
code = context.response.status_code
assert "status" in json_data
if code == 404:
assert "message" in json_data
else:
assert "user_id" in json_data | 44,726 |
def _cryptodome_encrypt(cipher_factory, plaintext, key, iv):
"""Use a Pycryptodome cipher factory to encrypt data.
:param cipher_factory: Factory callable that builds a Pycryptodome Cipher
instance based on the key and IV
:type cipher_factory: callable
:param bytes plaintext: Plaintext data to ... | 44,727 |
def is_gh_online():
"""
Check if GitHub is online.
The different services of GitHub are running in seperat services
and thus just being GitHub online does not mean,
that required parts are online.
"""
return _is_online("github.com", "/", 200, "OK") | 44,728 |
def commit(ctx):
"""
Commits confidocs. \n
For more information on commit commands
please enter the commit command followed by '--help' \n
Example: shipyard commit configdocs --help
""" | 44,729 |
def test_update_record_empty(client):
""" Test update_record empty """
#with empty record ids
response = client.simulate_put('/page/update_record')
assert response.status_code == 400
#with empty post body
response = client.simulate_put(
'/page/update_record',
params={'id':'CCSF-... | 44,730 |
def git_push_tag(target, version_name):
"""
Pushes the git tag to origin
"""
tag_name = get_git_tag_name(target, version_name)
print('pushing tag ' + tag_name)
sh.git.push('origin', tag_name) | 44,731 |
def _sorted_iteritems(dct):
"""Iterate over the items in the dict in a deterministic fashion."""
for k, v in sorted(_compat.iteritems(dct)):
yield k, v | 44,732 |
def get_items_with_pool(
source_key: str, count: int, start_index: int = 0, workers: int = 4
) -> Items:
"""Concurrently reads items from API using Pool
Args:
source_key: a job or collection key, e.g. '112358/13/21'
count: a number of items to retrieve
start_index: an index to read ... | 44,733 |
def fixup_pth_file(filename):
"""Fix up .pth files which name additional directories to be included in the path"""
lines = []
prev_lines = []
f = open(filename)
prev_lines = f.readlines()
f.close()
for line in prev_lines:
line = line.strip()
if (not line or line.startswith('#... | 44,734 |
def batch_data(words, sequence_length, batch_size):
"""
Batch the neural network data using DataLoader
:param words: The word ids of the TV scripts
:param sequence_length: The sequence length of each batch
:param batch_size: The size of each batch; the number of sequences in a batch
:return: Dat... | 44,735 |
def calc_portfolio_holdings(initial_investment: int, weights: pd.DataFrame, prices: pd.DataFrame) -> Tuple[pd.DataFrame, pd.DataFrame]:
"""
Calculate the initial portfolio holdings given am amount of cash to invest.
:param initial_investment: The initial investment used to purchase the portfolio (no partial... | 44,736 |
def sys_redis_configure_port(port=6379):
""" Configure redis-server port - Ex: (cmd:[port]) """
redis_conf = '/etc/redis/redis.conf'
sudo('sed -i "s/port\s\+[0-9]\+/port {}/g" {}'.format(port, redis_conf))
sys_etc_git_commit('Configured redis-server (port={})'.format(port))
sys_restart_service('redi... | 44,737 |
def ford_fulkerson(G, s, t, capacity='capacity'):
"""Find a maximum single-commodity flow using the Ford-Fulkerson
algorithm.
This is the legacy implementation of maximum flow. See Notes below.
This algorithm uses Edmonds-Karp-Dinitz path selection rule which
guarantees a running time of `O(nm^2)`... | 44,738 |
def index():
"""
Show the main page of Stream4Flow
:return: Empty dictionary
"""
# Do not save the session
session.forget(response)
return dict() | 44,739 |
def create_temporary_table_sql(model: Type[Model]) -> str:
"""
Get the SQL required to represent the given model in the database as a
temporary table.
We cache the results as this will be called for each request, but the model
should never change (outside of tests), so we can use a very small cache... | 44,740 |
def field_paths(h5, key='externalFieldPath'):
"""
Looks for the External Fields
"""
if key not in h5.attrs:
return []
fpath = h5.attrs[key].decode('utf-8')
if '%T' not in fpath:
return [fpath]
path1 = fpath.split('%T')[0]
tlist = list(h5[path1])
pa... | 44,741 |
def get_quantifier(ch, input_iter):
"""
Parse a quantifier from the input, where "ch" is the first character in the
quantifier.
Return the minimum number of occurrences permitted by the quantifier and
either None or the next character from the input_iter if the next character
is not part of the... | 44,742 |
def get_defined_vars(
operation: "OperationDefinitionNode",
) -> List["VariableNode"]:
"""
Retrieve a list of VariableNode defined inside the variableDefinitionNode list of an OperationDefinitionNode
:param operation: the operation definition node to look through
:type operation: "OperationDefiniti... | 44,743 |
def snv(img):
"""
standard normal variates (SNV) transformation of spectral data
"""
mean = np.mean(img, axis=0)
std = np.std(img, axis=0)
return (img - mean[np.newaxis, ...])/std[np.newaxis, ...] | 44,744 |
def fredkin(cell: int, live_count: int, neighbors: Neighbors = None) -> int:
"""\"Fredkin\" Game of Life rule
This rule can be specified using these strings:
- ``B1357/S02468``
- ``2468/1357``
- ``fredkin``
Parameters
----------
cell: int
Value of the current cell. ... | 44,745 |
def mad(arr):
""" Median Absolute Deviation: a "Robust" version of standard deviation.
Indices variabililty of the sample.
https://en.wikipedia.org/wiki/Median_absolute_deviation
"""
arr = np.ma.array(arr).compressed() # should be faster to not use masked arrays.
med = np.median(arr)
... | 44,746 |
def get_logs_directory():
"""Return path of logs directory"""
LDAModel_directory = get_LDAModel_directory()
logs_directory = LDAModel_directory / 'logs'
if not logs_directory.is_dir():
create_directory(logs_directory)
return logs_directory | 44,747 |
def svn_ra_rev_proplist(*args):
"""
svn_ra_rev_proplist(svn_ra_session_t session, svn_revnum_t rev, apr_hash_t props,
apr_pool_t pool) -> svn_error_t
"""
return apply(_ra.svn_ra_rev_proplist, args) | 44,748 |
def test_full_partition(mock_osp):
"""
When no segment boundaries are passed to Corpus#segments(), instances for
all 4096 segments should be generated.
"""
# Add all segments.
mock_osp.add_segments()
# Request all segments.
corpus = Corpus(mock_osp.path)
segments = corpus.segments... | 44,749 |
def gen_poly_model(XVALS, DATA_FLAT, degree: int = 15, debug: bool = DEBUG):
"""Polynomial fit model for data calculation. Uses np.polynomial.polyfit.
Args:
XVALS (array_like): one-dimensional array of x-values of data.
DATA_FLAT (array_like): one-dimensional array of y-values of data.
... | 44,750 |
def parse_date(s):
"""
Given a string matching the 'full-date' production above, returns
a datetime.date instance. Any deviation from the allowed format
will produce a raised ValueError.
>>> parse_date("2008-08-24")
datetime.date(2008, 8, 24)
>>> parse_date(" 2008-08-24 ")
datet... | 44,751 |
def setup_config(quiz_name):
"""Updates the config.toml index and dataset field with the formatted
quiz_name. This directs metapy to use the correct files
Keyword arguments:
quiz_name -- the name of the quiz
Returns:
True on success, false if fials to open file
"""
try:
... | 44,752 |
def unitary_connection(h_pre, h_post, n_pre, n_post, X):
"""
Gives the connectivity value between the n_pre unit
in the h_pre hypercolumn and the n_post unit in the h_post column
"""
hits_pre = X[:, h_pre] == n_pre
hits_post = X[:, h_post] == n_post
return np.sum(hits_pre * hits_post) | 44,753 |
def mase(y, y_hat, y_train, seasonality=1):
"""Calculates the M4 Mean Absolute Scaled Error.
MASE measures the relative prediction accuracy of a
forecasting method by comparinng the mean absolute errors
of the prediction and the true value against the mean
absolute errors of the seasonal naive mode... | 44,754 |
def spi_check(spi):
"""Check an spi pin."""
ored = spi.mosi.connected | spi.miso.connected | spi.sclk.connected
if ored and not spi.num_connections:
raise AlreadyConnectedError(f"Can't use {spi.name} because some pins "
"are already used in other connections.")
... | 44,755 |
def test_multi_level_env_mapping(params_func):
"""
test mapping of environement from different levels during the transitions
"""
params_input = params_func()
params_generator = RessimEnvParamGenerator(params_input)
env_dict = {}
for level in params_input.level_dict.keys():
params = ... | 44,756 |
def _resize_along_axis(inputs, size, axis, **kwargs):
""" Resize 3D input tensor to size along just one axis. """
except_axis = (axis + 1) % 3
size, _ = _calc_size_after_resize(inputs, size, axis)
output = _resize_except_axis(inputs, size, except_axis, **kwargs)
return output | 44,757 |
def getTournamentMatches(tourneyId):
"""
Return a dictionary from match id to match data for a tournament.
"""
if tourneyId not in matchDatas:
refreshMatchIndex(tourneyId)
return matchDatas[tourneyId] | 44,758 |
def compute_protien_mass(protien_string):
"""
test case
>>> compute_protien_mass('SKADYEK')
821.392
"""
p={'A':'71.03711','C':'103.00919','D':'115.02694','E':'129.04259','F':'147.06841','G':'57.02146','H':'137.05891','I':'113.08406','K':'128.09496','L':'113.08406','M':'131.04049','N':'11... | 44,759 |
def find_duration(data):
"""Finds the duration of the ECG data sequence
Finds the duration by looking at the last time value
as the first value is always at time = 0 seconds
:param data: 2D array of time sequences and voltage sequences
:return: Time duration of data sequence
"""
logging.i... | 44,760 |
def response(data, **kwd):
"""Returns a http response"""
return HttpResponse(data, **kwd) | 44,761 |
def load_config(filename='rasoconfig.json'):
""" load config from JSON file
Parameters
----------
filename : str
Filename of config file
Example File
------------
{
"marsdir": "",
"igradir": "",
"rasodir": "/home/mblaschek/workspace/raso_archive"
}
"""
impor... | 44,762 |
def test_uqi_unequal_kernel_size():
"""Test the case where kernel_size[0] != kernel_size[1]"""
preds = torch.tensor(
[
[
[
[1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0],
[1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0],
[1.0, 0.0, 0.0, 0.0... | 44,763 |
def load_actions(action_file: str) -> List[str]:
"""
Load unique actions from an action file
"""
return load_uniq_lines(action_file) | 44,764 |
def get_formula(name, sbml_model, params, assignment_rules, replacements):
"""
get a string representation for a function definition with parameters already replaced
@param name: function name
@type name: str
@param sbml_model: libsbml model
@type sbml_model: libsbml.model
@param params: par... | 44,765 |
def ConvertFile(filename_in, filename_out, loglevel='INFO'):
"""
Converts an ANSYS input file to a python pyansys script.
Parameters
----------
filename_in : str
Filename of the ansys input file to read in.
filename_out : str
Filename of the python script to write a translation... | 44,766 |
def do_work(teststats):
"""Parse arguments and handle them."""
startup_report = teststats.report_startup()
parser = setup_parser()
args = parser.parse_args()
# handle modifiers
output_path = args.output if args.output else "stdout"
# Do the work ...
drive_file = DriveFileRaw(True) i... | 44,767 |
def get_metadata_saml(idp_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetMetadataSamlResult:
"""
Use this data source to retrieve SAML IdP metadata from Okta.
## Example Usage
```python
import pulumi
import pulumi_okta as okta
e... | 44,768 |
def set_port(port):
"""
Sets the port to communicate with the kubernetes proxy
:param port: Port to communicate with the kubernetes API
:return: Kubernetes proxy port
"""
utils.K8S_PORT = int(port) | 44,769 |
def _average_latency(row: Dict):
"""
Calculate average latency for Performance Analyzer single test
"""
avg_sum_fields = [
"Client Send",
"Network+Server Send/Recv",
"Server Queue",
"Server Compute",
"Server Compute Input",
"Server Compute Infer",
... | 44,770 |
def load_dict_from_string(string: str) -> Dict[str, Any]:
"""Convert string to JSON string, convert to a dictionary, and return."""
logger.debug('Loading Dictionary from string: "{}"'.format(string))
json_string = jsonify_string(string)
try:
dict_ = json.loads(json_string)
except json.decod... | 44,771 |
def downscaling(dem_hresf,msk_hresf,wsl_lresf,wd_lresf,thr_val,thr_dpt,thr_decay,wd_hresf,gtiff=True):
"""
Downscale flood maps from coarse to a high resolution. Water
surface elevation from the coarser grid is substracted from high
resolution DEM, it will wet cells with elevation lower than water surf... | 44,772 |
def set_pause_style(style):
"""Set the pause style
Parameters
----------
pause_style : :class:`.PauseStyle` or str
pause style to use, can be a string if the style is registered in
pause.PAUSE_STYLES
"""
global _PAUSE_STYLE
if isinstance(style, str):
try:
... | 44,773 |
def _(expr, assumptions):
"""
Integer**Integer -> !Prime
"""
if expr.is_number:
return _PrimePredicate_number(expr, assumptions)
if ask(Q.integer(expr.exp), assumptions) and \
ask(Q.integer(expr.base), assumptions):
return False | 44,774 |
def train(model, trainLoader, optimizer, loss_function, device, trainParams):
"""
Function to train the model for one iteration. (Generally, one iteration = one epoch, but here it is one step).
It also computes the training loss, CER and WER. The CTC decode scheme is always 'greedy' here.
"""
trai... | 44,775 |
def reorder(A, B):
"""Change coefficient order from y**2 xy x**2 to x**2 xy y**2 in both A and B.
Parameters
----------
A : array
polynomial coefficients
B : array
polynomial coefficients
Returns
-------
A2, B2: numpy arrays
coefficients with changed order
... | 44,776 |
def collate_revs(old, new, key=lambda x: x, merge=lambda old, new: new):
"""
Given revision sets old and new, each containing a series
of revisions of some set of objects, collate them based on
these rules:
- all items from each set are yielded in stable order
- items in old are yielded first
... | 44,777 |
def _set_portgroup_in_vm(domain_name, portgroup, host_ip, vlan_tag):
"""
Set the vlan tag in network configuration of VM
This is required to ensure that VM fetches IP of its vlan from DHCP
"""
(connection_object, domain) = getVirshDomainConn(None, host_ip, domain_name)
xml = etree.fromstring(dom... | 44,778 |
def uninstall(db, really_uninstall=False):
"""Remove all traces of nfldb-projections."""
if really_uninstall:
print('Removing all traces of nfldb-projections...', end='')
with Tx(db) as c:
c.execute('DROP TABLE {}'.format(', '.join(nfldbproj_tables)))
c.execute('DROP TYPE... | 44,779 |
def load_conversation(
filename: str,
dictionary: corpora.Dictionary,
with_symbol: bool=True
) -> (Tuple[List[int], List[int]]):
"""対話コーパスをロードする。
Args:
filename (str): コーパスファイル
コーパスファイルの一行は
何 が 好き です か ?,Python が 好き です 。
のように、(source string, separat... | 44,780 |
def close_incons_reduction(incons: list):
"""
Two step:
0. under the same backends pair
1. the same input, choose largest.(done before)
* 2. different inputs with small distance. Do not update(not used)
"""
def is_duplicate(t: tuple, li: list):
"""unique inconsistency"""
for... | 44,781 |
def mf2tojf2(mf2):
"""I'm going to have to recurse here"""
jf2={}
items = mf2.get("items",[])
jf2=flattenProperties(items,isOuter=True)
#print jf2
return jf2 | 44,782 |
def pp_print(script, summary, captions):
"""
OPTIONAL
Pretty prints filename, script and summar.
:param summary: final generated summary from the NLP model
:param captions: script.Captions object
"""
table = Table(show_header=True, header_style="bold red")
table.add_column("VIDEO", styl... | 44,783 |
def import_all(filename):
""" Imports file contents from user with parameters from nueral net and later calculations
currently not robust to missing or incorrect arguments from file
currently does not convert values to int; done in later functions
inputs: filename - name of input file, curre... | 44,784 |
def fill_database(path: Union[str, Path], settings: SettingsConfig,
inputs: MeasurementInputs, alchemy: Alchemy,
parent_location_id: int, sex_id: int, child_prior: Dict[str, Dict[str, np.ndarray]],
mulcov_prior: Dict[Tuple[str, str, str], _Prior],
... | 44,785 |
def test_papers_have_mod_urls():
"""test_papers_have_mod_urls"""
query = """
MATCH (p:Publication)--(n)
WHERE (p.pubModUrl IS NULL or p.pubModUrl = '')
AND p.pubModId is not null
AND p.pubModId <> ''
RETURN count(DISTINCT labels(n)) as counter """
... | 44,786 |
def ydhms2dt(year,doy,hh,mm,ss):
"""
ydhms2dt Take a year, day-of-year, etc and convert it into a date time object
Usage: dto = ydhms2dt(year,day,hh,mm,ss)
Input: year - 4 digit integer
doy - 3 digit, or less integer, (1 <= doy <= 366)
hh - 2 digit, or less int, (0 <= hh <... | 44,787 |
def create_test_db(verbosity=1, autoclobber=False):
"""
Creates a test database, prompting the user for confirmation if the
database already exists. Returns the name of the test database created.
"""
# If the database backend wants to create the test DB itself, let it
creation_module = get_creat... | 44,788 |
def print_network(model, args):
""" Utility for printing out a model's architecture.
"""
logging.info('-'*70) # print some info on architecture
logging.info('{:>25} {:>27} {:>15}'.format('Layer.Parameter', 'Shape', 'Param#'))
logging.info('-'*70)
for param in model.state_dict():
p_name... | 44,789 |
def key_import(data, key_type=KEY_TYPE.SYMMETRIC, password=b''):
"""Imports a key or key generation parameters."""
key = _ctypes.c_void_p()
_lib.yaca_key_import(key_type.value, _ctypes.c_char_p(password),
data, len(data), _ctypes.byref(key))
return Key(key) | 44,790 |
def test_training_arguments_timestamp(monkeypatch, grim_config):
"""Test TrainingWrapperArguments correctly applies a timestamp."""
def mock_return():
return '2019-06-29_17-13-41'
monkeypatch.setattr(grimagents.common, "get_timestamp", mock_return)
grim_config['--timestamp'] = True
argume... | 44,791 |
def to_vsizip(zipfn, relpth):
""" Create path from zip file """
return "/vsizip/{}/{}".format(zipfn, relpth) | 44,792 |
def readMashDBParams(dbPrefix, kmers, sketch_sizes, mash_exec = 'mash'):
"""Get kmers lengths and sketch sizes from existing database
Calls :func:`~getKmersFromReferenceDatabase` and :func:`~getSketchSize`
Uses passed values if db missing
Args:
dbPrefix (str)
Prefix for sketch DB f... | 44,793 |
def crossval(config, label_data, image_features,
param_grid=None, use_fastr=False,
fastr_plugin=None, tempsave=False,
fixedsplits=None, ensemble={'Use': False}, outputfolder=None,
modus='singlelabel'):
"""
Constructs multiple individual classifiers based on th... | 44,794 |
def flw3i8e(ex, ey, ez, ep, D, eq=None):
"""
Compute element stiffness (conductivity)
matrix for 8 node isoparametric field element.
Parameters:
ex = [x1,x2,x3,...,x8]
ey = [y1,y2,y3,...,y8] element coordinates
ez = [z1,z2,z3,...,z8]
ep = [ir] ... | 44,795 |
def cidr_to_netmask(value):
"""
Converts a CIDR prefix-length to a network mask.
Examples:
>>> "{{ '24'|cidr_to_netmask }}" -> "255.255.255.0"
"""
return str(netaddr.IPNetwork("1.1.1.1/{}".format(value)).netmask) | 44,796 |
def rgb_to_name(rgb_triplet: IntTuple, spec: str = CSS3) -> str:
"""
Convert a 3-tuple of integers, suitable for use in an ``rgb()``
color triplet, to its corresponding normalized color name, if any
such name exists.
The optional keyword argument ``spec`` determines which
specification's list o... | 44,797 |
def _load_library(name, op_list=None):
"""Loads a .so file containing the specified operators.
Args:
name: The name of the .so file to load.
op_list: A list of names of operators that the library should have. If None
then the .so file's contents will not be verified.
Raises:
NameError if one... | 44,798 |
def test_invalid_signature_str():
"""Test for https://github.com/smarie/python-makefun/issues/36"""
sig = "(a):"
@with_signature(sig)
def foo(a):
pass | 44,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.