content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_memos(): """ Returns all memos in the database, in a form that can be inserted directly in the 'session' object. """ records = [] for record in collection.find({"type": "dated_memo"}): record['date'] = arrow.get(record['date']).isoformat() del record['_id'] record...
41dd1b854407d3ca9476e02a41a05733e25bbfca
64,100
import json def process_serial_data(serial): """ Parse Lemur options and convert them to Vault parameter in json format. :param options: Lemur option dictionary :return: All needed parameters for Vault roles endpoint in json formatted string. """ current_app.logger.info('*********** url: ' + s...
918cc3c929e71fe2d6a2842b43b19c497993bb8f
64,101
def betterEvaluationFunction(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: <write something here so we know what you did> """ successorGameState = currentGameState newPos = successorGameStat...
0251183e55db1a16d1338fcc3b7a4f5d85debbcd
64,102
def _observables_plots(): """ Metadata for observables plots. """ def id_parts_plots(obs): return [(obs, species, dict(label=label)) for species, label in [ ('pion', r'$\pi$'), ('kaon', '$K$'), ('proton', '$p$') ]] return [ dict( title='Yields', ...
dd991a5c5f1b6e155892431387a5839f28dca11a
64,103
def remove_existID_pixels(givenvalue_pixels_positions, idx_array): """Delete the existed ID pixels who's in nparray idx_array After computing pixels connectivity, we get a set of pixels which have connectivity and have the same ID. We get these pixels positions set as nparray idx_array as well. Then we...
eb788c82295cafee2ec54e6bc06aab06d269cc34
64,104
def order_edges(G): """ Find a total ordering of the edges in DAG G, as an intermediate step to obtaining the CPDAG representing the Markov equivalence class to which it belongs. Raises a ValueError exception if G is not a DAG. Parameters ---------- G: np.array the adjacency matrix ...
83221c94ae6ee2c6296c05d2d120209b776cfd60
64,105
def _get_possible_conformers_rdkit(mol): """ A helper function for conformer search Uses rdkit to automatically generate a set of len(mol.atoms)-3)*30 initial geometries, optimizes these geometries using MMFF94s, calculates the energies using MMFF94s and converts them back in terms of the RMG atom o...
f567baee04b9afe9e68e87725e1b1834eb3adf6d
64,106
from typing import List def finalize_data( data_frame: pd.DataFrame, index_cols: List[str] = INDEX_COLS ) -> pd.DataFrame: """Perform final data cleaning after all other data transformation steps. Params ------ data_frame (pandas.DataFrame): Data frame that has been cleaned & transformed. Re...
b3d3e8cf6d792e6397ccc767412b11a97ba1c739
64,107
def _string_join(self, strings): """ Joins a list of strings together using the calling string as a separator Parameters ---------- strings : list of strings Examples -------- sep = ibis.literal(',') sep.join(['a','b','c']) Returns ------- joined : string """ r...
b2ca59e2b78934dbd48ed201b4345c305adbdf9e
64,108
import csv import collections def parse_rnaseq_file(filename, simplify_protein_names=True): """Parse the given rnaseq file""" # Example: # '/mnt/e/TCGA-BRCA/e14229d4-0b13-4a10-b3f8-4da098c1d218/unc.edu.4c80c4a1-7e99-4f9e-b32c-898ae20206c5.2612041.rsem.genes.normalized_results' with open(filename, 'r')...
fc51a05cee82c11120c150361b37196fca5013b9
64,109
import functools def env_default(**options): """ Use env variable, if set, otherwise execute function to compute attribute. """ not_given = object() def decorator(func): name = getattr(func, "env_name", func.__name__) type = getattr(func, "env_type", str) default = getattr...
ee2a85f995e585d1195351b8f77320e9c1087e89
64,110
def getChipName(chipID): """ Determine the name of the chip from the first byte of the chipID. Raises a KeyError if the chip is not supported by this driver. """ shortID = (chipID & 0xff00) >> 8 return chipIDs[shortID]
cd56c2b804e74b4310c44dd70d8487851e94bbcb
64,111
import json def add_magnet(): """ Adds a magnet link to the downloads list and starts it. Required parameters: * magnet link """ if 'link' not in request.values: return json.jsonify({ 'success': False, 'message': 'You need to send along a link to add' })...
face4d78fb34e73029399c7692d671509288cd98
64,112
def load_helper(helper): """Loads short descriptions about commands into an array """ #areas helper['ADAREA'] = 'ADD AREA' helper['CHAREA'] = 'CHANGE AREA' helper['DXAREA'] = 'DELETE AREA' helper['LIAREA'] = 'LIST AREAS' helper['LXAREA'] = 'SHOW AREAS FILE' helper['PRAREA'] = 'PRINT ...
b856d263cef9890432da06208d46176d6e607965
64,113
def get_avatar_bg_color(n: int) -> str: """ Get persistent shuffled colors for avatars :param n: Positive number, usually user id :return: """ # Wrap possibly too long number n = n % _AC_PRIME # i = n * _AC_PRIME % len(AVATAR_COLORS) return AVATAR_COLORS[i]
579c74aff175881a2ab267703c145ec9bf84e27e
64,114
def leftpart(text, sep): """ leftpart """ if isstring(text): arr = text.split(sep, 1) if len(arr) >= 1: return arr[0] elif isarray(text): return [leftpart(item, sep) for item in text]
dc556902689e0d9b2cf93f93123ce3db20112c9a
64,115
import curses def setup_curses(): """Setup terminal/curses state.""" window = curses.initscr() curses.noecho() window = curses.newwin( WINDOW_HEIGHT + (VERT_PADDING * 2), WINDOW_WIDTH + (HORIZ_PADDING * 2), WINDOW_TOP - VERT_PADDING, WINDOW_LEFT - HORIZ_PADDING, )...
979d53b03b1c5e26cb93eab1a5aa2311e04dca4d
64,116
def refine_network(graph_main, similars_idx, similars, weigh_bounds=(0.6, 1), filename=None, max_cluster_size=100, min_cluster_size=10, max_search_steps=1000, max_cuts=...
cc1a6c1fc69f6491e672d837445edec93837738c
64,117
def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding.""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
b54e233234a6dfe600efa469cf67669688439ca7
64,118
def a_simple_function(a: str) -> str: """ This is a basic module-level function. For a more complex example, take a look at `a_complex_function`! """ return a.upper()
a511eb8577e0440d0026c4762628fdb6de9be643
64,119
def build_estimator(model_dir, model_type): """Build an estimator appropriate for the given model type.""" wide_columns, deep_columns = build_model_columns() hidden_units = [100, 75, 50, 25] # Create a tf.estimator.RunConfig to ensure the model is run on CPU, which # trains faster than GPU for this model. ...
c745b0c3432656f84f4918f1a08712927ad18838
64,120
def reset_password(request): """ Reset a user's password. """ if request.method == 'POST': username = request.POST.get('username') new_password = HuxleyUser.reset_password(username) if new_password: if not settings.DEBUG: user.email_user("Huxley Password Reset...
925eb8899c699f9578633fa70720333520c4b0ad
64,121
from typing import Dict from typing import Any def get_missing_active(config: Settings, table_stats: dict) -> Dict[Any, Any]: """ Args: config: report Settings object table_stats: The overall statistics for the DataFrame. Returns: """ missing_map = { "bar": { ...
ba1c587f0895b9c01f3fc6f7b374a5a33a53fe19
64,122
def paginated_list(full_list, max_results, next_token): """ Returns a tuple containing a slice of the full list starting at next_token and ending with at most the max_results number of elements, and the new next_token which can be passed back in for the next segment of the full list. """ ...
99a20e3af4ff64d3de52eccbc00aea9fda735e00
64,123
from re import U def build_act(make_obs_ph, q_func, num_actions, scope="deepq", reuse=None): """Creates the act function: Parameters ---------- make_obs_ph: str -> tf.placeholder or TfInput a function that take a name and creates a placeholder of input with that name q_func: (tf.Variable,...
23bf715e2c548db12f6d33a85b6c3adac258be0b
64,124
import struct def bi_hash(v): """ Calculate BI hash from given value :param v: :return: """ bh = siphash24(SIPHASH_SEED, str(v)) return int(struct.unpack("!Q", bh)[0] & 0x7FFFFFFFFFFFFFFF)
4bd455970d7b22ff60a800417e4faf36755e576c
64,125
def normalize_with_max(x, axis=(0,1), data_chns='CPLX'): """ x is complex value x = x/(max(abs(x))) """ scalor = np.max(abs(x), axis) if data_chns == 'CPLX': normalized_x = cplx2float(x/scalor) return normalized_x if data_chns == 'MAG': normalized_x = abs(x/scal...
1b73fe60ab1c000f6824d83b1934deeccefa8854
64,126
def celsius_to_kelvin(deg_C): """Convert degree Celsius to Kelvin.""" return deg_C + 273.15
45eb2dd781adbab2db44f5a8ce5042b2834c7c00
64,127
def rebin(wavelength, flux, new_wavelength): """ Resample and rebin the input Sightline object's data to a constant dlambda/lambda dispersion. Parameters ---------- wavelength flux new_wavelength Returns ------- new_flux """ # TODO -- Add inline comments npix = len...
f9eb5bb45b784f1d5fea30f72f39959d39402299
64,128
async def get_alters(): """ Get alter fields of all alter objects. ?full=0 for basic information. """ action = {"mode":"get", "args":request.args} outgoing = Manage_DATA(action=action, alters=[Alter(id="*")]) incoming = await manage_post(outgoing) decoding = Manage(**incoming) return Al...
0825338cf53e9fa43fcbe65b3f1a0f2c2d2ab587
64,129
def set_diff(seq0, seq1): """Return the set difference between 2 sequences as a list.""" return list(set(seq0) - set(seq1))
b68abf4ae6eee79e7e9ce4a5c5110f9f298e9e41
64,130
def get_listing_content_type(req): """ Determine the content type to use for an account or container listing response. :param req: request object :returns: content type as a string (e.g. text/plain, application/json) :raises HTTPNotAcceptable: if the requested content type is not acceptable ...
5205ae5ee2b37a25b02ea5f4977198e79d467f97
64,131
from typing import Tuple from typing import Dict import json def list_policies(client: Client, *_) -> Tuple[str, Dict, Dict]: """List all policies. Args: client: Client object with request. *_: Returns: Outputs. """ policies_xml = client.list_policies_request() polici...
64198831175c84d250eeaac200375e33fc725f4a
64,132
def butterfly_support(size): """ Generate a butterfly support of a given size :param size: int :return: numpy array """ assert size % 2 == 0 support = np.kron(np.ones((2, 2)), np.identity(size // 2)) return support
d1c2c7f2861bed3195b47ffc9f64bc0cd41565a6
64,133
from os.path import expandvars, basename from glob import glob def all_models(): """ Get a list of models that are valid arguments to load_model() """ basedir=expandvars('$I3_BUILD/MuonGun/resources/tables/') suffix = '.single_flux.fits' return [p[:-len(suffix)] for p in map(basename, glob(basedir+'*'+suffix))]
ed9cc1c9fb980f342022ee82dce23828ac28df4d
64,134
import traceback def init_emu(leaf_ends, state_var, cmovs, finfo, fbytes, bitness): """sets up memory, sets hooks, etc""" BASE_ADDRESS = finfo['addr'] try: mode = UC_MODE_32 if bitness == 64: mode = UC_MODE_64 emu = Uc(UC_ARCH_X86, mode) emu.mem_map(page_align(...
3e9aead4ebbe099e256f7bc21c6f4fe79d1d843e
64,135
from typing import Union import abc def object_writable(model: Union[type, abc.Object]) -> abc.ObjectMeta: """ This function returns an instance of [sob.meta.Object](#meta-Object) which can be safely modified. If the class or model instance inherits its metadata from a class or base class, this functi...
adcc0875a04852d66fb64849c4b084e68e68fdd5
64,136
def radiation_pressure_freq_noise( ff, Pin, length, finesse, mass=2.92, lam=1064e-9, ): """Radiation pressure frequency noise for a total cavity in units of Hz/rtHz. Inputs: ------- ff: float audio frequency in Hz Pin: float cavity input power in watts len...
993fb9528857e83b66898f39507961bc81fa906b
64,137
import math def envpartners_all_in_one(dynophore, superfeature_id, frame_range=[0, None], frame_step_size=1): """ Plot interaction data for a superfeature, i.e. occurrences (frame series) and distances (frame series and histogram). Parameters ---------- dynophore : dynophores.Dynophore ...
0fc0aba552e4ce9e2315200ceecd67d1072775cd
64,138
from typing import Optional import time from io import StringIO def create_ap( cnx: Connection, phy: Optional[str] = None, interface: Optional[str] = None, ssid="tkn_walker", channel=1, psk=None, bssid=None, ip="10.1.1.1", ): """Creates Wi-Fi AP with hostapd. Args: cnx...
33604255cf3f9083b9f27fc54529dad7e8bf31c6
64,139
from django.db.models import Count def get_not_exeuted_details(): """ Returns count of not executed jobs, grouped by name, based on job type. """ values = Job.objects.values('name') result = list(values.filter(Q(executed=None) & Q(cancelled__isnull=True)) ...
3610aab34501278672b2d99f1b9f955bb1db32ac
64,140
import typing from datetime import datetime def load_data( price_source: str, tickers: typing.List[str], start: datetime, end: datetime, features: typing.List[str], ): """Returned price data to use in gym environment""" # Load data # Each dataframe will have columns date and a collecti...
669a894dee9987cb84b73af7fe4b0b02ff7ab705
64,141
import re def conviq(string): """ Convert image quality percentile string to decimal value. """ if np.logical_or('Any' in string, 'null' in string): iq = 1. else: iq = float(re.findall(r'[\d\.\d]+', string)[0])/100 if iq <= 0.2: iq = 0.2 # elif 0.2 < iq <...
8749b71083c43148d5dd3d29f8c3661004d86d91
64,142
def replace_field_refs_according_to_new_or_deleted_fields( formula: str, trash_ids_to_names, new_names_to_id ) -> str: """ Given a raw formula string lexs it into a token stream and goes through and replaces all field_by_id references to a id in the provided trash_ids_to_names with a field reference...
48306495f448c13e60bf1f3c00911db1388aa2e8
64,143
def get_age_group_metadata(gbd_round_id: int) -> pd.DataFrame: """ Gets age group metadata. """ df = db_queries.get_age_metadata(age_group_set_id=CascadeConstants.AGE_GROUP_SET_ID, gbd_round_id=gbd_round_id) df.rename(columns={'age_group_years_start': 'age_lower'...
ac1573cf97e032d96793e85f08509f96f364b79d
64,144
import sqlite3 def create_connection(db_file=msid_files['archfiles'].abs): """ create a database connection to the SQLite database specified by the db_file :param db_file: database file :return: Connection object or None """ conn = None try: conn = sqlite3.connect(db_file) ...
566ab1016c8bed8b86687ed7e67c2c7c6a93265e
64,145
import random def choose_param_numerical(min_val, max_val, param_type, sigma, current): """ Chooses a numerical parameter value via a uniformly or normally distributed random choice. Which one is used is determined at random. """ r = random() # sometimes choose value uniformly to avoid bei...
3605c725ce38af36ce87eb0c38e16ce33d9a9eef
64,146
import subprocess def call_with_timeout(args, timeout, **kwargs): """Runs an executable with an optional timeout. timeout 0 or None disables the timeout. """ proc = Popen( args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, **kwargs) if timeout: out = '' err = '' for t,...
a8fb3a7e8e17deb9fe4a45fcb2e4d8479228a44f
64,147
def get_points_2D(outputs, threshold=0.2): """Pour 1 personnage capté: [Pose(keypoints={ <KeypointType.NOSE: 0>: Keypoint(point=Point(x=717.3, y=340.8), score=0.98), <KeypointType.LEFT_EYE: 1>: Keypoint(point=Point(x=716.2, y=312.5), score=0.6), <KeypointType.RIGHT_EYE: 2>: Keypoint(point=Point(x=6...
524b350c7a5cceb60e07008ff00c8ee869e0b71b
64,148
import re def get_replica_prefix_from_node_name(node_name): """Get replica prefix from operation name.""" regex = re.compile(constant.REPLICA_PREFIX_FORMAT.format("([0-9]+)")) res = regex.search(node_name) return "" if res is None else res.group()
50a9470bf54a5827d7ceb1c392339ff624966da9
64,149
def signin_button(): """Returns the button image for sign-in.""" return send_file("templates/signin_button.png", mimetype='image/gif')
ad3bcac0ca0d51325d8b1ebcf961efe4c754dec8
64,150
import ast import typing def evaluate( node: ast.Node, env: objects.Environment ) -> typing.Optional[objects.Object]: """Evaluate AST recursively.""" if isinstance(node, ast.Program): return eval_program(node.statements, env) elif isinstance(node, ast.ExpressionStatement): return evalu...
72b6e0d3dde9595ddc56b1577d1ad271b5e1d50c
64,151
def get_nonbonded_force_from_openmm_system( openmm_system: openmm.System, ) -> openmm.NonbondedForce: """Get a single NonbondedForce object with an OpenMM System.""" for force in openmm_system.getForces(): if type(force) == openmm.NonbondedForce: return force
a34360f3bf127e49c497156626906000ccc85f96
64,152
import math def get_uniform_keys(n_keys, dim, seed): """ Generate random uniform keys (same initialization as nn.Linear). """ rng = np.random.RandomState(seed) bound = 1 / math.sqrt(dim) keys = rng.uniform(-bound, bound, (n_keys, dim)) return keys.astype(np.float32)
a4194cc926b45c052efef18b731159fbbd4ab584
64,153
import logging def return_sites(description): """ Find appropriate resources to deploy infrastructure, but don't do anything """ # Get RADL radl_contents = utilities.get_radl(description) if not radl_contents: logging.critical('RADL must be provided') return None # Get req...
eb9ff461211de759f20f1f53c90032fce7e2c164
64,154
def eig_sort(w, v): """ sort eignenvalues and eigenvectors by eigenvalue. """ ids = np.argsort(w) return w[ids], v[:, ids]
7ce5637073e2599b5bfdc9d2de2e10d43d2b2335
64,155
from typing import Optional import os def _run_notebook( config: cconfig.Config, notebook_file: str, publish: bool, # incremental: bool, num_attempts: int, ) -> Optional[int]: """ Run a notebook for a specific `Config`. :param config: config for the experiment :param notebook_...
298269ec1d79845cd5ffcf173f7d20526b758463
64,156
import binascii def generate_zos_keys(node_public_key): """Generate a new set of wireguard key pair and encrypt the private side using the public key of a 0-OS node. Args: node_public_key (str): hex encoded public key of 0-OS node. This is the format you find ...
39d5821a1d8fcb2937a7156bd259d3a2d43762c8
64,157
def filterMapAttrs(records=getIndex(), **tags): """matches available maps if their attributes match as specified""" if len(tags) == 0: return records # otherwise if unspecified, all given records match ret = [] for record in records: # attempt to match attributes if matchRecordAttrs(record, tags...
b5773be69b1f1e411fb528d3d3da8f8c377c210e
64,158
import random def get_seed(seed): """Get the seed to run the generator Args: seed : input seed Returns: seed to run instruction generator """ if seed >= 0: return seed return random.getrandbits(32)
b8ec781f30c302fe7f87f9182a1fccca0af0fdd7
64,159
def get_user_profile_rank_list_elements(organization_id, viewer_user_id, expression='limit 10', args=None): """ Return a rank list place of the user by id. """ if args is None: args = [] with connection.cursor() as cursor: cursor.execute( PROFILE_RANK_LIST_ELEMENTS_QUERY...
f8ee63f91a29ff0b12192b39632d68bb351c7dc5
64,160
import warnings import io def run(taskfile, nosubmitted=False, depjobs=None, nersc=None, nersc_queue="regular", nersc_maxtime=0, nersc_maxnodes=0, nersc_shifter=None, mpi_procs=1, mpi_run="", procs_per_node=0, nodb=False, out=None, debug=False): """Create job scripts and run them. This gets tasks...
f2a071acfbc67a75f4327d2c3640cea7f559c1de
64,161
def insurance(): """ Insurance Information Controller """ mode = session.s3.hrm.mode def prep(r): if mode is not None: auth.permission.fail() return True s3.prep = prep output = s3_rest_controller() return output
d5271522db43ee3db54570f5286d844afdfd55e7
64,162
def params_linear_and_squares(factors): """Index tuples for the linear_and_squares production function.""" names = factors + [f"{factor} ** 2" for factor in factors] + ["constant"] return names
8f7505cb2a07e08d3ad2686d52960d631cd7b458
64,163
def scale(df: pd.DataFrame, method: str) -> pd.DataFrame: """ scales features using different methods. Parameters ---------- df: pandas.DataFrame method: {"autoscaling", "rescaling", "pareto"} Scaling method. `autoscaling` performs mean centering scaling of features to unitary v...
2ce286e507e9574be0d33dd22046ce79dae34205
64,164
from typing import Union from typing import Iterable from pathlib import Path from typing import Any def access( path: Union[Pathlike, Iterable[str], Iterable[Path]], mode: str, **kwargs, ) -> Any: """ Access data (arrays and groups) from a variety of hierarchical array storage formats. Para...
71ecc1e9999808feefb544aed00f8ee99a47cb25
64,165
from typing import Tuple def metadataAppendCompatible(meta1: dict, meta2: dict) -> Tuple[bool, str]: """ Verifies two metadata dictionaries match in a set of required fields. If a field is present in only one or neither of the two dictionaries, this is considered a match. This is primarily intend...
8a3fc01d331f2f0c4dadb148819460092619f64c
64,166
def equal_bytes(*args): """equal_bytes(ea_t ea, uchar image, uchar mask, size_t len, bool sense_case) -> bool""" return _idaapi.equal_bytes(*args)
a97ffa4b7b875d2034630b0938bfeaa23603aade
64,167
from typing import Callable import itertools def _word_wrap(paragraph: str, width: float, measure_func: Callable[[str], float]): """Break text in multiple line.""" result = [] for line in paragraph.split("\n"): # handle empty lines if line == "": result.append("\n") ...
721185a4788e08a7126f8755157dc2d2f9442313
64,168
def node_weights(network, attribute=False): """ Obtains a spatial weights matrix of edges in a network if two edges share a node, they are neighbors Parameters: network: a network with/without attributes attribute: boolean if true, attributes of edges are added to a d...
7b3b1e1809e062dc9b6e5fc170b3867888ee4216
64,169
def import_ecdsa_privatekey_from_file(filepath, password=None): """ <Purpose> Import the encrypted ECDSA key file in 'filepath', decrypt it, and return the key object in 'securesystemslib.formats.ECDSAKEY_SCHEMA' format. Which cryptography library performs the cryptographic decryption is determined...
9e7c6e4845ed231dbf4f901d2dacea016fbbe633
64,170
from typing import Any from typing import Dict def rx_from(observable_input: Any) -> Observable: """Convert almost anything to an Observable. Anything means: - a dictionnary in an rx_dict - an async iterable - an iterable - something which can be cast to an Observable (have a ...
d2cecdf291fa781e93f4566b33f84becc8901a4f
64,171
import time def group(request, group): """Returns a page showing all hosts/services of the specified group""" stat, obj = parse() service_dict = {} host_list = hostlist_by_group(stat, obj, group) if not host_list: raise Http404 host_names = map(lambda x: x['host_name'], host_list) ...
407d29a84ea7ec647166b13a2cf24c5b59e1457e
64,172
import glob import os def get_component_drz_list(drizzled_image, drz_root_dir, flt_file_names): """Get a list of the drizzled exposure images associated with this combined drizzled image Usually this can just use glob to get a list of all the drizzled exposures for this filter, but it also handles the c...
b1434da3ce8e8fb2a3ffc38519e6bf3725f6c147
64,173
def set_model_internal_data(model, original_data, modified_data, deleted_data): """ Set internal data to model. """ model.__original_data__ = original_data list(map(model._prepare_child, model.__original_data__)) model.__modified_data__ = modified_data list(map(model._prepare_child, model._...
cf17f9f04342be01706530c79f9bb83cd8c03b73
64,174
def sub_parser_decorator(func=None, **parser_settings): """ Decorated for sub_parser argument definitions """ if not func: return partial(sub_parser_decorator, **parser_settings) def _wrapper(parser): sub_parser = parser.add_parser(**parser_settings) sub_parser.add_argument(...
eaa6c2635fc1e6deb1b7b51f3212a6c909f07e49
64,175
from typing import Union def get_subplots_titles(items, subplot_titles: Union[list, dict] = None) -> dict: """Standardize subplots titles in a dict""" # BUG: when passing a list, wrong subplotstitles if isinstance(subplot_titles, dict): pass elif subplot_titles is None: try: ...
0d0441d503d95a915021d54971eecd6ea4eeb606
64,176
def neg_binomial(x, n, p): """ Get the probability density for a negative binomial distribution. :param x: Edges of bins within which to calculate probability density :type x: :class:`~numpy.ndarray` :param int n: Number of trials (see :data:`~scipy.stats.nbinom`) :param int p: Probability of s...
65359ac707e971370708f143b744162e4b8fde4a
64,177
def vp_u(CPs, Pv, Alpha, RegFunction=0, RegParam=0): """ Induced velocity from one vortex particle on several control points CPs : n x 3 Pv : 3 Position of vortex particle Alpha : 3 Intensity of vortex particle RegFunction: Regularization function: 0: None ...
0b494f7e8844a2ec3acc23ee5367aa61ef433329
64,178
def convert_mask_data(data): """ Converts a numpy array mask to our internal complex polygon data representation. """ mask = np.uint8(np.array(data) > 0) contours, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) contours = [contours[i].reshape(-1, 2) for i in range(len(c...
fc486a6fc44d21c1a4a2fc446404f2e1ce676726
64,179
def tuple_as_atom(atom:tuple) -> str: """Return readable version of given atom. >>> tuple_as_atom(('a', (3,))) 'a(3)' >>> tuple_as_atom(('bcd', ('bcd',12))) 'bcd(bcd,12)' """ assert len(atom) == 2 return '{}({})'.format(atom[0], ','.join(map(str, atom[1])))
5c18f34733d839865eef35509f95c2d4d198a903
64,180
def compute_ms_ssim_dic(x_hat, code, max_value=1.): """ Compute (weighted) MS-SSIM for two YUV dictionnaries. Return one value: the ms_ssim """ res = 0 nb_values = 0 for x_hat_channel, code_channel in zip(get_y_u_v(x_hat), get_y_u_v(code)): nb_values += x_hat_channel.numel()...
1f156a7d1121b1d7693204633520da9484e7846c
64,181
def addReport(session, run_id, file_id, main_section, bugpath, events, bug_extended_data, detection_status, detection_time, severity_map): """ """ try: checker_name = main_s...
7b197700ecdd083a9a4aed2d985840ce622abed1
64,182
def create_ideal_periodic_signal(signal_length): """Create ideal ribo-seq signal. Parameters ---------- signal_length : int Length of signal to create Returns ------- signal : array_like 1-0-0 signal """ uniform_signal = np.array([4 / 6.0] * signal...
0385b2279cb7a8b7eb663c7991d013c8b1b5a245
64,183
def quadrupole_q20(fam_name, strength, simplified=False): """Segmented Q20 quadrupole model.""" segtypes = { fam_name: (fam_name, _pyaccel.elements.quadrupole), } # Q20 model # ========= # this (half) model is based on fieldmap # '2017-02-24_Q20_Model05_Sim_X=-14_14mm_Z=-500_500mm_I...
9768792bddc37e09cb87affc1a0d7b1d66678dc3
64,184
def get_engine(settings: dict, prefix: str = 'sqlalchemy.') -> Engine: """Reads config and create a database engine out of it. :param settings: Application settings :param prefix: Configuration prefixes :return: SQLAlchemy Engine """ url = settings.get('sqlalchemy.url') if not url: ...
c33dd66d13a3413ae6b78a4c04a8385c3500cc78
64,185
import struct def Fbytes(f): """ Return bytes representation of float """ return struct.pack("f", f)
117fb86216ad6983851923ac9dbd0196cc29b92d
64,186
def _debug_mode_enabled() -> bool: """ Return whether debug mode is currently enabled. Returns: ``bool``: whether debug mode is enabled """ return _DEBUG_MODE_ENABLED
84bf813633ddf6433ce980105aee79c166a3257c
64,187
def propMatVisc(zarray, n, params, t=1, Q=1, scaled=False, logtime=False): """Generate the viscous love-number propagator matrix for zarray. Inhomogeneities from elastic deformation and viscous migration of nonadiabatic density gradients are added using gen_viscb. Parameters ---------- z...
4c249c3c89e5a280d70575528fc860be0fb48fa9
64,188
def Vaknin(x): """ Vaknin correction for CSD analysis (Max Sherman [Brown U] implementation) Allows CSD to be performed on all N contacts instead of N-2 contacts See Vaknin et al (1989) for more details """ # Preallocate array with 2 more rows than input array x_new = np.zeros((x.shape[0]+2,...
53baf485af7c87a735f8cf6b62b03be0356ba47b
64,189
def shrink(data, is_valid): """ Simplify `data` subject to `is_valid(data)`. `data` is any JSON-form data (strings, bools, None, ints, floats, lists, and dicts). This is roughly analogous to the concept of `shrink` from `QuickCheck`. It's used in `bugpoint`. """ # This is in principle ...
3cd4e5db8e8547f3d405e601082be28ef4f71455
64,190
from typing import Optional from typing import List def diff_summary(a: anndata.AnnData, b: anndata.AnnData, select_parts: Optional[List[str]] = None): """ Emit a dictionary of differences between two AnnData objects. This is meant to be human readable, for debugging. The values are summary text stri...
b62a1e51aa906ba7a2d5d939eadebfd99afdfac4
64,191
import sqlite3 def connect_db(): """ データベースに接続します """ con = sqlite3.connect(app.config['DATABASE']) con.row_factory = sqlite3.Row return con
ef0430affc16989bc9fcfa9c03ef97b969924ccc
64,192
def getOverlappedSpaces(ifc_file): """ Function created to detect overlap spaces """ props = OCC.Core.GProp.GProp_GProps() spaces = ifc_file.by_type("IfcSpace") black_list = [] local_tolerance = 0.1 shapes = {} for sp in spaces: shapes[str(sp.GlobalId)] = ifcopenshell.geom.cr...
ae72058c58db7924f40ba6a2a5c5458d907f32b0
64,193
import logging import json def get_i2_object(config, object_type="Host", filter_states=None, filter_names=None, acknowledged=None, downtime=None): """Request Icinga2 API Endpoint /v1/objects Parameters ---------- config : dict dictionary with items parsed from config file object_type : st...
c7430901fc2f2aa4eea660a4d0b73512ca365a0e
64,194
import six def map_struct(func, struct, map_dict=True, map_list=True, map_tuple=False, map_set=False, cls=None, custom_mappings=None): """ Applies a function *func* to each value of a complex structured object *struct* and returns the output in the same structure. Example: .. code-block:: pyt...
ca4b4f40b286b2890de84788bf1a1319d70b1fef
64,195
def get_rays_relight_np(H, W, focal, c2w, lightdir): """Get ray origins, directions from a pinhole camera.""" i, j = np.meshgrid(np.arange(W, dtype=np.float32), np.arange(H, dtype=np.float32), indexing='xy') dirs = np.stack([(i-W*.5)/focal, -(j-H*.5)/focal, -np.ones_like(i)], -1) ...
362f45e2e41055bce20b01cd3e3eb274d606712a
64,196
def bin_threshold(mat, threshmin=None, threshmax=0.5): """ Generate binary segmentation from probabilities Parameters ---------- mat : np.array The data threshmin : float or None Minimum value on [0,1] to assign binary IDs from probabilities. thresmax : float Maximum...
8595eae8ff19df106d1ab906e1cc66b41d2aabcd
64,197
def get_text(name): """returns some text""" return "Hello "+name
0226a09df5cdbb0d50f4fe4168a0d5686b43b2da
64,198
def ipv4_cidr_to_netmask(bits): """ Convert CIDR bits to netmask """ netmask = '' for i in range(4): if i: netmask += '.' if bits >= 8: netmask += '%d' % (2 ** 8 - 1) bits -= 8 else: netmask += '%d' % (256 - 2 ** (8 - bits)) ...
a4be3fea1c59d77312de78e743a67470b444d651
64,199