content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def getNameFromAdcode(adcode):
"""
根据adcode(行政区编码)获取下级行政区名称
:param adcode:
:return:
{'name': ['北京市'],
'sub': ['东城区',
'西城区',
'朝阳区',
'丰台区',
'石景山区',
'海淀区',
'门头沟区',
'房山区',
'通州区',
'顺义区',
'昌平区',
'大兴区',
'怀柔区',
'平谷区',
'密云区',
'延庆区']}
"""
url = 'https://webapi.amap.com/u... | 5,295,100 |
def _process_entity(request, name, param_parser, key_translations):
"""Procesa una request GET o POST para consultar datos de una entidad.
En caso de ocurrir un error de parseo, se retorna una respuesta HTTP 400.
En caso de ocurrir un error interno, se retorna una respuesta HTTP 500.
Args:
requ... | 5,295,101 |
def compute_mean_sem(df, key='fold_change'):
"""
Computes the mean and standard error of the fold-change given a
grouped pandas Series.
"""
# Compute the properties
mean_val = df[key].mean()
sem_val = df[key].std() / np.sqrt(len(df))
# Assemble the new pandas series and return.
samp... | 5,295,102 |
def iplotConn(includePre=['all'], includePost=['all'], feature='strength', orderBy='gid', figSize=(10,10), groupBy='pop', groupByIntervalPre=None, groupByIntervalPost=None, removeWeightNorm=False, graphType='matrix', synOrConn='syn', synMech=None, connsFile=None, tagsFile=None, clim=None, fontSize=12, saveData=None, sa... | 5,295,103 |
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the classifier."""
save_file_folder = config.get(CONF_SAVE_FILE_FOLDER)
if save_file_folder:
save_file_folder = Path(save_file_folder)
if DATA_TORCHSERVE not in hass.data:
hass.data[DATA_TORCHSERVE] = []
... | 5,295,104 |
def main() -> int:
"""
Handle program invocation.
:returns: Exit code.
"""
logger.info('Initialising Database Connection')
db = ed_bgs.Database(config['database']['url'], logger)
ebgs = ed_bgs.EliteBGS(logger, db)
# return None
# Looping over monitored factions
for f in config['monitor_factions']:... | 5,295,105 |
def stop_vm(client, session, vm, params):
"""Stop an existing virtual machine. It will fail if the virtual machine does
not exist."""
if vm['state'] is None:
return { 'failed': True, 'msg': NOT_EXISTS_ERR }
if vm['state'] in ('hold', 'stopped'):
return { 'changed': False, 'vm_id': vm['id... | 5,295,106 |
def accuracy(predictions, labels):
"""
Evaluate accuracy from model predictions against ground truth labels.
"""
ind = torch.argmax(predictions, 1)
# provide labels only for samples, where prediction is available (during the training, not every samples prediction is returned for efficiency reasons)
... | 5,295,107 |
def _quick_reap():
"""Reaps a task."""
data = _gen_request_data(
properties=dict(dimensions={u'OS': u'Windows-3.1.1'}))
request = task_request.make_request(data)
_result_summary = task_scheduler.schedule_request(request)
reaped_request, run_result = task_scheduler.bot_reap_task(
{'OS': 'Windows-3.... | 5,295,108 |
def read_and_calculate(workspace, pdb_paths):
"""
Calculate a variety of score and distance metrics for the given structures.
"""
# Parse the given restraints file. The restraints definitions are used to
# calculate the "restraint_dist" metric, which reflects how well each
# structure achieves... | 5,295,109 |
def closure(func: Callable) -> Callable:
"""Wrap a method to eliminate the self keyword from its signature."""
# tried using @functools.wraps, but could not get it to work right
def wrapped(*args, **kwargs):
self = args[0]
if len(args) > 1:
args = args[1:]
else:
... | 5,295,110 |
def dynamic_stub(end, group, cardinalities, pool):
"""Creates an face.DynamicStub.
Args:
end: A base.End.
group: The group identifier for all RPCs to be made with the created
face.DynamicStub.
cardinalities: A dict from method identifier to cardinality.Cardinality
value identifying the card... | 5,295,111 |
def get_issns_for_journal(nlm_id):
"""Get a list of the ISSN numbers for a journal given its NLM ID.
Structure of the XML output returned by the NLM Catalog query::
NLMCatalogRecordSet
NLMCatalogRecord
NlmUniqueID
DateCreated
DateRevised
DateAu... | 5,295,112 |
def encode(lng, lat, precision=10, bits_per_char=6):
"""Encode a lng/lat position as a geohash using a hilbert curve
This function encodes a lng/lat coordinate to a geohash of length `precision`
on a corresponding a hilbert curve. Each character encodes `bits_per_char` bits
per character (allowed are 2... | 5,295,113 |
def filter_form(context, *args, **kwargs):
"""Тег представления filter form как таблицы.
"""
filter_form = (args[0] if len(args) > 0
else kwargs.get('filter'))
if not filter_form:
filter_form = context.get('filter')
if filter_form is None:
raise TemplateSyntaxErr... | 5,295,114 |
def test_equivalencies():
"""
Test that after import `u.spectral` equivalencies are not enabled in the global namespace.
"""
assert u.micron.is_equivalent(u.cm**-1) is False
assert u.micron.is_equivalent(u.Hz) is False
assert u.micron.is_equivalent(u.eV) is False
assert u.Hz.is_equivalent(u.... | 5,295,115 |
def test_set_m_after_relaxation(tmpdir):
"""
Check that Simulation.set_m changes the magnetisation for relaxation
even after some integration has taken place.
A system with two obvious stable states for "each spin" is
initialised; one in which the spin points in the +Z direction,
and one in whi... | 5,295,116 |
def test_lr_monitor_multi_lrs(tmpdir, logging_interval: str):
""" Test that learning rates are extracted and logged for multi lr schedulers. """
tutils.reset_seed()
class CustomBoringModel(BoringModel):
def training_step(self, batch, batch_idx, optimizer_idx):
return super().training_s... | 5,295,117 |
def non_max_suppression_bbox(bboxes, confidences, img_size, verbose=False):
"""
high confidence detections suppress all overlapping detections (including
detections at other scales). Detections can partially overlap, but the
center of one detection can not be within another detection.
:param bboxes: Nx4 nump... | 5,295,118 |
def inet_ntoa(i):
"""Convert an int to dotted quad."""
return '.'.join(map(str, [(i >> (3-j)*8) & 0xff for j in range(4)])) | 5,295,119 |
def cleanup_string(string):
"""
>>> cleanup_string(u', Road - ')
u'road'
>>> cleanup_string(u',Lighting - ')
u'lighting'
>>> cleanup_string(u', Length - ')
u'length'
>>> cleanup_string(None)
''
>>> cleanup_string(' LIT ..')
'lit'
>>> cleanup_string('poor.')
'poor'
... | 5,295,120 |
def test_group_silverkite_seas_components():
"""Tests group_silverkite_seas_components"""
silverkite_diagnostics: SilverkiteDiagnostics = SilverkiteDiagnostics()
time_col = "ts"
# Daily
date_list = pd.date_range(start="2018-01-01", end="2018-01-07", freq="H").tolist()
time_df = build_time_featur... | 5,295,121 |
def dem_mosaic_custom(output_directory,
verbose=False,
print_asp_call=False):
"""
Function to run ASP dem_mosaic.
"""
output_file = os.path.join(output_directory,'mosaic.tif')
stereo_output_directory = os.path.join(output_directory, 'stereo/stereo_run... | 5,295,122 |
def termConvection(t, y, schemeData):
"""
termConvection: approximate a convective term in an HJ PDE with upwinding.
[ ydot, stepBound, schemeData ] = termConvection(t, y, schemeData)
Computes an approximation of motion by a constant velocity field V(x,t)
for a Hamilton-Jacobi PDE (often calle... | 5,295,123 |
def is_field_allowed(name, field_filter=None):
"""
Check is field name is eligible for being split.
For example, '__str__' is not, but 'related__field' is.
"""
if field_filter in ["year", "month", "week", "day", "hour", "minute", "second"]:
return False
return isinstance(name, s... | 5,295,124 |
def run():
"""Requirements for task 2G"""
# a severity of moderate includes all currently active flood warnings
# severity.low includes warnings which were in force in the past 24 hours
stations = build_station_list()
update_water_levels(stations)
severity = SeverityLevel.moderate
print("... | 5,295,125 |
def build(help: dict) -> str:
"""Returns the formatted help string. See the GitHub page for info."""
global _cust_config
final_str = ""
terms = help["terms"]
if "config" in help:
_cust_config = help["config"]
else:
_cust_config = {}
# Terms
for term in terms:
if... | 5,295,126 |
def setup_logger(level):
"""
Setup a logger for the REST handler
"""
logger = logging.getLogger('splunk.appserver.lookup_editor.rest_handler')
logger.propagate = False # Prevent the log messages from being duplicated in the python.log file
logger.setLevel(level)
log_file_path = make_splunk... | 5,295,127 |
def _makePermission(perm, model, app_label='editorialmanager'):
"""
Retrieves a Permission according to the given model and app_label.
"""
from django.contrib.contenttypes import models
from django.contrib.auth import models as auth_models
ct = models.ContentType.objects.get(model=model, app_la... | 5,295,128 |
def greater_equal(lhs, rhs):
"""Broadcasted elementwise test for (lhs >= rhs).
Parameters
----------
lhs : relay.Expr
The left hand side input data
rhs : relay.Expr
The right hand side input data
Returns
-------
result : relay.Expr
The computed result.
"""
... | 5,295,129 |
def mergeVotingResult(vote: List[int], policevote: Optional[int] = None) -> Dict[int, float]:
"""
Count the vote result and the return the candidates with most votes
### Parameter
- vote: `List[int]`, the vote result
### Return
`List[int]`, the candidates with most votes
"""
voteList... | 5,295,130 |
def _create_dummy_zip_file():
"""
This function creates a dummy zip file and returns a path to the file
"""
text_file_path = _create_temp_file()
zip_file_path = _create_temp_file()
with zipfile.ZipFile(zip_file_path, "w") as zip_file:
zip_file.write(text_file_path)
os.remove(text_f... | 5,295,131 |
def testNumCommandOverflow(env):
"""Test JSON.NUMINCRBY and JSON.NUMMULTBY commands overflow """
r = env
if IS_SERDE_JSON:
env.skip()
# test overflow on root
r.assertOk(r.execute_command('JSON.SET', 'big_num', '.', '1.6350000000001313e+308'))
r.expect('JSON.NUMINCRBY', '... | 5,295,132 |
def get_avatar(burl, height):
""" xxx """
return_data = ''
uid = user_get_uid()
avatar_id = 0
connection = pymysql.connect(host=DB_SRV,
user=DB_USR,
password=DB_PWD,
db=DB_NAME,
... | 5,295,133 |
def signup():
"""
Presents an anonymous user with the registration form and adds their info to the database.
Uses user.set_password() to hash their password (instead of storing it plaintext).
"""
if current_user.is_authenticated:
return redirect(url_for('index'))
form = RegistrationForm... | 5,295,134 |
def update_version(jira_host, username, password, version_id, body):
"""
Updates specific version.
jira_host -- JIRA host to contact.
username -- JIRA username with administrative permissions.
password -- password of the username.
version_id -- version which should be updated.
body -- new v... | 5,295,135 |
def read_bdf(iterable):
"""
Read a BDF-format font from the given source.
iterable should be an iterable that yields a string for each line of the
BDF file - for example, a list of strings, or a file-like object.
"""
name = ""
pointSize = 0.0
resX = 0
resY = 0
comments = []
font = None
for line in iterabl... | 5,295,136 |
def parallel_apply(df, group_list, f, num_cores, print_every_n=1000, **kwargs):
"""
A lightweight version of apply using the multiprocess library
:param df: the pandas dataframe that needs to be grouped
:param group_list: a list of variable names to group by
:param f: the function that operates on ... | 5,295,137 |
def _do_generate_runner(endpoint):
"""
Get the hostname or IP of the runner.
Will try to get the public host name from AWS metadata first, then from
reverse lookup, and then fall back to using the local hostname
:return: An ip address or a hostname
:rtype: str
"""
try:
response... | 5,295,138 |
def set_home_exim_acl(owner: Owner) -> Collect[None]:
"""
Grant access to the user's ``.forward`` file for Exim.
"""
yield unix.set_nfs_acl(owner_home(owner), "Debian-exim@srcf.net", "RX") | 5,295,139 |
def basicConfig():
"""
Do basic configuration for the printing system by creating a
StreamHandler with a default Formatter and adding it to the
root logger.
"""
if len(print_root.handlers) == 0:
hdlr = logging.StreamHandler()
fmt = logging.Formatter(BASIC_FORMAT, style="{")
... | 5,295,140 |
def vectorized_is_element(array, choices):
"""
Check if each element of ``array`` is in choices.
Parameters
----------
array : np.ndarray
choices : object
Object implementing __contains__.
Returns
-------
was_element : np.ndarray[bool]
Array indicating whether each ... | 5,295,141 |
def what_am_I_from_prob(probabilities, no_of_guesses=5, true_class='', verbose=True):
"""Function to classify based on 'prob'ability layer inputs
probabilities: a vector of input probabilities
no_of_guesses: how many of the top probabilities do you want?
true_class: the real class name if known
outp... | 5,295,142 |
def main():
"""Main routine
"""
print("\nTesting raw_mosek")
print("====================")
print("m = n : ", args.n)
print("dataset: ", args.dataset)
if args.dataset == 'DOTmark':
print("class : ", args.imageclass)
print("method : ", args.method)
print("====================... | 5,295,143 |
def _parse_term_from_lists(
term_list: typing.List, networks: NetworkStore = None
) -> Term:
"""Term is a list where the first element is either a valid functor or the keyword 'list'.
If the first element is list, then this term is a list, we parse recursively all its elements and return them.
If the fi... | 5,295,144 |
def create_urine_features(charts):
""" features of urine color and appearance"""
res = charts.loc[charts.label.str.lower().str.contains('urine', na=False),
['hadm_id', 'eventtime', 'admittime', 'label',
'value', 'valuenum', 'unitname']]
# clean the label column
res['labe... | 5,295,145 |
def mavgen(opts, args) :
"""Generate mavlink message formatters and parsers (C and Python ) using options
and args where args are a list of xml files. This function allows python
scripts under Windows to control mavgen using the same interface as
shell scripts under Unix"""
import sys, textwrap, os
... | 5,295,146 |
def merge_user_settings(settings):
"""Return the default linter settings merged with the user's settings."""
user = settings.get('user', {})
default = settings.get('default', {})
if user:
tooltip_styles = default.get('tooltip_styles', {})
user_tooltip_styles = user.get('tooltip_styles',... | 5,295,147 |
def arrow3(location, target, length=None, clr="b"):
"""
Draw a 3D arrow using quiver.
Parameters
----------
location : numpy.ndarray
Starting point of the arrow
target : numpy.ndarray
Target point of the arrow
length : float (default: None)
Length of the arrow
cl... | 5,295,148 |
def RSRS1(dataFame, Sbuy=1.0, Ssell=0.8):
"""斜率指标交易策略
"""
data = dataFame.copy()
data['flag'] = 0 # 买卖标记
data['position'] = 0 # 持仓标记
position = 0 # 是否持仓,持仓:1,不持仓:0
for i in range(1, data.shape[0] - 1):
# 开仓
if data.loc[i, 'beta'] > Sbuy and position == 0:
data... | 5,295,149 |
def add_read_fields(parser: GooeyParser) -> None:
"""Add the read related fields to the GUI parser"""
read_group = parser.add_argument_group("Reading info")
read_group.add_argument(
"Starting date",
help="Pick the date when you started reading the book",
widget="DateChooser",
)
... | 5,295,150 |
def true_color_supported(env: Optional[Dict[str, str]] = None) -> bool:
"""Check if truecolor is supported by the current tty.
Note: this currently only checks to see if COLORTERM contains
one of the following enumerated case-sensitive values:
- truecolor
- 24bit
"""
... | 5,295,151 |
def rgb2gray(rgb):
"""
Change RGB color image into grayscale in RGB representation using colorimetric (perceptual luminance-preserving) conversion
:param rgb: NumPy array of the RGB image
:return: NumPy array of grayscale image, same shape as input
"""
r, g, b = rgb[:, :, 0]/255, rgb[:, :, 1]/2... | 5,295,152 |
def get_speech_features_from_file(filename,
num_features,
pad_to=8,
features_type='spectrogram',
window_size=20e-3,
window_stride=10e-3,
... | 5,295,153 |
def health() -> dict:
"""
Root Get
"""
health = schemas.Health(
name=settings.PROJECT_NAME, api_version=__version__, model_version=model_version
)
return health.dict() | 5,295,154 |
def site_response(sp, asig, linear=0, freqs=(0.5, 10), xi=0.03):
"""
Run seismic analysis of a soil profile - example based on:
http://opensees.berkeley.edu/wiki/index.php/Site_Response_Analysis_of_a_Layered_Soil_Column_(Total_Stress_Analysis)
Parameters
----------
sp: sfsimodels.SoilProfile ob... | 5,295,155 |
def calling(data):
"""Main function to parallelize peak calling."""
method = dd.get_chip_method(data)
caller_fn = get_callers()[data["peak_fn"]]
if method == "chip":
chip_bam = data.get("work_bam")
input_bam = data.get("work_bam_input", None)
name = dd.get_sample_name(data)
... | 5,295,156 |
def _try_community_name(row):
"""
Try to get community name from municipality description in other tables.
TODO: reverse geocode these instead?
"""
return row["MUNICIPALITY"].split("/")[0].replace(" Area", "") | 5,295,157 |
def _get_field_names(
schema_field_details: Tuple[Tuple[str, DataType], ...],
) -> Tuple[str, ...]:
"""Returns field names from schema fields."""
return tuple(field[0] for field in schema_field_details) | 5,295,158 |
def test_export_update_edits_dry_run():
"""test export then update after removing and editing files with dry-run flag"""
import glob
import os
import os.path
import shutil
import osxphotos
from osxphotos.cli import export
runner = CliRunner()
cwd = os.getcwd()
# pylint: disable... | 5,295,159 |
def strip_outer_matching_chars(s, outer_char):
"""
If a string has the same characters wrapped around it, remove them.
Make sure the pair match.
"""
s = s.strip()
if (s[0] == s[-1]) and s.startswith(outer_char):
return s[1:-1]
return s | 5,295,160 |
def trainval(exp_dict, savedir, args):
"""
exp_dict: dictionary defining the hyperparameters of the experiment
savedir: the directory where the experiment will be saved
args: arguments passed through the command line
"""
# Create data loader and model
train_set = datasets.get_dataset(
... | 5,295,161 |
def ParseAndUnwrap(code, dumptree=False):
"""Produces unwrapped lines from the given code.
Parses the code into a tree, performs comment splicing and runs the
unwrapper.
Arguments:
code: code to parse as a string
dumptree: if True, the parsed pytree (after comment splicing) is dumped
to ... | 5,295,162 |
def lr_schedule(step):
"""Linear scaling rule optimized for 90 epochs."""
steps_per_epoch = 30000 // FLAGS.batch_size
current_epoch = step / steps_per_epoch # type: float
lr = (1.0 * FLAGS.batch_size) / 32
boundaries = jnp.array((20, 40, 60)) * steps_per_epoch
values = jnp.array([1., 0.1, 0.01, 0.001]) * ... | 5,295,163 |
def make_chunks(infos, **kwargs):
"""Generate chunks from note infos"""
return s.chunked(make_sound(infos, **kwargs)) | 5,295,164 |
def get_sentence(lower=True):
"""Simple function to prompt user for input and return it w/o newline.
Frequently used in chat sessions, of course.
"""
sys.stdout.write("Human: ")
sys.stdout.flush()
sentence = input()
if lower:
return sentence.lower()
return sentence | 5,295,165 |
def water_to_image():
"""
Tests reading data from water file then generating waterrial map images
"""
data = water.read_water("assets/5000000000.water.extm")
water.generate_height_map(data, 'output/5000000000.water.extm.height.tiff')
water.generate_material_map(data, 'output/5000000000.water.ext... | 5,295,166 |
def plot_traces_by_qu_unexp_sess(analyspar, sesspar, stimpar, extrapar,
quantpar, sess_info, trace_stats, figpar=None,
savedir=None, modif=False):
"""
plot_traces_by_qu_unexp_sess(analyspar, sesspar, stimpar, extrapar,
... | 5,295,167 |
def test_commandobj_property_arg4():
"""Test: obj.arg4 is defined as the fifth positional argument"""
set_sys_argv()
c = Command()
assert c.arg4 == "shortdef" | 5,295,168 |
def to_cartesian(p, direction=1, axis='z'):
""" Converts a point given in (r, theta, z) coordinates to
cartesian coordinate system.
optionally, axis can be aligned with either cartesian axis x* or z and
rotation sense can be inverted with direction=-1
*when axis is 'x': theta goes from 0 at y-axis... | 5,295,169 |
def getLimits(locations, current, sortResults=True, verbose=False):
"""
Find the projections for each delta in the list of locations, relative to the current location.
Return only the dimensions that are relevant for current.
"""
limit = {}
for l in locations:
a, b = current.comm... | 5,295,170 |
def mclag_ka_session_dep_check(ka, session_tmout):
"""Check if the MCLAG Keepalive timer and session timeout values are multiples of each other and keepalive is < session timeout value
"""
if not session_tmout >= ( 3 * ka):
return False, "MCLAG Keepalive:{} Session_timeout:{} values not satisfying ... | 5,295,171 |
def ingest_datasets(butler, datasetType, datasets, collection, transfer="copy"):
""" Ingest datasets into a Gen3 butler repository collection.
Args:
datasetType (lsst.daf.butler.DatasetType): The refcat datasetType.
datasets (list of lsst.daf.butler.FileDataset): The refcat datasets.
col... | 5,295,172 |
def pack(fmt, *args):
"""pack() is wrapper of struct.pack
"""
value = struct.pack(fmt, *args)
result = []
if isinstance(value, str):
# For Python2
for v in value:
result.append(ord(v))
return result
elif isinstance(value, bytes):
# For Python3
... | 5,295,173 |
def get_teacher_information(gid):
"""
Retrieve the team information for all teams in a group.
Args:
gid: the group id
Returns:
A list of team information
"""
group = get_group(gid=gid)
member_information = []
for tid in group["teachers"]:
team_information = api.... | 5,295,174 |
def _filter_deprecation_warnings():
"""Apply filters to deprecation warnings.
Force the `DeprecationWarning` warnings to be displayed for the qiskit
module, overriding the system configuration as they are ignored by default
[1] for end-users. Additionally, silence the `ChangedInMarshmallow3Warning`
... | 5,295,175 |
def clear_shell():
"""Clear shell terminal."""
os.system('cls' if os.name == 'nt' else 'clear') | 5,295,176 |
def needs_owner(func):
"""Decorator to require the owner for the given function."""
@wraps(func)
def decorated_function(*args, **kwargs):
if args[0].chat.id != SETTINGS['owner']:
bot.reply_to(args[0], 'Sorry, you are not the owner of this bot')
return
return func(*ar... | 5,295,177 |
def decompose_to_device(operation: cirq.Operation, atol: float = 1e-8) -> cirq.OP_TREE:
"""Decompose operation to ionq native operations.
Merges single qubit operations and decomposes two qubit operations
into CZ gates.
Args:
operation: `cirq.Operation` to decompose.
atol: absolute er... | 5,295,178 |
def lucas(n):
""" compute the nth Lucas number """
a, b = 2, 1 # notice that all I had to change from fib were these values?
if n == 0:
return a
for _ in range(n - 1):
a, b = b, a + b
return b | 5,295,179 |
def do_map_eval(B, S, param, O, W = None, BGp = None):
""" This function evaluate the target function
given a output window set.
Args:
B: .
S: .
param: .
O: .
W: .
BGp: .
Returns: statTmp: .
"""
statTmp = {}
statTmp['W'] = np.array([])
statTmp['Xp'] =... | 5,295,180 |
def io_write_dout(conx: Connection, idx: int, val: bool) -> None:
"""Write 'val' to 'DOUT[idx]'.
:param idx: Index to write to
:type idx: int
:param val: Value to write
:type val: int
"""
io_write(conx, 'DOUT', idx, 1 if val else 0) | 5,295,181 |
def transform_disturbances(draws, shocks_mean, shocks_cholesky):
"""Transform the standard normal deviates to the relevant distribution."""
draws_transformed = draws.dot(shocks_cholesky.T)
draws_transformed += shocks_mean
draws_transformed[:, :2] = np.clip(
np.exp(draws_transformed[:, :2]), 0.... | 5,295,182 |
def double_c_array_or_none(seq):
"""If seq is None, returns None, else same as `double_c_array`."""
if seq is None:
yield None
else:
with double_c_array(seq) as arrayptr:
yield arrayptr | 5,295,183 |
def predict_one_scan_binary_class(rescaled_array, direction, checkpoint_path, array_info, batch_size=16, evaluate=False):
"""
:param array_info: stores information of the rescaled_array
:param rescaled_array: float32 array in shape [512, 512, 512, data_channel + enhanced_channel + semantic_channel]
or i... | 5,295,184 |
def shuffle_batch(labeled_tensors,
batch_size,
num_threads=1,
capacity=32,
enqueue_many=False,
min_after_dequeue=0,
seed=None,
allow_smaller_final_batch=False,
name=Non... | 5,295,185 |
def test_handle_host_deletion_commands(host, func_mock, direction_color, url_suffix):
"""
Given:
- (case1) A valid args and a single host to remove input
- (case2) A valid args and multiple hosts to remove input (comma seperated)
When:
- Running host deletion co... | 5,295,186 |
def natural_keys(text: str) -> Tuple[Union[int, str], ...]:
"""
alist.sort(key=natural_keys) sorts in human order
:see: http://nedbatchelder.com/blog/200712/human_sorting.html
:see: http://stackoverflow.com/a/5967539/1391325
"""
return tuple(__atoi(c) for c in __DIGITS_PATTERN.split(text)) | 5,295,187 |
def return_dict_of_attrs(obj):
"""
Returns dictionary of attributes of object that are not private or None,
and which top namespace is not sqlalchemy or wpipe.
Parameters
----------
obj
Input object.
Returns
-------
attrs : dict
Dictionary of attributes of obj.
... | 5,295,188 |
def BenefitSurg(t):
"""Surgery benefits"""
return SizeBenefitSurg(t) * PolsSurg(t) | 5,295,189 |
def configure_server_module(mod_path):
"""
Configure elements that need to be added to the server for the provided module to be built
Parameters
__________
mod_path: Path to the package.
"""
global ADD_TO_CONFIG, USER_MODS
mod_cfg = mod_path + "/server/ServerModules.cfg"
# ak_... | 5,295,190 |
def _get_edge_attrs(edge_attrs, concat_qualifiers):
""" get edge attrs, returns for qualifiers always a list """
attrs = dict()
if "qualifiers" not in edge_attrs:
attrs["qualifiers"] = []
elif edge_attrs["qualifiers"] is None:
attrs["qualifiers"] = edge_attrs["qualifiers"]
if at... | 5,295,191 |
def destroy_raid_bdev(client, name):
"""Destroy pooled device
Args:
name: raid bdev name
Returns:
None
"""
params = {'name': name}
return client.call('destroy_raid_bdev', params) | 5,295,192 |
def get_closest_point_index(pt, pts):
""" Closest point index of the pts from pt. """
distances = [rs.Distance(p, pt) for p in pts]
min_index = distances.index(min(distances))
return min_index | 5,295,193 |
def show_box_plot(data, x_labels=None, y_label=None, fig_number=None, save_to_filename=None):
"""!
Show box plot
"""
fig = plt.figure(fig_number)
fig.clf()
ax = fig.add_subplot(111)
plt.boxplot(data)
plt.setp(ax, xticklabels=x_labels)
plt.ylabel(y_label)
plt.show(block=False)
... | 5,295,194 |
def IFS(FS, T0=2 * np.pi, m_start=-4, m_stop=4, x_min=0, x_max=2 * np.pi, x_num=10):
"""Function to reconstruct (or check) the periodic function from the
obtained Fourier coefficients"""
m = np.arange(m_start, m_stop + 1)
m = np.reshape(m, (-1, m.size))
M = np.tile(m, (x_num, 1))
x = np.linspa... | 5,295,195 |
def delete(params):
"""Deletes one user file metadata key as specified.
Future work should allow a list of files."""
dsid = params.get("--dsid", "missing_id")
name = params.get("--name", "__NO_NAME_")
rsp = server.file_keys.delete(dsid, name)
if rsp is None:
reportApiError(server, f"F... | 5,295,196 |
def get_rate_limit():
"""rate limit"""
method = 'GET'
path = '/open/api/v2/common/rate_limit'
url = '{}{}'.format(ROOT_URL, path)
params = {'api_key': API_KEY}
response = requests.request(method, url, params=params)
print(response.json()) | 5,295,197 |
def get_calendar(username, base_url='https://github.com/'):
"""retrieves the github commit calendar data for a username"""
base_url = base_url + 'users/' + username
try:
url = base_url + '/contributions'
page = urllib2.urlopen(url)
except (urllib2.HTTPError,urllib2.URLError) as e... | 5,295,198 |
def stop_comm_msg_create(pid: int, ts: float) -> message.Message:
"""
create a message to stop the comm_handler
:param pid: agent pid
:type pid: int
:param ts: timestamp
:type ts: float
:return: stop communication handler message
:rtype: Message
"""
return message.Message(pid,... | 5,295,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.