content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from rmgpy.data.kinetics.family import ReactionRecipe
def _convert_3_atom_2_bond_path(start, mol):
"""
Searches for 3-atom-2-bond [X=X-X+] paths paths starting from the parameter atom.
If a correct path is found, the starting atom receives an unpaired electron while
the bonds in the delocalization pat... | b17985d982614c53ee4adeea06e7e5b361306690 | 3,600,500 |
def correlateArrays(pdi, arr1, arr2, multiplier=1.0, newName='', pdo=None):
"""Make sure to pass array names and integer associated fields.
Use helpers to get these properties."""
if pdo is None:
# TODO: test this
pdo = pdi.DeepCopy()
# Get the input arrays
(name1, field1) = arr1[0],... | ce1cc7402efd5fb06ae1b95da20934bad5b83ed7 | 3,600,501 |
import pandas as pd
def indices_stats_df(sort_size=False, with_sql=False):
"""Return statistics on indices.
See https://www.postgresql.org/docs/current/monitoring-stats.html
"""
result = execute_raw(
r"""
SELECT
pt.tablename AS TableName,
t.indexname AS IndexName,
... | c7d8d363d00b834c3900a92c70c3a350d83f2144 | 3,600,502 |
def peakgene_overlaps(combos, same_genes, normalize=False):
"""Count the number of genes that overlap when examing the hg19 & hg38
GISTIC runs' focal peaks."""
venn_numbers, gsu, gsi = [], [], []
for coh, ad in combos:
print(coh)
# put all significant genes in a list
fnames = ['... | 70e6ce4d185d97135fb0aff7c2712c08ad7b911e | 3,600,503 |
import six
def _create_intermediate_tables(docs, schema):
"""
return {
table_name: {
row_id_number: {
column_name: cell_data,
...
},
...
},
...
}
"""
INT = '#'
def lookup(doc, keys):
for key ... | 8d53f65ecb7827a87627abe3bf07e03bed2d739a | 3,600,504 |
from typing import Dict
def plot_goal_ternary(df: pd.DataFrame,
kpis: Dict[str, callable],
goals: Dict[str, callable],
control_params: set) -> None:
"""
Arguments
---
df: Observation dataframe
kpis: Dictionary of funtions that scores a given combi... | b2422dc2975cbf1da0fb59cc4d027492d1bb1f57 | 3,600,505 |
from unittest.mock import Mock
def mock_channel_file(
offered_by, channel_id, playlist_id, create_user_list=False, user_list_title=None
):
"""Mock video channel github file"""
content = f"""---
offered_by: {offered_by}
channel_id: {channel_id}
playlists:
- id: {playlist_id}
{"create_user_list: true... | 3042a7fc6f0fb622db8bf035a408672ddd6408ab | 3,600,506 |
def cmdline(argv, flags):
"""A cmdopts wrapper that takes a list of flags and builds the
corresponding cmdopts rules to match those flags."""
rules = dict([(flag, {'flags': ["--%s" % flag]}) for flag in flags])
return parse(argv, rules) | 522879927ba5242f6c738428e3fa4294bb98ffe8 | 3,600,507 |
def get_globalLock_ratio(name):
"""Return the global lock ratio"""
try:
result = get_rate(NAME_PREFIX + 'globalLock_lockTime') / \
get_rate(NAME_PREFIX + 'globalLock_totalTime') * 100
except ZeroDivisionError:
result = 0
return result | 8824f867375175f38ec2fc586467bff7ff39b5a8 | 3,600,508 |
def tfx_to_tifix(in_arr, t_map, f_map):
"""Sum a (t, f, ...) array into a (ti, fi, ...) array."""
in_arr_shape = in_arr.shape
n_time = in_arr_shape[0]
n_chan = in_arr_shape[1]
n_tint = np.max(t_map) + 1
n_fint = np.max(f_map) + 1
out_dtype = get_output_dtype(in_arr)
trailing_dims = ... | 6269c3dd824d8d23cbfccb6b03c076dc7c5d0323 | 3,600,509 |
import sys
def auth_client(key=None,endpoint=None):
"""Authenticate the client"""
if(key is None):
print("Cognitive Service Key not found, modify the config.yml file")
sys.exit("Impossibile to use the program without correct configuration")
if(endpoint is None):
print("Cognitive S... | 290defba70413a7053c24b19ab0721789ca6cbf3 | 3,600,510 |
import numpy
def _planarEOM_dxdv(x,t,pot):
"""
NAME:
_planarEOM_dxdv
PURPOSE:
implements the EOM, i.e., the right-hand side of the differential
equation, for integrating phase space differences, rectangular
INPUT:
x - current phase-space position
t - current time
... | 3adf7f76598e76b5d32e2c83b8e906ad9182b815 | 3,600,511 |
import json
def get_offset2docidx(doc = None, corenlp_file = None):
"""
This function gets the mapping from the document-level offset of a word to its document-level word index
"""
# get a dictonary of character offset to sentid
if doc is None and corenlp_file is None:
raise NameError("... | e228f8eb878581abe8f0679f9d1f99d6012eecd0 | 3,600,512 |
import os
def get_thumbnail_folder():
"""Returns a path to the thumbnail folder.
The returned path might not exist.
"""
if os.name == "nt":
thumb_folder = os.path.join(USERDIR, "thumbnails")
else:
cache_folder = os.path.join(xdg_get_cache_home(), "thumbnails")
thumb_folde... | 54ec7313754b10b1bd446554469b23701f8611f1 | 3,600,513 |
def trainerServerInput(tf_transform_output):
"""Creates an input function reading from raw data.
Args:
tf_transform_output: Wrapper around output of tf.Transform.
Returns:
The serving input function.
"""
raw_feature_spec = RAW_DATA_FEATURE_SPEC.copy()
# Remove label since it is not... | 6ebfeb7e930171de688241e666f96a1b45df6f19 | 3,600,514 |
from functools import reduce
def reorder_spatial_and_reduce_axes(sch, op, axis_map, split_axis_list, reduce_split_axis_list, extents_info=None):
"""Reorder spatial and reduce axes
"""
pre = []
ones = []
for k, v in axis_map.items():
if not isinstance(v, (list, tuple)):
if v.dom is None:
ex... | 69e198b07350ae678063b369fdd3a3cb52c91fd5 | 3,600,515 |
from functools import wraps
def run_only_once(resolve_func):
"""
Make sure middleware is run only once,
this is done by setting a flag in the `context` of `ResolverInfo`
Example:
class AuthenticationMiddleware:
@run_only_once
def resolve(self, next, root, info, *args, *... | 9742318ca44ec92d7826d561968c87cea62db1bf | 3,600,516 |
import os
def read_docs_with_doc_id_and_name(f):
"""
Parse file into a map from doc id to mention and relation raw strings
:param f: The annotation file
:return: A map from doc id to corresponding mention and relation annotations, which are stored as raw string
"""
all_docs = {}
mention_li... | a02e5f2758e5eb6636c210c21f241445bff192ea | 3,600,517 |
def content_type_headers(filename, content_type=None):
"""Returns a dict with the content-type header for a file.
Guesses the mimetype for a filename and returns a dict
containing the content-type header.
.. code-block:: python
>>> content_type_headers('example.txt')
{'Content-Type': 'text/plain'}
>>> con... | b429d4345052ec7836071f19c1e261bea88df8c1 | 3,600,518 |
def constructLinkedList(n):
"""
方法功能:创建单链表
说明:上方的 removeDup() 对于升序、降序均有效,不妨建一个升序链表
"""
head = LNode()
cur = head
for i in range(n):
tmp = LNode()
if i % 2 == 0:
tmp.val = i
else:
tmp.val = i - 1
cur.next = tmp
cur = tmp
retu... | 2df6ae23fc43716972651597f8d5f20f63979693 | 3,600,519 |
import time
def ncesvd(matrix_train, embeded_matrix=np.empty((0)),
iteration=4, rank=200, fb=False, seed=1, root=1.1, **unused):
"""
PureSVD algorithm
:param matrix_train: rating matrix
:param embeded_matrix: item or user embedding matrix(side info)
:param iteration: number of random ... | bd0da84172b84bd636f5fda243c49e155300ebaa | 3,600,520 |
def create_new_single_server(db, name, ip, section_id, colorId):
"""
Add new server to data base.
"""
query = ''' INSERT INTO servers(ip, name, section_id, color_id)
VALUES("%s","%s","%s","%s") ''' % (ip, name, section_id, colorId)
result = get_db_with_actions(db, query)
creat... | 46da87d7c5df2c89cfc75f08b3f651c19d9f52ca | 3,600,521 |
import ctypes
def corrDn(image, filt, edge_type='reflect1', step=(1, 1), start=(0, 0), stop=None):
"""Compute correlation of image with filt, followed by downsampling.
These arguments should be 1D or 2D arrays, and image must be larger (in both dimensions) than
filt. The origin of filt is assumed to be ... | 9c4f844bfceb41c8d97f08fcaefbe29363e6ef4c | 3,600,522 |
def ldapmask2filemask(ldm):
"""Takes the access mask of a DS ACE and transform them in a File ACE mask.
"""
RIGHT_DS_CREATE_CHILD = 0x00000001
RIGHT_DS_DELETE_CHILD = 0x00000002
RIGHT_DS_LIST_CONTENTS = 0x00000004
ACTRL_DS_SELF = 0x00000008
RIGHT_DS_READ_PROPERTY = ... | a461fd5bdc6498df345491f38885a63b0dcbefc2 | 3,600,523 |
import re
def get_input_size(filename):
"""Gets input size and # of channels."""
with open(filename) as input_file:
for line in input_file:
match = re.match(r'^input.*\(None, (\d*), (\d*), (\d*)\)', line)
if match is not None:
x = int(match.group(1))
... | 3e753e5ac74babcbe4f48830cfde7a3002f7cc37 | 3,600,524 |
def consumption_per_minute(depth, bottle_size, sac=DEFAULT_BOTTOM_SAC, silent=True):
"""returns the consumption in bars/minute of a bottle of a given size for
a given SAC"""
sac = float(sac)
ata = depth_to_ata(depth)
liters_per_minute = ata * sac
bars = liters_to_bars(liters_per_minute, bottle_s... | 1455ac9baafcc2ecf940d78df798f04ca3a0e089 | 3,600,525 |
from typing import List
import torch
def javascript_dataloader(
*args,
augmentations: List[dict],
sp: spm.SentencePieceProcessor,
program_mode: str = "identity",
subword_regularization_alpha: float = 0,
max_length: int = 1024,
max_target_length: int = 256,
spm_unigram_path: str = None,... | e2a5c70be691e6c91bb21e9d72467495a48c1687 | 3,600,526 |
def define_features_tfidf(columns, training_data, testing_data = None, ngramrange=(1, 1)):
"""
Define the features for classification using TFIDF.
Parameters
----------
column: String or list of strings if using multiple columns
Names of columns of df that are used for... | b660c48a4d35ae671abc0b707b2746c70b2d62e5 | 3,600,527 |
def logout():
"""Log out and return login form."""
app = current_app._get_current_object()
app.logger.info('%s logged out', current_user.email)
logout_user()
flash('You have been logged out.')
return redirect(url_for('auth.login')) | 3fde7b0994468082117b6ff26eae7c97872ad0dc | 3,600,528 |
import os
from pathlib import Path
def get_generated_keys():
"""
get_generated_keys function gets the .key & .pub files in the project directory.
:return: private and public key file name
"""
priv_keys = []
pub_keys = []
for file in os.listdir("."):
if file.endswith(".key"):
... | f287a38964c1ce6b63180c861a106095cb49d5f3 | 3,600,529 |
def indexOfSmallestInt(listOfInts):
"""
return index of smallest element of non-empty list of ints, or False otherwise
That is, return False if parameter is an empty list, or not a list
parameter is not a list consisting only of ints
By "smallest", we mean a value that is no larger than any other
... | 63afb453b13ad4da75c83e9a7f6b409f58739d7e | 3,600,530 |
def augment_spectrogram(sg):
"""Augments a spectrogram by randomly masking out time and frequency ranges,
as described in the "SpecAugment" paper.
"""
sg = np.copy(sg)
freq_len, time_len = sg.shape
max_freq_len = np.ceil(MAX_MASK_PERCENT * freq_len)
max_time_len = np.ceil(MAX_MASK_PERCENT *... | 4f601fb357c3f2f614e1963b58820ec0464047bb | 3,600,531 |
def field_with_classes(field, *classes):
"""
Adds the specified classes to the HTML element produced for the field.
"""
return field.as_widget(attrs = { 'class': ' '.join(classes) }) | 2b9929b2629fafaafbe1d2537afc0a9a601eed53 | 3,600,532 |
import tkinter as Tkinter
import tkinter.filedialog as tkFileDialog
def directory_from_gui(
initialdir='.',
title='Choose directory'): # pragma: no cover
"""
Opens dialog to one select directory
Parameters
----------
initialdir : str, optional
Initial directory, in which ... | e0b43a044c0e05815023de2275cc0ff1ffb01d8e | 3,600,533 |
def first_pos():
"""
This function will be used to reset the robot back to a home position. Initial variables will be
collected from the user.
"""
# Reference the Empty state and return dictionary.
global EMPTY
global return_dict
# Add gripper statuses to the return dictionary to set them to E... | 4d8b4cdc2fe33d1766c43456a3847ebd2f8539c0 | 3,600,534 |
def query(query_string):
"""Run database query."""
db_host = "w-v-cabledb-0"
db_user = "root"
db_pass = "maxlab"
db_name = "cabledb_test2"
try:
with MySQLdb.connect(db_host, db_user, db_pass, db_name) as db_session:
db_session.execute(query_string)
return db_session.fetchall()
except MySQL... | c6d55b2bfc81d945a0c09622591c17ca361d1502 | 3,600,535 |
import os
import logging
def logger(name):
"""Return an existing or new logger.
The name should be a string like 'sharp' to create the child
logger 'cocomud.sharp'. The log file 'logs/{name}.log' will be
created.
If the name is specified as an empty string, a main logger is
created. It wil... | 82009e22419cac03b4be239fad15b7a4e8a60339 | 3,600,536 |
def _test_path_to_file_url(path):
"""
Convert a test Path to a "file://" URL.
Args:
path: a tests.lib.path.Path object.
"""
return 'file://' + path.resolve().replace('\\', '/') | b13025da535fe43e074f79411ab4be55c766a572 | 3,600,537 |
def instantiate(repo, name=None, filename=None):
"""
Instantiate the generator and filename specification
"""
default_transformers = repo.options.get('transformer', {})
# If a name is specified, then lookup the options from dgit.json
# if specfied. Otherwise it is initialized to an empty list ... | 6a280b91598d9e0dd41d99165d0474b3dcdde7f3 | 3,600,538 |
import subprocess
def test_process_fail(benchmark_dummy, monkeypatch):
"""XXX a negative path of a very simple test"""
def run_mock(_args, **_):
return ProcessMock(1)
monkeypatch.setattr(subprocess, 'run', run_mock)
with pytest.raises(subprocess.CalledProcessError):
benchmark_dummy.run... | c72d6c554e51cf8ad26be844960d658d37494b32 | 3,600,539 |
def toImg(fmat, shape):
"""
TODO: azad mar. 04 févr. 2020 14:10:52 CET
Converts from fmat to img.
"""
img = np.zeros(shape)
try:
l, w, c = img.shape
for i in range(c): img[:,:,i] = np.reshape(fmat[0:,i],(l,w))
except ValueError:
try:
l, w = img.shape
... | 3ca37aed8e18d6a91bea1a1eb0c461c61be31d30 | 3,600,540 |
def extract_status_from_cell(cell_text):
"""
Extracts the candidates in the race from string.
:return: a list of (candidate, party, elected)
"""
tokenizer = RegexpTokenizer(".+?\(.+?\)")
tokens = tokenizer.tokenize(cell_text)
res = set()
for token in tokens:
token = token.strip(... | ee2b52ed9df85c71407724d984c85cfb3cfd19ae | 3,600,541 |
import os
import multiprocessing
def _step12_mcl(run_dir, mcl_input_file):
"""Markov Cluster Algorithm: http://www.micans.org/mcl/
Input:
mclInput file
Output:
mclOutput file
mcl my_orthomcl_dir/mclInput --abc -I 1.5 -o my_orthomcl_dir/mclOutput
"""
# Run mcl
mcl_dir = cr... | fa7e46a9ad6293ebb1bbd84dc9788ec879ffe694 | 3,600,542 |
def get_kwargs_geomark(data):
"""
:param data: ser data dict
:return: kwargs for development.DevelopmentGISLayer.geomark
"""
kwargs = {
# 'project': data.get('project', None),
'layer_type': 'geomark',
'geomark': data.get('location_n_geomark', None),
'notes': data.get(... | 14d294f624fd2e56eb8a5d36ab53662132ba94fc | 3,600,543 |
def horizon_block_estimator(data, d_u, k, horizon_length, func, **kwargs):
"""Horizon estimator, but in block format: so instead of estimating a rolling
horizon type of estimator, it is done on separate blocks.
"""
#calculate how many blocks are in the data
block_number = int(np.floor(len(data)... | d2d4bf729eebab6a4fe077bcb15ee2c89bab409c | 3,600,544 |
def SeqFISH(use_test_data: bool = False) -> Experiment:
"""
Loads a single field of view from a SeqFISH dataset generated from cultured mES cells. These
data are published:
`<https://doi.org/10.1016/j.cell.2018.05.035>`_
This dataset contains 1140 images acquired across 12 channels, 4 imaging roun... | af88f6beb95572c268b6321b5c01d4774e61ebbb | 3,600,545 |
def isfloat(x):
"""Returns True if input is a float; False otherwise.
Parameters
----------
x : any
Input can be of any type.
Returns
-------
y : bool
True is `x` is a float, False otherwise.
Notes
-----
A table showing what isfloat returns for various types:
... | c14a54924c83a1791a418d846a8f4981e0f94a2f | 3,600,546 |
def TKN(token, wsL='', wsR=r'\s*'):
"""Syntactic Sugar for 'Series(Whitespace(wsL), Text(token), Whitespace(wsR))'"""
return withWS(lambda: Text(token), wsL, wsR) | f3411ddb9cc01534b2bb652ab62509cfdd293f8f | 3,600,547 |
def getScreen():
"""Takes a screenshot and saves it as screenshot.png in the current
working directory"""
img=ImageGrab.grab()
img.save("screenshot.png")
return("screenshot.png") | 1b07b33e97b10d4c0f79e6ab162e5a74da45bbb0 | 3,600,548 |
def make_date(last="1 year"):
"""Function that generates a value for a DateType field.
Parameters
----------
last : str
Interval for generated date relative to current timestamp.
Default: '1 year'
Returns
-------
datetime.date.Date
"""
return make_timestamp(last).d... | 95a46d6d69d745f00293b2d7cdaf6ebb8dd136b9 | 3,600,549 |
from typing import Dict
import socket
def create_labels(platform: Platform) -> Dict[str, str]:
"""Returns dict of topology and hostname labels"""
labels = dict()
# Topology labels
labels["sockets"] = str(platform.sockets)
labels["cores"] = str(platform.cores)
labels["cpus"] = str(platform.cpus... | 7f519ef9dc41a82639b69ad99e99ba0363454cc9 | 3,600,550 |
def insert_replacement_rows(df, replacement_rows_dict):
"""
A trick (suggested at https://stackoverflow.com/a/63736275/2668831)
to insert rows with floating point row index to put them between
the (standard, integer-valued) existing row indices.
This is vectorised using numpy linspace (omitting the... | c7fa17d3b19cfbfa9e8ac29ec15f22c85baa3a09 | 3,600,551 |
import warnings
def init_detector(config, checkpoint=None, device='cuda:0'):
"""Initialize a detector from config file.
Args:
config (str or :obj:`mmcv.Config`): Config file path or the config
object.
checkpoint (str, optional): Checkpoint path. If left as None, the model
... | d2d52e31aadf6a5aaeaa7bf9fe372c4b55bd443a | 3,600,552 |
import os
def get_fasta(code, spec_name, work_dir="./", alternative_name=""):
"""
Try to find cDNA fasta file among our 3 searching methods.
Alternative name for the method using name to find fasta. Alternative name is then the only one tested.
"""
try : #Find through assembly ID
obj ... | 7b1ece6522ad4bbb94ee6adb0ea2befa1f19ca97 | 3,600,553 |
def fibonacci(number:int) -> int:
"""
Returns the n'th fibonacci sequence number
>>> fibonacci(number=10)
55
"""
# Initializing Magic Matrix
a = [[1, 1, ], [1, 0]]
# Initializing Identity Matrix
res = [[1, 0], [0, 1]]
# Fast Exponentiation (log(n) complexity)
while... | 636f2138a9e9396aaf238984a0b439e7b6bd740b | 3,600,554 |
from datetime import datetime
def day_ahead_belief_about_ex_post_time_slot_event(
ex_post_time_slot_sensor: Sensor, test_source_a: BeliefSource
):
"""Define day-ahead belief about an ex post time slot event."""
return TimedBelief(
source=test_source_a,
sensor=ex_post_time_slot_sensor,
... | 0113b08140839a01f61a757fbd8ad0285998e570 | 3,600,555 |
def get_docker_details(args):
"""
:type args: CommonConfig
:rtype: dict[str, any]
"""
docker = find_executable('docker', required=False)
info = None
version = None
if docker:
try:
info = docker_info(args)
except SubprocessError as ex:
display.warn... | 4051e90ffa2d8d573ddc5583a3bf15357c461dd3 | 3,600,556 |
from IPython import get_ipython
def is_ipython() -> bool:
"""Check if script is executed in IPython (incl. Jupyter)
Examples:
>>> is_ipython()
True
Returns:
bool: [description]
"""
try:
except BaseException:
return False
if get_ipython() is not None:
... | 1fd1d1d3f0250e61b1fc93d8ca4ffd7bd2928ca5 | 3,600,557 |
def create_model_name(src):
"""Generate a name for a source object given its spatial/spectral
properties.
Parameters
----------
src : `~fermipy.roi_model.Source`
A source object.
Returns
-------
name : str
A source name.
"""
o = ''
spatial_type = src['S... | d305dd26bc6017f3fce5db2a5267fa6e74df3bc6 | 3,600,558 |
def _det_and_inv(A):
"""Get matrix det and inv, with special cases for small matrices"""
if tt.eq(A.ndim, 0):
det = A
inv = 1/A
elif tt.eq(A.shape, (1,1)):
det = A[0,0]
inv = 1/A
else:
det = tt.nlinalg.det(A)
inv = tt.nlinalg.matrix_inverse(A)
return... | 735f9341c285ce015d11efccc2565531a5af50d1 | 3,600,559 |
from typing import Union
from pathlib import Path
from typing import Literal
from typing import Tuple
import os
def load_xp(path: Union[str, Path], order: Literal["C", "F"] = "C") -> Tuple[Console, ...]:
"""Load a REXPaint file as a tuple of consoles.
`path` is the name of the REXPaint file to load.
Usua... | 97535908bb7d7f217afa585ce146ecbb0e23289e | 3,600,560 |
def sha384(data: __Union[str, bytes]) -> str:
"""Returns hexadecimal representation of sha384 hashed data"""
if isinstance(data, str):
data = data.encode("utf-8")
return __hashlib.sha384(data).hexdigest() | d68f714ff38d3ac77c62f9a114508fe029500cc3 | 3,600,561 |
def hanning_filter(gtab, filter_width):
""" create a hanning window
The signal is premultiplied by a Hanning window before
Fourier transform in order to ensure a smooth attenuation
of the signal at high q values.
Parameters
----------
gtab : GradientTable
filter_width : int
Return... | febd5c6f7808a19903cb6dc6b7b49236e9f1d5a0 | 3,600,562 |
def dtype(x):
"""Returns the dtype of a Keras tensor or variable, as a string.
# Arguments
x: Tensor or variable.
# Returns
String, dtype of `x`.
# Examples
```python
>>> from keras import backend as K
>>> K.dtype(K.placeholder(shape=(2,4,5)))
'float32'
... | 94669336a40b956d7d2291970de085ecab00b4cb | 3,600,563 |
def _CreateSwarmingArgs(build,
suite,
board,
priority,
timeout_mins=None,
run_skylab=False):
"""Create args for swarming client.
Args:
build: Name of the build, will be part of the swarming t... | 28fa89fd713016f4b86d18b77fa55344f267f282 | 3,600,564 |
def get_theme(theme_id, api_key=None):
"""
Gets details about specific set theme.
Args:
theme_id: str or int
Rebrickable theme ID.
api_key: str or None
Rebrickable API access key. If set to None the one set by
rebrick.init() is used.
... | 847653d5ba28ea4f8cd48ff842b342b8a9e52540 | 3,600,565 |
def csv_to_list(value):
"""
Converts the given value to a list of strings, spliting by ',' and removing empty strings.
:param str value: the value to split to strings.
:return: a list of strings.
:rtype: List[str]
"""
return list(filter(None, [x.strip() for x in value.split(',')])) | dbfb90dccf8d48a46f528ca02e958306e8dcc266 | 3,600,566 |
def load_population_data():
"""Load and prepare country populations with same keys as covid19 data."""
# Load population data
populations_counties = pd.read_csv('https://www2.census.gov/programs-surveys/popest/datasets/'
'2010-2019/counties/totals/co-est2019-alldata.cs... | cd8cf9ebcc1e1a1890b20d02c2e4611f8035858b | 3,600,567 |
from pathlib import Path
import os
def collect_leaf_paths(root_paths):
"""Collects all paths to leaf folders."""
leaf_paths = [p for p in Path(root_paths).glob('**') if not os.walk(p).__next__()[1]]
return leaf_paths | 0c75bb94211710b156460702a8135448543f938d | 3,600,568 |
def calc_CP_fit_fraction(sess, pdf_particle, pdf_antiparticle, x, switches, norm_sample):
"""
Calculate CPC and CPV fit fractions for PDF components
sess : TF session
pdf_particle : PDF of particle decay
pdf_antiparticle : PDF of anti-particle decay
x ... | 2f1b6c92578dc5416e6f8e0e57340f7d13da7b20 | 3,600,569 |
def expand_quantized(sample, feat_idxs):
"""
Get the neighbouring value (shift '1' right and left) in a quantized one-hot feature vector.
:param sample: Initial node.
:type sample: numpy array.
:param feat_idxs: Indexes pointing to transformable features in the sample array.
:type feat_idxs: nu... | 86e95bee22b89be10a5fade8493b051a009abe27 | 3,600,570 |
def is_primary() -> bool:
"""Is Primary Device"""
return get_rank() == 0 | e0c43bf971988407d1392fb457fb3ca0be53c729 | 3,600,571 |
def action(name=None, permission=None, methods=None):
"""
Mark decorated method to be accesible as an action.
#TODO: Document arguments.
"""
def inner_action(func):
return add_action_info(
func,
name=name,
permission=permission,
methods=metho... | 4eff55bf4cf068a53bd6db44fb78024d9a42d249 | 3,600,572 |
def advect(dens, dx, dy, dt, u):
"""
second-order upwind method for 2d advection
Advects density in some subdomain by velocity u,
given timestep dt and grid spacing (dx, dy).
"""
gradx = np.zeros_like(dens)
grady = np.zeros_like(dens)
if u[0] > 0.:
gradx[2:, :] = (3*dens[2:, :] ... | a90bf3678115246556cf8c63cd603d57007bd182 | 3,600,573 |
import os
def store_uploaded_file(title, uploaded_file):
""" Stores a temporary uploaded file on disk """
upload_dir_path = '%s/static/taskManager/uploads' % (
os.path.dirname(os.path.realpath(__file__)))
if not os.path.exists(upload_dir_path):
os.makedirs(upload_dir_path)
# A1: Injec... | 5c6234a3259ea5ed682046ffb0cd3e00d1e839cd | 3,600,574 |
def load_labels_as_index(label_filename):
"""
Load a set of labels (with no attached vectors) from a text file, and
represent them in a pandas Index.
"""
labels = [line.rstrip('\n') for line in open(label_filename, encoding='utf-8')]
return pd.Index(labels) | 950cd2dae2f920e4afe894c91328fecaea05c078 | 3,600,575 |
def omp_get_dynamic():
"""Return the value of the dyn-var ICV, which determines whether \
dynamic adjustment of the number of threads is enabled or disabled.
This routine returns 1 if dynamic adjustment of the number of threads
is enabled for the current task; it returns 0, otherwise. If an
i... | 1a93b85905be8397ba6077b031903d36b519f93d | 3,600,576 |
def MACD(ds, count, fastperiod=-2**31, slowperiod=-2**31, signalperiod=-2**31):
"""Moving Average Convergence/Divergence"""
ret = call_talib_with_ds(ds, count, talib.MACD, fastperiod, slowperiod, signalperiod)
if ret is None:
ret = (None, None, None)
return ret | 4a917ffcf070d7cacd831dc7873f2e5d34bdba81 | 3,600,577 |
import math
def plot_all_params(predictions_dict, method='best', weighting='exp'):
"""Plots mean and variance bar graphs for all the sampled params for different (scenario, config).
It is assumed that the user provides a dict with 1st layer of keys as the scenarios and 2nd layer
of keys as the con... | c103e306474d425d89804e26d0c8e91a7050b4b1 | 3,600,578 |
def Main():
"""
:return:
"""
a = 1
b = 2
c = a + b
return c | 6482b416105d1ba23f564d6a47a52b7cba9c38bc | 3,600,579 |
def input_stream(fd, sze, url, params):
"""Opens a StringIO whose data is everything after the url scheme.
For example, `raw://hello_world` would return `hello_world` when read by the task.
"""
return (cStringIO.StringIO(url[6:]), len(url) - 6, url) | d0c0af167669bfd5755de15e6cc091df6637152c | 3,600,580 |
def _describe(in_fc):
"""Simply return the arcpy.da.Describe object.
**desc.keys()** an abbreviated list::
'OIDFieldName'... 'areaFieldName', 'baseName'... 'catalogPath',
'dataType'... 'extent', 'featureType', 'fields', 'file'... 'hasM',
'hasOID', 'hasZ', 'indexes'... 'lengthFieldName'... 'name', ... | 58bcad583514ff82e7ef3e8ce3f678f1081d28fd | 3,600,581 |
def users_login():
""" Login page """
if current_user.is_authenticated():
return redirect(url_for('gallery_home'))
form = LoginForm()
if form.validate_on_submit():
user = User.find_by_name(form.username.data)
if user is None or not user.is_valid_password(form.password.data):
... | 62d2e4a8eedd32e7b57f919bb23acba34cffae8e | 3,600,582 |
def trim_walkers(res, threshold=-1e4):
"""Remove walkers with probability below some threshold. Useful for
removing stuck walkers
"""
good = res['lnprobability'][:, -1] > threshold
trimmed = {}
trimmed['chain'] = res['chain'][good, :, :]
trimmed['lnprobability'] = res['lnprobability'][good,... | ba8e3ebbb2c6948be06d4d1bbd3871011763d71c | 3,600,583 |
def train_step(model, optimizer, batch, n_actions):
"""1 step optimize policy."""
obsers, actions, weights = batch
actions_mask = tf.one_hot(actions, n_actions)
with tf.GradientTape() as tape:
# log(a|s) R(tau)
logits = model(obsers)
log_probs = tf.reduce_sum(actions_mask * tf.... | ce86de0759669460fc6c2acd6f859755b8aac417 | 3,600,584 |
import copy
def printcc (lst,extra=2):
"""
Prints a list of lists in columns, customized by the max size of items
within the columns (max size of items in col, plus 'extra' number of spaces).
Use 'dashes' or '\\n' in the list-of-lists to print dashes or blank lines,
respectively.
Usage: printcc (lst,extra=2)
R... | c432de7c0213e370c1f565b20579f691b716e4cd | 3,600,585 |
def get_zip_location_map():
"""make dictionaries taking zip code to province and municipality
"""
bmap = pd.read_csv("../Belgium-Geographic-Data/dist/metadata/be-dictionary.csv",error_bad_lines=False)
bmap["PostCode"] = bmap["PostCode"].astype(int,errors='ignore')
pro = {}
mun = {}
fn = { "... | 2f2064dd73d809b0fabf01bf6e8930b5371639a3 | 3,600,586 |
def _str_eval_true(eval, act, ctxt) :
"""Returns false."""
return [False] | eb0fd9b576b55133319752f86750159c9684ba0c | 3,600,587 |
def CalculateMaxAtomTypeEState(mol):
"""
#################################################################
Calculation of maximum of E-State value of specified atom type
res---->dict type
Usage:
result=CalculateMaxAtomTypeEState(mol)
Input: mol is a molecu... | ecdb2eb9db340eef0725941fd22eeba1b6a73933 | 3,600,588 |
import os
def get_cred_from_file(key):
"""Read credential information from a file."""
filepath = os.path.join(os.path.expanduser('~'), '.%s' % key)
with open(filepath) as f:
return f.read().rstrip() | b19d2bd27d336a939dab51d9781768cee30bdbd3 | 3,600,589 |
def swapaxes(dat, ax1, ax2):
"""Swap axes of a Data object.
This method swaps two axes of a Data object by swapping the
appropriate ``.data``, ``.names``, ``.units``, and ``.axes``.
Parameters
----------
dat : Data
ax1, ax2 : int
the indices of the axes to swap
Returns
---... | 576ec10826c3ab92465052edcadf38cf04952c02 | 3,600,590 |
def update_weight(y, unsupervised_weight, next_weight):
"""update weight of the unsupervised part of loss"""
y[:, -1] = next_weight
unsupervised_weight[:] = next_weight
return y, unsupervised_weight | c961714c248ba4c0f752be568115e444e1d963e2 | 3,600,591 |
def pad(image, ts=0, bs=0, ls=0, rs=0, color=(0, 0, 0)):
"""Pads the image through adding pixels to each side of the image.
params:
image: A numpy ndarray, which has 2 or 3 dimensions
ts: An integer, which is the amount to pad the top side
of the image
bs: An integer, which i... | 6acc2b3f97a4aeaf98a524434d646fa12c2eb6c5 | 3,600,592 |
import re
def find_slug(url, prefix, postfix):
"""Извлекает slug из url по известным границам prefix, postfix"""
pattern = f'{prefix}.+{postfix}'
slug = re.search(pattern, url).group()
return slug.lstrip(prefix).rstrip(postfix) | 7fb0b99989ef05f83b370b0c40c7e82c05e51ab7 | 3,600,593 |
def initial_basin_chain(HB_gdf, cl_gdf, buf_wid=0.1):
"""
Finds the chain of drainage basins from the upstream-most centerline point
to the sink (e.g. ocean).
Parameters
----------
HB_gdf : GeoDataFrame
[description]
cl_gdf : GeoDataFrame
Centerline coordinates
buf_wid :... | 30141717fe7e0ae6218492a1c97271867107ee5a | 3,600,594 |
def send_dronelog(dronelog):
"""Post the drone log to the central server."""
try:
post_dronelog = RES_CS.find_suitable_operation(
SCHEMA.AddAction, CENTRAL_SERVER.DroneLog)
resp, body = post_dronelog(dronelog)
assert resp.status in [200, 201], "%s %s" % (resp.status, resp.re... | 9e3f901bc41182620e8d90809be75b930213ddb9 | 3,600,595 |
def data_augmentation(original_image, original_mask):
"""进行样本和掩膜的随机增强
Args:
original_image: 原始图片
original_mask: 原始掩膜
Return:
image_aug: 增强后的图片
mask_aug: 增强后的掩膜
"""
original_height, original_width = original_image.shape[:2]
augmentations = Compose([
Ho... | b6436b895d5657c75a8e892caea51996225347e8 | 3,600,596 |
import select
def populate_past_github(db, org, include_list): # noqa: C901
"""
PSEUDOCODE:
- 1. Query github api for org string that was passed
- 2. Query repos(projects) in that organization via the repos_url
- a. Create a Project for each repo via the project processor
... | 30336f59a9dfaaf98fad2712a2bfd0c3898650be | 3,600,597 |
import re
def is_url(value):
"""Return whether or not given value is a valid URL."""
regex = re.compile(
r"^"
# startchar <
r"<?"
# protocol identifier
r"(?:(?:https?|ftp)://)"
r"(?:"
r"(localhost)"
r"|"
# host name
r"(?:(?:[a-z\... | 3a50e541a9e62156a89693d15d248080abb3718f | 3,600,598 |
import random
def greedy_file_select(aud_len, aud_files):
"""
Select x number of files greedily till aud_len is satisfied
Args:
Returns:
"""
len_sofar = 0
files_sofar = []
total_aud_ixs = list(range(len(aud_files)))
while True:
rand_ix = random.sample(total_aud_ixs, 1)[... | da947a88e43af576c3aeb6fc23bb9c072f612872 | 3,600,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.