content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def getComponentReadingClassByType(componentType):
"""Given the path mapping of a point, get the class that it belongs to"""
componentClass = None
if componentType == "AHU":
componentClass = AHUReading
elif componentType == "VFD":
componentClass = VFDReading
elif componentType == "Filter":
componentClass =... | 5,311,500 |
def feature_importance_map(feat_imp,
method_labels,
base_output_path,
feature_names = None,
show_distr = False,
plot_title = 'feature importance',
show_all = ... | 5,311,501 |
def from_rotation_matrix(mtr):
"""
See
http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/
"""
mtr = tf.convert_to_tensor(mtr)
def m(j, i):
shape = mtr.shape.as_list()
begin = [0 for _ in range(len(shape))]
begin[-2] = j
begin[-1... | 5,311,502 |
def findSimilarVectors(single_id):
"""
Return a list of _id's that are most similar to the original id
"""
topic_result, distances = nearestNeighbors.similar_from_id(single_id, 5)
topic_result = json.dumps(topic_result, default = json_util.default)
print(topic_result)
return topic_result | 5,311,503 |
def set_sleep(sleep=False):
"""When the option 'sleep' is True, after plotting the computation is paused for 0.01 secs. Optionally, the sleeping time (in secs) can be fixed if a the number is passed (eg: sleep=0.001). The default value is False."""
if sleep==False and type(sleep)==bool:
h.sleep=None
... | 5,311,504 |
def format_msg(fmt, use_color=False):
"""Replace $RESET and $BOLD with corresponding ANSI entries"""
if use_color:
return fmt.replace("$RESET", RESET_SEQ).replace("$BOLD", BOLD_SEQ)
else:
return fmt.replace("$RESET", "").replace("$BOLD", "") | 5,311,505 |
def add_week_course_activity(course_id: int, weektime_id: int, cur_week: int ,course_stage2: bool):
"""
添加每周的课程活动
"""
course = Course.objects.get(id=course_id)
examine_teacher = NaturalPerson.objects.get_teacher(
get_setting("course/audit_teacher"))
# 当前课程在学期已举办的活动
conducted_num = Ac... | 5,311,506 |
def afwd(data):
"""
AFWD - Request 4WD status
"""
return data | 5,311,507 |
def create_timestamp_anti_leech_url(host, file_name, query_string_dict, encrypt_key, deadline):
"""
创建时间戳防盗链
Args:
host: 带访问协议的域名
file_name: 原始文件名,不需要urlencode
query_string_dict: 查询参数,不需要urlencode
encrypt_key: 时间戳防盗链密钥
deadline: 链接... | 5,311,508 |
def centroid_points_xy(points):
"""Compute the centroid of a set of points lying in the XY-plane.
Warning
-------
Duplicate points are **NOT** removed. If there are duplicates in the
sequence, they should be there intentionally.
Parameters
----------
points : list of list
A seq... | 5,311,509 |
def driver(tag):
"""
Determine driver module
:Parameters:
`tag` : ``str``
Connection tag
:Return: Driver module
:Rtype: ``module``
:Exceptions:
- `DBConfigurationError` : DB not configured
- `KeyError` : DB name not found
- `ImportError` : Driver not found
... | 5,311,510 |
def check_not_none(param):
"""
deprecated. Recommand using misc.check_not_none
"""
misc.check_not_none(param) | 5,311,511 |
def theaterChase(strip, color, wait_ms=50, iterations=5):
"""Movie theater light style chaser animation."""
led_on(strip, ColorVal.NONE)
for j in range(iterations):
for q in range(3):
for i in range(0, strip.numPixels()-q, 3):
strip.setPixelColor(i+q, color)
s... | 5,311,512 |
def setup_logging(debug=False, filename="my_log.txt", log_format=None):
"""
Default logger
"""
logLevel = logging.DEBUG if debug else logging.INFO
if log_format is None:
log_format = "%(asctime)s [%(levelname)s] %(message)s"
logging.basicConfig(filename=filename, level=logLevel, format=l... | 5,311,513 |
def test_max_q_action_selector(stats, max_a):
"""tests :func:~online_pomdp_planning.mcts.max_q_action_selector"""
info = {}
assert max_q_action_selector(stats, info) == max_a
sorted_q_vals = info["max_q_action_selector-values"]
assert sorted_q_vals[0][0] == max_a
assert len(sorted_q_vals) == le... | 5,311,514 |
def should_force_reinit(config):
"""Configs older than 2.0.0 should be replaced"""
ver = config.get("cli_version", "0.0.0")
return int(ver.split(".")[0]) < 2 | 5,311,515 |
def _import_package(*args, **kwargs):
""" Import modules and things from a package """
package_name = kwargs['package_name']
if PACKAGES[package_name] is None:
if len(args) < 2:
return None
return (None for _ in args)
module = kwargs.get('module')
modules = []
for ... | 5,311,516 |
def file_rename():
"""Docstring."""
sample_files = [
"bin/init.d/securetea.sample",
"bin/systemd/securetea.service.sample"
]
script_dir = get_setuptools_script_dir()
print("herrr" + script_dir)
string = "/usr/bin/securetea"
for file in sample_files:
with open(file) a... | 5,311,517 |
def check_tag_list(tag_list):
""" Makes a list of any tags entered on the command line. """
tags = []
if len(tag_list) != 0:
tags = tag_list[0].split(",")
return tags | 5,311,518 |
def debug_test_user(test_user, prefix=''):
"""
Print all user attributes to standard out, except password.
Parameters:
- prefix: Defaults to `''`. If not the empty string, printed before
the user information
"""
if prefix is not '':
print(prefix)
profile = test_user.profile
... | 5,311,519 |
def test_fst_ap_config_pri_zero(dev, apdev, test_params):
"""FST AP configuration Priority zero"""
res = run_test_ap_configuration(apdev, test_params, fst_pri = '0')
if res == 0:
raise Exception("hostapd started with a zero fst priority") | 5,311,520 |
def get_devices_from_file():
"""Load pre-analysed device data from a JSON file"""
global _devices
_devices = []
with open(JSON_PATH, 'r') as f:
rjson = json.load(f)
for device in rjson.values():
_devices.append(Device.dict_import(device)) | 5,311,521 |
def tipo_cambio_agregar():
"""
Agregar nuevo registro a 'tipos_cambio'
"""
form = SQLFORM(db.tipos_cambio, submit_button='Aceptar')
if form.accepts(request.vars, session):
response.flash = 'Registro ingresado'
return dict(form=form) | 5,311,522 |
def update_pagination():
"""
The update_pagination function increates the state value for the 'page' the user is on related
to a search performed
"""
st.session_state.page += 1 | 5,311,523 |
def start_uploading(main_pid):
""" Start the process of uploading stdout/stderr """
process = Process(target=upload_stdout_stderr, args=(main_pid,))
process.start()
return process | 5,311,524 |
def describe(repos: Dict[str, str]) -> str:
"""
Return the status of all repos
"""
name_width = max(len(n) for n in repos) + 1
for name in sorted(repos):
path = repos[name]
head = get_head(path)
dirty, staged, untracked, color = _get_repo_status(path)
yield f'{name:<{... | 5,311,525 |
def accounts_post(**kwargs):
""" add new account and set first transaction with rests of money """
obj = json.loads(request.data.decode('utf-8', 'strict'))
new_account = Account(
title=obj['title'],
currency_id=int(obj['currency.id']))
DB.add(new_account)
DB.flush()
if fl... | 5,311,526 |
def list(config):
"""List datasets."""
data = [
["ID", "STATUS", "NAME", "SIZE"],
["-" * 80, "-" * 80, "-" * 80, "-" * 80],
]
datasets = config.trainml.run(config.trainml.client.datasets.list())
for dset in datasets:
data.append(
[
dset.id,
... | 5,311,527 |
def labels_to_image_model(labels_shape,
n_channels,
generation_labels,
output_labels,
n_neutral_labels,
atlas_res,
target_res,
output_shap... | 5,311,528 |
def save_best_parameters(
save_methods, save_methods_rewrite, path_save, best_parameters
):
"""
Save Hyperparameters
"""
if exists(path_save + ".json") and save_methods_rewrite["json"] == 0:
with open(path_save + ".json", "r") as json_file:
dictionary = json.load(json_file)
... | 5,311,529 |
def compare(reqs_1: List[str], reqs_2: List[str]):
"""Compare 2 requirements.txt files (lists) and exit if they don't match.
Lines that don't match are printed to stderr.
"""
diff_lock = "\n".join(list(set(reqs_1) - set(reqs_2)))
diff_pip = "\n".join(list(set(reqs_2) - set(reqs_1)))
if diff_loc... | 5,311,530 |
async def unpack_from_prior_in_place(
message: dict, resolvers_config: ResolversConfig
) -> Optional[DID_URL]:
"""
Unpacks from_prior field within a given message from JWT (compactly serialized JWS with claim set)
if the message contains from_prior.
In result, the message will contain the unpacked f... | 5,311,531 |
def ensure_file_abs_path_valid(file_abs_path: Text) -> Text:
""" ensure file path valid for pytest, handle cases when directory name includes dot/hyphen/space
Args:
file_abs_path: absolute file path
Returns:
ensured valid absolute file path
"""
project_meta = load_project_meta(fil... | 5,311,532 |
def remove_leading_character(string, character):
"""
If "string" starts with "character", strip that leading character away.
Only removes the first instance
:param string:
:param character:
:return: String without the specified, leading character
"""
if string.startswith(character):
... | 5,311,533 |
def _rfind(lst, item):
"""
Returns the index of the last occurance of <item> in <lst>. Returns -1 if
<item> is not in <l>.
ex: _rfind([1,2,1,2], 1) == 2
"""
try:
return (len(lst) - 1) - lst[::-1].index(item)
except ValueError:
return -1 | 5,311,534 |
def main_callback():
"""!
Publish to error node and inverse kinematics nodes the data, in particular the
jacobian matrix, the tracking vectors and the data needed to compute the errors.
"""
##########################################################################
# Entry point when receveing a... | 5,311,535 |
def plot_all_continuous_efficiency_with_diefk(diefkDF: np.ndarray, colors: list) -> list:
"""
Generate radar plots that compare dief@k at different answer completeness in a specific test
as in <doi:10.1007/978-3-319-68204-4_1>.
This function plots the results reported in "Experiment 2".
"Experiment... | 5,311,536 |
def measure_int_interval(interval: Interval[int]) -> Optional[int]:
"""Return the size of the integer interval."""
if interval.lower_bound is None or interval.upper_bound is None:
return None
if interval.is_empty():
return 0
return interval.upper_bound - interval.lower_bound + 1 | 5,311,537 |
def mkdir(folder_path: str) -> None:
"""Creates recursively the path, ignoring warnings for existing directories."""
try:
makedirs(folder_path)
except OSError:
pass | 5,311,538 |
def temp_bringup_ui_for(obj, kind=None):
""" Create UI and temporarily bring it up to allow operations while it's up
Examples
--------
>>> obj = <whatever view object you want to build the UI for>
>>> with temp_bring_up_for(obj) as ui:
... <add explorations and assersions on the ui object>
... | 5,311,539 |
def get_case_statuses(read_only):
""" Get a list of the case statuses that are read-only. """
if read_only:
return CaseStatusEnum.read_only_statuses()
else:
return [status for status, value in CaseStatusEnum.choices if not CaseStatusEnum.is_read_only(status)] | 5,311,540 |
def laggauss(deg):
"""
Gauss-Laguerre quadrature.
Computes the sample points and weights for Gauss-Laguerre quadrature.
These sample points and weights will correctly integrate polynomials of
degree :math:`2*deg - 1` or less over the interval :math:`[0, \\inf]`
with the weight function :math:`f... | 5,311,541 |
def start(dict_path, word, debug):
"""Stargaze can parse and query stardict dictionary files."""
if debug:
logging.basicConfig(level=logging.DEBUG)
logger.info("Verbose messages are enabled.")
d = Dictionary(dict_path)
print(d.lookup(word)) | 5,311,542 |
def list_uiactions(content, request=None, registry=None, category=''):
""" List ui actions for specific content """
if request is not None:
registry = request.registry
url = request.resource_url(content)
else:
url = ''
actions = []
for name, action in registry.adapters.looku... | 5,311,543 |
def create_singularity_cmd(args):
"""Function that creates and returns the BIDS App singularity run command.
Parameters
----------
args : dict
Dictionary of parsed input argument in the form::
{
'bids_dir': "/path/to/bids/dataset/directory",
'output_... | 5,311,544 |
def define_index(min_date: int, max_date: int, interval: str) -> int:
"""
Return the index of a specific date
"""
interval_minutes = constants.TICKER_INTERVAL_MINUTES[interval]
return int((max_date - min_date) / (interval_minutes * 60)) | 5,311,545 |
def map_box(sbox, dbox, v):
"""
sbox is (lat1, lat2, long1, long2),
dbox is (x1, x2, y1, y2),
v is (lat, long).
result is (x, y)
"""
xscale = abs(dbox[1]-dbox[0])/abs(sbox[3]-sbox[2])
yscale = abs(dbox[3]-dbox[2])/abs(sbox[1]-sbox[0])
x = (v[1]-sbox[2]+dbox[0])*xscale
y = (v[0]-... | 5,311,546 |
def clash_iter(atoms, min_clash=0.4, radii_attr='radius'):
"""
Returns an iterator over pairs:
-clash value
-the pair of clashing atoms
min_clash.
"""
max_radii = max([getattr(a, radii_attr) for a in atoms])
gridhash = GridHash([(a.coordinates, a) for a in atoms], max_radii*2 - m... | 5,311,547 |
def test_get_min_param_value_for_best_neighbors_coverage() -> None:
"""
Check that get_min_param_value_for_best_neighbors_coverage works as expected.
"""
# We only test on hnsw because this index is fast to build
embeddings = np.float32(np.random.rand(30001, 512))
hyperparameter_str_from_param ... | 5,311,548 |
def test_depset() -> None:
"""Test call to try this stuff out..."""
if bool(False):
print('running test_depset()...')
def doit() -> None:
from ba._error import DependencyError
depset = DependencySet(Dependency(TestClass))
try:
depset.resolve()... | 5,311,549 |
def recognize_po_file(filename: str) -> bool:
""" Recognize .po file """
if filename.endswith(".po"):
return True
return False | 5,311,550 |
def circle_xy(x0, y0, r0):
"""
To obtain cartesian coordinates of a circle
@param x0: float
x coordinate of the center of the circle
@param y0: float
y coordinate of the center of the circle
@param r0: float
radius of the circle
@return: np.array([float]),np.array([float]... | 5,311,551 |
def generate_dataset(
splits,
output_directory,
label_map_name,
metadata_name,
window_size_sec,
hop_len_sec,
n_mels,
freq_max,
train_chunk_len_sec,
eval_chunk_len_sec,
min_box_percent,
n_train_shards,
n_eval_shards,
... | 5,311,552 |
def _build_dev_requirements() -> List[Requirement]:
"""Load requirements from file."""
with open(REQUIREMENT_PATH, "rt") as req_file:
return list(parse_requirements(req_file.read())) | 5,311,553 |
def scrape_video_menu(url):
""" Scrape videos from url
Args:
url (str): url to scrape from (e.g. https://www.exploratorium.edu/video/subjects)
Returns TopicNode containing all videos
"""
LOGGER.info("SCRAPING VIDEOS...")
video_topic = nodes.TopicNode(title="Videos", source_id... | 5,311,554 |
def multiply_nums(n1, n2):
"""Function to multiplies two numbers.
n1 : Must be a numeric type
n2 : Must be a numeric type
"""
result = n1 * n2
return result | 5,311,555 |
def _get_setup(
benchmark: GroupedBenchmark,
runtime: RuntimeMode,
language: Language,
stmt: str,
model_path: Optional[str]
) -> str:
"""Specialize a GroupedBenchmark for a particular configuration.
Setup requires two extra pieces of information:
1) The benchmark stmt. This is needed ... | 5,311,556 |
def setup_init(timestep=1./240, iterations=150, gravity=-9.5):
"""
This function give an initial setup to the reset
"""
p.setPhysicsEngineParameter(numSolverIterations=iterations)
p.setTimeStep(timestep)
p.setGravity(0, 0, gravity)
p.setRealTimeSimulation(False)
p.stepSimulation() | 5,311,557 |
def update_from_sheets(request):
"""Create Student model instances from excel sheet."""
if request.method == 'POST':
sheet = request.FILES['sheet']
# Temporarily save the file
fs = FileSystemStorage(location=settings.TEMP_ROOT)
filename = fs.save(sheet.name, sheet)
file_p... | 5,311,558 |
async def read_temperature(request: web.BaseRequest):
"""
Request handler for retrieving local sensor data.
Args:
request: aiohttp request object
"""
from sense_hat import SenseHat
context = request.app["request_context"]
sense = SenseHat()
temperature = sense.get_temperature()... | 5,311,559 |
def expressions():
"""Return a sequence of test expressions."""
A = Lambda('a')
X = Lambda('x')
Y = Lambda('y')
Z = Lambda('z')
XA = Lambda(X, A)
XY = Lambda(X, Y)
XZ = Lambda(X, Z)
YZ = Lambda(Y, Z)
XYZ = Lambda(XY, Z)
xX = Lambda('x', X)
xyX = Lambda('x', Lambda('y', X)... | 5,311,560 |
def misc_tasks_to_goals(real_goals, misc_goals, extra_time=0):
"""
Converts misc-goal tasks into goals for themselves. That is, each task is a
goal for itself consisting of only one task (itself).
Args:
real_goals: [Goal] representing real goals
misc_goals: [{node}] representing mis... | 5,311,561 |
def normalize_timedelta(val):
"""
produces a normalized string value of the timedelta
This module returns a normalized time span value consisting of the
number of hours in fractional form. For example '1h 15min' is
formatted as 01.25.
"""
if type(val) == str:
val = parse_ti... | 5,311,562 |
def up_to(s, i, c):
"""Il faudrait commenter, je ne sais plus ce que ça fait."""
t = []
k = i
while s[k] != c:
t.append(s[k])
k += 1
return "".join(t) | 5,311,563 |
def main():
"""CollatzPy CLI"""
return 0 | 5,311,564 |
def bf_get_users(selected_bfaccount):
"""
Function to get list of users belonging to the organization of
the given Blackfynn account
Args:
selected_bfaccount: name of selected Blackfynn acccount (string)
Retun:
list_users : list of users (first name -- last name) associated with the o... | 5,311,565 |
def load_service(service: str, version: str = None, model_type="service-2") -> ServiceModel:
"""
For example: load_service("sqs", "2012-11-05")
"""
service_description = loader.load_service_model(service, model_type, version)
return ServiceModel(service_description, service) | 5,311,566 |
def test_matrix_inverse(test_case: Tuple[Matrix, Any]) -> None:
"""
Test that runs the async test code.
:param test_case: tuple containing a matrix and its inverse
"""
mpc.run(async_test_matrix_inverse(test_case)) | 5,311,567 |
def get_file_size_gb(file_path):
"""Get File Size by GB"""
if os.path.exists(file_path):
size = round((os.path.getsize(file_path) / 1024 / 1024 / 1024), 1)
LOG.debug("Target File Size : {} ({} GB)".format(file_path, size))
return size
else:
return 0 | 5,311,568 |
def _kv_to_dict(meta):
"""Transform a list with key/value strings into a dictionary.
"""
try:
return dict(m.split("=", 1) for m in meta)
except ValueError:
raise _errors.MachineError("Invalid parameter (%s)." % (meta, )) | 5,311,569 |
def _flip_row_coordinates(move):
"""Flips a coordinate of a move horizontally.
Args:
move: row, col index or None if pass move
Returns:
Horizontally flipped move if move was not None
"""
if move is None:
return move
row, col = move
row = go.BOARD_SIZE - 1 - row
... | 5,311,570 |
async def EventShadowban(
ctx: GuildMessageCreateEvent,
config: Dict[str, Any] = tanjun.inject(type=Dict[str, Any]),
) -> None:
"""Silently delete user messages in the configured channels."""
if not config["shadowban"]["enable"]:
return
elif ctx.author.id not in config["shadowban"]["users"]... | 5,311,571 |
def faultReturnHandler(func):
"""
Handles functions with return.
Decorated function returns erro message if something went wrong.
"""
@wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs);
except Exception as error_message:
... | 5,311,572 |
def tag_t_offset_compare_key():
"""
Convert a tag_t_offset_compare function into a key=function
This method is modeled after functools.cmp_to_key(_func_).
It can be used by functions that accept a key function, such as
sorted(), min(), max(), etc. to compare tags by their offsets,
e.g., sorted(t... | 5,311,573 |
def comp_coulomb_den(sv, ao_log=None, funct=coulomb_am, dtype=np.float64, **kvargs):
"""
Computes the matrix elements given by funct, for instance coulomb interaction
Args:
sv : (System Variables), this must have arrays of coordinates and species, etc
Returns:
matrix elements (real-space overl... | 5,311,574 |
def dmp_gcd(f, g, u, K):
"""
Computes polynomial GCD of `f` and `g` in `K[X]`.
Examples
========
>>> R, x, y = ring("x y", ZZ)
>>> f = x**2 + 2*x*y + y**2
>>> g = x**2 + x*y
>>> R.dmp_gcd(f, g)
x + y
"""
return dmp_inner_gcd(f, g, u, K)[0] | 5,311,575 |
def preferences():
"""Render preferences page && save user preferences"""
# save preferences
if request.method == 'POST':
resp = make_response(redirect(urljoin(settings['server']['base_url'], url_for('index'))))
try:
request.preferences.parse_form(request.form)
except Va... | 5,311,576 |
def freq2lin(freq_hz):
"""Compatibility hack to allow for linearly spaced cosine filters
with `make_erb_cos_filters_nx`; intended to generalize the
functionality of `make_lin_cos_filters`.
"""
return _identity(freq_hz) | 5,311,577 |
def test_full_exch_hex_9_shells():
"""
Test the x component of the exchange field when using 9 shells of
neighbours in a 9 X 9 hexagonal lattice with square and diagonal
arrangement
We set J=1 for every shell and set the s_x component of the spins as the
lattice site number:
[0, 1, 2, 3, ..... | 5,311,578 |
def make_fancy_image(image, visuals, IM_VISUALS_DIR, VERSION):
""" Make a fancy image, e.g. for a paper or presentation.
Parameters
----------
image:
A clone of the original image for calibration, can draw on it.
visuals:
Each item consists of *two* tuples, for target and actual, re... | 5,311,579 |
def _GetVersionFromCrx(crx_path):
"""Retrieves extension version from CRX archive.
Args:
crx_path: path to CRX archive to extract version from.
"""
with zipfile.ZipFile(crx_path, 'r') as crx_zip:
manifest_contents = crx_zip.read('manifest.json')
version = json.loads(manifest_contents)['version']
... | 5,311,580 |
def get_fuzzy_continuous_sets(divisions, point_set_method='point_set'):
"""Generate a list with the triangular fuzzy sets of
a variable of a DataFrame given the peaks of
the triangles
Parameters
----------
divisions : list
List of tuples with the names of the sets and the peak of the tr... | 5,311,581 |
def gen_iclr_data(dir, sent_data, score_fn, limit_to=None, merge=True):
"""
Create PeerReview ICLR dataset from sentiment lexicon
"""
iclr_data = [fname for fname in os.listdir(os.path.join(dir, 'reviews'))][:limit_to]
n = limit_to or len(iclr_data)
y = np.zeros(n)
x = np.zeros((n, len(sc... | 5,311,582 |
def angle_distance_degree(deg1: float, deg2: float) -> float:
"""
Return the distance between angles.
:param deg1: the starting angle, in degrees.
:param deg2: the ending angle, in degrees.
:return: the distance in range [-180, 180]
"""
return _s_dist(deg1, deg2, 360) | 5,311,583 |
def _get_transf_matrix(n: int, transform_type: str,
dec_levels: int = 0, flip_hardcoded: bool = False) -> (np.ndarray, np.ndarray):
"""
Create forward and inverse transform matrices, which allow for perfect
reconstruction. The forward transform matrix is normalized so that the
... | 5,311,584 |
def get_hierarchical_data_for_apps(apps):
"""
Return a hierarchical data structure consisting of nested OrderedDicts for all data collected for apps listed
in `apps`. The format of the returned data structure is:
```
{
<session_1_code>: {
'code': ...,
'label': ...,
... | 5,311,585 |
def test_load_multiple_set_on_schema(tag_schema, tags_jsonapi):
"""Tests that loading multiple objects in one go works when configured on the schema."""
tags, errors = tag_schema(many=True).load(tags_jsonapi)
assert errors == {}
assert len(tags) == 3
for tag in tags:
assert hasattr(tag, 'tag... | 5,311,586 |
def get_available_source_annotations(doc: Optional[str] = None, docs: Optional[List[str]] = None) -> List[str]:
"""Get a list of available annotations generated from the source, either for a single document or multiple."""
assert doc or docs, "Either 'doc' or 'docs' must be provided"
available_source_annota... | 5,311,587 |
def get_GEOS_data_folder4dt(dt=None, product='GEOS_CF', host=None,
mode='fcast', collection='inst3_3d_aer_Np',
inc_collection=True):
"""
Get the data folder location for a given GEOS product and datetime
"""
# Where is the data for the product?
... | 5,311,588 |
def detect_handwritten_ocr(path):
"""Detects handwritten characters in a local image.
Args:
path: The path to the local file.
"""
from google.cloud import vision_v1p3beta1 as vision
client = vision.ImageAnnotatorClient()
with io.open(path, 'rb') as image_file:
content = image_file.... | 5,311,589 |
def getOptions():
""" Created the option parser according to spec above.
Also allows standard svn hook arguments """
optargs = sys.argv[1:]
if len(optargs) == 2 and re.search(r'^\d+$', optargs[1]):
optargs = ['-p', optargs[0], '-r', optargs[1]]
# options as global variables
(options, args) = parser... | 5,311,590 |
def safe_md5(open_file, block_size=2**20):
"""Computes an md5 sum without loading the file into memory
This method is based on the answers given in:
http://stackoverflow.com/questions/1131220/get-md5-hash-of-a-files-without-open-it-in-python
"""
md5 = hashlib.md5()
data = True
while data:
... | 5,311,591 |
def test_napalm_eos_facts(device_inventory):
"""
Test the napalm library by gathering facts and ntp config from vEOS.
"""
devices = device_inventory["all"]["children"]["arista"]["children"]["vEOS"]["hosts"]
driver_eos = get_network_driver("eos")
for host in devices:
veos = driver_eos(... | 5,311,592 |
def generator_order_code(sex=None):
"""
生成顺序码
:param sex:
:return:
"""
order_code = random.randint(101, 1000)
if sex == 1:
order_code = order_code - 1 if order_code % 2 == 0 else order_code
if sex == 0:
order_code = order_code if order_code % 2 == 0 else order_code - 1
... | 5,311,593 |
def fasta_reader(fa, q, *filters):
# TO DO
# Check packing/unpacking
# Should this be just a list, even if it's empty?
"""
Reader worker for the fa file in the specified q(ueue)
Applies a filter on the sequence length > 1. This
is there to parse out
(a) empty sequence strings
(b) se... | 5,311,594 |
def test(model, test_inputs, test_labels):
"""
Runs through one epoch - all testing examples
:returns: accuracy
"""
num_predict_corrections = 0
num_times_we_guessed_zero = 0
num_batches = len(test_labels)
for batch_no in range(num_batches):
test_input = test_inputs[batch_no]
... | 5,311,595 |
def mirantis(cred):
"""
:returns: list
[{'region': str, 'timestamp': int, 'nodes': list}]
"""
return _openstack(Provider.OPENSTACK, cred) | 5,311,596 |
def load(path, encoding="utf-8"):
"""
从文件夹加载 CDTB 格式文档
:param path: 文档文件夹路径
:param encoding: 文档编码
:return structure.tree.Discourse 生成器
"""
return CDTB.load(path, encoding=encoding) | 5,311,597 |
def load_spikes(filename, recording_number):
"""
Loads spike data, using memory mapping to improve performance
The returned data is not memory mapped
Input:
=====
filename - string
path to the data file (.spikes, .events, or .continuous)
recording_index - int
... | 5,311,598 |
def _get_exchange_info() -> pd.DataFrame:
"""
Returns a dataframe of exchange listings for initializing the Universe class
Called upon initialization of the Universe class, updates the stock listings
that are available by default when gathering stock data from the internet
Returns:
A dataf... | 5,311,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.