content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import time def read_device(net_connect, sleep=1): """Sleep and read channel.""" time.sleep(sleep) output = net_connect.read_channel() print(output) return output
b0c4c300a088886558203649f57c10cc34b88e21
59,500
import os def __work_mode__(path: str): """Determines the desired mode of operation""" if os.path.isfile(path): # Input is file return "file" if os.path.isdir(path): # Input is dir return "dir" else: return "no"
a26a214653855244cd9b0e9ed7fa5ca058e9d81d
59,501
import PIL def Solarize(img, v): """ Applies PIL.ImageOps.solarize to the image """ assert 0 <= v <= 256, f"{v} out of range [0, 256]" return PIL.ImageOps.solarize(img, v)
b43bacce81b8fee0dd60603e610d7c17280f552e
59,502
def is_numeric_array(x): """ Returns whether an object is a ground numeric array. """ return False
8d119f10f08f08552c9dfb59fa13dd0bf644f47c
59,503
def cosine(vector1, vector2): """ related documents j and q are in the concept space by comparing the vectors : cosine = ( V1 * V2 ) / ||V1|| x ||V2|| """ return float(np.dot(vector1,vector2) / (np.linalg.norm(vector1) * np.linalg.norm(vector2)))
dd4daeec53440625532c50608a2914481bc8b0d1
59,504
def parse_coach_ec_df(infile): """Parse the EC.dat output file of COACH and return a dataframe of results EC.dat contains the predicted EC number and active residues. The columns are: PDB_ID, TM-score, RMSD, Sequence identity, Coverage, Confidence score, EC number, and Active site residues Args: ...
2abad4b8b2ab8013e16e6cd6fac6eda3f1338d80
59,505
from pathlib import Path from typing import Optional from typing import Tuple def get_grouping( inpDir: Path, pattern: Optional[str], groupBy: Optional[str], chunkSize: Optional[int] = None, ) -> Tuple[str, int]: """This function produces the best combination of variables for a given chunksize ...
1b818e331af105e4999677d9a4dca7ddf7896f7d
59,506
import requests def line_notify(func): """ プログラムの終了をLINEに通知 Parameter ---------- func : function 関数 Return ------- wrapper : function 関数 """ @wraps(func) def wrapper(*args, **kwargs): """ デコレーターの中身 Parameters ---------- ...
6218bbce72196a1fd35b1d12b242cdce65d58037
59,507
def config_item_context(CONFIG_SCHEMA): """Create a configuration context. Args: CONFIG_SCHEMA: This is a function which can take a minimum of zero arguments and returns an instance of BaseConfig. This BaseConfig defines the schema for all configuration objects manipulated...
28eaff4bd7bab3f88fd9558a35906127ce686d73
59,508
from gzip import GzipFile from typing import Any import json def gzip_load_var(gzip_file:str) -> Any: """ Load variable from .json.gz file (arbitrary extension!) Parameters ---------- gzip_file : str Filename containing the gzipped JSON variable Returns ------- var : Any ...
b9f6fbad33b40bb18a1418f3134b0889d5344183
59,509
import os import html def render_template(template_file: str, context: dict) -> str: """Replace placeholders in template_file accordingly to context. &, <, > will be escaped to HTML-safe sequences""" template_path = os.path.join(TEMPLATE_DIR, template_file) with open(template_path, encoding=ENCODING) as f...
ffa0a5190fca4f969f9ff8b9716062b1811a59f0
59,510
def evaluate_classification(dataset, classification_algorithm, n_folds, *args): """ Evaluates a provided classification algorithm on a given dataset using cross-validation with n folds """ # creates cross-validation folds folds = cross_validation_split(dataset, n_folds) fold_accuracies = list()...
255d4c30792a86d7662ca3774300b8456a2a9187
59,511
from pathlib import Path def project_gitignore(path: Path): """Parse all project gitignores (including in folders)""" ignores = [] for item in path.iterdir(): if item.name == ".gitignore": ignores += gitignore(item, for_path=True) if item.is_dir(): ignores += projec...
e58b42f6b64a4fa0a701f964dc724856cf82db97
59,512
def calc_average_sfs(freqs, lineage_sizes, lineage_uids, bins): """ Calculate mean SFS over an ensemble by taking mean value at each bin """ S = np.empty((len(lineage_uids), len(bins)-1)) for i, lineage_uid in enumerate(lineage_uids): myFreqs = freqs[lineage_uid].values() myLeaves = lineage_...
c72d6ad183532fef05040ccf431b58612bbddccd
59,513
def item_validator(name, func): """Class factory for item validators""" return type(name, (ItemBaseValidator,), { '__call__': lambda self, x: func(x), 'setup': lambda self: None, 'teardown': lambda self: True })
de5b9649be6394d3cbfdfcf9f021bc96eb589f33
59,514
import numpy def mult_arrays( target_raster_path, gdal_type, target_nodata, raster_path_list): """Multiply arrays and be careful of nodata values.""" nodata_array = numpy.array([ pygeoprocessing.get_raster_info(path)['nodata'][0] for path in raster_path_list]) def _mult_arrays(*ar...
186fc9542ab71df8121068771f9eb0a5730bd934
59,515
def generate_infrared_noise(duration: float, f_sample: float) -> np.ndarray: """ generates a real valued time domain signal of 'infrared' noise. Signal is aprox. scaled to ~[-1;1]. :param duration: duration the noise signal should have in seconds :param f_sample: sample frequency, determines the frequen...
88456ee9258e5b1b25252f6787235c7793b46e89
59,516
def generateMoons(n): """ 生成月牙型数据 """ data, _ = make_moons(n_samples=n, noise=0.08) return data
5630d518731b3f66e3cb6f8aff9df3d33bd7ea03
59,517
import os def verify_directory_layout(project_dir): """ Verifies if directory from path has Maven's "Standard Directory Layout" (src/main/java) :param project_dir: path to the project :raises FileNotFoundError: when a directory is requested but doesn't exist :raises NotADirectoryError: when path ...
583f3523df356a9ff30f488d1f5d400baef18701
59,518
from lmfit import Parameters from astropy.coordinates import SkyCoord from astropy import units as u def pars_to_params(pars, params=None): """ Converts a dictionary of par file parameters from read_par() to an lmfit Parameters() class to use in models By default, parameters are not varied """ ...
f7d32441462443aadce2e3ed2620c1a512dfdd51
59,519
import traceback def local_bestrefs(parameters, reftypes, context, ignore_cache=False): """Perform bestref computations locally, contacting the network only to obtain references or mappings which are not already cached locally. In the case of the default "auto" mode, assuming it has an up-to-date client...
07dc3195207c92c9d973b3bcb9390b84195cd1de
59,520
def get_azure_ctx(): """ Construct context object to allow tiledb to access Azure container. """ config = tiledb.Config() config["vfs.azure.storage_account_name"] = azconfig["account_name"] config["vfs.azure.storage_account_key"] = azconfig["account_key"] config["vfs.azure.blob_endpoint"] = ...
44ee1d286680d7d7736525e5d6ce3aab062c3d6b
59,521
def five_point_derivative(f,x,h): """#5-point function to calaculate 1st derivative""" h = float(h) return (1/(12*h))*(f(x-2*h)-f(x+2*h)- 8*f(x-h)+8*f(x+h))
186eb1ad0a01d96a85fb0d52bf0def8d3a0d00c0
59,522
def play(data: list, turns: int): """ Play the game. """ # Start the game. previous = {} # No comp so speak exists. for turn, speak in enumerate(data, 1): previous[speak] = turn # Take 4th turn. A bit annoying. spoke = 0 turn += 1 # Carry on... for turn in range(tu...
1b444ac7d1975bade8b7757eeb6429370a24f867
59,523
import decimal def get_total_income(fn): """Quick analysis returning total income for this CSV""" headers, data = headers_data(fn) total = 0 for row in data: d = dict(zip(headers, row)) amount = d['Amount'] if amount[0].isdigit(): total += decimal.Decimal(row[3]) ...
3a4bbe69ab704fac4ea4c3d5c94caf38d1c83131
59,524
def is_half_ended(line: str) -> bool: """ Check if we a given a last line of a multiline statement with brackets """ if line.count(')') > line.count('('): return True if line.count('}') > line.count('{'): return True if line.count(']') > line.count('['): return True
1bb5e0cbb3eca1addde477706fb090ce5c7a9090
59,525
def fraction_of_critical_cases_60(): """ Real Name: b'fraction of critical cases 60' Original Eqn: b'0.1' Units: b'dmnl' Limits: (None, None) Type: constant b'' """ return 0.1
69e397e2b319494b899122ce1efd3a27f96b06de
59,526
def cmd(c): """ Run an external process and return the results. """ if type(c) is str: c = c.split() process = Popen(c, stdout=PIPE, stderr=PIPE) out, err = process.communicate() return process.returncode, to_str(out), to_str(err)
ad3b8ed3f7e7f243d256e020932c461c22c695a5
59,527
def unique_count(value): """Count the number of unique characters in the string representation of a scalar value. Parameters ---------- value: scalar Scalar value in a data stream. Returns ------- int """ unique = set() for c in str(value): unique.add(c) ...
3a1481e06e6b5a57a2e4c28dc3b9b34dd5c3a977
59,528
def process_fft(procstatus, dscfg, radar_list=None): """ Compute the Doppler spectra form the IQ data with a Fourier transform Parameters ---------- procstatus : int Processing status: 0 initializing, 1 processing volume, 2 post-processing dscfg : dictionary of dictionaries ...
f3b99891c0308decd12d1c0410b0843bddf12163
59,529
def get_dataset_data_masked(dataset, bands=None, x=0, y=0, x_size=None, y_size=None, ndv=NDV, mask=None): """ Return one or more bands from the dataset with pixel quality applied :type dataset: datacube.api.model.Dataset :type bands: list[Band] :type x: int :type y: int :type x_size: int ...
bdd5af5c48d990805396bc206d920a50105df5a8
59,530
import os def compare_file_contents(path_a, path_b) -> bool: """ Compares two files and returns whether the files are equal. """ if os.stat(path_a).st_size != os.stat(path_b).st_size: return False with open(path_a, 'rb') as file_a, open(path_b, 'rb') as file_b: while True: ...
372aa296b1daa6a5e60083e65c0e6b5847bc03a8
59,531
def me(): """Return user information including name, picture and email.""" url = config.get('base_uber_url') + 'me' response = app.requests_session.get( url, headers=generate_ride_headers(session.get('access_token')), ) if response.status_code != 200: return 'There was an er...
2aed075f9406b20dddc97830a903b6c07f61effd
59,532
import os def _read_nnsa_kb_core(filename, **kwargs): """ Reads a NNSA KB Core waveform file and returns a Stream object. .. warning:: This function should NOT be called directly, it registers via the ObsPy :func:`~obspy.core.stream.read` function, call this instead. :type filename: ...
da3fbdeb65bfc92cd60c95c6494d73cc2364320b
59,533
import os def make_workdir(run_dir, ccp4_jobid=None, ccp4i2_xml=None, rootname=SIMBAD_DIRNAME + '_'): """Make a work directory rooted at work_dir and return its path Parameters ---------- run_dir : str The path to a run directory ccp4_jobid : int, optional CCP4-assigned job identifi...
e181f5a11ecc1d950f7ddddb9bcc080f49ea61b9
59,534
def category_table_build(osm_table_name, categorysql): """ Returns an SQL OSM category table builder Args: osm_table_name (string): a OSM PostGIS table name Returns: sql (string): a sql statement """ sql = ("INSERT INTO category_%s (osm_id, cat) " "SELECT DISTINCT o...
147812bb68845e3fd0dca7e805f610d26428eac3
59,535
def cspad_cctbx_from_psana(nda_in): """returns cctbx array of ASICs (64, 185, 194) from cspad array (32, 185, 388) """ segs, rows, cols = shape_in = (32,185,388) size = segs * rows * cols colsh = cols/2 if nda_in.size != size: raise ValueError('Input array size: %d is not consistent wit...
d1ac54519a5dc2605717b220c6bc3b15d9414264
59,536
def fper(input, precision=3, mixed_fraction=False): """ Format PERcentage Multiply input by 100 and round it to the number of decimal points specified by precision (default 3) """ value = iiw(around(input * 100, precision)) if mixed_fraction: value = ffrac(value) return rf"{value}%...
f8dc15735482a15569b6925d69f2904b9c9a69c0
59,537
def hpo_mapping() -> pd.DataFrame: """Return dataframe containing phenotype HPO mapping.""" df = pd.read_csv( "http://compbio.charite.de/jenkins/job/hpo.annotations.monthly/lastSuccessfulBuild/artifact/annotation/ALL_SOURCES_ALL_FREQUENCIES_phenotype_to_genes.txt", sep="\t" ) columns = d...
0093c437639853c6f8726c6d5b0a545cd4ea146a
59,538
import time import re def get_uniqueID(idPrefix): """Generates a unique id """ t = time.ctime() uid = '_'.join([idPrefix, t]) return re.sub(r'[: ]', '_', uid)
b36bdd7548343f69cd2c093f66c74314d37b9665
59,539
def prev_next_submission(submission): """Return adjacent sumbission objects for the given submission.""" return (Submission.earlier_submission_for_group(submission), Submission.later_submission_for_group(submission))
b23328e6cbe809c42e2be575447ae584e83720b2
59,540
import json def test_mechanisms(): """Checks factsheet mechanisms. Checks that there is no empty list or dict. Checks that 'type' is either exponential or decay or uniform. Checks that if type is exponential, there is an according ['dist']='exp' field in parameter file. Idem if type is de...
2ecbc7cfc0bca7fc57c6ef748487a12cc0d21d22
59,541
def _path_create(self, graph): """ Construct a path within the specified `graph` from the nodes and relationships within this :py:class:`Path` instance. This makes use of Cypher's ``CREATE`` clause. """ return _path__create(self, graph, unique=False)
a7bc4dd458fc5856b3412705d3727e038499888f
59,542
from typing import Union import copy def headline(text, **kwargs) -> str: """ex. header('your text here', halign='^', width=100, pad=True, header=True, char='#', clip=True) :param text: :type text: :param kwargs: :type kwargs: :return: :rtype: str """ hdict = {'left': '<...
35b51c169263e444cd4b7d5fd00196f3dedc8952
59,543
def layer_norm(x, filters=None, epsilon=1e-6, scope=None, reuse=None): """Layer normalize the tensor x, averaging over the last dimension.""" if filters is None: filters = x.get_shape()[-1] with tf.variable_scope(scope, default_name="layer_norm", values=[x], reuse=reuse): scale = tf.get_vari...
d3e4caa3834a69be372b0c3c78e50eac8b2ea4d9
59,544
def solve(A, b): """ Solve a system of equations Ax = b by Gaussian elimination Parameters ---------- A : 2d-array The LHS of the system of equations. The number of rows must not be less than the number of columns, but can be more. b : array-like The RHS of the syste...
8a5a5f374f92fae7e4a495a334666dcc62dd212d
59,545
def get_event_subscriptions(ip, login_account, login_password): """Get event subscriptions :params ip: BMC IP address :type ip: string :params login_account: BMC user name :type login_account: string :params login_password: BMC user password :type login_password: stri...
4b9b2cf3f2c83505a77d18ba663e90a5aeb780fb
59,546
async def system_health_info(hass): """Get info for the info page.""" info = await system_info.async_get_system_info(hass) return { "version": f"core-{info.get('version')}", "installation_type": info.get("installation_type"), "dev": info.get("dev"), "hassio": info.get("hassi...
d29af8a006ab187123f3b70c0bfbb88807f1a276
59,547
def _generate_image_and_label_batch(image, label, min_queue_examples, batch_size, shuffle): """Construct a queued batch of images and labels. Args: image: 3-D Tensor of [height, width, 3] of type.float32. label: 1-D Tensor of type.int32 min_queue_examples: int32, min...
c4499cc46769f622a821657cec1b552ca132211f
59,548
def count_helices(d): """Return the helix count from structure freq data.""" return d.get('H', 0) + d.get('G', 0) + d.get('I', 0)
8469adabac42937009a1f8257f15668d630a7ca8
59,549
def get_dataframe(subset, data_home): """ This method retrieves the dataframe and creates IDs for the dataframe """ data = fetch_20newsgroups(data_home=data_home, subset=subset, categories=None,\ shuffle=True, random_state=42, remove=('headers', 'footers', 'quotes'),\ download_if_missing=True, r...
04f1f25d61a5d6cd0016e805d1dd9f1cbf8c6f87
59,550
def find_all_gauges(imagePath,blurs,imgss,LURD): """ 通过点击鼠标得到面积 """ LURD = np.array(LURD) mianji = abs((LURD[0]-LURD[1])[0]*(LURD[0]-LURD[1])[1]) # 应变片面积 #mianji = 400 blur = blurs.copy() imgs = imgss.copy() row,col = blurs.shape[:2] blurs = cv2.convertScaleAbs(blur,alpha=1.5,bet...
dcf42b76f89da724e4f838be3a1ceafd9acf8cb4
59,551
def stop_words_remover(df): """ This function removes stopwords from a list containing list of tweets which matches with stopwords from a dictionary than returns a modified dataframe """ list_of_tweets = [] final_list_of_tweets = [] for row in df['Tweets']: list_of_tweets.appen...
3e68e35c2e36e86200364ff3a2c42865bef50403
59,552
def solve(lines: Lines, steps: int) -> int: """Solve the problem.""" bodies = parse_input(lines) system = OrbitalSystem(bodies) # system.print_state() for step in range(steps): system.step() # system.print_state() return system.total_energy()
ec8f48c70da04a0a6c8058f92911dda89e62edf9
59,553
def staff_check(user): """If TODO_STAFF_ONLY is set to True, limit view access to staff users only. # FIXME: More granular access control needed - see https://github.com/shacker/django-todo/issues/50 """ if defaults("TODO_STAFF_ONLY"): return user.is_staff else: # If uns...
080e6a28414210dea471f188626eeeca0a9050c6
59,554
def get_market_gainers(**kwargs): """ Top-level function for obtaining top 10 market gainers from the Stocks list endpoint """ return MoversReader(mover='gainers', **kwargs).fetch()
a39fa1cf2f87fc11bedf6d052727d5d76bbf6d34
59,555
import ipaddress def parse_listen_addr(listen_addr): """ Parse an address of the form [ipaddress]:port into a tcp or tcp6 Twisted endpoint description string for use with ``twisted.internet.endpoints.serverFromString``. """ if ':' not in listen_addr: raise ValueError( "'%s'...
70a1278bf49a41868d85c56bdbcb5d01ae49a6d1
59,556
import pandas import os def FusionResultats(dossier,csvpathtemp,resultatspath,DIR_SORTIE,DossierResultasInterm,patharchives=None,erreurautorisee = 0.25, verbose=1): """ Fusion des tableurs de résultats Parameters ---------- - dossier : string, chemin vers le dossier principal où se situe...
8aa1ea47e83e99ee3124caa6d87d36e9b56946b5
59,557
def is_style(style): """Check if a style is included in the BJCP guidelines. Keyword arguments: style-- string naming a suspected style """ styles = all_styles() if style in styles: return True else: return False
94da84cc200a89ac09c4b7e63400af285ee19083
59,558
import os def buildShadowMaskImage(dqfile,detnum,extnum,maskname,bitvalue=None,binned=1): """ Builds mask image from WFPC2 shadow calibrations. detnum - string value for 'DETECTOR' detector """ # insure detnum is a string if type(detnum) != type(''): detnum = repr(detnum) _funcroot ...
8517e94761749b75e1454b12e9a52c2186462b75
59,559
from typing import Any def to_number(s: str, default: Any = float("NAN")) -> Any: """文字列を数値化 Example: >>> to_number('△12,345') -12345 >>> to_number('12,345') 12345 >>> to_number('12円34銭') 12.34 >>> to_number('98%') 98 >>> to_number('abc')...
b7083eff9d73fc7e6cc2f31a8a7000f8dbef4d87
59,560
def import_from_file(request): """Import pages from a CSV file. The CSV format is compatible with the one that the CSV exporter generates. This means it's possible to export pages to CSV, make changes and then import the file to bulk update them. Import is all-or-nothing. If there is at least one ...
dcdc370df5022711e7efde4f6e020e0330b46ac1
59,561
def make_data_island(density, bulk_modulus, firing_temperature, binders, powders, tag=None): """Helper function to create a relatively involved data island.""" binder_specs = keymap(lambda x: MaterialSpec(name=x), binders) powder_specs = keymap(lambda x: MaterialSpec(name=x), powders) binder_runs = key...
70506855b72516e227bc3c4fe821bb1b5a9d7763
59,562
def merge_segmentations(segmentations, xy_offsets, extend=True, f_accept=0.2, post_merge_dilate=1): """ Parameters ---------- segmentations xy_offsets extend f_accept post_merge_dilate Returns ------- """ # merge detections masks by align, summa...
6ffb92410ac903c30860087b8dce6e62fa6471cf
59,563
def home(): """ Root/Home Page - Shows the ReST API Paths """ return jsonify(routch.getall())
2808444f0cd7c82f3438dca2ae6fa3942fd2b614
59,564
from datetime import datetime import itertools def satisfies(query, **kwargs): """Check whether a given datetime object satisfies day and time predicates Keyword Args: month: The month predicate (January, February, ...) day: The day of month predicate [1 31) weekday: The day of week p...
e36ff908a31e71eab242b9ff6cf4df6721a1fbf7
59,565
def register_model(model_type): """Registers a model by name.""" def _decorator(model_cls): if model_type in MODEL_REGISTRY: raise ValueError('model type %s already registered' % model_type) MODEL_REGISTRY[model_type] = model_cls model_cls.model_type = model_type ret...
573fc50c86e8faa724b05b55d17b03e63b8edbcf
59,566
def open_dataset(fname): """Open a single dataset from fv3chem outputs (nemsio or grib2 currently) Parameters ---------- fname : string Filename to be opened Returns ------- xarray.Dataset Description of returned object. """ names, nemsio, grib = _ensure_mfdataset_...
121a88820fc328ae83f28529d03c9b01c2d559ce
59,567
def load_reward(reward_type: str, reward_path: str, venv: VecEnv) -> common.RewardFn: """Load serialized reward. Args: reward_type: A key in `reward_registry`. Valid types include {reward_types}. reward_path: A path specifying the reward. venv: An environment that the policy...
6acad5fb4c25b42bb2619df637153390c6741783
59,568
def mod_sigmoid(z, scope='', reuse=None): """ ModSigmoid implementation, using a coupled alpha and beta. """ with tf.variable_scope('mod_sigmoid_' + scope, reuse=reuse): alpha = tf.get_variable('alpha', [], dtype=tf.float32, initializer=tf.constant_initializer(0.0...
88589612442a73ceab165ae93035c1c0d711b55d
59,569
def javascript(filename, type='text/javascript'): """A simple shortcut to render a ``script`` tag to a static javascript file""" if '?' in filename and len(filename.split('?')) is 2: filename, params = filename.split('?') return '<script type="%s" src="%s?%s"></script>' % ( type, sta...
dbb8eef4adfeca91afe328dfe414d894bed68b39
59,570
def get_hip_file_path(filepath, is_caffe2 = False): """ this function should be in sync with the hipified script in third-party/hipify_torch/hipify/hipify_python.py unfortunately because it's a normal python (instead of Starlark) we cannot simply import from there The general rule of converting...
13dd969dab7762285acf00b6ac2bc1a3463b5288
59,571
from .query_parser import parse_query from . import extra_functions import inspect def run_query(query, data, additionals={}, from_file=False, processes=1, listen=False): """ Run query. This function will utilize global imports if used as a library: >>> import hashlib >>> list(run_query('.a', [{"a": ...
e849daf18ca28eed7d1702cc0a5549b8244cd332
59,572
import subprocess def exec(command): """runs shell command and capture the output""" result = subprocess.run(command, shell=True, capture_output=True) if result.returncode: return result.stderr.decode("utf-8").strip(), result.returncode return result.stdout.decode("utf-8").strip(), result.r...
47b8b8b4aad3e63894045bf37911ccab131ac485
59,573
def likelihood(mprofile, oprofile, ostd, log=True): """ Compute the (log)likelihood function given a measured concentration profile (with known measurement error) and predicted profile(s). Parameters ---------- mprofile : 1-d or n-d array_like the modelled concentration prof...
d085548f942795bbbb6ab284edcfe764e47e07ac
59,574
def renumber(): """ Renumber units and options throughout the current document. Units must be numbered consecutively and options must be numbered starting at 0 within each unit. """ print 'edit::renumber:' filename = session.filename return BookManager.renumber_units(filename)
0e8a0c01cbc4e650882629d9ffba4e63f992779c
59,575
def to_py_type(val): """Convert numpy val to python primitive equivalent. Ex: Given: val = np.array([True, False]) Returns: [True, False] Given: val = np.array(32, dtype=np.int) Returns 32 """ if not isinstance(val, (_np.ndarray, _np.generic)): return val # val is np.ndarray o...
9e3fbfde3b63e036d31e179ca65b9627c115f9be
59,576
def get_consultants(): """Get all users who are consultants""" return (User.query.filter_by(is_consultant=True) .order_by(User.username))
e2e294b644fddcf60fac7069971b016b5c4d19a1
59,577
def regulon_weight_assignment(regulator, expr, filtered_regulon): """ Assigns probability and weights for regulator - target interactions Args: regulator (str): Regulator to expand interaction network expr (:obj: `pandas DataFrame`) : pandas DataFrame containing scaled expression data of ...
188a0653ca6dcacc42c11541e172c311d2f0128a
59,578
import requests def update_blacklist(): """Check for Blacklist update and load them into db.""" blacklist_url = config.postprocess.get('blacklist_url') if blacklist_url: response = requests.get(blacklist_url) lines = response.text.splitlines() blacklists = [] for line in l...
621fa727d9372bbe9c6d001ffc32174081853572
59,579
import fromage.utils.mol as mol_init def per_select(self, labels, old_pos=False): """ Select a molecule out of a Mol in a periodic system. Parameters ---------- labels : int or list of ints The number of the atoms from which the molecules are generated old_pos : bool Option to...
d818e803b41a85fc501aac1fa0f5e0fea8596e5f
59,580
def readThermoEntry(entry, Tmin=0, Tint=0, Tmax=0): """ Read a thermodynamics `entry` for one species in a Chemkin file. Returns the label of the species and the thermodynamics model as a :class:`NASA` object. Format specification at http://www2.galcit.caltech.edu/EDL/public/formats/chemkin.htm...
ca6caa7e39e62d18c6543bb5bf7f539bdd43bcae
59,581
from typing import Optional from typing import List def preview_card( box: str, name: str, image: str, title: Optional[str] = None, items: Optional[List[Component]] = None, caption: Optional[str] = None, label: Optional[str] = None, commands: Optional[Li...
04fe247074f4d46ebe2d97fea17cd6855a64a9c6
59,582
import os import json def check_completeness_single_job(out_file: str, job_no: int, iteration: int) -> bool: """ Check whether an individual inference job has been completed. Args: out_file: n5 file to save inference to. ...
a9ce3adab9121ac6044d535e8e4e4d3f7781a371
59,583
from typing import Iterable def iterable_to_cursor(iterable: Iterable) -> CursorFunc: """Get a cursor function from an iterable. """ iterator = iterable_to_iterator(iterable) return iterator_to_cursor(iterator)
24f3f2361c4e1a3371d4b87289fbfb3a88dfb356
59,584
def range(*args): """ range([start], end [,step]) nd version of range, where each arg can be a vector of the same length Parameters: [start] (vector): the start """ # if passed in scalars call the built-in range if not isinstance(args[0], (list, tuple, np.ndarray)): return...
0c4172a243acf75e8ac3e0421b142ce9ff9bf4c5
59,585
def max_key(d, fn=identity): """Find the maximum value in a dictionary and return the associated key. If we want to compare values using something other than their numeric values, we can specify a function. For example, with a dict mapping strings to strings, fn=len would return the key with the longest...
42e017fc3e58acb659dec8f0c854ca7c9860f94f
59,586
def rectangle2(c, w, h, angle=0, center=True): """ create rotated rectangle for input into PIL ImageDraw.polygon to make a rectangle polygon mask Rectagle is created and rotated with center at zero, and then translated to center position accepts centers Default : center options for...
268726fbce3b0c70190e8f962927cb9444c9689d
59,587
import requests import json def duckduckgo(search, appName=""): """Gives instant answers from DuckDuckGo (https://duckduckgo.com/). Keyword arguments: search -- <str>; what you are searching for (case sensitive) appName -- <str>; the name of your app Return value: { "...
7bb2958986b0e1b0219e7d1a63e475ff840f0136
59,588
def init_dataset(cfg): """ Use path in cfg to init a dataset the dataset should be the following format - Each Image should be named in (pid)_c(camid)_(iid).jpg where pid is the person id, camid is camera id, iid is image id(u...
d12eb0e566eb3294c54189cba7bf2a6c56d551a5
59,589
def set_workflow_for_object(obj, workflow): """Sets the passed workflow to the passed object. If the object has already the given workflow nothing happens. Otherwise the object gets the passed workflow and the state is set to the workflow's initial state. **Parameters:** workflow The ...
3a1fce7a2cb203a6b07e9d15b1f242deddd7be25
59,590
import requests def http_request(method, url_suffix, params=None, body=None, do_not_refresh_token=False): """ Generic request to Microsoft Graph """ token = get_token() response = requests.request( method, BASE_URL + url_suffix, headers={ 'Authorization': 'Beare...
1dffb199e01380311a5fbf721d49ea0fc4dbb885
59,591
def Max(*args): """Maximum over a set of real or integer terms""" return get_env().formula_manager.Max(*args)
74df4b162aff7ffdda17cecd579c283fa803d164
59,592
import os def generate(batch, size): """Data generation and augmentation # Arguments batch: Integer, batch size. size: Integer, image size. # Returns train_generator: train set generator validation_generator: validation set generator count1: Integer, number of tra...
b5f1fa5baaa3e6f77db2c0005d8e1a52fb66d981
59,593
def set_bmask_name(*args): """set_bmask_name(enum_t id, bmask_t bmask, char name) -> bool""" return _idaapi.set_bmask_name(*args)
61870c3de5cb47993a6ec00b1f50587b429f3940
59,594
def install_chrome_driver(context): """ Method to install webdriver for chrome """ options = webdriver.ChromeOptions() options.add_argument("--no-sandbox") options.add_argument("--disable-setuid-sandbox") options.add_argument("--disable-dev-shm-usage") options.add_argument("--disable-ext...
1d5b3f794ead6807c45497f98cfbfce9f2ce4341
59,595
def split(y, top_db=60, ref=np.max, frame_length=2048, hop_length=512): """ codes from https://github.com/librosa/librosa use this code fragments instead of importing librosa package, because of our server has a problem with importing librosa. """ non_silent = _signal_to_frame_nonsilent(y, ...
0b367e16c09219c014fa9d997056fceb03347986
59,596
def to_wordlist_linguaview_xml(sentence): """ Get wordlist in LinguaView XML representation. :return: """ word_list = etree.Element("wordlist") word_list.attrib["length"] = str(len(sentence)) for i in sentence: tok = etree.Element("tok") tok.attrib["id"] = str(i.id) t...
082c5d366e08579ef8c362c0a72cf0d88df51896
59,597
import os def load(): """ Load the synced audit modules. """ if __salt__['config.get']('hubblestack:nova:autosync', True): sync() for nova_dir in _hubble_dir(): if not os.path.isdir(nova_dir): return False, 'No synced nova modules/profiles found' log.debug('loadin...
cebc5b7e2be0db0ae8fd214e06919cabf6cb39a2
59,598
def binary_to_decimal(number): """ Calculates the decimal of the given binary number. :param number: decimal number in string or integer format :return integer of the equivalent decimal number """ decimal = [] number = list(str(number)[::-1]) for i in range(len(number)): ...
6d615b9bc5a50cc9d2a970fa77c989fa95d0d77e
59,599