content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import logging def find_bad_positions(coverage_matrix, target_folder = None, trait = None, samplename = None, trait_cutoff = None, whitelist = None): """ Walk through all bases and find contigous regions of bases that fail the coverage/strandbias cutoff Create an output fil...
02fbcb688fc763a414805c3c898027c14b12b9f0
35,500
def s_norm(p_string, uppercase=False): """ Filters out all punctuation, normalizes the casing to either lowercase or uppercase of all letters, and removes extraneous whitespace between characters. That is, all whitespace will be replaced by a single space character separating the words. :param p_string The str...
69519ddfb2fd58bab3b6db9695946a168ce3eec4
35,501
def _venv_changed(session: nox.sessions.Session) -> bool: """Return True if the installed session is different to that specified in the lockfile.""" result = False if _venv_populated(session): expected = _file_content(_session_lockfile(session)) actual = _file_content(_session_cachefile(sess...
a5723d9e3f5f71f3f7b83dc0bfa6ed659c9dca13
35,502
import random def greedy_policy(A, s, Q, epsilon = None): """在给定一个状态下,从行为空间A中选择一个行为a,使得Q(s,a) = max(Q(s,)) 考虑到多个行为价值相同的情况 """ max_q, a_max_q = -float('inf'), [] for a_opt in A: q = get_dict(Q, s, a_opt) if q > max_q: max_q = q a_max_q = [a_opt] elif ...
12ae83e3c28e6d65d4b3cc81aa712657c82834c3
35,503
def login_user(cursor, username): """ create new session for user with username, return session key """ userid = get_userid(cursor, username) key = token_urlsafe() cursor.execute( "REPLACE INTO sessions ('userid', 'key') VALUES (?, ?)", (userid, key) ) return key
b507aa966608a372df785b3e7d3c8a1a26c2d23a
35,504
def tapisize(fieldKeyName): """Transforms a string into a Tapis query parameter """ return fieldKeyName.lower()
cc8032a6cc9e822193430134bb33da8aef74cf06
35,505
def get_minions(returner): """ Return a list of all minions CLI Example: .. code-block:: bash salt '*' ret.get_minions mysql """ returners = salt.loader.returners(__opts__, __salt__) return returners["{0}.get_minions".format(returner)]()
f4dd2a96884ddfc356b3214b89bfd1da96e15a40
35,506
from typing import Union import torch def nx_second_order_proximity( G: Union[nx.Graph, nx.DiGraph], node_ids: Union[Tensor, ndarray, list], whole_graph_proximity: bool = True, to_batch: bool = False, distance_metric: str = "cosine", norm_rows_in_sample: bool = False, norm_rows: bool = Tru...
1eb2e37e0d52b0428843f71adc901a02c62eadb5
35,507
def calculate_average_resolution(sizes): """Returns the average dimensions for a list of resolution tuples.""" count = len(sizes) horizontal = sum([x[0] for x in sizes]) / count vertical = sum([x[1] for x in sizes]) / count return (horizontal, vertical)
06dac1834989df96ce7bff88c435dd4067bfccbd
35,508
def is_enum0(*args): """ is_enum0(F) -> bool Is the first operand a symbolic constant (enum member)? @param F (C++: flags_t) """ return _ida_bytes.is_enum0(*args)
137b34efa475738ff3a9d1633822f1a1c7a0ca32
35,509
def view(image, ui_collapsed=False, annotations=True, interpolation=True, cmap=cm.viridis, mode='v', shadow=True, slicing_planes=False, gradient_opacity=0.2): """View the image. Creates and returns an ipywidget to visualize the image. The image can be 2D or 3D. The type of the image can be an...
5c71f27ba46258ad97dade0cab04fbf65e8e3c22
35,510
import click def install_chute(ctx, chute, node, follow, version): """ Install a chute from the store. CHUTE must be the name of a chute in the store. NODE must be the name of a node that you control. """ client = ControllerClient() result = client.install_chute(chute, node, select_versio...
90781fc0c9d4cca877f44b9b93be2c8d075fa4a3
35,511
from pathlib import Path def create_folder(subfolder: str, folder: str) -> None: """ Function for creating folder structure for saved stationdata """ path_to_create = Path(folder, subfolder) Path(path_to_create).mkdir(parents=True, exist_ok=True) return None
e50052d22cb8385e1c3a83caa643ec0d0289d1b0
35,512
import sys import os def source_provider_blender(filename): """ Return source code of the file referred by filename. Support for debugging of Blender Python scripts. Blender scripts are not always saved on disk, and their source has to be queried directly from the Blender API. http://www...
beec37ecb12d487beff12488898757a26e6bb223
35,513
def locate_spikes_peakutils( data, fps=58.21, thresh=0.7, min_dist=None, max_allowed_firing_rate=1 ) -> np.ndarray: """ Find spikes from a dF/F matrix using the peakutils package. The fps parameter is used to calculate the minimum allowed distance \ between consecutive spikes, and to disqualify cell...
e32c8ebc8024b4547592769744051b6d30897851
35,514
def has_valuable(camera): """Function checks if the camera sees any valuable. @param camera: webots camera object to use for the recognition @returns True if a valuable is detected, False otherwise """ # Check if camera has recogniton and is enabled if not camera.hasRecognition() or camera.getRe...
5ff65e4dc52abbcd42700168fb7aa26e83aa2aab
35,515
def _partition_fold(v,data): """ partition the data ready for cross validation Inputs: v: (int) cross validation parameter, number of cross folds data: (np.array) training data Outputs: list of partitioned indicies """ partition = [] for i in range(v): if i...
fc833b5120c5d8e479af1758f86e0541c5d7d87c
35,516
def get_distance(m, M, Av=0): """ calculate distance [in pc] from extinction-corrected magnitude using the equation: d=10**((m-M+5-Av)/5) Note: m-M=5*log10(d)-5+Av see http://astronomy.swin.edu.au/cosmos/I/Interstellar+Reddening Parameters --------- m : apparent magnitude M : absol...
b4773065d7cf1bc793400ac344c4ca7a580f8567
35,517
def get_csr_as_text(csr_filename): """Convert CSR file to plaintext with OpenSSL.""" return _run_openssl(['req', '-in', csr_filename, '-noout', '-text']).decode('utf-8')
f08d1d914b992474e2c51406bab58f2f2ad37c6c
35,518
from typing import List from pydantic import BaseModel # noqa: E0611 def search_filter_sort_paginate( db_session, model, query_str: str = None, filter_spec: List[dict] = None, page: int = 1, items_per_page: int = 5, sort_by: List[str] = None, descending: List[bool] = None, current...
60f1b769a5ccafeeb6da01412f439a4f1234e75f
35,519
def rename_entry(*args): """ rename_entry(ord, name, flags=0x0) -> bool Rename entry point. @param ord: ordinal number of the entry point (C++: uval_t) @param name: name of entry point. If the specified location already has a name, the old name will be appended to a repeatable ...
d70cd7b42b8e6b4e748c7c2599a46859dd5f6059
35,520
from typing import Iterable from typing import Tuple def split_file_to_annotations_and_definitions(lines: Iterable[str]) -> Tuple[EnumLines, EnumLines, EnumLines]: """Enumerate a line iterable and splits into 3 parts.""" enum_lines = sanitize_file_lines(lines) metadata, definitions, statements = multi_spl...
64a5f6f4d32f80d90f1247472564ae04e902ae1d
35,521
def _SafeCreateLogoutURL(mr): """Make a logout URL w/ a detailed continue URL, otherwise use a short one.""" try: return users.create_logout_url(mr.current_page_url) except users.RedirectTooLongError: if mr.project_name: return users.create_logout_url('/p/%s' % mr.project_name) else: retur...
06ee47ba38abb660096bace71704ddd0becd465a
35,522
from typing import Tuple from typing import Dict def random_speech_to_text( draw ) -> st.SearchStrategy[Tuple[SpeechToTextGen, Dict]]: """Generates different speech_to_text functions.""" kwargs = draw(random_speech_to_text_kwargs()) return speech_to_text(**kwargs), kwargs
035d905aba274f1083daae07e2492f9ae84cd21f
35,523
def line_neighbor_score(mat, idx, line_width=1, distance_range=(20, 40), window_size=5, line_trick='min', neighbor_trick='mean', metric='diff'): """ :math: enrichment-score = line-trick(line) - neighbor-trick(neighbor) :param idx: (int) stripe location index :param mat: (2D ndar...
a3b4a49479c5bcf7f12e4bb23affda942ec3670e
35,524
def plugin_name_to_layerapi2_label(plugin_name): """Get a layerapi2 label from a plugin name. Args: plugin_name (string): the plugin name from which we create the label. Returns: (string): the layerapi2 label. """ return "plugin_%s@%s" % (plugin_name, MFMODULE_LOWERCASE)
c91a5c463e3b15e324c049e9557a2711031dcb95
35,525
def unscii(font_name): """ Given a font name, return a font object for usage. """ return UnsciiFont(font_name)
41a8a03417d1d231cbd2bf99b09d8efd98afcd8c
35,526
def get_environ_dict(): """Return a dictionary of all environment keys/values.""" return { 'os.environ': _get_os_environ_dict(( 'AUTH_DOMAIN', 'CURRENT_CONFIGURATION_VERSION', 'CURRENT_MODULE_ID', 'CURRENT_VERSION_ID', 'DEFAULT_VERSION_HOSTNAME', 'FE...
056b8499db4dbc14db904eb5f1c01ed49ae39a18
35,527
def k_from_a_ea(a, e_a, temp, r_gas): """ convert using "alternate" form of Arrhenius eq :param a: pre-exponential factor :param e_a: activation energy with units consistent with given r_gas :param temp: temperature in K :param r_gas: universal gas constant in units consistent with e_a and temps...
79415b8ee583e03282d7ab02b5e255d611e5677f
35,528
import argparse def get_args_parser(PORT: int = 4500): """ Extendable parser for input arguments Args: PORT: default port to be exposed """ parser = argparse.ArgumentParser(add_help=True, description="Backend service API") parser.add_argum...
8fcddec4df5f64c9425a028432ad7c80eae6542f
35,529
def extract_source_info(df_adverse_ev): """ Find information about who submitted the report """ qual_list = [] for i in range(0,len(df_adverse_ev)): if df_adverse_ev.iloc[i]['primarysource'] is not None: col_names = list(df_adverse_ev.iloc[i]['primarysource'].keys()) if 'qual...
246571a57467b03ed5f5bd2456108e4b93ec136f
35,530
import json def load_base_models_json(filename="base_models.json"): """Load base models json to allow selecting pre-trained model. Args: filename (str) - filename for the json file with pre-trained models Returns: base_models - python dict version of JSON key-value pairs """ with...
c17f123e192b94e6f87938bca10822ea785e2d91
35,531
def _parsedatetime_parse(date_string): """Parse the given date_string using the parsedatetime module.""" # for more details on how the parsedatetime.Calendar.parse function works, see: # https://github.com/bear/parsedatetime/blob/830775dc5e36395622b41f12317f5e10c303d3a2/parsedatetime/__init__.py#L1779 c...
a8ce67294d9c035c0777a2d1c0a4fe6e43f65154
35,532
import sys import os def main(argv=None, directory=None): """ Main entry point for the tool, used by setup.py Returns a value that can be passed into exit() specifying the exit code. 1 is an error 0 is successful run """ argv = argv or sys.argv # Init the path tool to work with the...
b7b0f1930d9631d1c99ca1cb045f98d1589d6f1a
35,533
from pathlib import Path import sys def read_tsv_or_parquet(filepath): """Read either a TSV or a parquet file by file extension.""" filepath = Path(filepath) if not filepath.exists(): logger.error(f'File "{filepath}" does not exist.') sys.exit(1) ext = filepath.suffix.lstrip(".") i...
6cbe14ec9a110d34220e2bbb1eaf9ffe194646cd
35,534
def BFMM( source, target = None, charge = None, dipole1 = None, dipole2 = None, compute_source_velocity = False, compute_source_analytic_gradient = False, compute_source_anti_analytic_gradient = False, compute_target_velocity =...
e1fbce824777c1d260e1e83a8a8fe7b1b2d05886
35,535
import sys def blast(args): """ %prog blast fastafile Run BLASTN against database (default is UniVec_Core). Output .bed format on the vector/contaminant ranges. """ p = OptionParser(blast.__doc__) p.add_option( "--dist", default=100, type="int", help="Merg...
15c5e5096079be9b10ac07a4f82ede511727fc05
35,536
def get_dihedrals(a, b, c, d): """ A function that gets dihedral angles between two residues. See set_neighbors6D for usage. """ b0 = -1.0*(b - a) b1 = c - b b2 = d - c b1 /= np.linalg.norm(b1, axis=-1)[:,None] v = b0 - np.sum(b0*b1, axis=-1)[:,None]*b1 w = b2 - np.sum(b2*b1, ...
91897e67e7d73eeb60dc73b2ba45e1aaeec5c470
35,537
def iexact(self, compiler, connection): """A method to extend Django IExact class. Case-insensitive exact match. If the value provided for comparison is None, it will be interpreted as an SQL NULL. :type self: :class:`~django.db.models.lookups.IExact` :param self: the instance of the class that own...
ebe51c6b8c34a0cc1746169e8fe6e8eb79e01152
35,538
import json def load_data_from_json(jsonfile): """Load the data contained in a .json file and return the corresponding Python object. :param jsonfile: The path to the .json file :type jsonfile: str :rtype: list or dict """ jsondata = open(jsonfile).read() data = json.loads(jsondata) r...
f0f7a0620be8ffcd15a57fd561dda8525866faa3
35,539
def grpc_check(fpath): """ Check whether grpc service is enabled in this .proto file. Note: only proto file with the following form will pass our check. service MyService { rpc MethodA(XXX) returns (XXX) { rpc MethodB(XXX) returns (XXX) { } } """ if not f...
17a1539f8913bb35d2e89f31d7f48acbc1f35b54
35,540
def bb_intersection_over_union(boxA, boxB): """ Computes IoU (Intersection over Union for 2 given bounding boxes) Args: boxA (list): A list of 4 elements holding bounding box coordinates (x1, y1, x2, y2) boxB (list): A list of 4 elements holding bounding box coordinates (x1,...
290d625dd3ed7ab37ecf3aa7f39a3b1727cecec0
35,541
import os def apath(path='', r=None): """Builds a path inside an application folder Args: path(str): path within the application folder r: the global request object """ opath = up(r.folder) while path[:3] == '../': (opath, path) = (up(opath), path[3:]) return os.path...
3d3e4c7db037281a93b929135ac180110d45bc1b
35,542
def area(boxlist, axis=-1): """Computes area of boxes. Args: boxlist: BoxList holding N boxes scope: name scope. Returns: a tensor with shape [N] representing box areas. """ with tf.name_scope('Area'): x_min, y_min, x_max, y_max = tf.split(value=boxlist, num_or_...
6c0e791b021d5196651c0b1830019f23840596fd
35,543
def _MatrixTriangularSolveGrad(op, grad): """Gradient for MatrixTriangularSolve.""" a = op.inputs[0] adjoint_a = op.get_attr("adjoint") lower_a = op.get_attr("lower") c = op.outputs[0] grad_b = linalg_ops.matrix_triangular_solve( a, grad, lower=lower_a, adjoint=not adjoint_a) if adjoint_a: grad_...
3faac87370dd9dfa589174976c7dd6bed76e4628
35,544
from typing import Dict from typing import Any def list_persons_command(client: Client, args: Dict[str, Any]) -> CommandResults: """Get persons list from TOPdesk. Args: client: The client to preform command on. args: The arguments of the persons command. Return CommadResults of list of p...
8fb8c1065b433e7821fa46d64332c2238d502f7f
35,545
def group_user_delete(user, group): """Delete an user from a certain group""" if not pagure_config.get("ENABLE_USER_MNGT", True): flask.abort(404) if not pagure_config.get("ENABLE_GROUP_MNGT", False): flask.abort(404) form = pagure.forms.ConfirmationForm() if form.validate_on_submi...
bc813bb31aed7798a59b117f7e1fb984f96dfc3b
35,546
def repair_follow_organization_view(request): """ Process the new or edit organization forms :param request: :return: """ # admin, analytics_admin, partner_organization, political_data_manager, political_data_viewer, verified_volunteer authority_required = {'verified_volunteer'} if not v...
38a78fdc21ab6c9b0a06e8447462fe5580e3df1c
35,547
def vect3_add(v1, v2): """ Adds two 3d vectors. v1, v2 (3-tuple): 3d vectors return (3-tuple): 3d vector """ return (v1[0]+v2[0], v1[1]+v2[1], v1[2]+v2[2])
b43fde71f0cc5e927879a2b6942c60de8ac6cc79
35,548
def voucher_received(cadde_provider=None, cadde_consumer=None, cadde_contract_id=None, hash_get_data=None, contract_management_service_url=None): # noqa: E501 """API. データ証憑通知(受信) 来歴管理I/Fにデータ証憑通知(受信)を依頼する。 Response: * 処理が成功した場合は200を返す * 処理に失敗した場合は、2xx以外を返す。Responsesセクション参照。 # noqa: E501 :...
28b4e29ea2d152a7c6f21581d3832ee77262fb0a
35,549
import multiprocessing def get_task_pool(thread=False): """ Get a new task pool, which is either a single-thread or process pool depending on the current config. Returns: A new :class:`multiprocessing.pool.Pool` instance. """ if thread or not config['app_multicore'] or config['enable_bac...
515ae5c2ac167df1eb0f4ba2c3d4795a9830e3eb
35,550
def get_date(article: ElementTree) -> int: """ Extracts the year of the article. If ArticleDate exist use its year otherwise use the year form JournalIssue """ d = article.find("ArticleDate") if d is not None: return int(d.find("Year").text) d = article.find("Journal").find("JournalI...
3ca2f13d234df411e904195d9d1c08534ada1cea
35,551
def split(column, pattern=''): """ Splits str around pattern (pattern is a regular expression) > pattern is a string representation of the regular expression """ return _with_expr(exprs.StringSplit, column, pattern)
d091a5e89adf0d5de994b9a11c1c856cea5a8494
35,552
import gc def convert( model, source="auto", inputs=None, outputs=None, classifier_config=None, minimum_deployment_target=None, convert_to='nn_proto', **kwargs ): """ Convert TensorFlow or Pytorch models to the Core ML model format. Whether a parameter is required may diffe...
0de2d8cb9ba2926b05262ea1754b112845b65033
35,553
def precut(layers, links, all_terms, user_info): """ This function cuts terms in layers if they do not exist inside the accuracy file of model 1. It also cuts all links if one of the terms inside does not exist inside the accuracy file of model 1. Finaly it cuts all terms taht do not exist insid...
cf04eec77d01ad931f7654a3743baaf51aad53fa
35,554
def computeMeanStd_binned_old( inDatas, valCol, binCol, binMin, binMax, binCount ): """Compute binned stats for a set of tables""" sums = np.zeros( binCount ) sumsSq = np.zeros_like( sums ) counts = np.zeros_like( sums ) bins = np.linspace( binMin, binMax, binCount+1 ) binSize = ( binMax - binMin ) / binCo...
195fc421b3091725e629e05e27c64a862c7fc31b
35,555
def Compute7(surface, multiple=False): """ Computes an AreaMassProperties for a surface. Args: surface (Surface): Surface to measure. Returns: AreaMassProperties: The AreaMassProperties for the given Surface or None on failure. """ url = "rhino/geometry/areamassproperties/compu...
f844f43b372ac2c8f124c27e346f9805583c3240
35,556
from typing import Optional from typing import Union def instantiate(config: Optional[Union[str, ClassDescription]], *args, **extra_kwargs): """Instantiates class given by `config.cls` with optional args given by `config.args` """ try: if config is None: return None elif ty...
c0f8f951212bb157b4ee8805615f83bad82db8e2
35,557
async def get_hm_generic_entity( central_unit: CentralUnit, address: str, parameter: str ) -> GenericEntity | None: """Return the hm generic_entity.""" hm_device = get_hm_device(central_unit, address) assert hm_device hm_entity = hm_device.entities.get((address, parameter)) assert hm_entity ...
25f2845951d7ab34155b7ee2347a8438b115a1eb
35,558
def dists2corners_numpy(a): """ :param a: dist ndarray, shape = (*, h, w, 4=(t, r, b, l)) :return a: Box ndarray, shape is (*, h, w, 4=(xmin, ymin, xmax, ymax)) """ assert a.ndim >= 3, 'must be greater than 3d' h, w, _ = a.shape[-3:] # shape = (*, h, w, 4=(xmin, ymin, xmax, ymax)) ret =...
3f20df4cb3bc8ab1f1a595e64514e7b722fd07a1
35,559
def cryptowatch_ohlc_data_for_pair(Pair): """gets ohlc data from cryptowatch, and return a dict of dataframes""" exchanges = list(Pair.markets) data = {} for ex in exchanges: data[ex] = cryptowatch_ohlc(Pair.name, ex, Pair.period, Pair.start, Pair.end) return data
4f482ae1575d68e193321db0c2bd7346d4bf0950
35,560
from io import StringIO def to_string_stream(x): """ For modules that require a encoding as ``str`` in both Python 2 and Python 3, we can't just encode automatically. """ if PY2 and isinstance(x, text_type): x = x.encode('utf-8') return StringIO(x)
8fd36bab988410881a560d27d4e8d54d36f58634
35,561
import os def get_all_scores(pdb_path, reference_pdb_path): """Assigns scores (lrmsd, irmsd, fnat, dockQ, bin_class, capri_class) to a protein graph Args: pdb_path (path): path to the scored pdb structure reference_pdb_path (path): path to the reference structure required to compute the diffe...
7900a6f26d633aef7a12cd382f1be7dbcfeec2fc
35,562
def run_epoch(model, data, optimizer): """ Run a train and validation epoch and return average bpd for each. """ traindata, valdata = data model.train() train_bpd = epoch_iter(model, traindata, optimizer) model.eval() val_bpd = epoch_iter(model, valdata, optimizer) return train_bpd...
5f441470347818e1c4f0fcdd67467100920bd6a0
35,563
def special_loss(logits, labels): """ This loss (and the rest of the training procedure) was taken from Philipp Kraehenbuehl's code. """ mask = labels != 255 labels1 = tf.clip_by_value(labels, 0, 1) lz = tf.nn.softplus(-tf.abs(logits)) * mask return tf.reduce_sum(lz + (tf.to_float(logits...
2dd1d3c967cf653a719ff993ff0b2de2d90404e2
35,564
def tobs(): """Return a list of all tobs for the most active station as a list of JSON""" # Query most active station station_list = session.query(Measurement.station, func.count('*')).group_by(Measurement.station).order_by(func.count(Measurement.station).desc()).all() mostactive=station_list[0][0]...
ad7461c3dacf715fee38a4fcdc292e58b2c48d2a
35,565
from datetime import datetime import sys import torch def _get_assignment_data_matches(net, mapping_assignment_dataloader, config, sobel=False, using_IR=False, get_data_fn=None, just_mat...
c130b2dde69cc58b6cbcd3777570fda8da0675e6
35,566
from scipy.special import lambertw def prox_max_entropy(X, step, gamma=1, type="relative"): """Proximal operator for maximum entropy regularization. g(x) = gamma sum_i x_i ln(x_i) has the analytical solution of gamma W(1/gamma exp((X-gamma)/gamma)), where W is the Lambert W function. If type ==...
7d5f1525ad1b7c413bad03b3aeba7b0af2e163ee
35,567
def phase_vocode(audio_data: np.ndarray, speed: float) -> np.ndarray: """Applies phase vocoding to a 'np.ndarray' representing WAV data.""" reader = ArrayReader(audio_data.transpose()) writer = ArrayWriter(reader.channels) phasevocoder(reader.channels, speed=speed).run(reader, writer) return writer....
e6d4d7e874c3f18c2c2a065b03d04d5e11d1963e
35,568
import os def fullPathListDir(dir: str) -> list: """ Return full path of files in provided directory """ return [os.path.join(dir, file) for file in os.listdir(dir)]
b456008e782e6f5a1d3471f5a9b5536ae4aad132
35,569
def partion_data_in_two(dataset, dataset_labels, in_sample_labels, oos_labels): """Partition dataset into in-distribution and OODs by labels. Args: dataset: the text from text_to_rank dataset_labels: dataset labels in_sample_labels: a list of newsgroups which the network will/did train on oos_label...
df3eda7d64c9060c6a8f1d45dbf5a0d5cd3c2436
35,570
def check_and_update_generation_args(args): """ checks all generation commandline arguments. Since these arguments are all lists and shorthand can be used, we expand them to match the expected length for instance, [1.0] becomes [1.0 1.0] if all other generation arguments are of length 2 """ hyperpar...
3d569b70b6ea4651af9cef0b7eafada1352b54a1
35,571
def category_condition_disable(request, structure_slug, category_slug, condition_id, structure): """ Disables a condition from a category :type structure_slug: String :type category_slug: String :type condition_id: Integer :type structure: OrganizationalStructure ...
87457c5b851bc791ec0e28d01100084948b9b58b
35,572
def stitch_image_pair(img_a, img_b, stitch_direc): """Function to stitch image B to image A in the mentioned direction Args: img_a (numpy array): of shape (H, W, C) with opencv representation of image A (i.e C: B,G,R) img_b (numpy array): of shape (H, W, C) with opencv representation of image B...
cc8143a3e9ebdae9a01c79a31a8fb7753bf0e2ee
35,573
def as_composite(identifier: str) -> str: """ Translate the identifier of a mapry composite to a composite name in Python. :param identifier: mapry identifier of a composite :return: translated to a Python identifier of a composite >>> as_composite(identifier='Some_URL_class') 'SomeURLClass' ...
9e08c59acc60fbdb4ca4667f9d6b06502d521083
35,574
def find_saturation(freq, saturation_values, attenuation): """ Return a saturation value based on the frequency and amount of attenuation :param int freq: the freq of interest, in Hz :param saturation_values: a dict containing the saturation values (keys are frequencies) :param attenuation: the amo...
a7f54ef3d80d0c1fbb5e51172812f2e4088dae1e
35,575
def lstm_temporal(x, h0, Wx, Wh, b): """ Forward pass for an LSTM over an entire sequence of data. We assume an input sequence composed of T vectors, each of dimension D. The LSTM uses a hidden size of H, and we work over a minibatch containing N sequences. After running the LSTM forward, we return ...
04cd724d1fb7a996986b97d33b5a38ecefaf8185
35,576
from numpy.distutils.cpuinfo import cpu import psutil from typing import OrderedDict import platform def get_info_hardware(): """Create a dictionary for CPU information.""" def _cpu_freq(): """psutil can return `None` sometimes, esp. in Travis.""" func = "psutil.cpu_freq: " try: ...
33d6dc139218d1e45907bb58100cdc95300d8785
35,577
from pathlib import Path def read_main_results_file(): """Return a Series where each row is one of the COMSOL Main results""" results_filepath = Path(MAIN_RESULTS_FILENAME) results_series = pd.read_table(results_filepath, sep=" ", squ...
b5f66df57cd89763af2d95fb22039c49a71f22c5
35,578
def coveralls_enable(request): """Enable coveralls for an experiment""" experiment = get_experiment_from_request_post(request) travis_instance = experiment.travis if travis_instance.enabled: existing_config = enable_coveralls(travis_instance) github_helper = get_github_helper(request, e...
df6021c2896eeaa8fcf395276d253023a69c5cba
35,579
import time from bs4 import BeautifulSoup def download_book(book_id, title, thumbnail, rating_text): """ Download book id=`book_id` by calling the website's `getPage(.,.,.)` function. """ print('in download_book, book_id =', book_id) with WebDriver("http://3asafeer.com/", delay=LOADING_WAIT_TIME_M...
f1ab4a91a1535fd25a5692a397222ff25f2216fe
35,580
def games_per_time_period(df, days_per_period=7): """Return list of describing n matches played each time period in days, from start to end of dataframe""" # define start and end dates to observe start = df['date'].min() # end is specified as 6 days after recorded final date of play, so pd.date_range be...
e0e327b8cdc8b04f2fde826cef90585e7e7be4cb
35,581
def get_image_dims(image_data, check_is_rgb=False): """Decodes image and return its height and width. Args: image_data: Bytes data representing encoded image. check_is_rgb: Whether to check encoded image is RGB. Returns: Decoded image size as a tuple of (height, width) Raises: ValueError: If ...
745ff6dccc5c7ebb6052abc142e0b8a0ceda269a
35,582
def open_mic_stream(pa, device_index, device_name): """ Open microphone stream from first best microphone device. """ if not device_index and device_name: device_index = find_input_device(device_name) stream = pa.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, inp...
8e69211e4aab87ca684a5ebf8ba222e2551f6734
35,583
def color_threshold(img): """ RGB color space threshold :param img: Undistorted image :return: Thresholded binary image Ref: Course notes """ yellow = select_yellow(img) white = select_white(img) combined_binary = np.zeros_like(yellow) combined_binary[(yellow >= 1) | (white >= 1)...
f11ddf7e452d7b8891562500819e41f9ea30bf0f
35,584
def perturb_box(box, min_iou=0.5, sigma_factor=0.1, rng=None): """ Perturb the input box by adding gaussian noise to the co-ordinates args: box - input box min_iou - minimum IoU overlap between input box and the perturbed box sigma_factor - amount of perturbation, relative to the box s...
5ad15e766123f887e6cfc19b818efe4542e06148
35,585
def smootherstep(a, b, x): """Improved S-curve interpolation function. Based on reference implementation of the improved algorithm proposed by Ken Perlin that is available at https://en.wikipedia.org/wiki/Smoothstep """ x = clamp((x - a)/(b - a), 0.0, 1.0) return x*x*x*(x*(x*6 - 15) + 10);
6fa2e8694f2171f0e73aa19042aad2c69384a9e7
35,586
def _clean_conargs(**conargs): """Clean connection arguments""" conargs['metadata'] = [x.strip() for x in conargs['metadata'].split(',') if x.strip()] return conargs
f5942f750949ab674bd99778e79ea35c2d0bb775
35,587
import json def select_customer(): """Select customers from customer_name.""" cursor = mysql.cursor(MySQLdb.cursors.DictCursor) TRN = request.form['TRN'] cursor.execute('''SELECT * FROM Customer WHERE TRN=%s''', (TRN,)) data = cursor.fetchone() if da...
8353a0d9bbcea731dd1ce0e2f031c22be5b673fe
35,588
def is_date(string): """ Returns whether the string can be interpreted as a date from using Python's dateutil.parser library. If it can parse, it will return true, and false otherwise. """ try: parse(string, fuzzy=False) return True except ValueError: return False
d07ad17c8d3a24b28e21b42c0907e6e2c281f8d2
35,589
import argparse import os import logging def get_adt_table( args: argparse.Namespace, edw: pyodbc.Connection, query_directory: str, ) -> pd.DataFrame: """ Get ADT table through one of the following methods: 1. Provide ADT table i. Filter patients by MRN ii. Filter temporally ...
895bfcaf21211a96ba6d8277918426576208eef1
35,590
def rosin_rammler(nbins, d50, md_total, sigma, rho_p, rho): """ This function is deprecated: Use psf.rosin_rammler() instead. Return the volume size distribution from the Rosin Rammler distribution Returns the fluid particle diameters in the selected number of bins on a volume basis from ...
3807c8c965caae492a3fecf6e803685cf7315710
35,591
def _get_layer(layer_idx, nn, for_pres): """ Returns a tuple representing the layer label. """ if nn.layer_labels[layer_idx] in ['ip', 'op']: fill_colour = _IPOP_FILLCOLOR elif nn.layer_labels[layer_idx] in ['softmax', 'linear']: fill_colour = _DECISION_FILLCOLOR else: fill_colour = _FILLCOLOR lab...
74ea378c5490eaf3c1e2cf7ab2413a55566725ea
35,592
from resistics.sampling import to_timedelta def inc_duration(win_size: int, olap_size: int, fs: float) -> RSTimeDelta: """ Get the increment between window start times If the overlap size = 0, then the time increment between windows is simply the window duration. However, when there is an overlap, th...
bdf754e3b1ace20cac1f99ef19dd04727594d710
35,593
def get_nearest(kd_node, point, dim, dist_func, return_distances=False, i=0, best=None): """ Find the closest neighbour of a point in a list of points using a KD-Tree. Based on a recipe from code.activestate.com """ if kd_node: dist = dist_func(point, kd_node[2]) dx = kd_node[2][i] -...
480ac80404d16cb8ed4de9093a56326b15ad56b9
35,594
def plot_estimated_vs_simulated_edges( graph, sp_Graph, lrn=None, max_res_nodes=None, lamb=1.0 ): """Function to plot estimated vs simulated edge weights to look for significant deviations """ assert lamb >= 0.0, "lambda must be non-negative" assert type(lamb) == float, "lambda must...
7921715ccedaa192f291b228e9b12963ae8789dd
35,595
def index_shape(geometry: Column, resolution: Column): """ Generate an H3 spatial index for an input GeoJSON geometry column. This function accepts GeoJSON `Point`, `LineString`, `Polygon`, `MultiPoint`, `MultiLineString`, and `MultiPolygon` input features, and returns the set of H3 cells at the specif...
a921f58eb31f24c3bbfb7b0b4e013b75ec2ad0f4
35,596
def mat_mul( input_tensor, weight_tensor, activation=None, activation_params=None, name="mat_mul"): """Compute a matrix multiplication for `input_tensor` and `weight_tensor`. Args: input_tensor: A 2D `Tensor`. Shaped as `NC`, where `N` is batch size and `C` is number of channels. weight_tenso...
f4b7755d6701438cd622837c976958dc511aa591
35,597
def get_events(wrapper, student: str = None, time: str = None) -> dict: """ list events """ start, end = get_dates(time) event_data = wrapper.get_events(start_date=start, end_date=end, login=student) return event_data
b682190334646889770c723693941da8c251db68
35,598
def merge_preclusters_ld(preclusters): """ Bundle together preclusters that satisfy the two criteria at the same time: * 1. gwas_snp of clusterA is within ld_snps of clusterB (in LD) * 2. (p-value of gwas_snp of clusterB * 10-3) <= p-value of gwas_snp of clusterA (<= p-value of gwas_snp of clusterB) Args: * ...
64b0a82181df9afa352a796d4943b8392bb742d7
35,599