content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def create_exchange_graph(exchange: ccxt.Exchange): """ Returns a simple graph representing exchange. Each edge represents a market. exchange.load_markets() must have been called. Will throw a ccxt error if it has not. """ graph = nx.Graph() for market_name in exchange.symbols: try: ...
f3412c4d34042e34962d743af5f328c210ba34d3
64,238
def Galactocentric_to_rotated(): """Transformation matrix from GC Cartesian to rotated coordinates.""" return GALACTOCENTRIC_ROT_MATRIX
3e68f468e3a4cc6c0f6b8237b1e3960690518e22
64,239
import functools def sgmcmc_sampler(build_sampler_fn): """ Decorator that turns a kernel factory into a sampler factory """ @functools.wraps(build_sampler_fn) def wrapper(*args, **kwargs): compiled = kwargs.pop('compiled', True) pbar = kwargs.pop('pbar', True) init_fn, my_k...
ba0b5c5dbb410194abe984f30050491c25c91239
64,240
def asynchronously(func): """Decorator to execute a function asynchronously.""" @catch_exceptions def wrapper(*args, **kwargs): Thread(target=func, args=args, kwargs=kwargs).start() return wrapper
237bb96d632c26b62ba13cadc82527c1abd23246
64,241
def get_bonded_tunnels_for_physical_tunnel( self, ne_pk: str, physical_tunnel_id: str, state: str = None, ) -> dict: """Get bonded tunnels associated with a particular physical tunnel .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint ...
852e07aa20005ff06819876e2546627aa86e8f5f
64,243
import torch def nll_gaussian_variablesigma(preds, target, sigma, epoch, temperature, total_epochs, add_const=True): """ Loss function for the case of variable sigma, with isotropic gaussian :param preds: prediction values from NN of size [batch, particles, timesteps, (x,y,v_x,v_y)] :param ...
8f497e1669f451dcd14a93b4a7914ff4fc19bca3
64,245
def replace_secret_of_hub_uri(uri_path: str, txt: str = '<secret>') -> str: """Replace the secret of the Jina Hub URI. :param uri_path: the uri of Jina Hub URI :param txt: text to replace :return: the new URI """ try: secret = parse_hub_uri(uri_path)[-1] if secret: ...
611e708bdce176799bf329a263c0e7d4e5a033cd
64,246
def construct_cv_grads(vbobj, lam, eps, elbo_gsamps=None, method="hessian"): """ main method to construct reduced variance reparameterization gradients using a variety of methods. Methods: - "mc" : full monte carlo estimator - "hes...
b5db7f8aafed23f138abe39fae207d2ed252d032
64,247
def add_edges(t, countDict, G, last_k): """ :param t: Tree of the sequnces available as states :param countDict: dicionary counting the occurence for each sequence :param G: the graph containing the states (each one is a sequence) :param last_k: the number of recent item considered :return: the ...
9016808d44230503521ba098aef4a5ac157fdf1d
64,248
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: """Set up MFP as config entry.""" if hass.data.get(DOMAIN) is None: hass.data.setdefault(DOMAIN, {}) _LOGGER.info(STARTUP_MESSAGE) username = config_entry.data.get(CONF_USERNAME) password = config_entr...
132b605a4b90a74e681ffa41b624eff1a1ca73ff
64,250
def build_graph(mode, config, sequence_example_file_paths=None): """Builds the TensorFlow graph. Args: mode: 'train', 'eval', or 'generate'. Only mode related ops are added to the graph. config: An EventSequenceRnnConfig containing the encoder/decoder and HParams to use. sequence_exampl...
fc3a1929c92db40e6c888eafb15d650fd4a6e221
64,251
def ignore(name): """ Files to ignore when diffing These are packages that we're already diffing elsewhere, or files that we expect to be different for every build, or known problems. """ # We're looking at the files that make the images, so no need to search them if name in ['IMAGES']: return Tru...
d5f64616480fa14c03b420165d2c89040a8cc768
64,252
def create_image(module, ecs, snapshot_id, image_name, image_version, description, instance_id, disk_mapping, client_token, wait, wait_timeout): """ Create a user-defined image with snapshots. :param module: Ansible module object :param ecs: authenticated ecs connection object :para...
96a1bb2adc53fb167ed974053450dedbcd054e8e
64,253
def add_active_handler(parent, **kwargs): """ deprecated function """ return internal_dpg.add_item_active_handler(parent, **kwargs)
ec39b3228b6e754cf4866e3c384eff81b24b165e
64,254
def get_school_class_by_level_id(): """ { "level_id": 2 }, """ domain = request.args.to_dict() return school_class_service.get_school_class_by_level_id(domain)
f22ab9abdf72a084bbb76302bae373589a82bafc
64,255
from typing import Any async def recover_password( email: str, db_session: AsyncSession = Depends(dependencies.get_db_session) ) -> Any: """ Send a password recovery email to the provided email address. """ user = await crud.user.get_by_email(db_session, email=email) if not user: awa...
caca8da49229e16d724539e5ccad3b4a0b5d57b5
64,256
from typing import Type from typing import Callable def multimethod(*types: Type) -> Callable: """ Function decorator for supporting method overloading. Based on an article written by Guido van Rossum (see https://www.artima.com/weblogs/viewpost.jsp?thread=101605). Best way to see its usage is by...
0320507d0cec5cee38e2b8aadb9b000db650874a
64,257
def ADS_matrix(log, T): """Return a matrix that represents whether events in the log actually always (A), never (N), or sometimes (S) followed each other. """ case_cnt = len(log.cases) T = transit_matrix(log, T) activities = log.activities ADS = dict() for v1 in list(activities) + ...
37ff65701e3611a9b6c4faba684adc4ec0e123de
64,258
def power(work, time): """ Power is the rate at which the work is done. Calculates the amountof work done divided by the time it takes to do the work Parameters ---------- work : float time : float Returns ------- float """ ...
48eb476658fa19a6002b428993bfa58c81634638
64,259
import io def calculateSubStacks(source, z = all, x = all, y = all, **args): """Calculates the chunksize and other info for parallel processing and returns a list of sub-stack objects The sub-stack information is described in :ref:`SubStack` Arguments: source (str): image source ...
b20d7aff2b45969d01460ed60f9daef0689c2562
64,260
def setup(app): """Sphinx extension entry point.""" app.require_sphinx('1.8') # For "config-inited" event app.connect('html-page-context', _html_page_context) app.connect('config-inited', _config_inited) return { 'version': __version__, 'parallel_read_safe': True, }
73dfa069fcb6e44edd96b45b73fcb0d63d8b1eb5
64,261
def trainingdb_show_email(request, item_container, data, item): """ zeigt die Daten der Online-Anmeldung """ class DmsItemForm(forms.Form): """ Elemente des Anmeldeformulars """ vorname = forms.CharField(required=False, widget=forms.HiddenInput(attrs={'value': data['vorname']}) ) nachname = fo...
ad0c25b70fe7995477799caee0a62469924368be
64,262
def reconstruct_from_estimator(input_examples, predict_results): """ the predict_results contains the prediction entity of the splited examples. We need to reconstruct the complete entitys for each example in input_examples. and return the results as dictionary. input_examples: each should contains (sta...
907edb81e26811b975f520a1685677e267e2afeb
64,263
def new_iface(ifname, device): """ Create Interface """ iface = Interface(ifname) if "mtu" in device: iface.config.mtu = device["mtu"] if "mac-address" in device: iface.ethernet.config.mac_address = device["mac-address"] return iface
216d4333424a3a240becb7e16fa33a81b47a3a00
64,264
def send_email(receivers, subject, content_text, content_html=None): """This method sends an email""" #Create the message if content_html: msg = MIMEMultipart('alternative') msg.set_charset("utf-8") part1 = MIMEText(content_text, 'plain', "utf-8") part2 = MI...
64333f9c81b97c348c235a68b0b1ad1097369884
64,266
def find(*patterns): """Decorate a function to be called for each time a pattern is found in a line. :param str patterns: one or more regular expression(s) Each argument is a regular expression which will trigger the function:: @find('hello', 'here') # will trigger once on "hello you"...
884005008791baba3a9949e9d2c02aee0f985552
64,267
import pyvex import simuvex import claripy def find_ioctls(p, dispatch_addr): """ Returns a list of potential IOCTL codes by symbolically executing starting at the provided function address """ s = p.factory.blank_state(addr=dispatch_addr) pg = p.factory.path_group(s) generic_reg_vals = set() val_addr = {} ...
d9c1a1b5aa6870f5bfd6ca81cba4a7a4c6f77f9d
64,268
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload HALO Home config entry.""" if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS): hass.data[DOMAIN].pop(entry.entry_id) return unload_ok
cf8d8777937ea94efef45f600d3532a2bbaefcf1
64,269
def LineGrouper(num, constructor=strip, ignore=is_empty): """Returns num lines at a time, stripping and ignoring blanks. Default constructor is string.strip, but can supply another constructor to transform lines and/or coerce into correct type. If constructor is None, passes along the lines without alt...
6ecf7d5dea2afea32f646afe200f07f3a7a7cdf4
64,270
def _basis2name(basis): """ converts the 'basis' into the proper name. """ component_name = ( 'DC' if basis == 'diffmap' else 'tSNE' if basis == 'tsne' else 'UMAP' if basis == 'umap' else 'PC' if basis == 'pca' else basis.replace('...
d359fc8a1fe91ccf954a5e0a1dbf69077d444a44
64,272
import concurrent def extract_frames_from_video(video_file, times, use_multithreading=False, blackbar_threshold=32, max_perc_to_trim=.20): """ Extracts multiple things from the video and even handles black bars :param video_file: what we are loading :param times: timestamps to use :param use_mult...
cdcf6dd5c9e3d1dfb18cbb29a6ccd89c25bc35e4
64,273
from datetime import datetime def get_reddit_comments_url(year, month): """Url for reddit comment data download.""" target_date = datetime.date(year, month, 1) url = _get_reddit_comments_path(target_date, _REDDIT_COMMENT_BASE_URL) return url
2863ead940cabf8e4734e8dc5d4148fe68aa4b12
64,274
from typing import List import ast from typing import cast def get_funcs(module) -> List[ast.FunctionDef]: """ get function list """ return [ cast(ast.FunctionDef, stm) for stm in ast.walk(module) if isinstance( stm, ast.FunctionDef)]
98d62ee1e13461cc13226037fa1233431533ca08
64,275
def remove_folders(bookmarks, folders): """Function to remove top level folders from bookmarks.""" for i, item in enumerate(bookmarks['Data Science']): if type(item) is dict: folder_name = list(item.keys())[0] if folder_name in folders: del bookmarks['Data Sc...
b2f6a85e9a518f475985124820ba931a442d3c38
64,276
def calfunc(obs_spectra, std_spectra, ext_spectra, airmass, exptime, error=False): """Given an observe spectra, calculate the calibration curve for the spectra. All data is interpolated to the binning of the obs_spectra. The calibrated spectra is then calculated from: C = ...
7a5eab40edfd87214cde49789c2d048c961496a0
64,277
def get_release_group_image_front(releasegroupid, size=None): """Download the front cover art for a release group. The `size` argument and the possible error conditions are the same as for :meth:`get_image`. """ return get_image(releasegroupid, "front", size=size, entitytype="re...
b519ec7632cf8a89a3c08e57c0b573c3d2c0c73f
64,278
def SUM(strArg, composList, atomDict): """ *Calculator Method* calculates the sum of a descriptor across a composition **Arguments** - strArg: the arguments in string form - compos: the composition vector - atomDict: the atomic dictionary **Returns** a float """ accum =...
1531318eb8db455ee99e2944a4518d4e61a1239f
64,279
def validate_report(reportname, print_files=False, write_file=False): """Validate cached.filelist for the given report""" try: result = models.Results.objects.get(resultsName=reportname) except ObjectDoesNotExist: print("No result object was found for '%s'" % reportname) return None ...
844e7b72887f07bab1be4d99894950aabc69815e
64,280
def lof_text(pwd, src): """creates a .txt file in pwd (LAStools bin) containing a list of .las/.laz filenames from src directory""" filename = pwd + 'file_list.txt' f = open(filename, 'w+') if type(src) == str: for i in las_files(src): f.write('%s\n' % i) else: # this i...
a28a632cc42063784c046efc89a2c4e1bcdac8d8
64,283
def host_is_locked(host): """ Returns true if the host is locked """ if HOST_ADMIN_STATE.LOCKED == host['administrative']: return True, "host is locked" return False, "host is not locked"
e73a0bad5229df8b81d597068714cb7ad646cdfe
64,285
import re def validate_container_name(name): """Make sure a container name accordings to the naming convention https://docs.openstack.org/developer/swift/api/object_api_v1_overview.html https://lists.launchpad.net/openstack/msg06956.html > Length of container names / Maximum value 256 bytes / Cannot c...
5bef8b304c004dc3169b6984b49a0d669fc9b7b3
64,286
def class_instances_from_soap_enveloped_saml_thingies(text, modules): """Parses a SOAP enveloped header and body SAML thing and returns the thing as a dictionary class instance. :param text: The SOAP object as XML :param modules: modules representing xsd schemas :return: The body and headers as cla...
9e92066769d904f76f948837ac16db55431efed4
64,287
def function(values): """A simple fitness function, evaluating the sum of squared parameters.""" return sum([x ** 2 for x in values])
ee96b0948e43eec1e86ffeeca681567d2a0afa53
64,288
def _parse_end(end): """Helper for `from_string`. Determines if an endpoint is INF, NEG_INF, int, or float. """ if end == 'inf': return INF if end == '-inf': return NEG_INF if end.isdigit(): return int(end) return float(end)
e3ee23adc8b78a8323868d21c1e066e940b2b595
64,289
def normalize(array): """ Normalize an array's value domain to [0, 1] Note: the original normalize function is at dnnbrain/utils/util.py but 'from dnnbrain.dnn.core import Mask' in the file causes import conflicts. Fix the conflicts in future. Parameter: --------- array[ndarray]...
c01bcc5de5e21a95efb4aad708352f7763772bc5
64,290
from pathlib import Path def write_metadata( metadata: MediaMetadata, media_filepath: Path, output_filepath: Path, overwrite: bool = False, quiet: bool = True, ) -> Path: """Apply some given metadata to some given media content. Args: metadata (MediaMetadata): The meta...
7c304faa8b44ca48e758430d82b9c6a77fe997ce
64,291
def preprocess_notice_xml(notice_xml): """Unfortunately, the notice xml is often inaccurate. This function attempts to fix some of those (general) flaws. For specific issues, we tend to instead use the files in settings.LOCAL_XML_PATHS""" notice_xml = deepcopy(notice_xml) # We will be destructive ...
61fb6c2e17a6a8bd11bdcd6750a48a8feef6b85b
64,292
import random def get_minibatches_indices(n, minibatch_size, shuffle=True, shuffleBatches=True, allow_smaller_final_batch=False): """ Inputs: n - An integer corresponding to the total number of data points Returns: minibatches - a list of li...
41945f0d985ccc173ebe4686139b8df0a9c0a35b
64,294
def create_redis_compose_node(name): """ Args: name(str): Name of the redis node Returns: dict: The service configuration for the redis node """ return { "container_name": name, "image": "redis:3.2.8", "command": "redis-server --appendonly yes", "deplo...
e6d01acc8b0c5c324ad3e0f6e5f527e2a6433705
64,295
def getInfo(request): """ 1건의 현금영수증 상태/요약 정보를 확인합니다. - https://docs.popbill.com/cashbill/python/api#GetInfo """ try: # 팝빌회원 사업자번호 CorpNum = settings.testCorpNum # 현금영수증 문서번호 MgtKey = "20211227-001" cashbillInfo = cashbillService.getInfo(CorpNum, MgtKey) ...
fc9778db50ac9c2a704ad9b38e63f6d2d695de7a
64,296
def join_germanic(iterable, capitalize=True, quoteChars="\"", concat="'"): """Like "".join(iterable) but with special handling, making it easier to just concatenate a list of words. Tries to join an interable as if it was a sequence of words of a generic western germanic language. Inserts a space between each ...
94b4117994b4d83ce47cfed7cd461741bb1c131c
64,297
import re def strip_between(a, b, string): """ Removes anything between (and including) string a and b inside the given string. """ p = "%s.*?%s" % (a, b) p = re.compile(p, re.DOTALL | re.I) return re.sub(p, "", string)
ef440f952b04273040eb847704f4bc6c897ad8c9
64,298
def dft(y, spect='ampl', **kwargs): """ Discrete Fourier transform. Parameters ---------- y : list Signal to transform. dt : float Time interval [s]. spectrum : str Type of spectrum to return: 'ampl'/'power'/'phase'. Default: 'ampl'. Returns ------- Y : list Ampl...
30b3de0a3fa5bf49b798ffd88bd131422e01f55a
64,299
def wrap_deepmind(env, reward_clip=True, frame_stack=4, scale=False): """Configure environment for DeepMind-style Atari. """ env = WarpFrame(env) if scale: env = ScaledFloatFrame(env) if reward_clip: env = ClipRewardEnv(env) if frame_stack: env = FrameStack(env, frame_sta...
00ec97ea2b4ddcca27ae8a38f03e29f841785027
64,300
import torch def receive_generate_info(): """ Needs to be synced up with send_generate_info """ input_info_tensor = torch.empty(10, dtype=torch.float32, device=torch.cuda.current_device()) torch.distributed.broadcast(input_info_tensor, 0) batch_size = int(input_info_tensor[0].item()) seq_l...
36d64aba0509bf3a898239687b1dc96f88d40b0e
64,301
def create_repo(path): """ Give the full path to then new repo with .git ending included. """ repo = Repo.init(path, bare=True) return repo
175cf64ad85ccade67cb50b066104326045bd5d1
64,302
def kis(verts_in, faces_in, height=0.0): """ each n-face is divided into n triangles which extend to the face centroid existing vertices retained equivalent to Blender poke operator """ flags_kis = {} verts_kis = verts_in[:] vert_tags = {'v{}'.format(i): i for i, v in enumerate(verts_kis...
ce66d178d317bd470367edd7c67a9e6811c84a04
64,303
import warnings def combine_batches( data, batch_labels, append_to_cell_names=None, common_columns_only=True ): """Combine data matrices from multiple batches and store a batch label. Parameters ---------- data : list of array-like, shape=[n_batch] All matrices must be of the same format ...
e202257a323e534584d87dadee41557835efce51
64,304
import torch def create_data_loader(inputs, tags, masks, batch_size: int, mode: str = 'train') -> DataLoader: """ Create data loader from inputs, tags and masks :param inputs: :param tags: :param masks: :param batch_size: :param mode: train and val :return: """ inputs = torch.t...
afd82b4198a5c8e376c88fcf4b64cccfa7b663ce
64,305
def file_name_to_multiline_readable( file: str, two_rows_only: bool = False, net_only: bool = False ) -> str: """Returns a stylised file_name to be human readable across multiple lines, e.g. for titling a plot. Args: file: Processed results filename with or without path. """ # remove path i...
8d00ddf7764a6458a28bbd9f5bb1317b392f64cd
64,306
from pathlib import Path from datetime import datetime def mediainfo(fp_in): """Returns abbreviated video/audio metadata for video files :param fp_in: filepath""" # extension and media type ext = file_utils.get_ext(fp_in) if ext in app_cfg.VALID_PIPE_IMAGE_EXTS: media_type = 'image' elif ext in app...
f8991fd9275806bf0e0617bf5ee72cc8bb9eae03
64,307
from typing import Any def build_post_double_headers_final_azure_header_get_request(**kwargs: Any) -> HttpRequest: """Long running post request, service returns a 202 to the initial request with both Location and Azure-Async header. Poll Azure-Async and it's success. Should NOT poll Location to get the fi...
1aea0fb2d79edd926fb079d3a9002b9a7759839e
64,308
def a_star(grid_map: GridTransitionMap, start: IntVector2D, end: IntVector2D, a_star_distance_function: IntVector2DDistance = Vec2d.get_manhattan_distance, avoid_rails=False, respect_transition_validity=True, forbidden_cells: IntVector2DArray = None) -> IntVector2DArray: """ :param avoid_...
c56e02fbd0cd094cc1e94e9a44ca048a252459fe
64,309
def sun_rot_elements_at_epoch(T, d): """Calculate rotational elements for Sun. Parameters ---------- T: float Interval from the standard epoch, in Julian centuries i.e. 36525 days. d: float Interval in days from the standard epoch. Returns ------- ra, dec, W: tuple (flo...
9a74edc686869eebd851200687fe4d10d38d550a
64,310
from scipy import integrate def Network_solve_RosslerSystem(args): """Returns a 2D-array of the trajectories of the coupled systems in the form [X1...n, Y1...n, Z1...n] Y0, 1D array of DOUBLE or INT: inital state of the form Y0 = [x1,x2, ...,xn, y1,y2, ...,yn, z1,z2,...,zn] d...
e6bc19e66d0e70bcc1a0bdbc767e43e11616c52a
64,311
def as_delayed_signal(arg, **kwargs): """Make sure that the given argument can be used as a signal. Parameters ---------- arg : sequence of 1 array_like followed by 1 or 2 scalars The first element is converted to a NumPy array, the second element is used as the sampling rate (in Hertz)...
9bfc25644cd859c39bcd46f39e7e39b5474401e5
64,312
def mejor_aerolinea(vuelos: dict) -> str: """ La mejor aerolínea Parámetros: vuelos (dict): Es un diccionario de diccionarios con la información de los vuelos. Retorno: str: El nombre de la mejor aerolínea (la que tenga menor retraso promedio) """ aero_con_promedioretraso = {} # vuel...
68816ae69bc3b7189e06f690c635739b6933eb17
64,313
def subexpd(global_step, start_step, end_step, start_val, end_val, warmup=True, stair=True): """Sub-exponential decay function. Duration decay is sqrt(decay).""" if warmup and start_step == 0: return lerp(global_step, start_step, end_step, start_val, end_val) decay_steps = tf.cast(end_step - start...
ea9fa39d46b32d29eddf2e8e0451054fd8c3a045
64,315
def _get_all_polylines_pm(edges): """ [pm] edges で指定したエッジ列を連続するエッジ列の集まりに分割してリストを返す get_all_polylines() から呼ばれる Pymel 版の実装。基本的には直接呼ばず get_all_polylines() を使う。 Args: edges (list[MeshEdge]): Returns: list[list[MeshEdge]]: """ polylines = [] rest_edges = edges intersectio...
ddb587e42a79837499986d84c4db127acbb62e8a
64,316
def register(): """ function to render registration form :return: """ form = RegistrationForm() if form.validate_on_submit(): user = User(username=form.username.data, email=form.email.data) user.set_password(form.password.data) db.session.add(user) db.session.com...
857082c6b7d7c885f2dc33abf859bf9458c44010
64,317
def android_devices(prefix, parsed_args, **kwargs): """ Returns all connected Android devices. :param prefix: The prefix text of the last word before the cursor on the command line. :param parsed_args: The result of argument parsing so far. :param kwargs: keyword arguments. :returns list: list ...
075a8addf0740ff5a4a8147244393323440cc6d8
64,319
def subsong_replaceext(filepath, subsongformat_type): """replace extension of subsong filepath with another extension will properly replace subsong extensions like .sub.imc filepath: a file path subsongformat_type: a key from extutils.SUBSONG_FORMATS. Pass the one corresponding to the extension ...
a655be08ffd81a03ebcceb1d33243cd24ddb5f39
64,320
def write_positions(positions): """parse float tuples of a text string return string """ result = "" if positions is not None: for x,y in positions: result = "%s %s,%s" % (result, x, y) return result
0587272400c2e835bcf2ebd3e55f65e2daa7ee1f
64,321
def NameAndAttribute(line): """ Split name and attribute. :param line: DOT file name :return: name string and attribute string """ split_index = line.index("[") name = line[:split_index] attr = line[split_index:] return name, attr
7595f51d728c5527f76f3b67a99eccd82fb9e8b7
64,322
def siteCallWrap(seq, orient, seqLen): """ Wraps kmerMatch, findConsArrays, and findCenter together Input: sequence, orientation, sequence length Output: list of called sites """ return(findCenter(findConsArrays(kmerMatch(seq)), orient, seqLen))
b7ee0855f92173bc816de16aa37814f8cbeae15d
64,323
import string def english_like(s: str) -> float: """higher is better""" if any(c not in string.printable for c in s): return -1 return sum(letter_frequencies.get(c, 0) for c in s)
52c1de13805bc6fa50193b08bc169e11e621c23f
64,324
def _datastore_wait_ready(popen): """Wait until the datastore emulator is ready to use. :type popen: :class:`subprocess.Popen` :param popen: An open subprocess to interact with. """ envs = {} emulator_ready = False while not emulator_ready: line = popen.stderr.readline() if l...
05f12bfbf77a95c0a2732cf606ba44fa3bf4b769
64,325
from typing import Sequence def order_certificate( minion_id, common_name, organization_id, validity_years, cert_key_passphrase=None, signature_hash=None, key_len=2048, dns_names=None, organization_units=None, server_platform=None, custom_expiration_date=None, comments=...
babc3f1f9090d34e7c334d44d3dd97d50c3e6eeb
64,326
def test(data, goal, net): """ Test the model. """ correct = 0 print("Testing...") for i in range(len(data)): classification = np.argmax(net.test(data[i][:])) answer = np.argmax(goal[i]) if(answer == classification): correct += 1 print("Score: " + str(correct *...
977ccdf1a61d6d667244e8a8cd59fbf8eafe4551
64,327
from datetime import datetime def sitemap(): """ Renders a sitemap. """ context = make_context() context['pages'] = [] now = datetime.date.today().isoformat() context['pages'].append(('/', now)) context['pages'].append(('/methodology/', now)) context['pages'].append(('/legislator...
98c788f7404e5b5b9c837c7061e8ea2261456491
64,329
def pre_process_features(observation): """Takes the raw observation vector of the environment and amends it to our needs. :param observation: The observation of the environment :return: A vector which contains the features which we want. """ IDX_SUC_NODES = 12 features = np.array(observation[:I...
94dd97adbb3c2bb54d64e5a669aae6062eae2adc
64,331
def calculate_accuracy(accepted_scores, accepted_labels): """This function calculates the gain of the second classifier, based on the true training instances accepted by the first classifier. Args: accepted_scores ([int]): Positive scores obtained from the second classifier ...
5845eb2d55500e007c633c280ef8963850805a82
64,332
def uuid(): """UUID for Test.""" return uuid4()
46085befe6d7365492ab3981a09e0ee29bccc264
64,333
def compute_mse(actual, forecast): """ Computes the Mean Squared Error between the tensors 'actual' and 'forecast', representing the ground truth outcomes and model outcomes, respectively. Args: actual (ndarray): Ground truth outcome forecast (ndarray): Model outcome Returns: ...
ff74d57e578869de27ceed9a478e49113a23a9f1
64,334
import crypt def _get_pem_key(credentials): """Gets private key for a PEM payload from a credentials object. :type credentials: :class:`service_account.ServiceAccountCredentials`, :param credentials: The credentials used to create a private key for signing text. :rtype: :clas...
b186381f17742b5f30a91fd766b0fc682db2dd3f
64,335
def bsplclib_Resolution(*args): """ * given a tolerance in 3D space returns a tolerance in U parameter space such that all u1 and u0 in the domain of the curve f(u) | u1 - u0 | < UTolerance and we have |f (u1) - f (u0)| < Tolerance3D :param PolesArray: :type PolesArray: float & :param ArrayDimension:...
65475a9a99ad27c75886f3c2348bac896c958d09
64,336
def transverse_width(Lambda, theta_s): """ Transverse Coherence Width (Zernike-Van Cittert Theorem). Params: Lambda: electron wavelength in Å. theta_s: convergence semi-angle of source (or image of source) in radians. Returns: transverse coherence width in Å. """ return Lambda / (2 ...
c822d9f3e0d493c40bac6e968b111b48915ede4a
64,337
def create_relationship_query(entity_map: dict, rel_name: str, rel_map: dict) -> str: """ Purpose: Create relationship definition query Args: entity_map: Entities map rel_name: The name of the relationship rel_map: Relationship Map Returns: graql_insert_query: The...
683a0a316c132db7ec5ee0f01c302c06c2a45d77
64,339
def leave_one_out(learner, dataset, size=None): """Leave one out cross-validation over the dataset.""" return cross_validation(learner, size, dataset, k=len(dataset.examples))
b215e552af9f9f8c7dd0bc64cc8b65adb6c16ad7
64,340
def unsigned(value, size): """ Make a value unsigned based on it's size. """ return value & u_maxes[size]
e2dd53c804acd6a7fe8150b275d1921b978167aa
64,341
def convert_data(inp, outp, data): """ Return data converted to the output format ... over-simplistic implementation for the moment ... @param inp,outp: input/output format like "cbfimage" @param data(ndarray): the actual dataset to be transformed """ return CONVERSION_DATA.get((inp, outp), lamb...
d4db6b4ec460b6239ea25471edbd6e9497d3f79e
64,342
import queue def kruskal(graph: UndirectedGraph) -> UndirectedGraph: """Kruskal algorithm. :param graph: an undirected graph with weighted edges :return: the minimal spanning tree""" mst = UndirectedSimpleGraph([v.id for v in graph.vertices]) edge_queue = queue.PriorityQueue() vertex_sets = D...
3ddffbe23513bdcfa9d9162841a5c219cd11d4f0
64,344
import torch import copy def clones(module: torch.nn.Module, n: int): """ Produce N identical copies of module in a ModuleList :param module: The module to be copied. The module itself is not part of the output module list :param n: Number of copies """ return torch.nn.ModuleList([cop...
e4807cda87c90af415555606e3308f07ff9ddf49
64,345
def convert_kwargs_to_str(kwargs, max_len=None): """ Convert kwargs to a string, allowing for some arguments to raise exceptions during conversion and ignoring them. """ length = 0 strs = ["" for i in range(len(kwargs))] for i, (argname, arg) in enumerate(kwargs.items()): try: ...
11e0d1defd9d8b90b530c1d011c4f9a315492311
64,346
def get_autodetected_TEST_SPEC(mbeds_list, use_default_toolchain=True, use_supported_toolchains=False, toolchain_filter=None, platform_name_filter=None): """ Function detects all connected to ...
c59e4b744b57595a742bd31eed297e10f39d184e
64,347
def build_copy_labels(config, example, emb_dicts, related_words_ids_mat): """ Get example question generation features. NOTICE: we can add different strategies for divide copy and non-copy part from tgt """ tgt, switch, copy_position, switch_oov, copy_position_oov, switch_soft, copy_position_soft, i...
70e63a2a80b090cd980ca323ab71573224f8692c
64,348
def filter_current_user_queryset(modelRelatedFieldObj): """ This handy method will allow you to limit the choices of modelRelatedFieldObj based on the current request user. """ if 'request' in modelRelatedFieldObj.context: user = modelRelatedFieldObj.context['request'].user if 'user'...
6c3a570cce171fac348ad50ab08d2b5890f52918
64,349
def append_age_banding(df): """ Method that appends a banding of the age field, which is consistent with the method `band_age`. **Note**: This method assumes that the DataFrame `df` include the (int) field named 'age', which is :param pandas.DataFrame df: DataFrame of transformed marathon data :re...
bf6a5dab84c952069da3a1c12ff39c5844cf1e28
64,350
def is_sorted(array): """ Check if array of numbers is sorted :param array: [list] of numbers :return: [boolean] - True if array is sorted and False otherwise """ for i in range(len(array) - 1): if array[i] > array[i + 1]: return False return True
8542e162aa96f7035d33f1eb7b7159031a8a41b8
64,351
def downsample_linearring(points,density,factor=None,closed_ring=1): """ Makes sure that points aren't *too* close together Allow them to be 0.3*density apart, but any edges shorter than that will lose one of their endpoints. """ if factor is not None: density = density * factor # should giv...
8e0f80fa5fc80038466266d1f092d12f9f1167e0
64,352