content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def ui_form_stations():
"""
This function lists all stations
"""
# get _all_ the stations
stations = station_get(0)
# render stations in HTML template
return render_template("stations.html", result=stations) | 07f53e694e135e0612c871c279e63432eeedf966 | 2,300 |
import json
import requests
def create_digital_object(obj):
"""
Create a digitial object for a cilantro object in AtoM.
:param Object obj: THE cilantro object
:return: str The generated URI for the digital object
"""
url = f"{atom_uri}/api/digitalobjects"
headers = {'REST-API-Key': atom_a... | 21a803e88330b538e9018116107c680ed6565bc4 | 2,301 |
def fitcreds():
"""
returns the ['credentials'] dictionary
:return: dictionary or None
"""
return fitcfg().get('credentials', None) | d8c30b43ae3c91fc7f08d2a47b401416da8b7d4b | 2,302 |
import re
def brace_expand(str):
"""Perform brace expansion, a lá bash."""
match = re.search('{(.+?)(,.*?)?}', str)
if match:
strings = brace_expand(replace_range(str,
match.start(),
match.end(),
... | a4426eb8d1ecfc3ac8d9b9ecff57c8364b372042 | 2,303 |
def create(number):
"""
create() : Add document to Firestore collection with request body.
Ensure you pass a custom ID as part of json body in post request,
e.g. json={'id': '1', 'title': 'Write a blog post'}
"""
try:
id = request.json['id']
todo_ref = user_ref.docume... | 94d703a4b310545d895e05dc9e872fb0b64e990b | 2,304 |
def sort_terms(node, parent_children, hierarchy):
"""Recursively create a list of nodes grouped by category."""
for c in parent_children.get(node, []):
hierarchy.append(c)
sort_terms(c, parent_children, hierarchy)
return hierarchy | 5ae737206f3859c01da6b8e9475db688e53a8d13 | 2,305 |
def sumPm(mirror):
"""Returns sum of all mechanical power from active machines"""
sysPm = 0.0
# for each area
for area in mirror.Area:
# reset current sum
area.cv['Pm'] = 0.0
# sum each active machine Pm to area agent
for mach in area.Machines:
if mach.cv['S... | 996891a5386f59fb111b5726552537d67e9c419c | 2,306 |
def chunk(rs, n, column=None):
"""Returns a list of rows in chunks
:param rs: a list of rows
:param n:
- int => returns 3 rows about the same size
- list of ints, [0.3, 0.4, 0.3] => returns 3 rows of 30%, 40$, 30%
- list of nums, [100, 500, 100] => returns 4 rows with break points\
... | cfaad9bd0b973e3bcf7474f46ad14d01b52924cf | 2,307 |
def get_file_detail(traffic_file):
"""
Args:
traffic_file: a name
Returns:
roadnet_file and flow_file name
"""
phase = None
roadnet_file = None
flow_file = None
for category in TRAFFIC_CATEGORY:
if traffic_file in list(TRAFFIC_CATEGORY[category].keys()):
... | 638efcc7254544d0cd0ab305cea12aed5a0e7ba2 | 2,308 |
async def root():
"""
:return: welcoming page returning Made by @woosal1337
"""
try:
return {f"Made by @woosal1337"}
except Exception as e:
return {f"{e} has happened!"} | 3d4e9acf038f60a9d91755eafcfb7e9dcfaa7a71 | 2,309 |
def sequence_accuracy_score(y_true, y_pred):
"""
Return sequence accuracy score. Match is counted only when two sequences
are equal.
"""
total = len(y_true)
if not total:
return 0
matches = sum(1 for yseq_true, yseq_pred in zip(y_true, y_pred)
if yseq_true == yseq_... | b1345aaa6fd0161f648a1ca5b15c921c2ed635ad | 2,310 |
def load_content(sentence_file):
"""Load input file with sentences to build LSH.
Args:
sentence_file (str): Path to input with txt file with sentences to Build LSH.
Returns:
dict: Dict with strings and version of string in lower case and without comma.
"""
sentences = {}
with ... | 31c3104179e995d59cffbea92caf2d32decc572c | 2,311 |
import collections
def _analyse_graph(graph):
""" Analyses a connected graph to find a set of distinct paths and a
topologically ordered sequence.
"""
# Make a copy without self-cycles to modify
g = graph.clean_copy()
g0 = g.copy()
# Start with the diameter of the graph
diameter = ... | 19bcc25117b962626db5386e8cf39625e315cd79 | 2,312 |
def rare_last_digit(first):
"""Given a leading digit, first, return all possible last digits of a rare number"""
if first == 2:
return (2,)
elif first == 4:
return (0,)
elif first == 6:
return (0,5)
elif first == 8:
return (2,3,7,8)
else:
raise ValueError... | 2b15d35a6281d679dce2dedd7c1944d2a93e8756 | 2,313 |
def decorrelation_witer(W):
"""
Iterative MDUM decorrelation that avoids matrix inversion.
"""
lim = 1.0
tol = 1.0e-05
W = W/(W**2).sum()
while lim > tol:
W1 = (3.0/2.0)*W - 0.5*dot(dot(W,W.T),W)
lim = npmax(npabs(npabs(diag(dot(W1,W.T))) - 1.0))
W = W1
return W | ddc67d5aee68acb6202f7ebd2f5e99a6bf9e3158 | 2,314 |
import webbrowser
def _open_public_images(username):
"""
:param username: username of a given person
:return:
"""
try:
new_url = "https://www.facebook.com/" + username + "/photos_all"
webbrowser.open_new_tab(new_url)
return 1
except Exception as e:
print(e)
... | bd488bae2182bd2d529734f94fb6fc2b11ca88d0 | 2,315 |
def fermat_number(n: int) -> int:
"""
https://en.wikipedia.org/wiki/Fermat_number
https://oeis.org/A000215
>>> [fermat_number(i) for i in range(5)]
[3, 5, 17, 257, 65537]
"""
return 3 if n == 0 else (2 << ((2 << (n - 1)) - 1)) + 1 | 4427ab7171fd86b8e476241bc94ff098e0683363 | 2,316 |
def get_id_ctx(node):
"""Gets the id and attribute of a node, or returns a default."""
nid = getattr(node, "id", None)
if nid is None:
return (None, None)
return (nid, node.ctx) | cbca8573b4246d0378297e0680ab05286cfc4fce | 2,317 |
def fitsfile_clumpy(filename,ext=None,header=True,**kwargs):
"""Read a (CLUMPY) fits file.
Parameters:
-----------
filename : str
Path to the CLUMPY .fits file to be read.
ext : {int,str}
The FITS extension to be read. Either as EXTVER, specifying
the HDU by an integer, o... | 70055d193bba1e766a02f522d31eb9f2327ccc64 | 2,318 |
from typing import Optional
def is_tkg_plus_enabled(config: Optional[dict] = None) -> bool:
"""
Check if TKG plus is enabled by the provider in the config.
:param dict config: configuration provided by the user.
:return: whether TKG+ is enabled or not.
:rtype: bool
"""
if not config:
... | 75f1ef48582777ea59d543f33517cf10c2871927 | 2,319 |
import math
from typing import Sequence
def da_cma(max_evaluations = 50000, da_max_evals = None, cma_max_evals = None,
popsize=31, stop_fitness = -math.inf):
"""Sequence differential evolution -> CMA-ES."""
daEvals = np.random.uniform(0.1, 0.5)
if da_max_evals is None:
da_max_evals = i... | 378d54d0da1e5ec36529ae3fa94fd40b9a2dbecd | 2,320 |
from typing import Set
def j_hashset(s: Set = None) -> jpy.JType:
"""Creates a Java HashSet from a set."""
if s is None:
return None
r = jpy.get_type("java.util.HashSet")()
for v in s:
r.add(v)
return r | 28ad96de2b973d006e38b3e5b3228b81da31f4b6 | 2,321 |
def get_year(h5, songidx=0):
"""
Get release year from a HDF5 song file, by default the first song in it
"""
return h5.root.musicbrainz.songs.cols.year[songidx] | eabd7cfd63a06448f7ef4c94f39a8d44af0d971e | 2,322 |
def _create_simulation_parametrization():
"""Convert named scenarios to parametrization.
Each named scenario is duplicated with different seeds to capture the uncertainty in
the simulation..
"""
named_scenarios = get_named_scenarios()
scenarios = []
for name, specs in named_scenarios.item... | 281dd9c70c9d60f2ffa8b02fb69341ffd3c2ad19 | 2,323 |
def calc_buffer(P, T, buffer):
"""
Master function to calc any buffer given a name.
Parameters
----------
P: float
Pressure in GPa
T: float or numpy array
Temperature in degrees K
buffer: str
Name of buffer
Returns
-------
float or numpy array
logfO2
"""
if buffer == 'NNO':
return calc_NNO(P... | acb75ec734e0c366d1424bee608ec2b32f4be626 | 2,324 |
def printImproperDihedral(dihedral, alchemical = False):
"""Generate improper dihedral line
Parameters
----------
dihedral : dihedral Object
dihedral Object
Returns
-------
dihedralLine : str
Improper dihedral line data
"""
V2 = dihedral.V2*0.5
V2_B = dihedral.... | bcfece212ac6cc0eb476cb96c44e6af910185bc7 | 2,325 |
import math
def inv_erf(z):
"""
Inverse error function.
:param z: function input
:type z: float
:return: result as float
"""
if z <= -1 or z >= 1:
return "None"
if z == 0:
return 0
result = ndtri((z + 1) / 2.0) / math.sqrt(2)
return result | 7ba55c0a0544f65b95c4af93b4ccdfa7d58faf2b | 2,326 |
from typing import Optional
import requests
def batch_post(
api_key: str, host: Optional[str] = None, gzip: bool = False, timeout: int = 15, **kwargs
) -> requests.Response:
"""Post the `kwargs` to the batch API endpoint for events"""
res = post(api_key, host, "/batch/", gzip, timeout, **kwargs)
retur... | 18d039f1bd430cb85a2e8ad18777e5a289aef41f | 2,327 |
from typing import List
import pickle
def load_ste_data(task_name: str) -> List[pd.DataFrame]:
"""Loads the STE data corresponding to the given task name.
Args:
task_name (str): The name of the STE data file.
Returns:
List[pd.DataFrame]: The STE data if found, else empty list.
"""
... | 71d24a5b16fdd0ae9b0cc8b30a4891388594c519 | 2,328 |
def bsplclib_CacheD1(*args):
"""
* Perform the evaluation of the of the cache the parameter must be normalized between the 0 and 1 for the span. The Cache must be valid when calling this routine. Geom Package will insure that. and then multiplies by the weights this just evaluates the current point the CacheParam... | 41b3834b17b79c0e738338c12e5078cff6cf87ea | 2,329 |
def velocity_filter(freq, corr_spectrum, interstation_distance, cmin=1.0,
cmax=5.0, p=0.05):
"""
Filters a frequency-domain cross-spectrum so as to remove all signal
corresponding to a specified velocity range.
In practice, the procedure (i) inverse-Fourier transforms the cros... | 56f460b190b8e3fc4d8936a22d9c677e592d3719 | 2,330 |
import io
import types
def transcribe_file(path, language):
"""
Translate an PCM_16 encoded audio signal stored in a file using Google's STT API (Google Cloud Speech).
This implementation should be changed to transcribe audio-bytes directly.
:param path: path to audio file holding audio bytes
:par... | 0dcee8c1987c897b14eb25e58612be5d7b284f1b | 2,331 |
def make_aware(dt):
"""Appends tzinfo and assumes UTC, if datetime object has no tzinfo already."""
return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc) | 4894449548c19fc6aef7cd4c98a01f49043b3013 | 2,332 |
import torch
def train(model, tokenizer, train_dataset, batch_size, lr, adam_epsilon,
epochs):
"""
:param model: Bert Model to train
:param tokenizer: Bert Tokenizer to train
:param train_dataset:
:param batch_size: Stick to 1 if not using using a high end GPU
:param lr: Suggested l... | 7b2ca610b0e52011b55fc8f8bf66f0129001ea1d | 2,333 |
def fastqcounter(infile):
"""
Returns the number of unique sequences in a fastq file
"""
#check if file is derep'd using DerepCheck()
derep = reptools.DerepCheck(infile)
n=0
if derep:
with open(infile) as fn:
for title,seq,qual in reptools.FASTQparser(fn):
... | 49b9704d77c3422bb82968bc23c0fa8b77b012a3 | 2,334 |
def raichuMoves(board,player):
""""Generate All raichu Successors"""
piece = "@" if player == "w" else "$"
possible_boards = []
raichu_locs=[(row_i,col_i) for col_i in range(len(board[0])) for row_i in range(len(board)) if board[row_i][col_i]==piece]
for each_raichu in raichu_locs:
new_boa... | a015d9f2d9505677e2fecf6df4e2dd4142c67a82 | 2,335 |
def check_supported():
"""返回模块是否可用"""
return True | 6575a81d5ad30a3bb9bb857bbdead2cd2e4ff340 | 2,336 |
def tf_batch_propagate(hamiltonian, hks, signals, dt, batch_size):
"""
Propagate signal in batches
Parameters
----------
hamiltonian: tf.tensor
Drift Hamiltonian
hks: Union[tf.tensor, List[tf.tensor]]
List of control hamiltonians
signals: Union[tf.tensor, List[tf.tensor]]
... | 76ef9633312fd81f47c04d028940febf6625c787 | 2,337 |
def noise_dither_bayer(img:np.ndarray) -> np.ndarray:
"""Adds colored bayer dithering noise to the image.
Args:
img: Image to be dithered.
Returns:
version of the image with dithering applied.
"""
imgtype = img.dtype
size = img.shape
#Note: these are very slow for large ... | 9b752e6ef09c9c3b8a3ff276cbef796c96609535 | 2,338 |
def get_match_rank(track, tagged_file):
"""
:param track:
:param files:
:type track: TrackMetadata
:return:
"""
filenames = [filter_filename(os.path.splitext(os.path.basename(filename.path))[0]) for filename in tagged_file]
rank1 = [0]*len(tagged_file)
# Alphabetically closest
... | 446b0a25f7466d2ce46d51637588ff2e2d49a681 | 2,339 |
import os
import random
def execshell_withpipe_ex(cmd, b_printcmd=True):
"""
Deprecated. Recommand using ShellExec.
"""
strfile = '/tmp/%s.%d.%d' % (
'shell_env.py', int(os.getpid()), random.randint(100000, 999999)
)
os.mknod(strfile)
cmd = cmd + ' 1>' + strfile + ' 2>/dev/null'
... | 36191036aebef1af26a2471735cc8a6f45e13d27 | 2,340 |
def parseData(file_name, delimiter=None, header_size=0, col_types=None, ret_array=False):
""" Parse data form a text file
Arguments:
file_name: [str] Name of the input file.
Keyword arguments:
delimiter: [str] Data delimiter (often a comma of a semicolon). None by default, i.e. space/tab
delimited data
h... | 184ba8a3176991c033bf339517650205089b4493 | 2,341 |
from typing import Dict
from typing import Any
from typing import List
def file_command(client: Client, args: Dict[str, Any], params: Dict[str, Any]) -> List[CommandResults]:
"""
Returns file's reputation
"""
files = argToList(args.get('file'))
since = convert_string_to_epoch_time(args.get('since'... | 3b1313607efe26c8736562d937dd99130b2e8cd8 | 2,342 |
import subprocess
def run_task(client, cmd, cwd, prerequire=[], shell=False, quiet=False):
""" run cmd, in cwd
cmd should be a list (*args), if shell is False
when wildcards are used, shell should be Ture, and cmd is just a string
prerequire is a list of futures that must be gathered befor... | 8c2aeeccfd36fcfa6fd72c5215f68a1f8946c032 | 2,343 |
import scipy
def Kane_2D_builder(N,dis,mu,B=0,
params={},crystal='zincblende',
mesh=0,
sparse='yes'):
"""
2D 8-band k.p Hamiltonian builder. It obtaines the Hamiltoninan for a 3D
wire which is infinite in one direction, decribed using 8-band k.p... | 237a706dc3047353b021538a2cf1a75ef6c2768b | 2,344 |
def has_loop(edges, threshold=2):
""" check if a list of edges representing a directed graph contains a loop
args:
edges: list of edge sets representing a directed graph i.e. [(1, 2), (2, 1)]
threshold: min number of nodes contained in loop
returns:
bool
"""... | 5442524bf75fb75cc5639ae4f7412b8935234413 | 2,345 |
def connect(host=None, dbname=None, user=None, password=None, minconn=1,
maxconn=4):
"""
Attempts to connect to Postgres.
"""
if not any((host, dbname, user, password)):
host, dbname, user, password = get_db_env()
if not any((host, dbname, user, password)):
raise Exceptio... | f8aea382b473023f5ea280be55a5b463b52eba49 | 2,346 |
def animate( data_cube, slit_data=None, slit_cmap="viridis", raster_pos=None, index_start=None, index_stop=None, interval_ms=50, gamma=0.4, figsize=(7,7), cutoff_percentile=99.9, save_path=None ):
"""
Creates an animation from the individual images of a data cube.
This function can be pretty slow and take 1... | af5649258a31280b7cfbca8d14794b0f8e6bd807 | 2,347 |
def tau_profile(ncols,vshifts,vdop,which_line,wave_cut_off=2.0):
"""
Computes a Lyman-alpha Voigt profile for HI or DI given column density,
velocity centroid, and b parameter.
"""
## defining rest wavelength, oscillator strength, and damping parameter
if which_line == 'h1':
lam0s,fs... | bc420a23397650ed19623338a7d45068621218e8 | 2,348 |
import logging
import sys
import requests
import os
def main(args):
"""
chandl's entry point.
:param args: Command-line arguments, with the program in position 0.
"""
args = _parse_args(args)
# sort out logging output and level
level = util.log_level_from_vebosity(args.verbosity)
ro... | 57bdf9d8a9da0725192b5f9f5e539d35a0fcad47 | 2,349 |
def welcome_page():
""" On-boarding page
"""
g.project.update_on_boarding_state()
if g.project.on_boarding['import']:
return redirect(url_for('data_manager_blueprint.tasks_page'))
return flask.render_template(
'welcome.html',
config=g.project.config,
project=g.project... | 4be4f1447a732a24ecfbee49c3daa7a31a16fec4 | 2,350 |
def brokerUrl(host):
"""We use a different brokerUrl when running the workers than when
running within the flask app. Generate an appropriate URL with that in
mind"""
return '{broker_scheme}://{username}:{password}@{host}:{port}//'.format(
host=host, **CONFIG_JOB_QUEUE) | e55d84f818b17680e196b6c013dd1b3972c30df8 | 2,351 |
def show_lat_lon_gps(
move_data,
kind='scatter',
figsize=(21, 9),
plot_start_and_end=True,
return_fig=True,
save_fig=False,
name='show_gps_points.png',
):
"""
Generate a visualization with points [lat, lon] of dataset.
Parameters
----------
move_data : pymove.core.MoveDa... | c34f8e868668d01d4214b9a5678440266f8f9a0a | 2,352 |
def filter_seqlets(seqlet_acts, seqlet_intervals, genome_fasta_file, end_distance=100, verbose=True):
""" Filter seqlets by valid chromosome coordinates. """
# read chromosome lengths
chr_lengths = {}
genome_fasta_open = pysam.Fastafile(genome_fasta_file)
for chrom in genome_fasta_open.references:
... | 6ab32cc2667f0b2e7b9d0dc15f1d3ca7ea2ebe46 | 2,353 |
def load_RIMO(path, comm=None):
"""
Load and broadcast the reduced instrument model,
a.k.a. focal plane database.
"""
# Read database, parse and broadcast
if comm is not None:
comm.Barrier()
timer = Timer()
timer.start()
RIMO = {}
if comm is None or comm.rank == 0:
... | 67f2cd7f1a345a801ac65dcb54347863c6c7c64a | 2,354 |
def format_top(data):
"""
Format "top" output
:param data: dict
:return: list
"""
result = []
if data:
if 'Titles' in data:
result.append(data['Titles'])
if 'Processes' in data:
for process in data['Processes']:
result.append(process)
... | 6fb5a4a18f8a87ee8bfffd30da1d9829024f987b | 2,355 |
def process_arguments(parser):
"""This function parses the input arguments."""
args = parser.parse_args()
# Distribute input arguments
request = args.request
if "num_tests" in args:
num_tests = int(args.num_tests)
else:
num_tests = None
# Test validity of input arguments
... | 19bb444ff578cc92bb99685e4405a25b8f12eaba | 2,356 |
def generate_sections(logdata: pd.DataFrame):
"""
Generates a list of SectionDescriptors based on iMotions packets
SlideStart and SlideEnd.
If the first Slide related packet is an End packet, the first
descriptor will include all timestamps up to that packet, else it
will drop the packets before.
The last desc... | 3f3d009965449a54a43d4751f15066b798c335d7 | 2,357 |
def etree2dict(element):
"""Convert an element tree into a dict imitating how Yahoo Pipes does it.
"""
i = dict(element.items())
i.update(_make_content(i, element.text, strip=True))
for child in element:
tag = child.tag
value = etree2dict(child)
i.update(_make_content(i, val... | e0c14295fb0d8459b7ab3be300213c6a99a43e5e | 2,358 |
def full_chain():
"""
GETing `/chain` will returns the full blockchain.
Returns:
The node's full blockchain list, as a JSON response.
"""
logger.info("Received GET request for the full chain")
return {
"chain": blockchain.chain,
"length": len(blockchain.chain),
} | 9987c95270cbdd89b9578cd987d4be29a2d60433 | 2,359 |
from click import _bashcomplete
def _patched_is_incomplete_option(all_args, cmd_param):
"""Patched version of is_complete_option.
Fixes issue testing a cmd param against the current list of
args. Upstream version does not consider combined short form args
and so a command like `guild check -nt <auto>... | f92fa77c7cfa74fec79f853ba948028951b1f736 | 2,360 |
def confirm_install() -> bool:
"""
Confirms that update should be performed on an empty install
"""
message = (
"The pack you are trying to update doesn't have a pack-manifest.json file. "
"Unless you are doing a first install, *THIS SHOULD NOT HAPPEN*. If you are doing a first install, ... | 2963e9913c56623064b712e817e6c768a8f600c3 | 2,361 |
def f_cv(x, dt):
""" state transition function for a
constant velocity aircraft"""
F = np.array([[1, dt, 0.5*dt*dt, 0, 0, 0],
[0, 1, dt, 0, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, dt, 0.5*dt*... | cfb142101598eaa635a6c4a4e45d411043cd99b9 | 2,362 |
import getpass
def prompt_for_password(args):
"""
if no password is specified on the command line, prompt for it
"""
if not args.password:
args.password = getpass.getpass(
prompt='Enter password for host %s and user %s: ' %
(args.host, args.user))
return args | 22fdb01fa07a83e53f0544a23e6ad014f7b21f88 | 2,363 |
def update_hparams(hparams, new_hparams):
""" Update existing with new hyperparameters """
if new_hparams is None:
return hparams
if isinstance(new_hparams, str) and new_hparams.endswith('.json'):
tf.logging.info("Overriding default hparams from JSON")
with open(new_hparams) as fh:
... | fa134d1c5b8d9cf406fc9e3133303b9897a59970 | 2,364 |
from typing import Any
import importlib
def relative_subpackage_import(path: str, package: str) -> Any:
"""[summary]
Args:
path (str): [description]
package (str): [description].
Returns:
Any: [description]
"""
if not path.startswith('.'):
path = '.' + p... | 2345267b60947f57098b0678dce845d858f2d2a8 | 2,365 |
def convertToNpArray(train,test):
"""
Converts the data into numpy arrays
:param train: training data csv path
:param test: test data csv path
:return: training data and labels, test data and labels
"""
train_data = pd.read_csv(train, delimiter=',', quotechar='"',
... | bc375946802e6dc75f9f52cd7b1665fe820287e7 | 2,366 |
import json
def attachment_to_multidim_measurement(attachment, name=None):
"""Convert an OpenHTF test record attachment to a multi-dim measurement.
This is a best effort attempt to reverse, as some data is lost in converting
from a multidim to an attachment.
Args:
attachment: an `openhtf.test_record.Att... | ff758924e1dfab00c49e97eefe6548a0de73c257 | 2,367 |
import torch
def similarity_iou_2d(pred_boxes, true_boxes):
"""
Return intersection-over-union (Jaccard index) of boxes.
Both sets of boxes are expected to be in (cx, cy, w, h) format.
Arguments:
pred_boxes (Tensor[B, 4, N])
true_boxes (Tensor[B, 4, M])
Returns:
iou (Tensor... | 7081906483860e475fbf7ad3c7801182ba8a5efd | 2,368 |
def get_atom_coords_by_names(residue, atom_names):
"""Given a ProDy Residue and a list of atom names, this attempts to select and return
all the atoms.
If atoms are not present, it substitutes the pad character in lieu of their
coordinates.
"""
coords = []
pad_coord = np.asarray([GLOBAL_PAD... | 7838ab6352a37b3731ee81f7beeebfde7676b24a | 2,369 |
def calculate_chord(radius, arc_degrees):
"""
Please see the wikipedia link for more information on how this works.
https://en.wikipedia.org/wiki/Chord_(geometry)
"""
# Calculate the arc_degrees in radians.
# We need this because sin() expects it.
arc_radians = radians(arc_degrees)
# C... | be59a06d33e69d5232fdea1cbdf6c5cef20f30fc | 2,370 |
def broadcast(right, left, left_fk=None, right_pk=None, keep_right_index=False):
"""
Re-indexes a series or data frame (right) to align with
another (left) series or data frame via foreign key relationship.
The index or keys on the right must be unique (i.e. this only supports
1:1 or 1:m relationhip... | 0be603caec1530427399a7b816eb63bbad71f239 | 2,371 |
def _is_arraylike(arr):
"""Check if object is an array."""
return (
hasattr(arr, "shape")
and hasattr(arr, "dtype")
and hasattr(arr, "__array__")
and hasattr(arr, "ndim")
) | 71bfbb7f93116879ee63bb4fc1ad8b3a3d8807c3 | 2,372 |
def tokenize_docstring(text):
"""Tokenize docstrings.
Args:
text: A docstring to be tokenized.
Returns:
A list of strings representing the tokens in the docstring.
"""
en = spacy.load('en')
tokens = en.tokenizer(text.decode('utf8'))
return [token.text.lower() for token in tokens if not token.is_... | c58c1dcf62d2b3de1f947cfd33f2c344b03532fb | 2,373 |
def conv_output_length(input_length, filter_size,
border_mode, stride, dilation=1):
"""Determines output length of a convolution given input length.
# Arguments
input_length: integer.
filter_size: integer.
border_mode: one of "same", "valid", "full".
strid... | 9e7f44b44e582f140dafdfd48c363d80fe8c4a46 | 2,374 |
import os
def source_ccp4():
"""Function to return bash command to source CCP4"""
if os.name == "nt":
return
return "source {}".format(os.path.join(os.environ["CCP4"], "bin", "ccp4.setup-sh")) | 7b3f2920906ff4e6b680e4696a66a67e56c72d03 | 2,375 |
def dblHour():
"""(read-only) Array of doubles containgin time value in hours for time-sampled monitor values; Empty if frequency-sampled values for harmonics solution (see dblFreq)"""
return get_float64_array(lib.Monitors_Get_dblHour) | a437965873c7764e2ddbebb81163887f6ddfca07 | 2,376 |
def select_uuid_like_indexes_on_table(model, cursor):
"""
Gets a list of database index names for the given model for the
uuid-containing fields that have had a like-index created on them.
:param model: Django model
:param cursor: database connection cursor
:return: list of database rows; the f... | c63cbf2e45a6c6e2591e627781b92a93cd101e27 | 2,377 |
def retrieve_jambalaya(request):
"""
Retrieve a jambalaya recipe by name or country of origin
---
serializer: JambalayaSerializer
parameters:
- name: name
description: name as found in recipe
type: string
paramType: query
required: false
- name... | 2263c091b172d9fce5698b40647484e06d2d37bb | 2,378 |
from typing import Union
def get_pymatgen(optimade_structure: OptimadeStructure) -> Union[Structure, Molecule]:
"""Get pymatgen `Structure` or `Molecule` from OPTIMADE structure.
This function will return either a pymatgen `Structure` or `Molecule` based
on the periodicity or periodic dimensionality of O... | 7cb4dbd9395b57931a27db87516c587062e65bb3 | 2,379 |
import torch
def get_meshgrid_samples(lower, upper, mesh_size: tuple, dtype) ->\
torch.Tensor:
"""
Often we want to get the mesh samples in a box lower <= x <= upper.
This returns a torch tensor of size (prod(mesh_size), sample_dim), where
each row is a sample in the meshgrid.
"""
samp... | 98a2c7b064d7b23824b547d0fc0a16eb37cb0923 | 2,380 |
from datetime import datetime
import random
def draw_nodes(start, nodes_list, cores, minute_scale, space_between_minutes,
colors):
"""
Function to return the html-string of the node drawings for the
gantt chart
Parameters
----------
start : datetime.datetime obj
start t... | 83ed57f8d494154d815ec189c002ff86393b2992 | 2,381 |
def has_understood_request(
sys_nlu: dict, slot: str, domain: str, lowercase_slots: bool = True
) -> bool:
"""Check if the system has understood a user request in a particular domain."""
# assume perfect system if NLU not available
if not sys_nlu:
return True
sys_nlu_requested = get_turn_a... | 676e11fe996bd88562d1e1404dd1bdd29f3e7d62 | 2,382 |
def lengthOfLongestSubstring(s):
"""
:type s: str
:rtype: int
"""
res = ""
n = 0
for i in s:
if i not in res:
res = res + i
else:
indexofi = res.find(i)
res = res[indexofi+1::] + i
k = len(res)
if k > n:
n = k
... | 951366d46a47030c5d37026bd6712eeb73c34af9 | 2,383 |
async def get_sequence_metadata(checksum: str, accept: str = ""):
"""Return Refget sequence metadata based on checksum value."""
headers = Headers()
url_path = "sequence/" + checksum + "/metadata"
try:
result = await create_request_coroutine(
url_list=metadata_url_list(checksum),
... | afe591946644d4723142971519926fcacb2a8aa4 | 2,384 |
from functools import reduce
def getattrs(o, *attrs, **kwargs):
"""
>>> getattrs((), '__iter__', '__name__', 'strip')('_')
'iter'
>>> getattrs((), 'foo', 'bar', default=0)
0
"""
if 'default' in kwargs:
default = kwargs['default']
c = o
for attr in attrs:
... | 64d55154d2399c7097476a8335eae81749588286 | 2,385 |
def maria_create_account(params):
"""root user and dbuser are created at startup.
grant all to dbuser is all we need to do after the DB starts
:type params: dict
"""
error_msg = 'ERROR: mariadb_util; maria_create_account; '
error_msg += 'action: %s user: %s error: %s'
password = Config.accou... | e26ba5044689f772b93cdd426d9d2995547ada3a | 2,386 |
def compute_coef_xz(y_val, coef_3d):
"""
compute the 2D polynoimal coefficients for a given x
:param x_val: value of x
:param coef_3d: the original 3D polynomials
:return:
"""
coef_xz = np.zeros((coef_3d.shape[1], coef_3d.shape[2]), dtype=coef_3d.dtype)
max_degree_y = coef_3d.shape[0] - ... | f65353f41bc142b16578750d15a098ae03458fd1 | 2,387 |
def bbox_overlaps(bboxes1, bboxes2, mode='iou'):
"""Calculate the ious between each bbox of bboxes1 and bboxes2.
Args:
bboxes1(ndarray): shape (n, 4)
bboxes2(ndarray): shape (k, 4)
mode(str): iou (intersection over union) or iof (intersection
over foreground)
Returns:
... | 665e9478b66b398536de48b250ee21aec16f4be0 | 2,388 |
def me_length_filter(me_iv_pairs, min_length=100):
"""Returns list of (InsertionVertices, InsertionVertices) tuples
with those containing paths going backwards through the ME sequence
filtered out
"""
filtered = []
for iv_pair in me_iv_pairs:
enter_iv, exit_iv = iv_pair
me_seq_l... | 9c344ee913f60aace3b8d94d04500d95166e67d6 | 2,389 |
def build_big_map_schema(data, schema: Schema) -> BigMapSchema:
""" Generate Big_map schema from the contract storage
:param data: Raw storage (Micheline expression)
:param schema: Storage schema
:returns: Mappings: Big_map id to JSON path and vice versa
:rtype: BigMapSchema
"""
bin_to_id =... | 370936598263897e5c0b2416e44bccfdfb151e6c | 2,390 |
import requests
def _get(session, urlTail):
# type: (Session, str) -> Dict
"""Make an HTTP(s) GET request to Batfish coordinator.
:raises SSLError if SSL connection failed
:raises ConnectionError if the coordinator is not available
"""
headers = {CoordConsts.HTTP_HEADER_BATFISH_APIKEY: sessio... | 2f7fb16117670465f4462cd0259932f1bfcb6e48 | 2,391 |
import functools
def compose(fns):
"""Creates a function composition."""
def composition(*args, fns_):
res = fns_[0](*args)
for f in fns_[1:]:
res = f(*res)
return res
return functools.partial(composition, fns_=fns) | 5c791f52f70707078e941fe169679ddc80a32782 | 2,392 |
import os
def load_participants_file():
"""
Load participants.tsv file and build pandas DF of participants
This function assumes that the file participants.tsv is present in the -path-results
:return: participants: pandas dataframe
"""
participants = pd.read_csv(os.path.join('participants.tsv'... | f55c32789563150fc574c8a98df2780c6a5903da | 2,393 |
def clr_tilcmt(*args):
"""
clr_tilcmt(ea)
"""
return _ida_nalt.clr_tilcmt(*args) | d1edcaee63ac58f6d82249ceb3a5fc9e35224fe9 | 2,394 |
import copy
def canarize_service(args, input_yaml, labels={}):
"""
Create a canary for an existing Service.
We do this by:
- adding a '-canary' suffix to the name of the Service
- adding a '-canary' suffix to all the labels in the Service selector
"""
res = []
# append the -canary to ... | 835d4f2dfd31d5db57254d97645bdd790c3d17dd | 2,395 |
def get_query_results(query):
"""
Get the data with common fields from the Close using the provided query.
:param query: Any Close search query eg. 'lead_status:Potential has:emails'
:return: 2D array with a header and results
"""
api = Client(CLOSE_API_KEY)
leads = api.get('lead', params={... | 826b6a3fa522a53c9d486aed7fdc38638f12eef0 | 2,396 |
def width_pcc_dmera_2d(n, D, supp):
"""
Optimal width of the circuit for the pcc after compression
Args:
n(int): Number of scales
D(int): Number of cycles per scale
supp(list): List of integers
Returns:
int: Optimal width
"""
supp_con = [convert_2d_to_1d(c,n)... | 0df74985ed16aa4bb0295655d5093fe4a40f03a2 | 2,397 |
def global_delete(key):
"""Delete an entity from the global cache.
Args:
key (bytes): The key to delete.
Returns:
tasklets.Future: Eventual result will be ``None``.
"""
batch = _batch.get_batch(_GlobalCacheDeleteBatch)
return batch.add(key) | b9d9f8189f10c0d287081e6d65505c15271a672d | 2,398 |
def get_drawing_x(image: Image = None) -> float:
"""
Get the x coordinate value of the current drawing position (x,y).
Some drawing functions will use the current pos to draw.(see line_to(),line_rel(),move_to(),move_rel()).
:param image: the target image whose drawing pos is to be gotten. None means i... | 6e176cb609868730bc44131d78fe646dccb84fdb | 2,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.