content
stringlengths
22
815k
id
int64
0
4.91M
def vvisegment2dict( link): """ Intern rutine for å gjøre om visveginfo-data til håndterbar liste """ start = round( float( link['FromMeasure'] ), 8 ) slutt = round( float( link['ToMeasure'] ), 8 ) mydict = { 'vegref' : str( link['County']).zfill(2) + str( link['Municipality'] )....
57,500
def pow_frac(T1, T2, freqs): """ Fractional power between two physical temperatures """ return bb_pow_spec(freqs, T1) / bb_pow_spec(freqs, T2)
57,501
def _generate_resources_cfg(ips: list = (), cpus: int = 4): """ Generates the resources.xml according to the given parameters. :param ips: List of ip of the worker nodes. :param cpus: Number of cores per worker node. :returns: The cfg file contents for the resources. """ # ./generate_resourc...
57,502
def setup_mongo() -> pymongo.collection.Collection: """Setup mongo client.""" client = pymongo.MongoClient("mongodb://localhost:27017/") vdm_database = client["vdm"] return vdm_database
57,503
def add_doub_doub(db1, db2, entityName): """ ## This function adds two doubles ## Input : db1 - double (number) : db2 - double (value) """ add = Add_of_double(entityName) add.sin1.value = db1 add.sin2.value = db2 return add
57,504
def test_sample_output_mapping(): """Test mapping from samples to output indices.""" assert sample_output_mapping(None, None) is None assert sample_output_mapping([0, 1], None) == [0, 1] assert sample_output_mapping([0, 1], [2, 1, 0]) == [2, 1] assert sample_output_mapping([0, 0], [2, 1, 0]) == [2...
57,505
def build_dataset(nb_holograms, nb_file, nb_holograms_class, nb_class, hol_dataset_list): """ Build a large dataset with datataset with small datasets. """ # Create new dataset nb_total = nb_holograms * nb_file hol_dataset = np.zeros([200, 200, nb_total], dtype=complex) init_list = np.aran...
57,506
def main(): """ NAME goprinc.py DESCRIPTION calculates Principal components from dec/iinc data INPUT FORMAT takes dec/inc as first two columns in space delimited file SYNTAX goprinc.py [options] [< filename] OPTIONS -h prints help message and quits ...
57,507
def test_list_base64_binary_length_1_nistxml_sv_iv_list_base64_binary_length_2_2(mode, save_output, output_format): """ Type list/base64Binary is restricted by facet length with value 6. """ assert_bindings( schema="nistData/list/base64Binary/Schema+Instance/NISTSchema-SV-IV-list-base64Binary-le...
57,508
def check_for_invalid_qos_spec_combination(info, volume_type): """Invalidate QOS spec if both legacy and non-legacy info is present.""" if info['legacy'] and info['spec']: msg = _('Conflicting QoS specifications in volume type ' '%s: when QoS spec is associated to volume ' ...
57,509
def percentage(value): """Return a float with 1 point of precision and a percent sign.""" return format(value, ".1%")
57,510
def PricingAddBondPricingDetails(builder, bondPricingDetails): """This method is deprecated. Please switch to AddBondPricingDetails.""" return AddBondPricingDetails(builder, bondPricingDetails)
57,511
def get_chunk_size(N, n): """Given a two-dimensional array with a dimension of size 'N', determine the number of rows or columns that can fit into memory. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of ar...
57,512
def get_peering_partner(peering): """ Inserts a new node of the type Peering partner and ensures that this node is unique for AS number. Returns the created node. """ try: return PEER_AS_CACHE[peering['as_number']] except KeyError: logger.info('Peering Partner {name} not in c...
57,513
def get_v3_atlas_fine_path(): """Get v3 atlas fine path. Returns ------- : pathlib.Path v3 atlas fine path. """ return get_data_dir() / "ccfv3_atlas_fine.nrrd"
57,514
def run_action(action, conv_list, params, return_dict): """ This method runs the specified action. Args: action(str): The action name, e.g., 'retrieval', 'qa', etc. conv_list(list): List of util.msg.Message, each corresponding to a conversational message from / to the user. This lis...
57,515
def delete_comment(comment_id): """Delete an existing comment. For admins only.""" if current_user.roles.role_label != 'admin': flash("Admin privileges required.", "danger") return redirect("/") if request.method == "POST": comment = Comment.query.get_or_404(comment_id) ...
57,516
def bfill(arr, dim=None, limit=None): """backfill missing values""" axis = arr.get_axis_num(dim) # work around for bottleneck 178 _limit = limit if limit is not None else arr.shape[axis] return apply_ufunc( _bfill, arr, dask="parallelized", keep_attrs=True, ...
57,517
def resource_descriptor(session, Type='String', RepCap='', AttrID=1050304, buffsize=2048, action=['Get', '']): """[Get/Set Resource Descriptor] """ return session, Type, RepCap, AttrID, buffsize, action
57,518
def dbdirname(db, rc): """Gets the database dir name.""" dbsdir = os.path.join(rc.builddir, '_dbs') dbdir = os.path.join(dbsdir, db['name']) return dbdir
57,519
def interpret_biology(all_cpgs_pickle,shapley_data_list,output_dir, analysis, n_workers, lola_db, individuals, classes, max_gap, class_intersect, length_output, set_subtraction, intersection, collections, gsea_analyses, gsea_pickle, depletion, overlap_test, cpg_set, top_global, extract_library): """Interrogate CpGs...
57,520
def delete_obj(patientid, objid): """ Get info of a doctor in the system. :param doctorid: doctor's uid :returns: a status, a str ( doctor's info on success, err info on failure) """ # print(doctorid) info = {} try: resp_dict = {} conn = swiftclient.client.Connection(co...
57,521
def min_version_string(): """Returns the minimum supported API version (as a string)""" return _MIN_VERSION_STRING
57,522
def coord_clip(pos, chrlen, binsize=128000, window_radius=16000000): """ Clip the coordinate to make sure that full window centered at the coordinate to stay within chromosome boundaries. coord_clip also try to preserve the relative position of the coordinate to the grid as specified by binsize...
57,523
def get_peak_length(lc_table, peak_frac=0.75): """Returns peak length for given lightcurve table """ lc_filled = fill_lightcurve(lc_table) peak = np.max(lc_table.flux) mask = lc_filled[:, 1] > peak_frac*peak time_slice = lc_filled[mask, 0] return time_slice[-1] - time_slice[0]
57,524
def filter_files(path_list: List[Path]): """ Categorize paths into libraries or files Libraries are resolved with the linker and are to be imported in a special location. They can only be ELF files. Files are referenced using their paths and have to be imported at the same location. They can b...
57,525
def get_collocations(relations): """ Calculate collocations based on the list of all relations in the corpus input: list of all binary syntactic relations in the corpus (result of get_relations()) output: pandas DataFrame with all syntactic collocations and their llr scores """ print('Calculatin...
57,526
def prefix(expof10): """ Args: expof10 : Exponent of a power of 10 associated with a SI unit character. Returns: str : One of the characters in "yzafpnum kMGTPEZY". """ prefix_levels = (len(SI_PREFIX_UNITS) - 1) // 2 si_level = expof10 // 3 if abs(si_level) > ...
57,527
def _Pick_CF3(st, cf3, iniPick, f=np.linspace(50, 1000, 20), tol=10e-3): """ input : st - stream object cf3 - characteristic function number 3 f - list of frequency (used instead of the Ns parameter) tol - maximum time to move a pick """ sr = st.traces[0].stats['sampling_rate'] ST =...
57,528
def flatten_dims(tensor, start=0, end=None, name=None): """Flatten a contiguous range of dimensions in a tensor. Args: tensor: The tensor or array to reshape. start: First dimension to flatten. An integer. end: One past the last the last dimension to flatten. An integer or `...
57,529
def ridgeTest(xArr, yArr): """ Desc: 函数 ridgeTest() 用于在一组λ上测试结果 Args: xArr:样本数据的特征,即 feature yArr:样本数据的类别标签,即真实数据 Returns: wMat:将所有的回归系数输出到一个矩阵并返回 """ xMat = np.mat(xArr) yMat = np.mat(yArr).T # 计算Y的均值 yMean = np.mean(yMat, 0) yMat = yMat - yMe...
57,530
def gumbel_softmax(logits, temperature, hard=True): """Sample from the Gumbel-Softmax distribution and optionally discretize. Args: logits: [batch_size, n_class] unnormalized log-probs temperature: non-negative scalar hard: if True, take argmax, but differentiate w.r.t. soft sample y Returns: [bat...
57,531
def create_Walternating_layered_ansatz(qc: qiskit.QuantumCircuit, thetas: np.ndarray, num_layers: int = 1): """Create Walternating layered ansatz Args: - qc (qiskit.QuantumCircuit): init circuit - thetas (np.ndarray): par...
57,532
def screen(corners, h=0.1): """ Creates a screen. Parameters ---------- corners : np.ndarray A (4 x 3) array that defines four corners of the screen. h : float A floating point number specifying the grid size. Output ------- grid : bempp.Grid A structured gr...
57,533
def stdoutIO(stdout=None): """ Catch the stdout of the imported notebook cells. Notes ----- Adapted from `stackoverflow.com/questions/3906232 <https://stackoverflow.com/questions/3906232/python-get-the-print-output-in-an-exec-statement/3906390#3906390>`_ Note that this approach does not captu...
57,534
def test_command_init_scenario(temp_dir, DRIVER): # noqa """Verify that init scenario works.""" role_directory = os.path.join(temp_dir.strpath, "test-init") cmd = [ "molecule", "init", "role", "test-init", ] result = molecule.util.run_command(cmd) assert result.r...
57,535
def execute(sql, con, cur=None, params=None, flavor='sqlite'): """ Execute the given SQL query using the provided connection object. Parameters ---------- sql : string Query to be executed con : SQLAlchemy engine or DBAPI2 connection (legacy mode) Using SQLAlchemy makes it possi...
57,536
def lower(s: "Stream[str]") -> "Stream[str]": """Computes the lowercase of a string stream. Parameters ---------- s : `Stream[str]` A string stream. Returns ------- `Stream[str]` A lowercase string stream. """ return s.apply(lambda x: x.lower()).astype("string")
57,537
def mean_feature(data, rolling_window, num): """Computes the mean for a given lag and its rolling window Given a set number of lags in the past, a set rolling window and the input dataset, computes the rolling average mean for the given window. Parameters ---------- data: pd.Dataframe ...
57,538
def test_for_loop_with_enumerate_start(): """ По умолчанию нумерация индексов последовательности начинается с 0, то есть enumerate(iter) можно переписать как enumerate(iter, start=0). Можно поменять начальное значение индексов при помощи переменной start """ list1 = ['Python'] f...
57,539
def cmgListToWaterArray(stacks:list,product="MOD09CMG") -> "numpy array": """ This function takes a list of CMG .hdf files, and returns a binary array, with "0" for non-water pixels and "1" for water pixels. If any file flags water in a pixel, its value is stored as "1" *** Parameters ---------- s...
57,540
def decode(packed_list): """ implement the function packed the string """ # Empty list of tuple decode_str = "" list_len = len(packed_list) for i in range(list_len): # element of packed list str_tuple_count = packed_list[i] # find number of counting from tuple ...
57,541
def travel_space_separated(curr): """Print space separated linked list elements.""" if curr is None: return "" print(curr.data, end=' ') travel_space_separated(curr._next)
57,542
def get_PDF_content(query_string, link): """ Gets all of the text from a PDF document Parameters ---------- query_string : string the query that generated the PDF document link : string the URL for the document Returns ------- string the visible text in...
57,543
def _generate_subparser(parser, name, description=None, subcommand=False): """Helper function to return a subparser with the given options""" subparser = parser.add_parser( name, description=description, formatter_class=RawDescriptionHelpFormatter ) if subcommand: subpar...
57,544
def identity_matrix(dim): """Construct an identity matrix. Parameters ---------- dim : int The number of rows and/or columns of the matrix. Returns ------- list of list A list of `dim` lists, with each list containing `dim` elements. The items on the "diagonal" are ...
57,545
def get_zscale(self): """Get the qcodes_colorbar scaling :return: str "linear" or "log" :raises: AttributeError """ if not hasattr(self, 'qcodes_colorbar'): raise AttributeError("Axes object does not have a colorbar.") if isinstance(self.qcodes_colorbar.formatter, ticker.LogFormatter):...
57,546
def train_logistic_regression(X_train, y_train, X_val, y_val, min_coef=1, max_iter=2000): """ Logistic regression training algorithm on binary features :param X_train: Pandas DataFrame of train set features :param y_train: Pandas Series of train set binary target :param X_val: Pandas DataFrame of v...
57,547
def result2list(foo): """Convert from ParseResults to normal list.""" if isinstance(foo, ParseResults): return [result2list(bar) for bar in foo] else: return foo
57,548
def OutputFitsFileExtensions(column_dicts, template, outfilename, mode="append", headers_info=[], primary_header={}): """ Function to output a fits file in my standard format. Parameters: =========== - column_dicts: list of dictionaries Maps the name of the column ...
57,549
def cluster_shutdown(cluster): """ Shutdown an entire cluster, cancelling any spot requests and terminating all instances in the cluster. Also permanently deletes any record of the cluster. RouteParams: cluster: the name of a cluster Returns: A status code indicating success ...
57,550
def collect_jsonschema_errors(metadata, convention, bq_json=None): """Evaluate metadata input against metadata convention using JSON schema returns False if input convention is invalid JSON schema """ # this function seems overloaded with its three tasks # schema validation, non-ontology errors, ont...
57,551
def kg2m3H2O_hot(kg): """kg -> m^3 (50 C hot water)""" return kg/988.1
57,552
def print_debug(name, *args, **kwargs): """Printing Debug Function to display formatted output in decorator options Args: name: Name of Process [like "Function Source:"] *args: Variable length argument list. **kwargs: Arbitrary keyword arguments. Returns: called print fu...
57,553
def feeder(url: str, archived: bool, archived_only: bool, verbose: bool) -> List[str]: """Create and return a list of urls according to the input.""" thread_urls = [] # list of thread urls if url.endswith(".txt"): with open(url, "r") as f: thread_urls.extend(map(str.strip, f)) # ...
57,554
def convert_torch_resnet_weights_to_serialClassificationNet(model, state_dict, strict=True): """Convert resnet weights from torchvision to vega weights name.""" names = convert_names(model) new_state_dict = OrderedDict() for name in names: state_name = name state_name = state_name.replac...
57,555
def main(argv): """ Main program """ if len(argv) < 2: print("Usage: {0} <input.cl>... <output.cpp>".format(sys.argv[0]), file = sys.stderr) return 2 with open(sys.argv[-1], 'w') as outf: print(dedent(''' #include <clogs/visibility_push.h> ...
57,556
def load_yaml(file_path): """Load a yaml file into a dictionary""" try: with open(file_path, 'r') as file: return yaml.safe_load(file) except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available return None
57,557
def push_entries(entries, calendar_id): """Shows basic usage of the Google Calendar API. Creates a Google Calendar API service object and outputs a list of the next 10 events on the user's calendar. """ credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service = ...
57,558
def build_column(min_trays, max_trays, xD, xB): """Builds the column model.""" m = ConcreteModel('benzene-toluene column') m.comps = Set(initialize=['benzene', 'toluene']) min_T, max_T = 300, 400 max_flow = 500 m.T_feed = Var( doc='Feed temperature [K]', domain=NonNegativeReals, ...
57,559
def coerce(fun): """Decorates a function and coerces each of the inputs of the function into a Forward object. Many of our functions would like to operate on Forward objects instead of raw values. For example, __add__ might get an integer in the case of Forward('x', 5) + 2, but we want the 2 to be ...
57,560
def average_gradients(model): """ Gradient averaging. """ size = float(dist.get_world_size()) for param in model.parameters(): if param.grad is not None: dist.all_reduce(param.grad.data, op=dist.ReduceOp.SUM) param.grad.data /= size
57,561
def DatasetWithIndices(cls): """ Modifies the given Dataset class to return a tuple data, target, index instead of just data, target. """ def __getitem__(self, index): data, target = cls.__getitem__(self, index) return data, target, index return type(cls.__name__, (cls,), { ...
57,562
def hex_int_range(min=None, max=None, min_included=True, max_included=True): """Validate that the config option is an integer in the given range.""" return All( hex_int, Range(min=min, max=max, min_included=min_included, max_included=max_included), )
57,563
def wq_reactor(wait_time=1, newline_time=3600, success_time=3600, iters=np.inf): """ Reactor Loop: Waits for tasks to finish in the Work Queue and executes follow-up functions if necessary. When running in Work Queue mode, this Parameters ---------- wait_time : int How long to wait in ...
57,564
def int2float_rd(x): """ See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_int2float_rd.html :param in: Argument. :type in: int32 :rtype: float32 """
57,565
def execute_graphql_request(payload): """Execute queries and mutations on the GraphQL API.""" url = 'http://graphql:5433/graphql' # Should be moved to config file headers = {'Content-Type': 'application/graphql'} response = requests.post(url, headers=headers, data=payload) status = response.status_...
57,566
def s3_put(bucket_name, file_path, file_name, payload): """ Use for Uploading a file as StringIO object :param str bucket_name: s3 bucket name :param str file_path: string name, sub folders are allowed :param str file_name: name that you need to be in destination S3 Bucket location :param String...
57,567
def add_contrastive_loss(hidden, hidden_norm=True, temperature=1.0, tpu_context=None, weights=1.0): """Compute the instance discrimination loss for the model. Args: hidden: hidden vector (`Tensor`) of shape (bsz...
57,568
def device_enable_twin(connectionId): # noqa: E501 """Enable device twins # noqa: E501 :param connectionId: Id for the connection :type connectionId: str :rtype: None """ # changed from return 'do some magic!' device_glue.enable_twin_sync(connectionId)
57,569
def timed_call(f, args): """Call function f with arguments args and time its run time. Args: f: The function to call args: The arguments to pass to f Returns: Return the result of the function call and how much time it takes as tuple e.g. (result, time). """ start...
57,570
def create_code_snapshot(root, dst_path, extensions=(".py", ".json"), exclude=()): """Creates tarball with the source code""" import tarfile from pathlib import Path with tarfile.open(str(dst_path), "w:gz") as tar: for path in Path(root).rglob("*"): if '.git' in path.parts: ...
57,571
def test_set_redis(): """ When Redis params are provided, set a connection instance. """ config = get_config('read/set-redis') # Should set an instance. assert isinstance(config.redis, StrictRedis) args = config.redis.connection_pool.connection_kwargs # Should use config args. a...
57,572
def count_words(texts): """ Counts the words in the given texts, ignoring puncuation and the like. @param texts - Texts (as a single string or list of strings) @return Word count of texts """ if type(texts) is list: return sum(len(t.split()) for t in texts) return len(texts.split())
57,573
def train_circuit(circuit,n_params,n_cnots,X_train,Y_train,X_test,Y_test,optim,optimoptions,inference='wall_clock',rate_type='accuracy',**kwargs): """Develop and train your very own variational quantum classifier. Use the provided training data to train your classifier. The code you write for this challeng...
57,574
def calvin_astgen(source_text, app_name, verify=True): """ Generate AST from script, return processed AST and issuetracker. Parameter app_name is required to provide a namespace for the application. Optional parameter verify is deprecated, defaults to True. """ cg, issuetracker = _calvin_cg(sou...
57,575
def file_response(request, filepath, block=None, status_code=None, content_type=None, encoding=None, cache_control=None): """Utility for serving a local file Typical usage:: from pulsar.apps import wsgi class MyRouter(wsgi.Router): def get(self, request): ...
57,576
def process_results(data_to_process, producer, output_topic): """ Process analyzed data and modify it into desired output. :param data_to_process: analyzed data :param producer: Kafka producer :param output_topic: Kafka topic through which output is send """ # Get half size of the distribut...
57,577
def fit(*views): """ Convenience method to both enable and apply natural fit width and height constraints with one call. Useful mainly for Buttons and Labels. You can provide several views, first view is returned. """ for view in views: enable(view) view.dock.fit() return views[0]
57,578
def get_subnetwork(project_id, context): """ Gets a subnetwork name. """ subnet_name = context.properties.get('subnetwork') is_self_link = '/' in subnet_name or '.' in subnet_name if is_self_link: subnet_url = subnet_name else: subnet_url = 'projects/{}/regions/{}/subnetworks/{}' ...
57,579
def TC_NTU(T1,T2,T3,T4,NTU): """ Outlet temperature of the cold side of the heat exchanger with given number of transfer units (for a counterflow heat exchanger only) """ C = (T1 - T2) / (T4 - T3) if C<1: E = (1 - exp((C - 1) * NTU)) / (1 - C*exp((C - 1) * NTU)) Ec...
57,580
async def telegraphs(grop): """For .create command, Creating New Group & Channel""" if grop.text[0].isalpha() or grop.text[0] in ("/", "#", "@", "!"): return if grop.fwd_from: return type_of_group = grop.pattern_match.group(1) group_name = grop.pattern_match.group(2) if t...
57,581
def quadraticEval(a, b, c, x): """given all params return the result of quadratic equation a*x^2 + b*x + c""" return a*(x**2) + b*x + c
57,582
def file_format_from_suffix(file_suffix: str) -> FileFormat: """Returns the file format associated with the file extension (`tfrecord`).""" if file_suffix not in _FILE_SUFFIX_TO_FORMAT: raise ValueError('Unrecognized file extension: Should be one of ' f'{list(_FILE_SUFFIX_TO_FORMAT.values()...
57,583
def redis_post_like_to_mysql(): """将redis中的点赞记录写入mysql """ key_value = red.hgetall('postlike') for k, v in key_value.items(): author_id = int(k.split('_')[0]) post_id = int(k.split('_')[1]) create_time = v post_like = PostLike(author_id=author_id, ...
57,584
def upgrade_tarball_install(config, new_tarball, preserve_old_install): """Performs an upgrade for an existing Scalyr Agent 2 that was previously installed using the tarball method. @param config: The configuration for this agent. @param new_tarball: The path to file containing the new tarball to install. ...
57,585
def grab_std_includes(headers: List[str], sources: List[str]) -> List[str]: """Grab all std includes from headers and sources""" total_std_includes: List[str] = [] for header in headers + sources: with open(header) as file: lines = file.readlines() std_include_lines = filte...
57,586
def get_testcase_params(): """ Returns the list of testcase parameters from the configuration file :return: dict """ testcase_parameters = dict() parameters = CONF_FILE.get_variable_list(cf.CFS_TESTCASE_PARAMETERS) for param in parameters: testcase_parameters[param] = CONF_FILE.get_...
57,587
def job_get_script_list(request, biz_cc_id): """ 查询业务脚本列表 :param request: :param biz_cc_id: :return: """ # 查询脚本列表 client = get_client_by_request(request) script_type = request.GET.get('type') kwargs = { 'bk_biz_id': biz_cc_id, 'is_public': True if script_type == '...
57,588
def encrypt_data(collector, key): """ This function encrypt the raw data in the collector with the pass in key value :param collector: Collector class with the raw data frame to encrypt :param key: public key use in the encryption :return: """ collector.logger.debug("Encrypting " + ty...
57,589
def stringdb_escape_text(text): """Escape text for database_documents.tsv format.""" return text.replace('\\', '\\\\').replace('\t', '\\t')
57,590
def process_impact_task(source_id, message): """Process an impact task.""" logging.info('Processing impact task for %s', source_id) regress_result = ndb.Key(osv.RegressResult, source_id).get() if not regress_result: logging.error('Missing RegressResult for %s', source_id) return fix_result = ndb.Key...
57,591
def put_metric_data(client, metric_name, metric_ns, asg, queue, metric): """Backoff wrapper for put_metric_data().""" client.put_metric_data( Namespace=metric_ns, MetricData=[ { "MetricName": metric_name, "Dimensions": [ {"Name": "...
57,592
def parse_args(): """ Parse command arguments. """ parser = argparse.ArgumentParser(description='validate data from starbust algo I for test (ex. chessboard test)') parser.add_argument('path', help='path to starburst filtered file') return parser.parse_args()
57,593
def get_spyderplugins_mods(prefix, extension): """Import modules that match *prefix* and *extension* from `spyderplugins` package and return the list""" modlist = [] for modname in get_spyderplugins(prefix, extension): name = 'spyderplugins.%s' % modname try: __import_...
57,594
def in_parallel(model, device_ids): """ Wraps a model in a DataParallel module such that it supports an input dictionary for multiple inputs rather than kwargs. """ return RemoveStatePrefix(DictToKwargs(torch.nn.DataParallel( KwargsToDict(model), device_ids)), 'module.module.module.')
57,595
def mean_ap(dist_mat, query_ids, gallery_ids, query_cams, gallery_cams): """Compute mean average precision (mAP)""" dist_mat = dist_mat.cpu().numpy() m, n = dist_mat.shape query_ids = np.asarray(query_ids) gallery_ids = np.asarray(gallery_ids) query_cams = np.asarray(query_cams) gallery_cams...
57,596
def check_account_age(key): """ Searches DynamoDB for stored user_id or account_id string stored by indicator creation rules for new user / account creation """ if isinstance(key, str) and key != "": return bool(get_string_set(key)) return False
57,597
def _is_cluster_volume(cluster_id, ebs_volume): """ Helper function to check if given volume belongs to given cluster. :param UUID cluster_id: UUID of Flocker cluster to check for membership. :param boto.ec2.volume ebs_volume: EBS volume to check for input cluster membership. :...
57,598
def serialize_sqla(data): """Serialiation function to serialize any dicts or lists containing sqlalchemy objects. This is needed for conversion to JSON format.""" # If has to_dict this is asumed working and it is used. if hasattr(data, 'to_dict'): return data.to_dict() if hasattr(data, '__d...
57,599