content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_at_content(sequence): """Return content of AT in sequence, as float between 0 and 1, inclusive. """ sequence = sequence.upper() a_content = sequence.count('A') t_content = sequence.count('T') return round((a_content+t_content)/len(sequence), 2)
6316d29cdb9d7129f225f2f79a50485fb6919e32
18,300
def page_not_found(e): """Handle nonexistin pages.""" _next = get_next_url() if _next: flash("Page Not Found", "danger") return redirect(_next) return render_template("404.html"), 404
9267c65fb842309cf1e877239be4d7fff7b1b634
18,301
def test_query(p: int = 1) -> int: """ Example 2 for a unit test :param p: example of description :return: return data """ return p
69c01914db1d7a5cebf1c4e78f7c5dc7f778b4b4
18,302
def mirror_1d(d, xmin=None, xmax=None): """If necessary apply reflecting boundary conditions.""" if xmin is not None and xmax is not None: xmed = (xmin+xmax)/2 return np.concatenate((2*xmin-d[d < xmed], d, 2*xmax-d[d >= xmed])) elif xmin is not None: return np.concatenate((2*xmin-d, ...
0b538222dd227171ac4a3cf1ac2d8a30361eccf1
18,303
def calc_vertical_avg(fld,msk): """Compute vertical average, ignoring continental or iceshelf points """ # Make mask of nans, assume input msk is 3D of same size as fld 3 spatial dims nanmsk = np.where(msk==1,1,np.NAN) v_avg = fld.copy() v_avg.values = v_avg.values*msk.values if 'Z' in...
7cd512cf2642864e9974e18ef582f541f65b3e96
18,304
import logging import sys def get_logger(log_file, log_level="info"): """ create logger and output to file and stdout """ assert log_level in ["info", "debug"] log_formatter = LogFormatter() logger = logging.getLogger() log_level = {"info": logging.INFO, "debug": logging.DEBUG}[log_level] ...
dc5b7398738f19a6045d874bde039deae17c0602
18,305
def replace(data, match, repl): """Replace values for all key in match on repl value. Recursively apply a function to values in a dict or list until the input data is neither a dict nor a list. """ if isinstance(data, dict): return { key: repl if key in match else replace(value,...
1b3dc8ac7521ec199cf74ebc8f4d8777827ab9fc
18,306
import time def get_current_date() ->str: """Forms a string to represent the current date using the time module""" if len(str(time.gmtime()[2])) == 1: current_date = str(time.gmtime()[0]) + '-' + str(time.gmtime()[1]) + '-0' + str(time.gmtime()[2]) else: current_date = str(time.gmtime()[0]...
480d44fc0153407960eacb875474fc02cb17c6c3
18,307
def to_jsobj(obj): """Convert a Jsonable object to a JSON object, and return it.""" if isinstance(obj, LIST_TYPES): return [to_jsobj(o) for o in obj] if obj.__class__.__module__ == "builtins": return obj return obj.to_jsobj()
ffd43b2d49f6dd0d3b6608a601e3bccc1be1a289
18,308
def EVAL_find_counter_exemplars(latent_representation_original, Z, idxs, counter_exemplar_idxs): """ Compute the values of the goal function. """ # prepare the data to apply the diversity optimization data = np.zeros((len(idxs), np.shape(Z)[1])) for i in range(len(idxs)): data[i] = Z[i...
985d260c74e78ffa6a47a52d6d5d30043b0b5495
18,309
from re import M def min_energy(bond): """Calculate minimum energy. Args: bond: an instance of Bond or array[L1*L2][3]. """ N_unit = L1*L2 coupling = bond.bond if isinstance(bond, Bond) else bond # Create matrix A a = np.zeros((N_unit, N_unit), dtype=float) for i in range(N_u...
e86adbde2cbb5135962360fd67c45704c935c123
18,310
from typing import Tuple def find_result_node(flat_graph: dict) -> Tuple[str, dict]: """ Find result node in flat graph :return: tuple with node id (str) and node dictionary of the result node. """ result_nodes = [(key, node) for (key, node) in flat_graph.items() if node.get("result")] if le...
d0aa0e7ba71c4eb9412393a3bea40965db1525fe
18,311
import string import random def password_generator(size=25, chars=string.ascii_uppercase + string.ascii_lowercase + string.digits): """Returns a random 25 character password""" return ''.join(random.choice(chars) for _ in range(size))
66cedb858d7ddef9b93b4f9ed8ffd854a722c14b
18,312
def create_cleaned_df(df, class_label_str): """Transform the wide-from Dataframe (df) from main.xlsx into one with unique row names, values 0-1001 as the column names and a label column containing the class label as an int. Parameters ---------- df : pandas DataFrame A DataFrame read in...
ac40ce5af2221db6e984537dfd3a8dcb5f25a4a7
18,313
def uni_to_int(dxu, x, lambda_val): """ Translates from single integrator to unicycle dynamics. Parameters ---------- dxu : Single integrator control input. x : Unicycle states (3 x N) lambda_val : Returns ------- dx : """ n = dxu.shape[1] dx = np...
bfd9f0f0e62fbedb9611f762267644ecb2b3de30
18,314
import struct def pack_binary_command(cmd_type, cmd_args, is_response=False): """Packs the given command using the parameter ordering specified in GEARMAN_PARAMS_FOR_COMMAND. *NOTE* Expects that all arguments in cmd_args are already str's. """ expected_cmd_params = GEARMAN_PARAMS_FOR_COMMAND.get(cmd_t...
bbe87233d338344ef2ed21b9555fcd4c22c959dc
18,315
import cupy as cp import cupyx.scipy.sparse.linalg as cp_linalg def get_adjacency_spectrum(graph, k=np.inf, eigvals_only=False, which='LA', use_gpu=False): """ Gets the top k eigenpairs of the adjacency matrix :param graph: undirected NetworkX graph :param k: number of top k eigenpairs to obtain ...
aef39f929c949edb13604c0e83b01b4d6025f06d
18,316
def make_system(*args, **kwargs): """ Factory function for contact systems. Checks the compatibility between the substrate, interaction method and surface and returns an object of the appropriate type to handle it. The returned object is always of a subtype of SystemBase. Parameters: ------...
06d0fbd8eb8ec6e39ec6aabb2192ab8f3455846e
18,317
def _batch_normalization(x, norm, scale=None, norm_epsilon=1e-16, name=None): """ Normalizes a tensor by norm, and applies (optionally) a 'scale' \\(\gamma\\) to it, as well as an 'offset' \\(\beta\\): \\(\frac{\gamma(x)}{norm} + \beta\\) 'norm', 'scale' are all expected to be of shape: ...
41d2f3be7d42fca4b505318e84afdce63aef2887
18,318
def place_owner_list(user_id): """ It retrieves the list of places for which the user is the owner. Parameters: - user_id: id of the user, which is owner and wants to get its own places. Returns a tuple: - list of Places owned by the user (empty if the user is not an owner) - status messag...
ea2c0df7f4e72bd0b7ace5ca9c341a71fd651b32
18,319
def job_met_heu(prob_label, tr, te, r, ni, n): """MeanEmbeddingTest with test_locs randomized. tr unused.""" # MeanEmbeddingTest random locations with util.ContextTimer() as t: met_heu = tst.MeanEmbeddingTest.create_fit_gauss_heuristic(te, J, alpha, seed=180) met_heu_test = met_heu.perf...
6aabf3c2628ecdb98b1ae939040a823be307c6f5
18,320
def download(): """Unchanged from web2py. ``` allows downloading of uploaded files http://..../[app]/default/download/[filename] ``` """ return response.download(request, db)
65e0e27b96b6701f2e04c98be702819908647956
18,321
import argparse def setupCLI(): """ Handles the command line arguments for running the code, making optional date arguments easier and cleaner to handle Returns ------- List of formatted Command Line arguments """ parser = argparse.ArgumentParser() parser.add_argument('databaseNa...
1bc20d2f6f8edd251d37f82f7d56b80a946d0519
18,322
import os def named_cache(path): """ Return dictionary of cache with `(package name, package version)` mapped to cache entry. This is a simple convenience wrapper around :py:func:`packages`. """ return {os.path.split(x.path)[1]: x for x in packages(path)}
2d860582ba5616df7e7d1d20c2f756859a4c62f7
18,323
def action_id2arr(ids): """ Converts action from id to array format (as understood by the environment) """ return actions[ids]
4d3f54078e99c73e0509b36ee39806c721690551
18,324
import argparse import sys def get_args(): """Get command-line arguments.""" parser = argparse.ArgumentParser( description='Emulate the tac program: print file(s) last line first.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('file', ...
e85c1ce545181f579270279e0225e628816ea888
18,325
from numpy import arccos, pi, dot from numpy.linalg import norm def cif_from_ase(ase,full_occupancies=False,add_fake_biso=False): """ Construct a CIF datablock from the ASE structure. The code is taken from https://wiki.fysik.dtu.dk/ase/epydoc/ase.io.cif-pysrc.html#write_cif, as the original ASE c...
e6f7abc9d8142d5e607d5cf8496104fa7468c7c3
18,326
from promgen import models def breadcrumb(instance=None, label=None): """ Create HTML Breadcrumb from instance Starting with the instance, walk up the tree building a bootstrap3 compatiable breadcrumb """ def site(obj): yield reverse("site-detail"), obj.domain def shard(obj): ...
5fec6c8b6d1bfdadec9405b3a4b73b119d7357f9
18,327
import os def parse_body_at(path_to_hdf5, num_frame, all=False): """ :param path_to_hdf5: path to annotations 'hdf5' file :param num_frame: frame to extract annotations from :param all: if True, all original landmarks are returned. Otherwise, only those used for evaluation are returned. :return: ...
af0e6efef103f1c018d7f74de2e63660444166e3
18,328
def get_loader(data_args, transform_args, split, task_sequence, su_frac, nih_frac, cxr_frac, tcga_frac, batch_size, is_training=False, shuffle=False, study...
9f29c63a0d20c71bc6d51f97ddc820709d978caa
18,329
from typing import Optional def get_domain(arn: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetDomainResult: """ The resource schema to create a CodeArtifact domain. :param str arn: The ARN of the domain. """ __args__ = dict() __args__['arn']...
bed4130d5ec77f859cfa7e200794990792b0d2e8
18,330
def collect_properties(service_instance, view_ref, obj_type, path_set=None, include_mors=False): """ Collect properties for managed objects from a view ref Check the vSphere API documentation for example on retrieving object properties: - http://goo.gl/erbFDz Original Source: https://git...
98cc1f6baa38f6c82452a0c3c5efb13a86a17b9e
18,331
import signal def _timeout(seconds): """Decorator for preventing a function from running for too long. Inputs: seconds (int): The number of seconds allowed. Notes: This decorator uses signal.SIGALRM, which is only available on Unix. """ assert isinstance(seconds, int), "@timeout(...
dec9909e662c3943d2bba56e116d6c212201aa42
18,332
def marginal_entropy(problem: dict, train_ixs: np.ndarray, obs_labels: np.ndarray, unlabeled_ixs: np.ndarray, batch_size: int, **kwargs) -> np.ndarray: """ Score is -p(x)log[p(x)] i.e. marginal entropy of the point. :param problem: dictionary that defines the problem, containing keys: ...
78751d2cae853f9595579578c38bf2974cea4316
18,333
def prepareNNImages(bact_img, ftsz_img, model, bacteria=False): """Preprocess raw iSIM images before running them throught the neural network. Returns a 3D numpy array that contains the data for the neural network and the positions dict generated by getTilePositions for tiling. """ # Set iSIM speci...
b43f064ebbb63043db047cc406ad64df1edb0b44
18,334
def get_key(val): """ Get dict key by value :param val: :return: """ for key, value in HANDSHAKE.items(): if val == value: return key
df5924127bec434cadbfae3a4d9e347c55678ae5
18,335
import re def valid_text(val, rule): """Return True if regex fully matches non-empty string of value.""" if callable(rule): match = rule(val) else: match = re.findall(rule, val) return (False if not match or not val else True if match is True else match[0] == va...
aa6f6ac3a3210d34b44eba1f2e8e8cff851ff038
18,336
def settings(): """Render the settings page.""" c = mongo.db[app.config['USERS_COLLECTION']] user = c.find_one({'username': current_user.get_id()}) if not user: return render_template() user['id'] = str(user['_id']) user.pop('_id', None) return render_template('settings.html', user=u...
3a6e3cb38680aea581f3fda1edb11fb0237df355
18,337
def exportAllScansS3(folder_id): """ Exports all Tenable scans found in a folder to S3. """ scan_list = [] scans = client.scan_helper.scans(folder_id=folder_id) for scan in scans: if scan.status() != 'completed': continue scan.download("./%s.html" % scan.details().info.name, format='html') s...
2f460d5cc0d96bfcaab8fca8d1f103120ae78ca4
18,338
import six def check_ontology_graph(ontology_key, survol_agent=None): """This checks that a full ontology contains a minimal subset of classes and attributes. This is for testing purpose only.""" url_script = { "survol": "ontologies/Survol_RDFS.py", "wmi": "ontologies/WMI_RDFS.py"...
a2508826f7e9438b58a5696aa38c1b947aa7c381
18,339
import functools import itertools import time import random import traceback import sys def Retry(retry_value=Exception, max_retries=None, initial_delay_sec=1.0, delay_growth_factor=1.5, delay_growth_fuzz=0.1, max_delay_sec=60): """Returns a retry decorator.""" if...
67e3abf2464ba65c070d8d19fa0a817a26e168cc
18,340
def download_handler(resource, _, filename=None, inline=False, activity_id=None): """Get the download URL from LFS server and redirect the user there """ if resource.get('url_type') != 'upload' or not resource.get('lfs_prefix'): return None context = get_context() data_dict = {'resource': re...
16fcf2ae97ff5d8d2d0d206c1e3035092a034006
18,341
def body_open(): """open the main logic""" return " @coroutine\n def __query(__connection):"
d8792f2b3237f024f20a12c6b7d371af1dbdb21e
18,342
import sqlite3 def db_add_entry(user_auth,\ name:str, user_id:str, user_pw:str, url:str=''): """ Add an entry into the credentials database, and returns the inserted row. If insertion fails, return None. """ # SQL Query sql = f'INSERT INTO {DB_TABLE}' sql += '(name, user_id, user_pw, ...
217c54215c9ee49ed8a32b6093e2b274ce0fe7fe
18,343
def First(): """(read-only) Sets the first sensor active. Returns 0 if none.""" return lib.Sensors_Get_First()
255eb920dae36a01f5e430c44a6922db7eaac0c9
18,344
def rch_from_model_ds(model_ds, gwf): """get recharge package from model dataset. Parameters ---------- model_ds : xarray.Dataset dataset with model data. gwf : flopy ModflowGwf groundwaterflow object. Returns ------- rch : flopy ModflowGwfrch rch package ""...
6af1fef950a951026d082762fd1dce99af7a3ab1
18,345
def _drawdots_on_origin_image(mats, usage, img, notation_type, color=['yellow', 'green', 'blue', 'red']): """ For visualizatoin purpose, draw different color on original image. :param mats: :param usage: Detection or Classfifcation :param img: original image :param color: color list for each cat...
12ae7544c1ddc415c237835cb14b112e186d0d15
18,346
def scale(*args, x = 1, y = 1): """ Returns a transformation which scales a path around the origin by the specified amount. `scale(s)`: Scale uniformly by `s`. `scale(sx, sy)`: Scale by `sx` along the x axis and by `sy` along the y axis. `scale(x = sx)`: Scale along the x axis only. `scale(y = sy)`: Scale along...
4853a2dd4dd8145cfbd502a38531a769674c203c
18,347
import os import pickle def load_tweet_users_posted_rumours(): """ load user history (whether a user posted any rumour in the past) :return: dict {timestamp at which the user posted a rumour: user_id} """ with open(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'tweet_users_poste...
626fc152aae0b38aa4531dafb4d917100bad37c8
18,348
import os def create_power_anomaly_pipeline(hparams): """ Generate anomalies of types 1 to 4 for a given power time series """ pipeline = Pipeline(path=os.path.join('run')) seed = hparams.seed # Type 1: Negative power spike potentially followed by zero values and finally a positive power spik...
c219434f68237e1d3b69dff924d684d377b9e9c5
18,349
async def async_setup_entry(hass, config_entry): """Set up Tile as config entry.""" websession = aiohttp_client.async_get_clientsession(hass) client = await async_login( config_entry.data[CONF_USERNAME], config_entry.data[CONF_PASSWORD], session=websession, ) async def asyn...
0aa031a56e32335cbe0aab83ff686eb970803b8c
18,350
def get_selection_uri_template(): """ Utility function, to build Selection endpoint's Falcon uri_template string >>> get_selection_uri_template() '/v1/source/{source_id}/selection.{type}' """ str_source_uri = get_uri_template(source.str_route) path_selection = selection.str_route param...
ec51a7ecc9476dfd060e717c11f4db9255a756dc
18,351
def conv_single_step(a_slice_prev, W, b): """ Apply one filter defined by parameters W on a single slice (a_slice_prev) of the output activation of the previous layer. Arguments: a_slice_prev -- slice of input data of shape (f, f, n_C_prev) W -- Weight parameters contained in a window - ma...
08528925783a6ad2e0d29e602aafe44082a8c50c
18,352
def _is_pyqt_obj(obj): """Checks if ``obj`` wraps an underlying C/C++ object.""" if isinstance(obj, QtCore.QObject): try: obj.parent() return True except RuntimeError: return False else: return False
7be1750807eaee9ab54ee144019909d3c6890c65
18,353
from typing import Optional from typing import Tuple def get_optimizer( optim_type: str, optimizer_grouped_parameters, lr: float, weight_decay: float, eps: Optional[float] = 1e-6, betas: Optional[Tuple[float, float]] = (0.9, 0.999), momentum: Optional[float] = 0...
b80ca6d38ada3aba310656c7609e73a34d8555b7
18,354
def forward(observations, transitions, sequence_len, batch=False): """Implementation of the forward algorithm in Keras. Returns the log probability of the given observations and transitions by recursively summing over the probabilities of all paths through the state space. All probabilities are in loga...
16e104ee3e4a55903b2874cbef74e9e63584174c
18,355
def fib(n): """Return the n'th Fibonacci number. """ if n < 0: raise ValueError("Fibonacci numbers are only defined for n >= 0.") return _fib(n)
e25907deae2884e3ec69ba8ae29fb362aa50dbe3
18,356
def check_column(board): """ list -> bool This function checks if every column has different numbers and returns True is yes, and False if not. >>> check_column(["**** ****", "***1 ****", "** 3****", \ "* 4 1****", " 9 5 ", " 6 83 *", "3 1 **", " 8 2***", " 2 ****"]) False >>> ...
b903d1b589cd2981cc374ff47f985151d341e7ec
18,357
def lines_len_in_circle(r, font_size=12, letter_width=7.2): """Return the amount of chars that fits each line in a circle according to its radius *r* Doctest: .. doctest:: >>> lines_len_in_circle(20) [2, 5, 2] """ lines = 2 * r // font_size positions = [ x + (font_...
43a7043d1c1632a9683476ab5cfa9d19f8105230
18,358
import subprocess import logging import sys import string def exec_psql(conn_str, query, **args): # type: (str, str, dict) -> str """ Executes SQL queries by forking and exec-ing '/usr/bin/psql'. :param conn_str: A "connection string" that defines the postgresql resource in the format {schema}://{user}:{password...
ee3200d84dacf245720fdf998769903f8463dea3
18,359
def capacitorCorrection(m_cap): """Apply a correction to the measured capacitance value to get a value closer to the real value. One reason this may differ is measurement varies based on frequency. The measurements are performed at 30Hz but capacitance values are normally quoted for 1kH...
1942c177d534bc5533bb636e10f0107c1230c81d
18,360
def code128_quebrar_partes(partes): """ Obtém as partes em que o Code128 deverá ser quebrado. Os códigos de barras Code128 requerem que os dados possuam um comprimento par, para que os dados possam ser codificados nessa simbologia. Embora a chave do CF-e-SAT possua 44 digitos, nem todas as míd...
98a558742f71e7323da7ff6c2a140962d58e59da
18,361
def wrist_mounted_calibration(calibration_data_folder, debug=False): """ Parse our config file and run handical. """ extrinsics_out_file = os.path.join(calibration_data_folder, 'extrinsics.txt') config_filename = os.path.join(calibration_data_folder, 'robot_d...
c98f4f2161bcb0f03503173fceb3e03e3825d069
18,362
def debug(func): """Only for debugging purposes: prints a tree It will print a nice execution tree with arguments and results of all decorated functions. """ if not SYMPY_DEBUG: #normal mode - do nothing return func #debug mode def decorated(*args, **kwargs): #r = f...
4541bad13af0d3ad6ce4ea368798fa5ea267fdf3
18,363
def get_s3_keys(bucket): """Get a list of keys in an S3 bucket.""" keys = [] resp = s3.list_objects(Bucket=bucket) for obj in resp['Contents']: keys.append(obj['Key']) return keys
2efb2e4e9a7ac943c3e35e69a0987933957800e1
18,364
from scipy.ndimage.filters import maximum_filter, minimum_filter def plot_maxmin_points(lon, lat, data, extrema, nsize, symbol, color='k', plotValue=True, transform=None): """ This function will find and plot relative maximum and minimum for a 2D grid. The function can be used to pl...
a1d17972540346e96337e54da72960dc9e1f8afe
18,365
def _get_results(model): """ Helper function to get the results from the solved model instances """ _invest = {} results = solph.processing.convert_keys_to_strings(model.results()) for i in ["wind", "gas", "storage"]: _invest[i] = results[(i, "electricity")]["scalars"]["invest"] retu...
d054ef85df5603d8b450c0e35cd65ab5fb1cc278
18,366
def _get_vlan_list(): """ Aggregate vlan data. Args: Returns: Tree of switches and vlan information by port """ log = logger.getlogger() vlan_list = Tree() for ntmpl_ind in CFG.yield_ntmpl_ind(): ntmpl_ifcs = CFG.get_ntmpl_ifcs_all(ntmpl_ind) for ifc in ntmpl_ifcs: ...
baae2d837f24d6b887d8facc1c0148d7e64f4239
18,367
def subtract_overscan(ccd, overscan=None, overscan_axis=1, fits_section=None, median=False, model=None): """ Subtract the overscan region from an image. Parameters ---------- ccd : `~astropy.nddata.CCDData` Data to have overscan frame corrected. overscan : `~astro...
9d5d8333949f77e86000f836051c92122b96c87b
18,368
from datetime import datetime def read_raw(omega): """Read the raw temperature, humidity and dewpoint values from an OMEGA iServer. Parameters ---------- omega : :class:`msl.equipment.record_types.EquipmentRecord` The Equipment Record of an OMEGA iServer. Returns ------- :class:`...
105e07d26774288319459ebdc485d75c3a909212
18,369
import math def get_spell_slots(pcClass, level): """Return a list containing the available spell slots for each spell level.""" spell_slots = [] if pcClass.casefold() == "Magic-User".casefold(): highest_spell_level = min(math.ceil(level / 2), 9) # MU_SPELL_SLOTS[level - 1] gives first lev...
792110a79eb00965ea72e067e47c8eff2be4c293
18,370
from datetime import datetime, timedelta def determine_dates_to_query_on_matomo(dates_in_database): """ Determines which dates need to be queried on Matomo to update the dataset. """ # determines which dates are missing from the database and could be queried on Matomo # NOTE: start date was set ...
40db63fb7ff339d5c306df37cf0f4b1765b91f90
18,371
from datetime import datetime import json import tempfile def handleMsg(msgJ): """Process the message in msgJ. Parameters: msgJ: dict Dictionary with command sent from client Returns: string JSON string with command response Commands are of the form: {'cmd' : 'getCCC', '...
020050ddfd82823decd6e2ecedcd639c1fee3922
18,372
def calc_total_energy(electron_energy, atomic_distance, energy0): """ Calculates the total energy of H2 molecule from electron_energy by adding proton-proton Coulomb energy and defining the zero energy energy0. The formula: E = E_el + E_p - E_0 where e is the total energy, E_...
3a948dc26e7147961e9c7677ef2b8b1d8f47d0ab
18,373
def k8s_stats_response(): """ Returns K8s /stats/summary endpoint output from microk8s on Jetson Nano. """ with open("tests/resources/k8s_response.json", "r") as response_file: response = response_file.read() return response
68413108eeea6bdd80a782b962f3a5c97e1a4b73
18,374
def display_credentials(): """ Function to display saved credentials. """ return Credentials.display_credential()
0cfb2e7529bd46ae3a05e21aeec25761c062e04b
18,375
from typing import Optional from typing import Dict def evaluate_absence_of_narrow_ranges( piece: Piece, min_size: int = 9, penalties: Optional[Dict[int, float]] = None ) -> float: """ Evaluate melodic fluency based on absence of narrow ranges. :param piece: `Piece` instance :...
4b487f1f749f31d33852d928b1b56d1489336827
18,376
from qalgebra.core.scalar_algebra import ( One, Scalar, ScalarTimes, ScalarValue, Zero, ) from typing import OrderedDict def collect_scalar_summands(cls, ops, kwargs): """Collect :class:`.ScalarValue` and :class:`.ScalarExpression` summands. Example:: >>> srepr...
a6b7ba05db9e9d6434f217bcc7a67f2b6f7ba22b
18,377
import os import gzip import dill def sge_submit( tasks, label, tmpdir, options="-q hep.q", dryrun=False, quiet=False, sleep=5, request_resubmission_options=True, return_files=False, dill_kw={"recurse": False}, ): """ Submit jobs to an SGE batch system. Return a list of the results of each job...
dd7658d0b16a75a303bdb8124809bdd3f74a4ad5
18,378
def _is_domain_interval(val): """ Check if a value is representing a valid domain interval Args: val: Value to check Returns: True if value is a tuple representing an interval """ if not isinstance(val, tuple): return False if not (is_int(val[0]) and is_int(val[1]) and (...
3de16ddc26429be14ab84825f659dcf05f89f1f3
18,379
def rndcaps(n): """ Generates a string of random capital letters. Arguments: n: Length of the output string. Returns: A string of n random capital letters. """ return "".join([choice(_CAPS) for c in range(n)])
0661de89cc1abbbc678f7764f90674f3e5fb7282
18,380
def cutByWords(text, chunkSize, overlap, lastProp): """ Cuts the text into equally sized chunks, where the segment size is measured by counts of words, with an option for an amount of overlap between chunks and a minim um proportion threshold for the last chunk. Args: text: The string with ...
0767eeab983f0d21a9fa14527a3962405019e110
18,381
def dsu_sort2(list, index, reverse=False): """ This function sorts only based on the primary element, not on secondary elements in case of equality. """ for i, e in enumerate(list): list[i] = e[index] if reverse: list.sort(reverse=True) else: list.sort() for i, e ...
3fb614ac732eb790caf8f7d209c4e14022b8352a
18,382
import functools def roca_view(full, partial, **defaults): """ Render partal for XHR requests and full template otherwise """ templ = defaults.pop('template_func', template) def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): if request.is_xhr: ...
eed45a5fc201667744cfe213ec61f5fba546d70b
18,383
async def _shuffle(s, workers, dfs_nparts, dfs_parts, column): """ Parameters ---------- s: dict Worker session state workers: set Set of ranks of all the participants dfs_nparts: list of dict List of dict that for each worker rank specifices the number of partiti...
7b9d8e7dc6687ee5fb661bb0912c6288f3473af9
18,384
def play_game(board:GoBoard): """ Run a simulation game to the end fromt the current board """ while True: # play a random move for the current player color = board.current_player move = GoBoardUtil.generate_random_move(board,color) board.play_move(move, color) #...
3fe2d050e9835bdbabbc81b999edbce7fa0c96d1
18,385
def logical_array(ar): """Convert ndarray (int, float, bool) to array of 1 and 0's""" out = ar.copy() out[out!=0] = 1 return out
74d96d519929ed7f5ddfd92b0fbcef4741a38359
18,386
from datetime import datetime import requests def otp_route( in_gdf, mode, date_time = datetime.now(), trip_name = '', ): """ Return a GeoDataFrame with detailed trip information for the best option. Parameters ---------- in_gdf : GeoDataFrame It should only contain two re...
d19ec8e46b1480697cf0c9c7a83f0a859651b344
18,387
import os def get_package_data(package): """ Return all files under the root package, that are not in a package themselves. """ walk = [(dirpath.replace(package + os.sep, '', 1), filenames) for dirpath, dirnames, filenames in os.walk(package) if not os.path.exists(os.path.j...
d64cec9a1740347ba0c1a6197f0966a27ab2c0c4
18,388
def tall_clutter(files, config, clutter_thresh_min=0.0002, clutter_thresh_max=0.25, radius=1, max_height=2000., write_radar=True, out_file=None, use_dask=False): """ Wind Farm Clutter Calculation Parameters ---------- files : list...
7eb26fbca4977e35f82f844f74d17269d7f80989
18,389
def serialize_bundle7(source_eid, destination_eid, payload, report_to_eid=None, crc_type_primary=CRCType.CRC32, creation_timestamp=None, sequence_number=None, lifetime=300, flags=BlockProcFlag.NONE, fragment_offset=None, total_adu_l...
712a2de8814e5a3bf7143b27aa2d0a6f360e7db4
18,390
def _get_chinese_week(localtime): """获取星期和提醒""" chinese_week = ["一", "二", "三", "四", "五", "六", "日"] tm_w_day = localtime.tm_wday extra_msg = "<green>当前正是周末啦~</green>" if tm_w_day in [5, 6] else "Other" if extra_msg == "Other": go_week = 4 - tm_w_day extra_msg = f"<yellow>还有 {go_week} ...
0a66bcf741c0d2e3cc9a238b5cb879c89333cc6b
18,391
def resnext101_32x16d_swsl(cfg, progress=True, **kwargs): """Constructs a semi-weakly supervised ResNeXt-101 32x16 model pre-trained on 1B weakly supervised image dataset and finetuned on ImageNet. `"Billion-scale Semi-Supervised Learning for Image Classification" <https://arxiv.org/abs/1905.00546>`_ ...
8c99c076278adfacd7764db50824a196a29341e5
18,392
def leaderboard(players=None, N=DEFAULTN, filename="leaderboard.txt"): """ Create a leaderboard, and optionally save it to a file """ logger.info("Generating a leaderboard for players: %r, N=%d", players, N) ratings, allgames, players = get_ratings(players, N) board, table = make_leaderboard(ratings, al...
e5ae7dcd1fd3c54e008b8e472d36b0af0de29463
18,393
def m_college_type(seq): """ 获取学校的类型信息 当学校的类型是985,211工程院校时: :param seq:【“985,211工程院校”,“本科”】 :return:“985工程院校” 当学校的类型是211工程院校时: :param seq:【“211工程院校”,“硕士”】 :return:“211工程院校” 当学校的类型是普通本科或者专科时: 如果获取的某人的学历信息是博士、硕士和本科时 输出的学校类型为普通本科 :param seq:【“****”,“...
bf72f60c51a67dd3e18a7dd1957bc2beb4f933fd
18,394
from owslib.wcs import WebCoverageService from lxml import etree def get_raster_wcs(coordinates, geographic=True, layer=None): """Return a subset of a raster image from the local GeoServer via WCS 2.0.1 protocol. For geoggraphic rasters, subsetting is based on WGS84 (Long, Lat) boundaries. If not geographic,...
5ae378077b3dbe480ef9fae37030d953e156936e
18,395
def del_local_name(*args): """ del_local_name(ea) -> bool """ return _ida_name.del_local_name(*args)
8db5674e8eb3917c21f189ebfa82525482ff712f
18,396
def solve_google_pdp(data): """Entry point of the program.""" # Create the routing index manager. manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']), data['num_vehicles'], data['depot']) # Create Routing Model. routing = pywrapcp.RoutingM...
2b269dbca031c0cf98f51c2e6a493ba7df71a1d6
18,397
from typing import Any def fetch_net(args: Any, num_tasks: int, num_cls: int, dropout: float = 0.3): """ Create a nearal network to train """ if "mnist" in args.dataset: inp_chan = 1 pool = 2 l_size = 80 elif args.dataset == "mini_i...
cbc3abb5140060ef52a69e44883a743249b5cd5e
18,398
from typing import Dict def are_models_specified(api_spec: Dict) -> bool: """ Checks if models have been specified in the API spec (cortex.yaml). Args: api_spec: API configuration. """ predictor_type = predictor_type_from_api_spec(api_spec) if predictor_type == PythonPredictorType an...
611ed794b45746e56bb8055a03251aa43d61d974
18,399