content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import socket def handle_googleapiclient_error(error, message=None, code=None, http_response=None): """Constructs a ``FirebaseError`` from the given googleapiclient error. This method is agnostic of the remote service that produced the error, whether it is a GCP service or otherwise. Therefore, this meth...
1eacd6fc4e5c8d38763ea03f6b9a0897521689ae
3,604,000
def poly_lr_scheduler(optimizer, init_lr, iteraion, lr_decay_iter=1, max_iter=100, power=0.9): """Polynomial decay of learning rate :param init_lr is base learning rate :param iter is a current iteration :param lr_decay_iter how frequently decay occurs, default is 1 ...
298597342c7411648881e75061d25d7cac9ef49c
3,604,001
import os def makedirs2file(filename: str) -> str: """ Creates all folders up to the desired file path Args: filename: path where the file will be saved in the future Returns: str: `filename` """ os.makedirs(upper_directory(filename, steps=1), exist_ok=True) return filen...
c468b4f1e340fef8f9fa41b133a7c33c7f95dda2
3,604,002
def StringSizer(field_number, is_repeated, is_packed): """Returns a sizer for a string field.""" tag_size = _TagSize(field_number) local_VarintSize = _VarintSize local_len = len assert not is_packed if is_repeated: def RepeatedFieldSize(value): result = tag_size * len(value) for element in ...
9919e194ee938a71ebcbdd166b19f5848477844d
3,604,003
from typing import Iterator from typing import Dict import csv def parse_csv(rows : Iterator[Row], common_time_pt : int) -> Dict[str, Subject[Filename]]: """ Read subject information from a csv file containing at least the columns 'subject_id', 'timepoint', and 'filename', and optionally a 'bitfield' colu...
f7d46848b8bb59b5685bf79100e8fe91c60cdeca
3,604,004
from pathlib import Path from datetime import datetime import html def build_historic_markers(dpt_code=None): """ This function reads through the 'historic_fires.csv' file stored in the /data folder. It takes as input a department code (as a character string), which will correspond to the department ...
800518df74711e302b39d656bc3e53d4418fba33
3,604,005
def ideal_reflection(b_Qi = (3, 4.5, 6), b_Qc = (3, 4.5, 6), b_theta = (-np.pi, 0, np.pi), b_fr = (1e9, 5e9, 11e9)): """ returns a Parametric1D model for an ideal notch resonator Params: Qi: The log10 of the internal quality factor ...
eb7b24583dd7df418ece7390a5f1d51764995d34
3,604,006
from pathlib import Path def get_dictionaries(base: Path) -> list[tuple[str, list[Path]]]: """Make a list of available dictionaries and the interesting files. :param base: The Apple Dictionaries root directory. :return: A list of tuples of name, files for each dictionary. """ all_dicts = sorted( ...
98068ecb847aa6975cc8dc7eed59b8948316f191
3,604,007
def copy_clb_desc(clb_desc, condition=CLBNodeCondition.ENABLED, weight=1): """ Produce a :class:`CLBDescription` from another, but with the provided conditions and weights instead of the original conditions and weights. :param clb_desc: the :class:`CLBDescription` to copy :param condition: the :cla...
e67ef372425697f374d9a480b7f953dcffc777df
3,604,008
import os def targ(pst, folder, typ, fil, interp=True, column=-1, **kwargs): """Read a binary file from targ ARGUMENT examples pst : 'DEV/JKB2t/X101a' folder : 'treg' typ : 'TRJ_JKB0' fil : 'ztim_llzrphaaas' """ p = icp.get.params() data_file = p[folder+'_path'] + '...
b2c2af89d15974ca663789d692c051e82a6a0175
3,604,009
def _send(cmd): """Actually run send tickets command.""" success = False try: rc = subproc.call(cmd) if rc == 0: success = True except subproc.CalledProcessError: pass # command failed return success
68da3807b7e6fd92b8e8eac38ca432c44101fc5b
3,604,010
def calculate_mean_vectors(X, y): """Calculates the mean samples per class Parameters: ----------- X : array-like, shape (m, n) - the samples y : array-like, shape (m, ) - the class labels Returns: -------- mean_vectors : array-like, shape (k, ) Those are the mean samples f...
0a6fd18aacba2d4d501c8530e39422be3440d3ac
3,604,011
import torch def gaussian_entropy(m_): """ https://en.wikipedia.org/wiki/Normal_distribution#Maximum_entropy """ return .5 + .5 * (np.log(2 * np.pi) + torch.log(m_.scale))
1d3f9ab2e8229919d864820e57482faf026b5389
3,604,012
import os def save_video(video: np.ndarray, video_name: str) -> str: """Creates a folder to hold videos if it doesn't exist yet, and saves the video. Args: video (np.ndarray): The video to save. Returns: The path to the video. """ # Create a video directory if it doesn't...
d828f78949bb7e3bf66d3a673a37f71d5cffa1e9
3,604,013
def CountEndElements(): """(read-only) Number of zone end elements in the active meter zone.""" return lib.Meters_Get_CountEndElements()
fbb5f5b7a01339431adbddb9b92b1c277bacf0a4
3,604,014
import re def simplify_credentials(credentials): """ Replace the key of the entries with host:port values. Returns a new dictionary from the credentials where the key will be replaced by 'host:port' values so protocols and product names will be removed if these are given. """ host_entry_patte...
3865a9ec7b5b78def9de017934ae5711052282b7
3,604,015
import math def strafe_time(x, speedxi, K): """Compute the time it takes to strafe for the given distance and initial speed. Always returns positive times. >>> vix = 400 >>> x = 1000 >>> K = strafe_K(30, 0.01, 320, 10) >>> tx = strafe_time(x, vix, K) >>> math.isclose(x, strafe_distan...
240b0ae0773b8361c7d1f9e477e21b4108880910
3,604,016
def generate_recipient_from(nhais_cypher): """ Generates the recipient cypher. This value can be deduced from the nhais_cypher provided. The nhais cypher can be 2 to 3 characters is length. If it is 2 characters in length it will append "01" to generate the recipient cypher If it is 3 characters in ...
ac29a09f246fc38b43301cc1b00a4056fc49e203
3,604,017
from typing import List from typing import Optional from typing import Dict from typing import Tuple from typing import Union import math from functools import reduce def render_on_map(lidarpc_rec: LidarPc, # type: ignore boxes_lidar: List[Box3D], ego_poses: List[EgoPose], # type...
7534c2af7c4fa9b2c554567b56be06765bdcda05
3,604,018
from pathlib import Path from typing import Tuple import pickle def convert_single(result_dir: Path, pickle_file: Path) -> Tuple[str, bool]: """Convert a pickle file representing a soong parser to a graph and store it in result dir. :param result_dir: Where to store the result :param pickle_file: Whi...
dd3cc551dfd67e13f7b5be7b057bdde1a79f8cd3
3,604,019
def removeDuplicates(aList): """ Remove duplicates in a list. """ if type(aList) != type([]): return aList result = [] for elem in aList: result.append(removeDuplicates(elem)) return _removeDuplicatesOneLevel(result)
40e208c245fa5ea5d29c26d7dd24f95ff6587821
3,604,020
def num2date(times, units, calendar='standard'): """ Extension to the netCDF4.num2date() function to correctly handle time strings of format '2010-01-01T00:00:00Z', as used by netcdf-java. Refer to netCDF4.num2date() for further documentation. """ # Patch to address the problem of netCDF4.num2d...
0bd385aa1cdd634ca5092d5a486240adb86a592e
3,604,021
def create_stack(heat_client, stack_name, template, parameters, environment=None): """ Create Stack """ stack_params = { 'stack_name': stack_name, 'template': template, 'parameters': parameters, 'environment': environment, } stack = heat_client.s...
6c6e838dcba1142762fd01b1ace36386c54ab8d8
3,604,022
from typing import Any def remove_member(client: Any, group_key: str, email: str): """Removes member from google group.""" return make_call(client.members(), "delete", groupKey=group_key, memberKey=email)
25be8a70f47e42566b4e34b79bf9e2c2e69e993e
3,604,023
def _convert_color(color): """Convert a 24-bit color to 16-bit. The input `color` is assumed to be a 3-component list [R,G,B], each with 8 bits for color level. This method will translate that list of colors into a 16-bit number, with first 5 bits indicating R component, last 5 bits indicating...
6635e30d574288146c5ff07bf3d0d1661cd33b97
3,604,024
def spenc(X, w, n_clusters=5, gamma=1, **kwargs): """Spatially encouraged spectral clustering. :cite:`wolf2018` Parameters ---------- X : array-like n x k attribute data w : libpysal.weights.W instance spatial weights matrix n_clusters : int, optional, default: 5 T...
ea42cc5ae3f1343b47396e3dbec464808d970229
3,604,025
def join_discovery (dfd, interface_address): """Join a socket to a multicast address for discovery. The *interface_address* must be a host name or IP address string that resolves to an IP (or IPv6) address bound to one of the network interfaces on the local host. The socket passed as *dfd* will be...
d70b711a51dc156d8ff36b1e215f5c2c37fcae50
3,604,026
def best_jshower(tracks): """Select the best JSHOWER track.""" return best_track(tracks, minmax=(krec.JSHOWERBEGIN, krec.JSHOWEREND))
d1b3fe116adabf1558a6b0806cfbcd0aec5a42fa
3,604,027
def plot_contours(ax, clf, xx: np.ndarray, yy: np.ndarray, **params): """ Generates a plot with the decision boundaries for a classifier. :param ax: matplotlib axes object :param clf: a classifier :param xx: meshgrid ndarray :param yy: meshgrid ndarray :param params: dictionary of params to...
a81e911fab132217057da00313e5419118095abf
3,604,028
import json def available_native_languages(): """ :return: jason with language codes for the supported native languages. curently only english... e.g. ["en", "fr", "de", "it", "no", "ro"]unquote_plus(flask.r """ available_language_codes = list(map((lambda x: x.code), Language.native_languages(...
590b3d3feba574462645472c63753a1c81d51c1b
3,604,029
from bs4 import BeautifulSoup def strip_attrs(soup:BeautifulSoup, *args:str): """ Strip certain attributes from tags. Args: soup (BeautifulSoup): A dictionary entry extracted from the GDLC azw dictionary args ([str]): A list of attributes to be stripped Returns: soup (Beautif...
e93dffa17b77dcfc71cad7b784f01e8ed549cc21
3,604,030
def MakeFutureReservationMessage(messages, reservation_name, sku_properties, time_window, share_settings, reservation_zone): """Constructs a future reservation message object.""" future_reservation_message = messages.FutureReservation( name=reservation_name, specificSkuP...
4ca46162638df14977e7292c25926aecc6b8876e
3,604,031
def prob_roadmap(data, num_samples, z_max): """ Creates a probabilistic roadmap by randomly sampling the environment and returning a connected graph free of collisions Args: data: obstacle data num_samples: number of points to be sampled z_maz: sample limit in the z axis ...
64956605d9141697e385c00b9c5bd028588f087a
3,604,032
def create_matcher(): """ Create different types of matchers to match descriptors. """ cross_check = bool(FEATURE_MATCHER == 'bf') if FEATURE_EXTRACTOR in ('sift', 'surf'): matcher = cv2.BFMatcher(cv2.NORM_L2, crossCheck=cross_check) else: matcher = cv2.BFMatcher(cv2.NORM_HAMMIN...
61f24e7ffc76526034340583bc864717e070a219
3,604,033
def read(handle, format) : """Turns a sequence file into a single SeqRecord. handle - handle to the file. format - string describing the file format. If the handle contains no records, or more than one record, an exception is raised. For example, using a GenBank file containing one record...
4f545fc21913e15cf7fc827601e63ccba4448b21
3,604,034
def convert_float_to_rational_fraction_approximation(xi, maxsize=10000): """ Convert a float to its best rational fraction approximation, where the size of the fraction numerator or denominator cannot exceed maxsize. Python 2.6 has this functionality built in, kind of :: from fractions imp...
678582bde7ff05316ca02147700c5bbb08f71107
3,604,035
def session_from_identity_service(identity_service): """Get Keystone Session from `identity-service` relation. :param identity_service: reactive Endpoint :type identity_service: RelationBase :returns: Keystone session :rtype: keystone_session.Session """ auth = keystone_identity.Password( ...
f62d6a44e701112ad13068d8a64ec8f506357190
3,604,036
def get_test_results_array(human, current_timestamp): """Will return an encoded test result array for this user's recent history (starting from current_timestamp). Negative results will be -1, unknown results 0, and positive results 1. """ results = np.zeros(human.conf.get("TRACING_N_DAYS_HISTORY")...
23c8521c7123e354389a61c83f2ae6a83027b7b8
3,604,037
import os def output_unconverted_csv_file(path, sheet_name): """ sheet_name(str: CSVに変換できないsheetの名前)に対し, sheet_name.csvを作成し, その中にsheet_nameを書き込んでから保存するメソッド. """ with open(os.path.join(path, "{}.csv".format(sheet_name)), 'w', newline='', encoding='cp932', errors='ignore') as unconvert...
87e8cfb56930d7aee2934d7f3154cae7c0b14e08
3,604,038
def resnet18(num_classes=1000, **kwargs): """resnet18""" return ResNet([2, 2, 2, 2], num_classes, BasicBlock)
86a688d2ce4141aa4ff03247f2220dbfbc7afc70
3,604,039
def list_get(lst, index, default=None): """ A safety mechanism for accessing uncharted indexes of a list. Always remember: safety first! :param lst: list :param index: int :param default: A default value :return: Value of list at index -or- default value """ assert type(lst) == list, "Re...
41ca83d6a9b0ba66858617b48dcb6c43ca5a6a54
3,604,040
from galpy.potential_src.planarPotential import planarPotential def verticalfreq(Pot,R): """ NAME: verticalfreq PURPOSE: calculate the vertical frequency at R in the potential Pot INPUT: Pot - Potential instance or list thereof R - Galact...
de29d91570a2ce675b0426ace818456a4b28077c
3,604,041
import argparse import logging import os def parse_args() -> tuple: """Parses the command line arguments Return: A tuple containing the command line arguments """ parser = argparse.ArgumentParser(description='Processes a command queue') parser.add_argument('workdir', help='the working fold...
08ba198ec6f4dad04d923d6517ab393022f1bcda
3,604,042
def lbfgs(g: Tensor, s: Tensor, y: Tensor, r: Tensor): """P226""" assert s.dim() == 3 # new, bch, dim assert y.dim() == 3 # new, bch, dim assert r.dim() == 3 # new, bch, 1 assert r.size(2) == 1 q = g # bch, dim k = s.size(0) a = [] for i in range(k - 1, -1, -1): ai = r[i]...
0bc3a543832d7fcd879328b9f140a1c52810153b
3,604,043
def queryObject(graph, patterns, optionalPatterns=[], initialBindings = None) : """ Creation of a L{Query} instance. @param patterns: either a L{GraphPattern<rdfextras.sparql.graph.GraphPattern>} instance or a list of instances thereof. Each pattern in the list represent an 'OR' (or 'UNION') br...
76bcbe8f8724bc56788885a7e777d02a07d69747
3,604,044
import re import warnings import os def read_tiff_stack(filename, range=None, zfill=4): """Read stack of tiff files. Searches all files in parent folder and opens them as a stack of images. Parameters ---------- filename One of the stack images. range : [int, int] Control load sli...
88fb98015d23fe28d476cdba857bb2aa3fd9401f
3,604,045
def DownloadFlags(flagList: list): """ 下载多面旗帜 :param flagList: 下载旗帜的列表 :return: 下载旗帜的数量 """ for flag in sorted(flagList): image = DownloadOne(flag) Show(flag) SaveFlag(image, flag.lower() + ".gif") return len(flagList)
f30c52377f0525ccc12e1b08dbd06c880a8bc75d
3,604,046
import torch def hhc_dgl_edge_compute_accuracy_unbatch(raw_scores, target): """ - raw_scores : shape (N_edges, 2) - target : dgl graph with target.edata['solution'] of shape (N_edges,1) """ assert raw_scores.shape[1]==2, f"Scores given by model are not given with two classes but with {raw_scores...
24278ab3837da16ea2872f14a421df35921657da
3,604,047
def _context_url_pypi(context): """return the full sdist pypi url""" # we need the pypi_name and the upstream_version variables to construct # the full url _context_check_variable(context, CONTEXT_VAR_PYPI_NAME, 'pypi_name') _context_check_variable(context, CONTEXT_VAR_U...
ae96ebe26c0324372c961e46704f4b5f9fe4dba8
3,604,048
from typing import List from typing import Union from typing import Tuple def executeToken(token: lexerTokens.baseLexerToken, inputDirection: direction, dataStack: List[int]) -> Union[Tuple[direction, List[int]], BaseException]: """ Executes the function associated with tokens :param token: Input token ...
8c75b9dd1446c54468dd6960114c7499d109cf3d
3,604,049
from typing import List def parse_der_certificates(der_bytes: bytes) -> List[Certificate]: """Parses a list of certificates from ASN.1 DER bytes. Args: der_bytes: List of X.509 certificates as ASN.1 DER bytes. Returns: A list of Certificate objects. Raises: X509CertificateEr...
24202bc29bd26e9a24de43da3bb8272f21aae066
3,604,050
def fmt_money(amount, precision=None): """ Convert to string with commas for thousands, millions etc """ number_format = webnotes.conn.get_default("number_format") or "#,###.##" decimal_str, comma_str, precision = get_number_format_info(number_format) amount = '%.*f' % (precision, flt(amount)) if amount.fi...
a1d12cebca14234a7109135d82fa7e29044bb3d4
3,604,051
def lru_cache(f): """Can be used as a decorator for least-recently used caching. This is helpful when traversing some edges several times during construction of the SPN, but also for reusing Tensors defined in upward computation vs. downward computation. Args: f (function): A function f(*args, ...
021c3b38733797862e6fa8f23f1b4e69563da17e
3,604,052
import time import os def gen_kaggle(KAGGLE_tasks, train_dir, valid_dir, test_dir, data_dir, shard_size=2000): """Load KAGGLE datasets. Does not do train/test split""" # TIMING time1 = time.time() # TIMING # Set some global variables...
fdd19d9aa2e66a7cf5bdac6e92552bfa2a9f370c
3,604,053
def hz_people_stat_task(): """ 人员盘点定时任务页 """ return render_template('hz_people_stat_task.html')
860ae6de42bc605c70aa793dbc188cff638906f0
3,604,054
def find_sense_type(wn, source, target): """Get the first relation type between the senses""" (source_synset, source_entry) = decompose_sense_id(source) entry = wn.entry_by_id(source_entry) sense = [sense for sense in entry.senses if sense.id == source][0] x = [r for r in source.sense_relations if r...
a7a84c69539968ff9aecc8283f5a37ea9b31f606
3,604,055
def delete_report(request, slug, pk): """ This view removes a report from the project detail page. For the user, it will appear as though the report has been deleted. In reality, the report is simply updated so that it is not longer rendered and available on the project detail page but it will ...
7244e0158d6bef6eecb6ff0319c3f377a0665fbe
3,604,056
def iterate_items(collection, *args, **kwargs): """ iterates over the items of given object. :param type collection: collection type to be used to iterate over given object's items. :rtype: iterator[tuple[object, object]] """ return iter(collection.items(*args, **k...
49fde9f9c027ff1fc64a57ee67b06c91033f8755
3,604,057
from typing import Tuple from pathlib import Path def _prepifg_multiprocessing(m_path: MultiplePaths, exts: Tuple[float, float, float, float], params: dict): """ Multiprocessing wrapper for prepifg """ thresh = params[C.NO_DATA_AVERAGING_THRESHOLD] hdr = find_header(m_path, params) hdr[ifc.INP...
62913ca2f8ef8f5c3f61751ec90e29468a900d3e
3,604,058
def nominal_vars(term): """Find all bound and free nominal variables.""" if not isinstance(term, Term): raise ValueError(term) elif is_nvar(term): return frozenset([term]) elif is_ivar(term) or is_atom(term): return frozenset() elif is_abs(term) or is_quote(term): ret...
87f6f4db74e2e49a49cb052bbc1d4968c118479e
3,604,059
def float2uint(np_raster, dtype): """ Função auxiliar para converter imagens em float, resultantes de filtros, para uint8 ou uint16 Args: np_raster (np.ndarray): imagem em float dtype (np.dtype): dtype a ser convertido Returns: (np.ndarray): imagem em uint8 ou uint16 """ i...
34c02525f9ebb97e318e32f09cfbb55066a031e0
3,604,060
def read_config(filenames=SEARCH_PATH): """Attempt to read local configuration files to determine spalloc client settings. Parameters ---------- filenames : [str, ...] Filenames to attempt to read. Later config file have higher priority. Returns ------- dict The configu...
a6c71f40eb0c86f86b2810b63189e8d1a9f38c6c
3,604,061
def evidence_keys(request: HttpRequest) -> HttpResponse: """ public page to display EKey details """ context = { 'keys': EvidenceKeyMap.instance().all_keys } return render(request, 'classification/evidence_keys.html', context)
ba15dd05010182d939953b78b74613b9c6bb7223
3,604,062
def sequential_or(*conditions): """ Use ``or`` operator between all conditions. Function is just a syntax sugar that make long Tensorfow logical conditions looks less ugly. Parameters ---------- *conditions Conditions that returns ``True`` or ``False`` """ first_condition, o...
66ff7729e36416d93957c32c7ae931891f9cd067
3,604,063
def _normalize_image(image, *, mean, stddev): """Normalize the image to zero mean and unit variance.""" image -= tf.constant(mean, shape=[1, 1, 3], dtype=image.dtype) image /= tf.constant(stddev, shape=[1, 1, 3], dtype=image.dtype) return image
7bb9f9ffc834bc8f8d778883708908c677f432bc
3,604,064
from pathlib import Path from typing import List def read_raw_data(folder: Path, split: str, lang: str) -> List[str]: """Makes sure we are reading each file at most once. There is 1000 sentences per file, one file per lang so the memory footprint is ok. """ file = folder / f"{lang}.{split}" asser...
451a795b8dcc8d4698f7538b7b55800f3015038d
3,604,065
def calc_first_class(d): """ Calculate percentage of first-class passengers :param d: data frame :return: rounded percents """ fst = np.sum(d['Pclass'] == 1) return round(fst / d['Pclass'].count() * 100, 2)
31f87528879429a2084826a5d9a1ed7c38c86ea1
3,604,066
def address_list(offset: int, limit: int): """List a subset of the address book""" return address_book()[offset:offset+limit]
148c6501953ab9e9327bcc0fa82268fac8426ab2
3,604,067
def two_mode_unitary_plots(target_unitary, learnt_unitary, square=False): """Plot the two-mode target and learnt unitaries as a matrix plot.. Args: target_unitary (array): the size [cutoff, cutoff] target unitary. learnt_unitary (array): the size [cutoff, gate_cutoff] learnt unitary. Retur...
133b58eec54d1871b3437a8c224d962e9444a92d
3,604,068
from typing import Tuple def is_multi_class(output_shape: Tuple[int, ...]) -> bool: """Checks if output is multi-class.""" # If single value output if len(output_shape) == 1: return False return True
66726be66cce6f837b40287b75c547d28d709a74
3,604,069
from typing import Optional import inspect async def axis(dataset_id: int, data_var: str, dim_name: str, query: Optional[str] = None, settings: config.Settings = Depends(config.get_settings)): """GET dimension values related to particular data_var""" ...
d509d01df02450f30df6cca79fc6c20298450931
3,604,070
def bipartite_single_sided_random_walk_with_restart( g, seeds, restart_prob, max_nodes_per_seed, max_visit_counts=0, max_frequent_visited_nodes=0): """Batch-generate random walk traces on given graph with restart probability. The graph must be a bipartite graph. A single random walk step i...
0dc44e2f06c6075a9e6971dc906d46d293bdc9d2
3,604,071
import copy_reg as copyreg import copyreg import types def _loading_multiprocess(): """ Black magic function to load to enable pickle in multiprocess """ try: except: def _pickle_method(m): if m.im_self is None: return getattr, (m.im_class, m.im_func.func_name) else: ...
c9b9689512752e0397e0f149344fa627fee04cfe
3,604,072
def configure_account_ldc_for_discovery(servicenow_url, ldc_sys_id, new_account_sys_id, discovery_schedule_id): """ Associates service accounts data center with specified discovery schedule to configure for discovery :param servicenow_url: ServiceNow endpoint URL :param ldc_sys_id: Id of discovery stat...
3d09c54ef6aeacd6da0b2cf6d86a18b08ad570e0
3,604,073
def cradmin_instance_url(context, appname, viewname, *args, **kwargs): """ Template tag implementation of :meth:`cradmin_legacy.crinstance.BaseCrAdminInstance.reverse_url`. Examples: Reverse the view named ``"edit"`` within the app named ``"pages"``: .. code-block:: htmldjango ...
9cea000ff75b68d536796cbcc323fef1b0a7059b
3,604,074
def server_state(request): """Get the status for a server. Anyone can request this, :param name: Name of VApp which we want to stop. :returns: The state, by name. """ vm_id, actor_id = _resolve_vm(request) return server.check_state(vm_id)
69c5ddcf6bc70e8d3a5c3494f85996e7318fc8fe
3,604,075
import logging import pathlib import time def getLogger(consolelevel=logging.INFO, filelevel=logging.DEBUG): """ Fuzzing Logger Simple Singelton Logger for file and stdout logging. """ logger = logging.getLogger("Packet Fuzzing") if len(logger.handlers) != 0: return logger logger.p...
7af58307097479361a32eb2855e21737b88d2e5d
3,604,076
from typing import Sequence def broadcast_in_dim(operand: Array, shape: Shape, broadcast_dimensions: Sequence[int]) -> Array: """Wraps XLA's `BroadcastInDim <https://www.tensorflow.org/xla/operation_semantics#broadcastindim>`_ operator. Args: operand: an array shape: the shape of...
ec611197f76332c2ff207139275082dfab9705ba
3,604,077
def QualityControl_Cast(*args): """ Cast(BaseObject o) -> QualityControl QualityControl_Cast(Seiscomp::Core::BaseObjectPtr o) -> QualityControl """ return _DataModel.QualityControl_Cast(*args)
2705d83114ff121b0436fe964ce4054014d7ab70
3,604,078
def read_js(filename): """ Reads a specific type of JS file to JSON JS file - defines one variable to be interpreted as JSON :param filename: JS file name :return: JSON """ with open(filename, 'r') as f: js_text = f.readlines()[0] # JS should all be on a single line equal_s...
44975caadd0421f1ab5dbf2baf4c71bab2f41355
3,604,079
def get_full_stream_catchment_area(db, watershed_id): """ returns the catchment of the entire selected stream. """ q = """ with subwscode_ltree as ( SELECT wscode_ltree as origin_wscode FROM freshwater_atlas_watersheds WHER...
f3779dfa9e743356ac10356f3061ee238b7bcfb2
3,604,080
import os def chunks_to_text(filename): """ Goes through all the chunks and uses google's speech to text api to detect the words in the file """ filename_without_ext = str(filename.split('.')[0]) chunks = [] result_text = {} # Stores each chunk and its corresponsing lyrics for file in os....
6b174ca5292c6cf0765ffa7fb4f935c6c690ed49
3,604,081
def execute(pagename, request): """ Temporary glue code for current moin action system """ if request.method != 'POST': return False, u'' return NewPage(request, pagename).render()
6ceba6e6a3118b9a1922f2be5ae2f9a432fba0e0
3,604,082
import string def html5_parse_legacy_color(input_str: str) -> HTML5SimpleColor: """ Apply the legacy color parsing algorithm from section 2.4.6 of HTML5. """ # 1. Let input_str be the string being parsed. if not isinstance(input_str, str): raise ValueError( "HTML5 legacy c...
5b397503c87d7671f9a7d6deb4a18b29c6bbba94
3,604,083
from typing import OrderedDict def _munsell_maximum_chromas_from_renotation(): """ Returns the maximum *Munsell* chromas from *Munsell Renotation System* data and caches them if not existing. Returns ------- tuple Maximum *Munsell* chromas. """ global _MUNSELL_MAXIMUM_CHROMAS...
4fd0d4456cc2bdbe3bd74a44cd96334e180490d6
3,604,084
def calculate_atom_symmetry_number(molecule, atom): """ Return the symmetry number centered at `atom` in the structure. The `atom` of interest must not be in a cycle. """ symmetry_number = 1 single = double = triple = benzene = num_neighbors = 0 # note that 0 is immutable for bond in atom....
d4b28f2b0cb793a5b6190c85c73bd56196ebec43
3,604,085
def parse_xml(xml_string): """ Parse an XML string into an lxml object. If the XML is invalid, None is returned. :param str xml_string: a string of XML :return: lxml object representing the XML content :rtype: etree._Element or None """ try: parsed = fromstring(xml_string) ...
21d0b67c77cb600b915643f4e7b68b9c4fb8543f
3,604,086
def _conformer_source(conf): """Determines source of given conformer.""" if not conf.HasField('properties'): if conf.duplicated_by == 0 and not conf.duplicate_of: raise ValueError( 'Unknown conformer source, no properties or duplicates: ' + str(conf)) return _ConformerSource.DUPLICATE # Ki...
0a2ac843cbc39086981567e99fe8697339a5f92c
3,604,087
import os def get_concepts_via_csv(): """ function to collect and process files in `data_steward/deid/config/internal_tables/concept_ids_suppression_files` to populate the _concept_ids_suppression lookup table :return: dataframe of concept_ids and information from all csv files located in specified f...
fb950b2b8345eb2c98b9378e97f40dfcaaa04cb7
3,604,088
import torch def get_discretized_transformation_matrix(matrix, discrete_ratio, downsample_rate): """ Get disretized transformation matrix. Parameters ---------- matrix : torch.Tensor Shape -- (B, L, 4, 4) where B is the batch size, L is the max cav...
fd6ab95dcbb6fca9cab6b35fd5e20998fc12472b
3,604,089
def qiskit_routing(circuit, device): """ Routing using qiskit :param circuit: Circuit object, Either qasm filepath or Cirq's circuit object :param device: Device object, Defines topology for hardware specific routing :returns depth: int, Circuit depth according to tket routing strategies """ ...
060e203cf293ed35c622b598849f1066942f4e48
3,604,090
import re def remove_surrogates(s): """ The following is a helper function, used to convert two-character surrogate sequences into single characters. This is needed because some systems create surrogates but others don't. """ pieces = re.split('(&#\d+;)', s) for i in range(3, len(pieces)-...
31426a1cc76838dec58d78c8ab8a951f84f4eda0
3,604,091
def basic_bn_stem(model, data, dim_in, **kwargs): """Add a basic DenseNet stem. For a pre-trained network that used BN. An AffineChannel op replaces BN during fine-tuning. """ dim = dim_in p = model.Conv(data, 'conv1', 3, dim, 7, pad=3, stride=2, no_bias=1) p = model.AffineChannel(p, 'conv1_bn'...
37469f6baccdc9ec0de5228b6398963e8a984a57
3,604,092
import torch def calc_word_prob(rnn, word, revmap, hidden=None, average=False): """Given some hidden state, calculate the probabilty of a given word""" word_buffer = " " word += ' ' probs = [] if not hidden: hidden = Variable(torch.zeros(rnn.n_layers, 1, rnn.hidden_size).cuda()) for i,...
0bdd0aa0435c1534064e856bad2005c662fb9fe0
3,604,093
def code_reassembly(structure): """ Recursively re-assemble the results of pyparsing analyzed tokens """ reassembled = [] for element in structure: if isinstance(element, pyparsing.ParseResults): reassembled.append(code_reassembly(element)) else: reassembl...
c9f14134d4bebefd559cf1fe4697098b8e163028
3,604,094
def fib_modified(a, b, n): """Computes the modified Fiboniacci-style function.""" for _ in range(2, n): a, b = b, a + b * b return b
103433c685d672019b42c1fd1a17a34bd3727764
3,604,095
def beamform_mvdr(Y, X_mask, N_mask, ban=False): """ Souden MVDR beamformer. Args: Y: CuPy array of shape (channel, time, frequency). X_mask: CuPy array of shape (time, frequency). N_mask: CuPy array of shape (time, frequency). ban: If True, use blind analytic normalization. ...
fc811383055ca8832df56769f899d3961463f0d0
3,604,096
def vit_deit_small_distilled_patch16_224(cfg): """ DeiT-small distilled model @ 224x224 from paper (https://arxiv.org/abs/2012.12877). ImageNet-1k weights from https://github.com/facebookresearch/deit. """ model = VisionTransformer(patch_size=cfg.CONFIG.MODEL.PATCH_SIZE, em...
eeccbe5127dda5ff94cdebb2afd6a976143f9904
3,604,097
def generate_class_object(object_name, attributes, template=None, bases=None, with_dump=False, dump_file=None): """ Generate class object. Args: object_name(string): object name attributes(list or dict): attribute template(string):...
96e5bb64ccfa5b5d9eb0d1cfbb5546a74f0f99dc
3,604,098
from numpy import asarray from numpy.testing import assert_equal def nan_equal(a,b): """Are two arrays containing nan identical, assuming nan == nan?""" a,b = asarray(a),asarray(b) try: assert_equal(a,b) except: return False return True
a5f3186e202e22d79f46781fe3c9e6a1936f4a6a
3,604,099