content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def stringify_array(v, maxDepth=None, maxItems=-1, maxStrlen=-1): """ Convert a dict to a string representation. Parameters: d(dict) : the data dict to convert maxDepth (int|None): if > 0, then ellipsise structures deeper than th...
17bf5008c7a263c102f0fa03fdcc708c0fcc9a0f
3,638,400
import pickle def rpickle(picke_file, state=None): """ Save the state of the gps file treated """ logger.warning('Running rpickle ...') results = [] if picke_file.isfile(): with open(picke_file, 'rb') as read_pickle: results += pickle.load(read_pickle) # print results ...
a3f0cc46d6992032d008053e679ec75c64805141
3,638,401
import jsonschema import json import pkg_resources import os def test_pydist(): """Make sure pydist.json exists and validates against our schema.""" # XXX this test may need manual cleanup of older wheels def open_json(filename): return json.loads(open(filename, 'rb').read().decode('utf-8')) ...
e29ee534accf932ac2b1b407a8c6bc83201e10f7
3,638,402
def should_print(test_function): """should_print is a helper for testing code that uses print For example, if you had a function like this: ```python def hello(name): print('Hello,', name) ``` You might want to test that it prints "Hello, Nate" if you give it the name "Nate". To d...
16a1f675d3dced411fe5a6ffdc566db61ca7890f
3,638,403
def fista(y, A, At, reg_weight, noise_eng, max_iter=100, update_reg=False, **kwargs): """ The FISTA algorithm for the ell1 minimisation problem: min_x |y - Ax|^2 + reg * |x|_1 :param y: the given measurements (here it is the Fourier transform at certain frequencies) :param A: the mapping from the sp...
dece002fff126c68bb6427eb37de5972a24bec00
3,638,404
def produce_segmentation(indices: list[list[int]], wav_name: str) -> list[dict]: """produces the segmentation yaml content from the indices of the probabilistic_dac Args: indices (list[list[int]]): output of the probabilistic_dac function wav_name (str): the name of the wav file (with the .wav ...
cd8267e90f5e69589325a4e261d3f8136b36cc53
3,638,405
def trac_get_tracs_for_object(obj, user=None, trac_type=None): """ Returns tracs for a specific object. """ content_type = ContentType.objects.get_for_model(type(obj)) qs = Trac.objects.filter(content_type=content_type, object_id=obj.pk) if user: qs = qs.filter(user=user) if trac_typ...
9617fc5e417e40fb27bfe90b2f87434902cdb70b
3,638,406
def size_from_ftp(ftp, url): """Get size of a file on an FTP server. Parameters ---------- ftp : FTP An open ftplib FTP session. url : str File URL. Returns ------- int Size in bytes. """ url = urlparse(url) return ftp.size(url.path)
50d21fa95669a9863b32de3a67eda78de713fe7c
3,638,407
def set_name_line(hole_lines, name): """Define the label of each line of the hole Parameters ---------- hole_lines: list a list of line object of the slot name: str the name to give to the line Returns ------- hole_lines: list List of line object with label ...
a57667f269dac62d39fa127b2a4bcd438a8a989b
3,638,408
import torch def dist_to_boxes(points, boxes): """ Calculates combined distance for each point to all boxes :param points: (N, 3) :param boxes: (N, 7) [x, y, z, h, w, l, ry] :return: distances_array: (M) torch.Tensor of [(N), (N), ...] distances """ distances_array = torch.Tensor([]) b...
b3305ec8a4c8d5e0d5cf520e9e22d2c5377fe1de
3,638,409
import logging import os def print_listdir(x): """.""" log = logging.getLogger('SIP.workflow.function') log.info('HERE A') print('Task id = {} {}'.format(x, os.listdir('.'))) return x, os.listdir('.')
738fa091d5f7f9bca0bf43edfbf09eafcba87ba3
3,638,410
def blackwhite2D(data,xsize=None,ysize=None,show=1): """blackwhite2D(data,xsize=None,ysize=None,show=1)) - display list or array data as black white image default popup window with (300x300) pixels """ if type(data) == type([]): data = array(data) w,h = data.shape[1],data.shape[0] ...
78a76fab9f3eb989697b695c8d7b82c877f8dc9a
3,638,411
def contains_digit(s): """Find all files that contain a number and store their patterns. """ isdigit = str.isdigit return any(map(isdigit, s))
941bcee8b6fbca6a60a8845f88a3b5765e3711bb
3,638,412
def to_signed(dtype): """ Return dtype that can hold data of passed dtype but is signed. Raise ValueError if no such dtype exists. Parameters ---------- dtype : `numpy.dtype` dtype whose values the new dtype needs to be able to represent. Returns ------- `numpy.dtype` "...
7be15d324eef6f9686a5866a92ad365a67949424
3,638,413
def listen_for_wakeword(): """Continuously detecting the appeareance of wakeword from the audio stream. Higher priority than the listen() function. Returns: (bool): return True if detected wakeword, False otherwise. """ gotWakeWord = core.listen_for_wakeword() return gotWakeWord
49f600ed303fb9bea11cb9247653c66272fc5491
3,638,414
import sys def import_string(import_name): """Returns a callable for a given setuptools style import string :param import_name: A console_scripts style import string """ import_name = str(import_name).replace(":", ".") try: import_module(import_name) except ImportError: if "."...
2e636dd65c5432f46999e14c46b63ca9e1db7570
3,638,415
from scipy.stats import kurtosis def kurtosis(x,y): """ Calculate kurtosis of the probability distribution of the forecast error if an observation and forecast vector are given. Both vectors must have same length, so pairs of elements with same index are compared. Description: Ku...
b4242f58db8a48dbe9bec03ec641ae78858c28f7
3,638,416
def preprocess_text(sentence): """Handle some weird edge cases in parsing, like 'i' needing to be capitalized to be correctly identified as a pronoun""" cleaned = [] words = sentence.split(' ') for w in words: if w == 'i': w = 'I' if w == "i'm": w = "I'm" ...
4e1d69eaf0adc1ede6bc67563e499602e320e76b
3,638,417
import pkgutil import os def _GetModuleFromPathViaPkgutil(module_path, name_to_give): """Loads module by using pkgutil.get_importer mechanism.""" importer = pkgutil.get_importer(os.path.dirname(module_path)) if importer: if hasattr(importer, '_par'): # par zipimporters must have full path from the zip...
d95eaf07f355a1fbb726d331e2a61ea4e8cf94e1
3,638,418
def weighted_l2_loss(gt_value, pred_value, weights): """Computers an l2 loss given broadcastable weights and inputs.""" diff = pred_value - gt_value squared_diff = diff * diff if isinstance(gt_value, float): gt_shape = [1] else: gt_shape = gt_value.get_shape().as_list() if isinstance(weights, float)...
e7ebc8486a965912b28136013af0e5f4ade403bd
3,638,419
def csr_scale_rows(*args): """ csr_scale_rows(npy_int32 const n_row, npy_int32 const n_col, npy_int32 const [] Ap, npy_int32 const [] Aj, npy_bool_wrapper [] Ax, npy_bool_wrapper const [] Xx) csr_scale_rows(npy_int32 const n_row, npy_int32 const n_col, npy_int32 const [] Ap, npy_int32 const [] Aj, ...
887f6c51d297649232d6fd297380c551dbb47008
3,638,420
import os def get_homography_calibration_files(fullpath=True): """ Returns a list of the homography calibration yaml files in the homgraphies directory of the mct configuration. """ file_list = os.listdir(homographies_dir) dummy, params_file = os.path.split(homography_calibrator_params_file) ...
b6ddcdbee2305fb136a380e0c530aa534f584981
3,638,421
def complexity_hjorth(signal): """**Hjorth's Complexity and Parameters** Hjorth Parameters are indicators of statistical properties initially introduced by Hjorth (1970) to describe the general characteristics of an EEG trace in a few quantitative terms, but which can applied to any time series. The pa...
af5b5fb8925055da4cf48facadd1bed257e40f76
3,638,422
import pandas def load_gecko(): """ target variable is column "A375 Percent rank" """ data_nonessential = pandas.read_excel(settings.pj(settings.offtarget_data_dir, 'GeCKOv2_Non_essentials_Achilles_A375_complete.xls')) #(4697, 31) data_all_A375 = pandas.read_csv(settings.pj(settings.offtarget_data...
31c2db07261fb1b242f4c52808c3b7e6312b1e54
3,638,423
def get_sample_eclat(name): """Read a tweet sample from a sample file and return it in a format eclat can process. """ sampleFile = open(name) X = [] Y = [] line = sampleFile.readline() while line != '': row = line.split() Y.append(int(row[0])) x = [] ...
dd5daa2cd19b087c4b59379b8d3b2c2ea9ec27de
3,638,424
from datetime import datetime def submission_storage_path(instance, filename): """ Function DocString """ string = '/'.join(['submissions', instance.submission_user.user_nick, str(instance.submission_question.question_level), str(instance.submission_question.question_level_id)]) string += '/'+...
587785869da8906234bb572e9d635a892dc3270b
3,638,425
def distance_to_center(n): """Return Manhattan distance to center of spiral of length <n>.""" dist = distances_to_center() for _ in range(n - 1): next(dist) return next(dist)
1301d0370a3f3dca72fb003073522376fd0790c0
3,638,426
import logging as log def detect_tachycardia(heart_rate, age): """ This function makes best guess as to whether tachycardia is being exhibited :param float heart_rate: heart rate in bpm :param int age: age of user/patient :return ble tachycardia: whether or not tachycardia detected """ lo...
2e6dafb581da8599cc71b790f10f45a9789bd617
3,638,427
from typing import List from typing import Mapping from typing import Any from typing import Optional import inspect async def _assert_preconditions_async(preconditions: List[List[Contract]], resolved_kwargs: Mapping[str, Any]) -> Optional[BaseException]: """Assert that the p...
d89c355ed56e350a619e1d7324c8341bb74f827c
3,638,428
import re def moveGeneratorFromStrList (betaStringList, string_mode = True): """ generate the final output of move sequence as a list of dictionary. Input : ['F5-LH', 'F5-RH', 'E8-LH', 'H10-RH', 'E13-LH', 'I14-RH', 'E15-LH', 'G18-RH'] Length of the list: how many moves in this climb to the target...
c2905fffd9d1873c79239199027697e5c6162731
3,638,429
from datetime import datetime def generateVtBar(row): """生成K线""" bar = VtBarData() symbol, exchange = row['symbol'].split('.') bar.symbol = symbol bar.exchange = exchangeMapReverse[exchange] if bar.exchange in ['SSE', 'SZSE']: bar.vtSymbol = '.'.join([bar.symbol, bar.exc...
5beecf78f932c8e1bf76c680157ecd29fbdf9567
3,638,430
import sqlite3 def index_with_links(): """post request that the form link uses """ db = sqlite3.connect('link_shortner.db') c = db.cursor() link = request.forms.get('link') generated_id = gen_id() #row = db.execute('SELECT * from links where link_id=?', generate_id).fetchone() c.execut...
38e4ee6e63bacbc55a40533759c06b836a050e56
3,638,431
import torch import os def SinGAN_generate(Gs, Zs, reals, styles, NoiseAmp, opt, in_s=None, scale_v=1, scale_h=1, n=0, gen_start_scale=0, num_samples=10): """ Generate image with the given parameters. Returns: I_curr(torch.cuda.FloatTensor) : Current Image """ #if torch.is_tensor(in_s) == ...
a6dbd66a8b991033e58ac507c52982d6742c0254
3,638,432
def divide_blend(img_x: np.ndarray, img_y: np.ndarray) -> np.ndarray: """ Blend image x and y in 'divide' mode :param img_x: input grayscale image on top :param img_y: input grayscale image at bottom :return: """ result = np.zeros_like(img_x, np.float_) height, width = img_x.shape f...
27207b209c871a794162ee5b2932344a185668e7
3,638,433
from typing import Hashable from typing import Optional from typing import Tuple from typing import Any def table_to_bipartite_graph( table: Tabular, first_part_col: Hashable, second_part_col: Hashable, *, node_part_attr: str = "part", edge_weight_attr: str = "weight", first_part_data: Opt...
ba37a806e96a4c1747fddf9789115d7a1eb4d074
3,638,434
def init_wavefunction(n_sites,bond_dim,**kwargs): """ A function that initializes the coefficients of a wavefunction for L sites (from 0 to L-1) and arranges them in a tensor of dimension n_0 x n_1 x ... x n_L for L sites. SVD is applied to this tensor iteratively to obtain the matrix product state. ...
8f1a4d456945d9a345f560ee3d87dadbf353e7d3
3,638,435
def num_channels_to_num_groups(num_channels): """Returns number of groups to use in a GroupNorm layer with a given number of channels. Note that these choices are hyperparameters. Args: num_channels (int): Number of channels. """ if num_channels < 8: return 1 if num_channels < 3...
e2095fba2b1b9cdada72d354ddcd781d99e4aa48
3,638,436
def response_message(status, message, status_code): """ method to handle response messages """ return jsonify({ "status": status, "message": message }), status_code
e9dd25f237f264835d507af01a71ef9c826bf28d
3,638,437
def glDrawBuffers( baseOperation, n=None, bufs=None ): """glDrawBuffers( bufs ) -> bufs Wrapper will calculate n from dims of bufs if only one argument is provided... """ if bufs is None: bufs = n n = None bufs = arrays.GLenumArray.asArray( bufs ) if n is None: n = a...
ef5a83ea633138d4cb18d8d2d20736d8c1942bc0
3,638,438
def compare_rendered(obj1, obj2): """ Return True/False if the normalized rendered version of two folium map objects are the equal or not. """ return normalize(obj1) == normalize(obj2)
b7debf048ea41b882003283b6e3b94d257f0e0fa
3,638,439
async def _get_device_client_adapter(settings_object): """ get a device client adapter for the given settings object """ if not settings_object.device_id and not settings_object.id_scope: return None adapter = adapters.create_adapter(settings_object.adapter_address, "device_client") ad...
411b52a4e916d55b46933afbfa4e8513243b4397
3,638,440
def is_reserved(word): """ Determines if word is reserved :param word: String representing the variable :return: True if word is reserved and False otherwise """ lorw = ['define','define-struct'] return word in lorw
0b0e3706bcafe36fc52e6384617223078a141fb2
3,638,441
def verify_figure_hash(name, figure=None): """ Verifies whether a figure has the same hash as the named hash in the current hash library. If the hash library does not contain the specified name, the hash is added to the library. Parameters ---------- name : string The identifier for the...
09ee240c9efbeddd4a0f33401d80b918175a579e
3,638,442
def x_span_contains_y(x_spans, y_spans): """ Return whether all elements of y_spans are contained by some elements of x_spans :param x_spans: :type x_spans: :param y_spans: :type y_spans: """ for i, j in y_spans: match_found = False for m, n in x_spans: i...
c366a5a5543e2fe9f6325cd3d31eccffb921693c
3,638,443
import argparse def parse_args(): """Parse arguments and return them :returns: argparse object """ parser = argparse.ArgumentParser() parser.add_argument( '-c', '--config', help='configuration file', required=True) return parser.parse_args()
d0fc1399c058f53558e08f13811c9709e518fd84
3,638,444
import time def log(fn): """ logging decorator for the for the REST method calls. Gets all important information about the request and response, takes the time to complete the calls and writes it to the logs. """ def wrapped(self, *args): try: start = time() ret...
8efcfcf043c220565092971749a12876a55641dc
3,638,445
def deal_line(text_str1, text_str2, para_bound=None): """行合并和段落拆分""" global result_text text_str2 = text_str2.strip() len_text_str2 = len(text_str2) if len_text_str2 > 3 and len(set(text_str2)) == 1: # 处理 ***** 这类分割线 st = list(set(text_str2))[0] # new_file.write(' ' + st * 24 +...
b984cefd842071fed3359ac36f8bae46e916e956
3,638,446
def resized_image(image: np.ndarray, max_size: int) -> np.ndarray: """Resize image to feature_process_size.""" h, w = image.shape[:2] size = max(w, h) if 0 < max_size < size: dsize = w * max_size // size, h * max_size // size return cv2.resize(image, dsize=dsize, interpolation=cv2.INTER_...
a32f0639b8b59cef8817861d123b5c304b7c243c
3,638,447
def load_folder_list(args, ndict): """ Args: dict : "name_run" -> path """ l = [] for p in ndict: print("loading %s" % p) l.append(load_pickle_to_dataframe(args, p)) d = pd.concat(l) d = d.sort_values("name_run") print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%...
bd434fd93b3cb06a18d40edc48f8119442e7f0ff
3,638,448
def charge_initial(): """ Not currently in use, parking spot id gets passed in and it carries over and passes it into the stripe charge view. """ spot_id = int(request.args.get('id')) spot = AddressEntry.query.get(spot_id) return render_template('users/charge_initial.html', key=stripe_keys['...
f971b5c69954ce2026d2c4b08d6877c9f7da6067
3,638,449
import csv def read_csv_from_file(file): """ Reads the CSV data from the open file handle and returns a list of dicts. Assumes the CSV data includes a header row and uses that header row as fieldnames in the dict. The following fields are required and are case-sensitive: - ``artist`` ...
89cfce0be6270076230051a6e852d1add3f4dcaf
3,638,450
def findOutliers(time, flux, gap=None, threshold_sigma=4, precision_days=0.0205, maxClusterLen = 2 ): """ Identify single point outliers. Preserves consecutive outliers, and those that are evenly spaced in time. This protects short dur...
223f0c06febb9699f5d8fda6fa8b4d2f54713e45
3,638,451
def identify_denonavr_receivers(): """ Identify DenonAVR using SSDP and SCPD queries. Returns a list of dictionaries which includes all discovered Denon AVR devices with keys "host", "modelName", "friendlyName", "presentationURL". """ # Sending SSDP broadcast message to get devices devices ...
712cba308d150ec179a390c27ae6931595cdffa9
3,638,452
def get_index_settings(index): """Returns ES settings for this index""" return (get_es().indices.get_settings(index=index) .get(index, {}).get('settings', {}))
6d5d13bc30fdf8db666206bb07c3310394f3ff44
3,638,453
import hashlib import six def make_hashkey(seed): """ Generate a string key by hashing """ h = hashlib.md5() h.update(six.b(str(seed))) return h.hexdigest()
38d088005cb93fc0865933bbb706be171e72503a
3,638,454
import asyncio async def report(database, year, month, limit): """Get a report.""" matches_query = """ select count(*) as count from matches where extract(year from played)=:year and extract(month from played)=:month """ players_query = """ select count(distinct players...
91059c5a8bd44536f24a7edbb88ff27b9036b83a
3,638,455
import sys def compose_ntx_graph(input_file=None, delimiter=None, weighted=None): """ This function creates a networkx graph from provided file :param input_file: Input file path :param delimiter: separator for the column of the input file :param weighted: Simple yes/no if the input file is weight...
d2622fac8ca97083c49a054406ccb44752f54871
3,638,456
def dy3(vector, g, m1, m2, L1, L2): """ Abbreviations M = m0 + m1 S = sin(y1 - y2) C = cos(y1 - y2) s1 = sin(y1) s2 = sin(y2) Equation y3' = g*[m2 * C * s2 - M * s1] - S*m2*[L1 * y3^2 * C + L2*y4^2] ------------------------------------------------------------- ...
b93086cfcbb9d5f32143279ad01972d3f8719a78
3,638,457
from typing import Any def getType(resp: falcon.Response, class_type: str, method: str) -> Any: """Return the @type of object allowed for POST/PUT.""" for supportedOp in get_doc(resp).parsed_classes[class_type]["class"].supportedOperation: if supportedOp.method == method: return supportedO...
d20b77b4f40d266e685ce87f67d8f2fcbcfbe3eb
3,638,458
def full_data_numeric(): """DataFrame with numeric data """ data_dict = {'a': [2, 2, 2, 3, 4, 4, 7, 8, 8, 8], 'c': [1, 2, 3, 4, 4, 4, 7, 9, 9, 9], 'e': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] } df = pd.DataFrame(data_dict) return df
ebd105f2648475dc7dcd40f51482d18e29486254
3,638,459
def fix(x): """ Replaces spaces with tabs, removes spurious newlines, and lstrip()s each line. Makes it really easy to create BED files on the fly for testing and checking. """ s = "" for i in x.splitlines(): i = i.lstrip() if i.endswith('\t'): add_tab = '\t' ...
ecd3a4d7f470feae1b697025c8fbf264d5c6b149
3,638,460
def get_collect_method(collect_method_name): """Return the collect method.""" try: collect_method = CollectMethod.get(name=collect_method_name) except ValueError: raise RuntimeError(f'Collect Method {collect_method_name} not found!') return collect_method
b80fcb916d461deea1784386062017291292f218
3,638,461
def TriangleBackwardSub(U,b): """C = TriangleBackwardSub(U,b) Solve linear system UC = b """ C = solve(U,b) return C
95c7fb76ad02a5546a79b95f18b51fe385307329
3,638,462
from unittest.mock import patch def test_binance_query_balances_unknown_asset(function_scope_binance): """Test that if a binance balance query returns unknown asset no exception is raised and a warning is generated. Same for unsupported asset.""" binance = function_scope_binance def mock_unknown_asse...
7521fd3039398c3eedccb16e16202687b4c28b2d
3,638,463
def petsc_to_stencil(x, Xh): """ converts a numpy array to StencilVector or BlockVector format""" x = x.array u = array_to_stencil(x, Xh) return u
6df02bbbfb9e9e386ca03510f2e4d563a6fed1aa
3,638,464
from typing import Optional import contextlib def index_internal_txs_task(self) -> Optional[int]: """ Find and process internal txs for monitored addresses :return: Number of addresses processed """ with contextlib.suppress(LockError): with only_one_running_task(self): logger....
b1a40ec713ff8d302f5c47b2c5d41300c699f3b4
3,638,465
import math def make_lagrangian(func, equality_constraints): """Make a Lagrangian function from an objective function `func` and `equality_constraints` Args: func (callable): Unary callable with signature `f(x, *args, **kwargs)` equality_constraints (callable): Unary callable with signature `...
c5795cded21e9cc4a7092eee63b88a4fac3b346a
3,638,466
import argparse def render_task(task: todotxt.Task, namespace: argparse.Namespace, level: int = 0) -> str: """Render one task.""" indent = (level - 1) * " " + "- " if level else "" rendered_task = colorize(reference(task, namespace), namespace) rendered_blocked_tasks = render_blocked_tasks(task, name...
ff50a060c7898bba5aac02f85d9eefd903465cf0
3,638,467
def ungroup(expr): """Helper to undo pyparsing's default grouping of And expressions, even if all but one are non-empty. """ return TokenConverter(expr).addParseAction(lambda t: t[0])
c007a51e5073d8a3cbcbe52ca32ad84d58f4100a
3,638,468
import os def remove_tmp_directories(): """ remove tmp directories submitted in tmp_directories Returns: True """ for tmp_dir in tmp_directories: os.remove(tmp_dir) return True
43d37e8382ada5073f072832a83f78f027003048
3,638,469
from typing import Type from typing import List from typing import cast def get_actual_type(arg_type: Type, kind: int, tuple_counter: List[int]) -> Type: """Return the type of an actual argument with the given kind. If the argument is a *arg, return the individual argument item. """ ...
cb113cea89f5fd6835314c53b35afce4fa3b74a1
3,638,470
def test_qnn_legalize(): """Test directly replacing an operator with a new one""" def before(): x = relay.var("x", shape=(1, 64, 56, 56), dtype='int8') y = relay.qnn.op.requantize(x, input_scale=1, input_zero_point=0, ...
b6f4a930e5c7156e60a5b26583b6e8fc48a6f441
3,638,471
import yaml def load(data, schema, yamlLoader=yaml.UnsafeLoader): """ Loads the given data and validates it according to the schema provided. Data must be either JSON or YAML, it must be a dictionary, a path, or a string of JSON. Schema must be JSON, it must be a dictionary, a path, or a string of JSO...
e7f29e1b61e60ce1cac5b1b1217f1df645691c17
3,638,472
from typing import List def calculate_slice_rotations(im_stack: np.ndarray, max_rotation:float = 45) -> List[float]: """Calculate the rotation angle to align each slice so the objects long axis is aligned with the horizontal axis. Parameters ---------- im_stack : np.ndarray A stack of ima...
42c0fdbdf02e937f449cb3ca137588003c715651
3,638,473
def calc_rest_interval(data): """ SubTool for Investigate: after median_deviation filters through all the points run entropy on the remaining non_rest points. This will filter the close but could still be rest points. """ lst, rest = median_deviation(data) average = median(data) st_entr...
7710e0784a5a025d99c8ead9799b1062942e3cdc
3,638,474
def get_objanno(fin_anno, godag, namespace='all'): """Get annotation object""" fin_full = get_anno_fullname(fin_anno) return get_objanno_factory(fin_full, godag=godag, namespace=namespace)
5e071190596ab37943d4001b4f03cf20d6395e06
3,638,475
def create_table_descriptives(datasets): """Merge dataset descriptives.""" df = pd.concat( [pd.read_json(ds, orient="index") for ds in datasets], axis=0 ) df.index.name = "dataset_name" return df
7c4554381ffb14572d949c27035411567d69e25d
3,638,476
def get_ngram_universe(sequence, n): """ Computes the universe of possible ngrams given a sequence. Where n is equal to the length of the sequence, the resulting number represents the sequence universe. Example -------- >>> sequence = [2,1,1,4,2,2,3,4,2,1,1] >>> ps.get_ngram_universe(sequence, 3) 64 """ # if...
3dbfe1822fdefb3e683b3f2b36926b4bb066468f
3,638,477
from typing import Union from typing import Iterable def as_nested_dict( obj: Union[DictLike, Iterable[DictLike]], dct_class: type = DotDict ) -> Union[DictLike, Iterable[DictLike]]: """ Given a obj formatted as a dictionary, transforms it (and any nested dictionaries) into the provided dct_class ...
a89261253174ce5b75d61343f0b45d3fe65e12f9
3,638,478
def twoindices_positive_up_to(n, m): """ build 2D integer indices up to n (each scanned from 0 to n) """ if not isinstance(n, int) or n <= 0: raise ValueError("%s is not a positive integer" % str(n)) nbpos_n = n + 1 nbpos_m = m + 1 gripos = np.mgrid[: n : nbpos_n * 1j, : m : nbpo...
63f850703f7598f1a4611c13700aa1921d77dd1a
3,638,479
import os import glob def get_data_lists(data, MOT=False): """ Prepare rolo data for SORT Arguments: data: config of the following form: { 'image_folder': data_folder + 'images/train/', 'annot_folder': data_folder + 'annotations/train/', ...
537c3a8e1ffa8ab0a6835738b2032f26e1157406
3,638,480
def ban_user(request, user): """Bans a given user.""" user = User.query.filter_by(username=user).first() if user is None: raise NotFound() next = request.next_url or url_for('admin.bans') if user.is_banned: request.flash(_(u'The user is already banned.')) return redirect(next...
dd8c2a43a3843a6055e9e690d8cffee8cfac2b0e
3,638,481
def lastDate(): """[summary] lastDate() function: return the total revenue of the nearest day Returns: [type]: [description] """ lastDate = totalDate().tail(1) last_date = lastDate.iloc[0]['total'].round(2) return last_date
93130bf39dc2a82fa2cae11a6ea11468211f61b6
3,638,482
from libmkMeteo import mkmeteo4lingrars from liblingraRS import lingrars def processlingrarow(col, rows, pixelWidth, pixelHeight, xO, yO, plot, netcdffile, rsdir, becsmosdir): """ Launch a single pixel of processing for LingraRS :param col: column in Grassland raster file :param rows: total rows in Gr...
b0b19c514ed1ca1ad324962fac0023b7af501503
3,638,483
import json def multitask_result(request): """多任务结果""" task_id = request.GET.get('task_id') task_obj = models.Task.objects.get(id=task_id) results = list(task_obj.tasklog_set.values('id','status', 'host_user_bind__host__hostname', 'host...
c9c37fe4852a8c04662a5061445c1565400e94a1
3,638,484
from typing import Dict def process_xpath_list(node, property_manifest: Dict): """ Return a list of values as a result of running a list of XPath expressions against an input node :param node: Input node :param property_manifest: Manifest snippet of the property :return: List of values """...
e52ef3a7ff6b2f74554a69a5fec53125c077f6e5
3,638,485
def collect_username_and_password(db: Session) -> UserCreate: """Collect username and password information and validate""" username = get_username("Enter your username: ") password = get_password("Enter your password: ") verify_pass = get_password("Enter your password again: ") if password != verif...
be1557a4aa24cfb653c5e03f7f3cb340be1a6c1b
3,638,486
def replace_header(input_df): """replace headers of the dataframe with first row of sheet""" new_header = input_df.iloc[0] input_df = input_df[1:] input_df.columns=new_header return input_df
c8946fc269dd313b80df421af8d0b3fc6c47aed7
3,638,487
def cartToRadiusSq(cartX, cartY): """Convert Cartesian coordinates into their corresponding radius squared.""" return cartX**2 + cartY**2
3fb79d2c056f06c2fbf3efc14e08a36421782dbd
3,638,488
def unique_entity_id(entity): """ :param entity: django model :return: unique token combining the model type and id for use in HTML """ return "%s-%s" % (type(entity).__name__, entity.id)
c58daf9a115c9840707ff5e807efadad36a86ce8
3,638,489
def normalize_tuple(value, n, name): """Transforms a single int or iterable of ints into an int tuple. # Arguments value: The value to validate and convert. Could be an int, or any iterable of ints. n: The size of the tuple to be returned. name: The name of the argument being ...
cf396bac48b720686bb65ae7ab91b2e4cb22ac0e
3,638,490
def load_user(user_id): """ @login_manager.user_loader Passes in a user_id to this function and in return the function queries the database and gets a user's id as a response... """ return User.query.get(int(user_id))
2c2a2e7f6f9a5bc7392056bfd16402c9d2e96c22
3,638,491
def replaceall(table, a, b): """ Convenience function to replace all instances of `a` with `b` under all fields. See also :func:`convertall`. .. versionadded:: 0.5 """ return convertall(table, {a: b})
19d6c0fb60c71994de02deafb5ec9c2995aba622
3,638,492
def get_job_metadata(ibs, jobid): """ Web call that returns the metadata of a job CommandLine: # Run Everything together python -m wbia.web.job_engine --exec-get_job_metadata # Start job queue in its own process python -m wbia.web.job_engine job_engine_tester --bg #...
24ba96d6a71f105057a9fc9012de9edb187787d5
3,638,493
import math def create_learning_rate_scheduler(max_learn_rate, end_learn_rate, warmup_proportion, n_epochs): """Learning rate scheduler, that increases linearly within warmup epochs then exponentially decreases to end_learn_rate. Args: max_learn_rate: Float. Maximum learning rate. end_lea...
5c5649e429ad5f138894d30064c24bf23e547f85
3,638,494
def matchyness(section, option): """Assign numerical 'matchyness' value between target and value Parameters: section -- target value option -- proposed match """ if section != option: return _hc.NEQ if isinstance(section, rt.flask_placeholder): if isinstance(option, rt.flask_placeholder): return _hc.PP ...
c8e3773a8afe190181fd7552460852a27b2534d3
3,638,495
def log_sum_exp_elem(*a): """ :param a: elements :return: (a[0].exp() + a[1].exp() + ...).log() """ bias = max(a).detach() ans = bias + sum([(ai-bias).exp() for ai in a]).log() return ans
a87871a7c8af9d2c6c8db683ba63124319d09a0d
3,638,496
def car_portrayal(agent): """Visualises the cars for the Mesa webserver :return: Dictionary containing the settings of an agent""" if agent is None: return portrayal = {} # update portrayal characteristics for each CarAgent object if isinstance(agent, CarAgent): if agent.is_fro...
68c0bffb02299f2b03abf6ee2dc590375ad8e2a5
3,638,497
import re from typing import OrderedDict def _load_spc_format_type_a(filepath: str): """load A(w,k) in the spc format type a Args: filepath (str): output filename Returns: np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray: kcrt, Awk, kdist, energy, kpath """ with open(fi...
0a5c3f316875495e37502dd426e6eee7dd76ee53
3,638,498
def variable_to_json(var): """Converts a Variable object to dict/json struct""" o = {} o['x'] = var.x o['y'] = var.y o['name'] = var.name return o
86497a7915e4825e6e2cbcfb110c9bc4c229efed
3,638,499