content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_api_client() -> Any:
"""Return API client for testing purpose."""
from medtagger.api.rest import app
app.testing = True
return app.test_client() | 50,600 |
def verify_ospf3_metric(device,
interface,
metric,
max_time=60,
check_interval=10):
"""Verify the OSPF3 metric
Args:
device (obj): Device object
interface (str): Interface name
metric (str): ... | 50,601 |
def _train_model_with_pretrained_vectors():
"""Generate toy-model-pretrained.bin for use in test_load_native_pretrained.
Requires https://github.com/facebookresearch/fastText/tree/master/python to be installed.
"""
import fastText
training_text = datapath('toy-data.txt')
pretrained_f... | 50,602 |
def parse_args():
# Taken from Fast R-CNN
"""Parse input arguments."""
parser = argparse.ArgumentParser(description='Train a Fast R-CNN network')
parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [0]',
default=0, type=int)
parser.add_argument(... | 50,603 |
def init_pepolar_estimate_wf(debug=False, generate_report=True, name="pepolar_estimate_wf"):
"""Initialize a barebones TOPUP implementation."""
from nipype.interfaces.afni import Automask
from nipype.interfaces.fsl.epi import TOPUP
from niworkflows.interfaces.nibabel import MergeSeries
from sdcflows... | 50,604 |
def copy_cache(
cache: t.Optional[t.MutableMapping],
) -> t.Optional[t.MutableMapping[t.Tuple[weakref.ref, str], "Template"]]:
"""Create an empty copy of the given cache."""
if cache is None:
return None
if type(cache) is dict:
return {}
return LRUCache(cache.capacity) | 50,605 |
def main():
"""Mainline function."""
mediaList = buildMediaList()
randomList = selectMedia(mediaList)
if len(randomList) > 0:
maybeDeleteOldPlaylist()
writePlaylist(mediaList, randomList) | 50,606 |
def get_plugins(metadata):
"""Return the registered plugins.
Load and return all registered plugins.
"""
plugins = load_plugins()
if not plugins:
raise NoPluginsError("No plugins found")
results = []
for p in sorted(plugins.get_all(), key=attrgetter("name")):
if metadata:
... | 50,607 |
def _ConvertUnmatchedResultsToStringDict(unmatched_results):
"""Converts |unmatched_results| to a dict of strings for reporting.
Args:
unmatched_results: A dict mapping builder names (string) to lists of
data_types.Result who did not have a matching expectation.
Returns:
A string dictionary repr... | 50,608 |
def _parse_map(parser, callback):
"""
Searches the stream of JSON tokens for key/value pairs.
Calls itself recursively to handle subdirectories.
:param parser: iterator, returning JSON parse event tuples.
:param callback: callback to call when a key/value pair is found.
"""
# Expect a sequ... | 50,609 |
def get_resource(chmod_permission, *paths):
"""Take a relative filepath and return the actual path. chmod_permission is
needed because our packaging might destroy the permission."""
full_path = os.path.join(os.path.dirname(__file__), *paths)
os.chmod(full_path, chmod_permission)
return full_path | 50,610 |
def get_color(r, g, b, a):
""" converts rgba values of 0 - 255 to the equivalent in 0 - 1 """
return (r / 255.0, g / 255.0, b / 255.0, a / 255.0) | 50,611 |
def atSendCmdSTTradeGetAccountList():
""" 获取策略测试的账户列表信息
:return: list of todotdict, eg: [todotdict{'Name':'', 'Handle':xxx, 'Status':'online'}]
"""
func_name = 'atSendCmdSTTradeGetAccountList'
atserial.ATraderSTTradeGetAccountList_send()
res = recv_serial(func_name)
return res.result | 50,612 |
def load_data(filename):
"""Load a binary data."""
path = os.path.join(os.path.dirname(__file__), "data", filename)
with open(path) as fptr:
return fptr.read() | 50,613 |
def escape_version(version):
"""
Escaped version in wheel filename. Doesn't exactly follow
the escaping specification in :pep:`427#escaping-and-unicode`
because this conflicts with :pep:`440#local-version-identifiers`.
"""
return re.sub(r"[^\w\d.+]+", "_", version, flags=re.UNICODE) | 50,614 |
def annotation(annot,
palette,
tlim=None,
y_segments=0.5,
seg_height=0.1,
y_labels=0.6,
t_shift_label=0.01,
patch_kwargs=None,
text_kwargs=None,
ax=None):
"""plot segments with labe... | 50,615 |
def union_degree(node_df, edge_df, degree_df, OD_full_path):
"""
Inputs:
node_df, edge_df - the node and edge specific df from get_specific_df
OD_full_path - output of shortest_path
degree_df - output of get degree df
Outputs:
edge_degree_df, node_degr... | 50,616 |
def test_categories_from_dates_with_offset(sample_data):
"""It should create a new column 'my_categories'"""
df = pd.DataFrame(sample_data)
expected = df.copy()
expected['my_categories'] = [
'Category 1',
'Category 1',
'Category 1',
'Category 1',
'Category 1',
... | 50,617 |
def paths(resources, resource_strip_prefix):
"""Return a list of path tuples (target, source) where:
target - is a path in the archive (with given prefix stripped off)
source - is an absolute path of the resource file
Tuple ordering is aligned with zipper format ie zip_path=file
Args:
... | 50,618 |
def register_lib(load_path: str):
"""Register a library of env_names with env_descs."""
global ENV_DESCS
if '.' not in load_path:
load_path = f'brax.experimental.composer.envs.{load_path}'
env_lib = importlib.import_module(load_path)
ENV_DESCS.update(env_lib.ENV_DESCS) | 50,619 |
def parseTagCompound( input, handler ):
"""
Reads a TAG_Compound from input.
Calls handler.startCompound().
For each entry in the TAG_Compound:
1. Reads the type and name of the entry from input and calls handler.name()
2. Calls an appropriate parse*() function (e.g. parseInt) to read th... | 50,620 |
def get_content(extra_file: ExtraFileTypeDef) -> Optional[str]:
"""Get serialized content based on content_type.
Args:
extra_file: The extra file configuration.
Returns:
Serialized content based on the content_type.
"""
content_type = extra_file.get("content_type")
content = e... | 50,621 |
def to_bs():
"""Example Registry Pipeline that loads existing pipelines"""
return [("pbsmrtpipe.pipelines.dev_04:pbsmrtpipe.tasks.dev_hello_world:0", "pbsmrtpipe.tasks.dev_txt_to_fasta:0")] | 50,622 |
def get_total_reflectance(mco_filename):
"""
extract reflectance from mco file.
Attention: mco_filename specifies full path.
Returns: the reflectance
"""
return get_diffuse_reflectance(mco_filename) + \
get_specular_reflectance(mco_filename) | 50,623 |
def generate_unit_squares(image_width, image_height):
"""Generate coordinates for a tiling of unit squares."""
# Iterate over the required rows and cells. The for loops (x, y)
# give the coordinates of the top left-hand corner of each square:
#
# (x, y) +-----+ (x + 1, y)
# | ... | 50,624 |
def inject_misc_tags(soup, chrome_app_manifest, root_path, html_path):
"""
Injects meta and link tags into an HTML document.
Args:
soup: BeautifulSoup HTML document. Will be modified.
chrome_app_manifest: Manifest dictionary of _Chrome App_.
root_path: Path to the root directory of the web app from t... | 50,625 |
def mutate(c, gp, pmut):
"""Mutation of chromosome
Based on the probability to mutate, it selects a random gene to change. It selects
a random other creature to take a new gene from a gene pool.
Args:
c: creature's chromosme to be changed.
gp: gene pool to select from.
pmut: pr... | 50,626 |
def test_update_employee(test_app, test_data, response_data):
""" Update employee"""
response_without_changes = test_app.put(
f'/api/employee/',
data=response_data.req,
)
assert response_without_changes.status_code == 422, f'данные не должны ' \
... | 50,627 |
def main() -> NoReturn:
"""
Run CLI Interface.
Return:
NoReturn
"""
args = get_args()
logging.basicConfig(
format=LOGGER_FORMAT,
level=getattr(logging, args.loglevel.name),
)
if args.data:
try:
data = json.loads(args.data)
except json... | 50,628 |
def _(shape: numpy.ndarray):
"""
If a shape is an array of points, compute the minima/maxima
or let it pass through if it's 1 dimensional & length 4
"""
if (shape.ndim == 1) & (len(shape) == 4):
return shape
return numpy.array([*shape.min(axis=0), *shape.max(axis=0)]) | 50,629 |
def invoke_spec2d(path, maskname):
"""
Runs spec2d in the given path, assuming there's a {maskname}.plan file
Note that you have to manually close the returned proc.stdout!
"""
import subprocess
planfn = os.path.abspath(os.path.join(path, maskname + '.plan'))
logfn = os.path.abspath(os.pat... | 50,630 |
def subus_to_s(path_labfile):
"""HTSのをきりたんの形式に変換"""
time_order_ratio = 10 ** (-7)
with open(path_labfile, 'r') as f:
lines = [s.strip().split() for s in f.readlines()]
# この時点で [[発声開始, 発声終了, 発音記号], ]
s = ''
for l in lines:
# print(l, end='\t -> ')
tmp = (float(l[0]) * tim... | 50,631 |
def selectHierarchy(node):
""" get the hierarchy of the current given object
:param node: the object to search through
:type node: string
:return: list of the objects children and current object included
:rtype: list
"""
ad = cmds.listRelatives(node, ad=1, f=1) or []
ad.append(... | 50,632 |
def logErrorAndReturnOK(error_msg='Error found in Task'):
"""Logs the given error message and returns a HTTP OK response.
Args:
error_msg: Error message to log
"""
logging.error(error_msg)
return http.HttpResponse() | 50,633 |
def make_std_gaussian(var_names):
"""
Make a d dimensional standard Gaussian.
:param var_names: The variable name of the factor.
:type var_names: str list
:return: The standard Gaussian
:rtype: Gaussian
"""
assert var_names, "Error: var_names list cannot be empty."
dim = len(var_nam... | 50,634 |
def has_prefix(sub_s):
"""
:param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid
:return: (bool) If there is any words with prefix stored in sub_s
"""
# In order to accelerate program
for i in lis:
if i.startswith(sub_s) is True:
return True
return False | 50,635 |
def sum_numbers_loop(n: int) -> int:
"""
BIG-O Notation = O(n)
"""
result = 0
for i in range(n + 1):
result += i
return result | 50,636 |
def read_rw(subset='dev'):
"""
Parses the rare word similarity test collection.
"""
lang1, lang2 = 'en', 'en'
filename = get_support_data_filename('rw/rw-{}.csv'.format(subset))
with open(filename) as file:
for line in file:
parts = line.split()
yield parts[0], pa... | 50,637 |
def create_app(package_name, package_path, settings_override=None,
register_security_blueprint=True):
"""Returns a :class:`Flask` application instance configured with common
functionality for the RiskManager platform.
:param package_name: application package name
:param package_path: app... | 50,638 |
def range(imageOrFilter) :
"""Return the range of values in a image of in the output image of a filter
The minimum and maximum values are returned in a tuple: (min, max)
range() take care of updating the pipeline
"""
import itk
img = image(imageOrFilter)
img.UpdateOutputInformation()
img.Update()
c... | 50,639 |
def define_components(mod):
"""
Augments a Pyomo abstract model object with sets and parameters that
describe load zones and associated power balance equations. Unless
otherwise stated, each set and parameter is mandatory.
LOAD_ZONES is the set of load zones. Each zone is effectively modeled as a
... | 50,640 |
def get_unique_id():
"""Generate and set unique identifier of length 10 integers"""
identifier = uuid.uuid4()
return str(identifier.int)[:10] | 50,641 |
def erb_fir_filters(signal, edges, fs):
"""
Generates a bank of FIR filters for a given set of erb edges following the approach of
Hopkins et al. (2010), such that each filter has a response of -6 dB (relative to the
peak response) at the frequencies at which its response intersects with the
resp... | 50,642 |
def restart(*args, **kwargs):
"""Return an instance of this to restart a workflow with the new input."""
return restart_type(args, kwargs) | 50,643 |
def show_fields( grid, fieldtype ):
"""
Show the field `fieldtype` on the interpolation grid
Parameters
----------
grid: an instance of FieldInterpolationGrid
Contains the field on the interpolation grid for
on particular azimuthal mode
fieldtype : string
Name of the fi... | 50,644 |
def FourierMaskRandom(width, height,proportion, R):
"""
Create a random sampling pattern where each point is sampled from :
1 if r < R
1/(1-r)**2 if r > R
with 0<R<1
Args:
width (int): Size of output mask in x... | 50,645 |
def redis_cache(
prefix: str,
/,
key_func: Any = None,
skip_cache_func: Any = lambda *args, **kwargs: False,
timeout: Optional[Union[int, float, datetime.timedelta]] = 60 * 60 * 24 * 7,
include_posargs: Optional[list[int]] = None,
include_kwargs: Optional[list[str]] = None,
allow_unset: ... | 50,646 |
def variable_summaries(var):
"""Attach a lot of summaries to a Tensor (for TensorBoard visualization)."""
with tf.name_scope('summaries'):
mean = tf.reduce_mean(var)
tf.summary.scalar('mean', mean)
with tf.name_scope('stddev'):
stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))
tf.summary.scalar('stddev',... | 50,647 |
def get_shapes_from_group(group):
""" Gets all object shapes existing inside the given group
:param group: maya transform node
:type group: str
:return: list of shapes objects
:rtype: list str
.. important:: only mesh shapes are returned for now
"""
# checks if exists inside maya sce... | 50,648 |
def main():
"""
Train Classifier Main function
This function applies the Machine Learning Pipeline:
1) Extract data from SQLite db
2) Train ML model on training set
3) Estimate model performance on test set
4) Save trained model as Pickle
"""
if len(sys.argv... | 50,649 |
def bond_quatinty(price, investment, minimum_fraction=0.1):
"""
Computes the quantity of bonds purchased given the investment,
bond price per unit, and the minimum fraction of a bond that
can be purchased
:param investment: Amount of money that will be invested
:param minimum_fraction:... | 50,650 |
def get_mysql_version(version_string):
"""Get MySQL version."""
return version.parse(re.sub("-.*$", "", version_string)) | 50,651 |
def find_template(templates_list, template_name):
"""
Function returns copy of a template with a name template_name from templates_list.
"""
result_list = [template for template in templates_list if template_name == template['name']]
return deepcopy(result_list[0]) if result_list else {"template":{}... | 50,652 |
def dct_compress(X, n_components, window_size=128):
"""
Compress using the DCT
Parameters
----------
X : ndarray, shape=(n_samples,)
The input signal to compress. Should be 1-dimensional
n_components : int
The number of DCT components to keep. Setting n_components to about
... | 50,653 |
def nan_divide(a: NDArrayOrFloat, b: NDArrayOrFloat) -> NDArrayOrFloat:
"""Helper function to avoid divide by zero in arrays and floats.
Args:
a: Numerator
b: Denominator
Returns:
a/b replace div0 by np.nan
"""
bc_shp = check_broadcastable(a=a, b=b)
return np.div... | 50,654 |
def get_folder_sessions(id):
"""
Get a list of sessions in the given folder
To fetch all elements, this endpoint can be called multiple times,
starting at pageNumber = 0 and incrementing the page number until
no results are returned.
"""
url = "{}/{}/sessions".format(panopto_url("folders"),... | 50,655 |
def neighbours(image, i, j):
"""Define neighbours of the current pixel
Arguments:
image {numpy.ndarray} -- image
i {int} -- row coordinate of the pixel
j {int} -- column coordinate of the pixel
Returns:
list -- list of pixels that are neighbours of current pixel
... | 50,656 |
def pair_plot(
z,
colors=None,
panel_size=None,
scatter_kwargs=None,
u=None,
v=None,
trajectories=None,
traj_kwargs=None,
quiver_kwargs=None,
save_name=None,
start_idx=None,
end_idx=None,
**kwargs
):
"""Pair plot with all dimension pairs."""
if scatter_kwargs ... | 50,657 |
def mutation_delete_musicplaylist(identifier: str):
"""Returns a mutation for deleting a musicplaylist object based on the identifier.
Arguments:
identifier: The unique identifier of the musicplaylist object.
Returns:
The string for the mutation for deleting the musicplaylist object based ... | 50,658 |
def train_and_evaluate(config: ml_collections.ConfigDict):
"""Trains and evaluates the model.
The training will run for config.num_epochs.
Args:
config: The configuration to use; specifies training parameters such as the
number of epochs to train for as well as model parameters like the number
o... | 50,659 |
def check_for_repeating_characters(tokens, character):
"""
References:
:func:`re.findall`
Args:
tokens ():
character ():
Returns:
"""
replacements = []
pattern = "([" + character + "{2,}]{2,4})"
for token in tokens:
if len(token) > 12:
if no... | 50,660 |
def md5sum(filename):
""" Compute the MD5 hash for a given filename """
blocksize = 65536
hasher = hashlib.md5()
with open(filename, "rb") as fid:
buf = fid.read(blocksize)
while len(buf) > 0:
hasher.update(buf)
buf = fid.read(blocksize)
return hasher.hexdiges... | 50,661 |
def get_local_platform():
"""Returns the name of the local platform; eg: 'linux_x86_64' or 'macosx_10_8_x86_64'.
:returns: The local platform name.
:rtype: str
"""
# TODO(John Sirois): Kill some or all usages when https://github.com/pantsbuild/pex/issues/511
# is fixed.
current_platform = Platform.curren... | 50,662 |
def test_commonsig_readonly(RefSimulator):
"""Test that the common signals cannot be modified."""
net = nengo.Network(label="test_commonsig")
sim = RefSimulator(net)
for sig in itervalues(sim.model.sig['common']):
sim.signals.init(sig)
with pytest.raises((ValueError, RuntimeError)):
... | 50,663 |
def time_stamp():
"""Current time stamp"""
ts = datetime.now()
return ts.strftime('%d-%b-%Y %H:%M:%S') | 50,664 |
def fromDict(moduleDict):
"""Factory function recreating any moduleItem or moduleItem subtype from a dictionary-serialized representation.
If implemented correctly, this should act as the opposite to the original object's toDict method.
If the requested module is builtIn, return the builtIn module object of... | 50,665 |
def delete_entry_tag(sender, instance, **kwargs):
"""
Deletes EntryTag for Entry corresponding to specified
TaggedItemBase instance.
:param sender: the sending TaggedItemBase class.
:param instance: the TaggedItemBase instance.
"""
from ..models import (
Entry,
EntryTag
... | 50,666 |
def setup_cli():
"""
Create the cli argument interface, and parses incoming args.
Returns a tuple:
- the argument parser
- the parsed args
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"--availability",
const="csm_availability_windows",
def... | 50,667 |
def cache_root(environ=None):
"""
The root directory for zipline cache files.
Parameters
----------
environ : dict, optional
An environment dict to forward to zipline_root.
Returns
-------
cache_root : str
The zipline cache root.
"""
return zipline_path(['cache']... | 50,668 |
def save_wechat_config(request):
"""
保存微信配置信息
"""
# 只有管理员有权限
if not request.user.is_superuser:
return redirect('admin:index')
conf_name = request.POST.get('conf_name')
conf_value = request.POST.get('conf_value')
if not conf_name or not conf_value:
return render_json({'re... | 50,669 |
def ParseQuickEditCommand(
cnxn, cmd, issue, config, logged_in_user_id, services):
"""Parse a quick edit command into assignments and labels."""
parts = _BreakCommandIntoParts(cmd)
parser = AssignmentParser(None, easier_kv_labels=True)
for key, value in parts:
if key: # A key=value assignment.
v... | 50,670 |
def clean_empty_dirs(root_dir,ignore_prefixes=["."]):
"""
Check the directory tree for any empty directories, or directories that
contain only empty directories (etc.)
Then delete any such directories.
Do not delete inside any directories which begin with one of the
ignore_prefixes.
"""
... | 50,671 |
def get_dict_X_dynamic(ar_iterations, forecast_cycle, input_k):
"""Provide information to load the dynamic data required by an AR model."""
dict_X_past = {}
for i in range(ar_iterations+1):
idxs = get_idx_lag(idx_start=0, ar_iteration=i, forecast_cycle=forecast_cycle, input_k=input_k)
idxs_p... | 50,672 |
def CMDterminate(parser, args):
"""Tells a bot to gracefully shut itself down as soon as it can.
This is done by completing whatever current task there is then exiting the bot
process.
"""
parser.add_option(
'--wait', action='store_true', help='Wait for the bot to terminate')
options, args = parser.p... | 50,673 |
def calculate_equilibrium(
model, P, T, z, number_of_trial_phases=3, compare_trial_phases=False,
molar_base=1.0, optimization_method=OptimizationMethod.PYGMO_DE1220,
solver_args=PygmoSelfAdaptiveDESettings(50, 250)
):
"""
Given a mixture modeled by an EoS at a known PT-conditions, calculate the ther... | 50,674 |
def PpapiFromPPVar(scope, type_defn, input_expr, variable, success,
exception_context, npp):
"""Gets the string to get a value from a pp::Var.
This function creates a string containing a C++ code snippet that is used to
retrieve a value from a pp::Var. If an error occurs, like if the pp::Var
is not of the ... | 50,675 |
def s3_include_debug_js():
"""
Generates html to include the js scripts listed in
/static/scripts/tools/sahana.js.cfg
"""
request = current.request
scripts_dir = os.path.join(request.folder, "static", "scripts")
sys.path.append(os.path.join(scripts_dir, "tools"))
import me... | 50,676 |
def get_closing(image, n_erode=1, n_dilate=1, kernel=(5,5)):
"""
Performs the specified number of dilations, followed by the specified number
of erosions to get the closing of the image.
Parameters
----------
image : np.ndarray
The image to perform the closing on.
n_erode : int, op... | 50,677 |
def ZAdrift(pminitial, pmfinal, pos, smoothing = 0, deconvolve = 0, lptbool = 0):
"""
This function takes in initial density field, calculates ZA displacement, \
shifts the particle with that displacement and paints them.
"""
if not lptbool:
ZAdisp = ZA(pminitial, pos)
elif lptbool == ... | 50,678 |
def plot_equity_curve(strategy, benchmark=None):
"""
Plot Equity Curves: Strategy vs (optionally) Benchmark
Both arguements are daily balance.
"""
fig = plt.figure()
axes = fig.add_subplot(111, ylabel='Portfolio value in $')
axes.plot(strategy['close'], label='strategy')
if benchmark is... | 50,679 |
def create_candlestick(open, high, low, close, dates=None, direction="both", **kwargs):
"""
**deprecated**, use instead the new_plotly.graph_objects trace
:class:`new_plotly.graph_objects.Candlestick`
:param (list) open: opening values
:param (list) high: high values
:param (list) low: low valu... | 50,680 |
def sine_f0(duration: float, srate: int) -> np.ndarray:
"""Return the f0 contour of a sine wave of duration seconds long."""
sine_arr = np.sin(2 * np.pi * np.arange(srate * duration) * 440.0 / srate).astype(
np.float64
)
f0 = pyworld.stonemask(sine_arr, *pyworld.dio(sine_arr, srate), srate)
... | 50,681 |
def prepare_graph(data_folder: str, topology: str, n_nodes: int):
"""
Generates the graph adjacency matrix, assigns positions for plotting with Kamada-Kawai layout.
All data are stored under the folder `{data_folder}/{topology}` path.
:param data_folder: A string containing the data folder path
:par... | 50,682 |
def make_opts(string: str) -> Dict[str, str]:
"""Parse Make opts, eg "DEBUG=1 TILES=1" => {"DEBUG": "1", "TILES": "1"}."""
if string:
return {arg: val for arg, val in (opt.split("=") for opt in string.split(" "))}
else:
return {} | 50,683 |
def generate_download_list(years, doctype='grant'):
"""
Given the year string from the configuration file, return
a list of urls to be downloaded
"""
if not years: return []
urls = []
link = 'https://www.google.com/googlebooks/uspto-patents-grants-text.html'
if doctype == 'application':
... | 50,684 |
def readable_uuid(source: Union[str, uuid.UUID], *, _tt=str.maketrans('+/', '-_')) -> str:
"""
Formats the given UUID using modified base64 without padding.
Returns a string of exactly 22 characters length.
"""
if isinstance(source, str):
source = read_uuid(source)
return base64.b64enco... | 50,685 |
def auto_sigma_y(sino, weights, snr_db = 30.0, delta_pixel = 1.0, delta_channel = 1.0):
"""Computes the automatic value of ``sigma_y`` for use in MBIR reconstruction.
Args:
sino (ndarray):
3D numpy array of sinogram data with shape (num_views,num_slices,num_channels)
weights (ndarra... | 50,686 |
def print_(args: argparse.Namespace, success: bool, message: str) -> None:
"""
Print function with extra coloring when supported and/or requested,
and with a "quiet" switch
"""
COLOR_SUCCESS = '\033[32m'
COLOR_FAILURE = '\033[31m'
COLOR_RESET = '\033[0m'
if args.quiet:
return
... | 50,687 |
def neighborhoods(as_geo=False):
"""Neighborhood names and centers (lon, lat).
Note: Names take from from the Parking meter data at:
http://seshat.datasd.org/parking_meters/treas_parking_meters_loc_datasd.csv
Location taken from wikipedia, or manual estimates derived via Google Maps.
(This should ... | 50,688 |
def list_projects(base_url: str, api_key: str) -> Tuple[Any, Optional[error.URLError]]:
"""GET /projects.[format]"""
try:
params = {
"key": api_key
}
req = request.Request(f"{base_url}/projects.json?{parse.urlencode(params)}")
with request.urlopen(req) as res:
... | 50,689 |
def run_command(cmd, run_dir, log_dir, name, critical=True):
"""Run the command with output to logs."""
sys.stdout.write('[%s] ' % name)
sys.stdout.flush()
flag_file = os.path.join(log_dir, '%s.done' % name)
if os.path.exists(flag_file):
print 'already done'
return
stdin = ope... | 50,690 |
def TMC_GetSimpleMea(WaitTime=100, mode = 1) : #TMC_GetSimpleMea - Returns angle and distance measurement - geocom manual p.95
"""
[GeoCOM manual **p132**]
Returns the angles and distance measurement data. This command does not issue a new distance measurement.
A distance measurement has to be started ... | 50,691 |
def index_at_direction(cell_index_array, direction):
""" Returns the index of the neighbouring cell in the given direction"""
index_array = cell_index_array.copy()
if (
(index_array[1] == GRID_SIZE - 1 and RIGHT in direction) or
(index_array[1] == 0 and LEFT in direction) or
(index_array[0] == 0 and UP in dir... | 50,692 |
def _create_average_ops(params):
"""Build moving average ops."""
tf.logging.info('Creating moving average ops')
with tf.variable_scope('moving_average'):
moving_average_step = tf.get_variable(
'step', [], dtype=tf.float32, trainable=False)
all_vars = tf.trainable_variables()
average_pairs = []
... | 50,693 |
def reset_color_picker(modal_open, font_color):
"""
Reset the color-picker to white font color after closing the modal
component.
Parameters
----------
modal_open : bool
A boolean that describes if the modal component is open or not
font_color : dict of { 'hex': str,
... | 50,694 |
def generate_extension(ext_def):
"""Generate extension constructors."""
assert "name" in ext_def, "invalid extension name"
ext_path = ext_def["name"].replace(".", os.path.sep) + ".pyx"
ext_root = os.path.dirname(ext_path)
ext_def["sources"] = [ext_path]
if "extra_objects" in ext_def:... | 50,695 |
def get_tree_effects(tree: Any) -> List[str]:
"""
Return all effects of a tree as action strings.
I.e. traverses the tree and returns the first child of each falback node,
and the postconditions of the last child of each sequence node.
Args
----
tree: the Behavior Tree to traverse.
... | 50,696 |
def obtainTagVersionList(adshList, fileLocation):
""" Scans the Pre file to find the Tags and the Versions used in the filing in question so as to populate the Tags table with only that subset """
with open(fileLocation + 'pre.txt') as fileHandle:
tagVersionList = list()
# read schema and adv... | 50,697 |
def to_document(model, document_class):
"""Convert a model object to a database document.
:param BaseModel model: The model object to convert. This instance must have a to_dict() method that returns
a dictionary of the model data.
:param class document_class: The type of the document class to conve... | 50,698 |
def test_log_override_log_level(mocker):
"""By default logging set to INFO using basicConfig."""
mock = mocker.patch("logging.basicConfig")
mocker.patch("msrc.appconfig.read_all.logger.hasHandlers",
return_value=False)
c, _ = msrc.appconfig.read_all.gather(
mk_class(("a", int)),... | 50,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.