content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import traceback def redirect_auth_oidc(auth_code, fetchtoken=False, session=None): """ Finds the Authentication URL in the Rucio DB oauth_requests table and redirects user's browser to this URL. :param auth_code: Rucio assigned code to redirect authorization securely to IdP via...
ec70b5c5d1b264ad48569fa955f0edcaaa1374fa
3,628,597
def inception_crop_with_mask( image, mask, resize_size=None, area_min=5, area_max=100): """Applies the same inception-style crop to an image and a mask tensor. Inception-style crop is a random image crop (its size and aspect ratio are random) that was used for training Inception models, see https://www.cs....
2f342b49035fd9a6e095a2debae3df6250718ec9
3,628,598
from datetime import datetime def should_build_new_prices() -> bool: """ Determine if prices were built recently enough that there is no reason to build them again :return: Should prices be rebuilt """ cache_file = CACHE_PATH.joinpath("last_price_build_time") if not cache_file.is_file(): ...
0cc1f673cf39c554aa1ad72ff4c7e0a5f90cc713
3,628,600
def config_nat_pool_binding(dut, **kwargs): """ Config NAT pool bindings Author:kesava-swamy.karedla@broadcom.com :param :dut: :param :config: add/del: :param :binding_name: :param :pool_name: :param :nat_type: :param :twice_nat_id: :param :acl_name: usage: config_nat_p...
e64204b575684fb57e3ab2a025771edad329d902
3,628,601
def database_obj_to_py(obj, fingerprints_in_song=False): """ Recursively convert Fingerprint and Song sqlalchemy objects to native Python types (lists and dicts). Args: obj (database.schema.Fingerprint|database.schema.Song): ``audio`` module Fingerprint or Song object. finge...
49d89c0e93ee492f911e1c42e0bfc6af9232c8ba
3,628,602
import csv def get_outputs(output_file): """ Parse ``output_file`` which is a csv file and defines the semantics of the output of a neural network. For example, output neuron 1 means class "0" in the MNIST classification task. """ outputs = [] mode = "rt" with open(output_file, mo...
b001942bc270952c9bb82537d0b5033c9ee968ff
3,628,603
def auto_adjust(img): """Python translation of ImageJ autoadjust function. Parameters ---------- img : ndarray Returns ------- (vmin, vmax) : tuple of numbers """ # calc statistics pixel_count = int(np.array((img.shape)).prod()) # get image statistics # ImageStatistics ...
861ff4d7c2eaea9e10341f718fd9cfab33a9eab8
3,628,604
def ChanPcaKmeansDS(ds, xvec='bias', chan='cf', mod=lambda y: y, comps=6,nclust=4, fig=None): """ :param ds: xarray dataset :param xvec: name of dataset coordinate :param chan: selected channel :param mod: if desired, pass the modifier for the plotting of the histogram via lambda functions :...
487bd468a77340b13f5e5702e24ed87e092f41f9
3,628,605
def elements(elements, axis=0): """ Calculates an node 2-d-array from an element 2-d-array, uses the [:, 1], [:, -2] entries of the calculated node 2-d-array to fill the first als last row of the node 2-d-array. """ nodes = np.asarray((elements[:, :-1] + elements[:, 1:])) * .5 return np.hsta...
6be65159469972db6d69ce1b4975e84ef1aef4d4
3,628,606
def convert_date_to_unix(date_string): """Convert date input to unix timestamp. Args: date_string: the date input string. Returns: (int) converted timestamp. """ if not date_string: return None return int(dateparser.parse(date_string).timestamp() * 1000)
a3cc4e363d7940df904e02b4e5d5d34a3a58a322
3,628,607
def decoder(decoder_inputs, initial_state, cell, output_size, loop_function=None, dtype=None, scope=None): """ The Decoder Function which returns the decoder hidden states after decoding the whole output args: decoder_inputs: The inputs to the decoder, either the targets during training or t...
ea8272815be6a0cb206505a811b522ec36f9e7df
3,628,608
from typing import Sequence def kron(nodes: Sequence[BaseNode]) -> BaseNode: """Kronecker product of the given nodes. Kronecker products of nodes is the same as the outer product, but the order of the axes is different. The first half of edges of all of the nodes will appear first half of edges in the result...
d52f6fe4c5a3c5980f6bf8b94543dc9201c3ac7d
3,628,609
def diskmounter() -> Mounter: """Fixture with an unversioned disk filesystem mounter.""" return unversioned_mounter(DiskFilesystem)
d3c67839dc7c0d3cb452235c8d4aa29b9a829ee7
3,628,610
def stations(): """Return a JSON list of stations from the dataset.""" # most_active_stations = session.query(measurement.station, func.count(measurement.station)).\ # group_by(measurement.station).\ # order_by(func.count(measurement.station).desc()).all() stationr...
b70109e02d15177343c4d2f8cf8fce078f5c2bf6
3,628,611
def search_sorted_matrix(matrix, target): # Write your code here. """ 1 4 7 12 15 1000 2 50 500 1001 3 1002 4 """ result = [-1, -1] row = 0 if len(matrix) == 0: return result col = len(matrix[0]) - 1 while col >= 0 and row < len(matrix): ...
26a2dd0d714b0cdf88822dc2f956fc9d7f9cd02f
3,628,612
def get_io_functions_from_lib(lib, load_func_name='load', dump_func_name='dump', load_kwargs={}, dump_kwargs={}): """Helper to create loader and dumper functions for libraries""" def loader(input_stream, args): return getattr(lib, load_func_name)(input_stream, **load_kwargs) def dumper(output, outpu...
1d81031c7e5421f190f8c8936d92f2a5a2d999bf
3,628,613
def get_pane_id(session: str, window: int, pane: int): """ Get a given pane ID Parameters ---------- session : str Name of the session window : int Window number of pane pane : int Pane index in the window """ injected = get_injected_pane_data(session, window...
f795859c6a8b5546e220e6d715ca3e3eec984b0f
3,628,614
def normalize_signs(arr1, arr2): """Change column signs so that "column" and "-column" compare equal. This is needed because results of eigenproblmes can have signs flipped, but they're still right. Notes ===== This function tries hard to make sure that, if you find "column" and "-column"...
8f44bafdbacc5dcbbc339985092bb459ce7294b1
3,628,615
def draw_lines(img, lines, scale): """ this function draw lines on a picture, according to scale first point from the left is added in case of absence last point from the right is added in case of absence returns updated image """ if lines is not None and len(lines) > 0: # calculate...
4da51115d3037b9b938fdafef65bb5a6f22176f3
3,628,616
def tokenize_de(text): """ 将德语文本从字符串标记为字符串列表 """ return [tok.text for tok in spacy_de.tokenizer(text)]
9d5cf22d2356202b8818348edb3c36b6562106b4
3,628,617
import socket def port_in_use(port, host=LOCALHOST): """Returns True when a port is in use at the given host. Must actually "bind" the address. Just checking if we can create a socket is insufficient as it's possible to run into permission errors like: - An attempt was made to access a socket i...
7249e6fe405d4577301c78eaa576c181b99816b1
3,628,618
async def video_feed(): """Video streaming route. Put this in the src attribute of an img tag.""" return StreamingResponse(gen(Camera()), media_type='multipart/x-mixed-replace; boundary=frame')
27051c6d2adb1dd30a477055b175d8a85103bd46
3,628,620
def logout(): """ Log out the user """ session.clear() return json_response(status=200, response_data={"success": True})
01a6a15f1ec4c654ff8b0b0c79254bc4962fce95
3,628,621
import base64 import json def get_secrets(secret_name): """ Get secrets from AWS Secrets Manager """ session = boto3.session.Session(profile_name="platform-dev") client = session.client( service_name="secretsmanager", region_name="eu-west-1" ) try: response = client.get_se...
8c7d19b34c27f706ec4e6b6e214fa2f42a8e2ec8
3,628,622
def load(savime_element: LoadableSavimeElement) -> str: """ Get the load query string for a loadable element. :param savime_element: A loadable savime element. :return: The load query for the savime element. """ return savime_element.load_query_str()
650387cbde39fd82dcd5484542bd210b3a7ced56
3,628,625
def topo_flat(x,y): """ flat """ z = where(x < 204.91213, 30., -30.) return z
b7d55b2eaff9ebc78645ccf0b2c2f13210eaef3f
3,628,626
def softmax_xent(*, logits, labels, reduction=True, kl=False): """Computes a softmax cross-entropy (Categorical NLL) loss over examples.""" log_p = jax.nn.log_softmax(logits) nll = -jnp.sum(labels * log_p, axis=-1) if kl: nll += jnp.sum(labels * jnp.log(jnp.clip(labels, 1e-8)), axis=-1) return jnp.mean(nl...
9c59907d365088c6bf54be861db0a67631dbf8cf
3,628,627
from typing import Dict from typing import Any def sign_block_data( data: Dict[str, Any], private_key: str, hash_alg: str = 'keccak256' ) -> Dict[str, str]: """sign block data :param data: dict :param private_key: hex str (private key) :param hash_alg: `keccak256` or `sha256`, the default val...
26da624c26885fc3c9b20a0e1229c398f627d63a
3,628,629
def convert_label(label_img): """ covert label """ label_processed = np.zeros(label_img.shape[0:]).astype(np.uint8) for index in range(label_img.shape[2]): label_slice = label_img[:, :, index] label_slice[label_slice == 10] = 1 label_slice[label_slice == 150] = 2 label_slice...
d76e9b2557048f0bee1d657fb5d50283819e7d4e
3,628,630
def update_hand(hand, word): """ Does NOT assume that hand contains every letter in word at least as many times as the letter appears in word. Letters in word that don't appear in hand should be ignored. Letters that appear in word more times than in hand should never result in a negative count; ins...
2f87fe20335d2080b51b2fd40c55a226e1c79b8a
3,628,631
def list_zeroes(line): """ Takes a list of integers and removes all non-zero elements. """ zeroes = [] for item in line: if item == 0: zeroes.append(item) return zeroes
f10d6a59f8a6f00cb22d5f6ee6ce2087a4969b8e
3,628,632
def ecef_to_lla2(x_m, y_m, z_m): """Convert ECEF cartesian coordinates to WGS84 spherical coordinates. This converts an earth-centered, earth-fixed (ECEF) cartesian position to a position on the Earth specified in geodetic latitude, longitude and altitude. This code assumes the WGS84 earth model. ...
63495e6b1407cc3714b5ee44b115bc47725b0a19
3,628,633
def ObjectToDict(obj): """Converts an object into a dict.""" keys = [ k for k in dir(obj) if not k.startswith("__") ] return { k : getattr(obj, k) for k in keys }
f2679daab84d5cee2c7f319d1d34f3c669971cd6
3,628,634
def ortho(subj_coord, obj_coord, subj_dim, obj_dim): """ It returns a tuple of 3 values: new dim for combined array, component of subj_origin in it, component of obj_origin in it. """ if subj_coord > obj_coord: return (subj_coord + (obj_dim - obj_coord), 0, subj_coord - obj_coord) ...
36a3127b0721ac87e81259432823eab26fc015e9
3,628,636
def _unravel(nodes,tets,index): """Returns a list containing the node coordinates of the tet stored in the 'index' position in the 'tets' list.""" return [nodes[tets[index][0]],nodes[tets[index][1]],nodes[tets[index][2]],nodes[tets[index][3]]]
e8428de351db2a84a4875a81b47d07b03a67efd9
3,628,637
def pairwise(accuracy_balanced, method_names, out_results_dir, num_repetitions): """ Produces a matrix of pair-wise significance tests, where each cell [i, j] answers the question: is method i significantly better than method j? The result would be based on a test of choice. The...
06618051f2aad89c8eb75877a37f18ba243b4150
3,628,638
def visdom_image(vis, image,win_name): """ eg : visdom_image(vis=vis, image=drawn_image, win_name='image') :param vis: 由 setup_visdom 函数创建 :param image: 单幅图片张量,shape:[n,w,h] :param win_name: 绘图窗口名称,必须指定,不然会一直创建窗口 :return: """ vis.image(img=image, win=win_name) ...
145ad236c0e07a79195a573b562ffd9a8654be96
3,628,639
def generate_splits_type3(in_data, slot_data, intent_data, instance_types_per_client=3, clients_per_instance_type=3): """Creates non-IID splits of the dataset. Each client is given only a fixed number of inte...
ae2c2472ba32f737160e69fbe7a77fded9407b07
3,628,640
def file_num2size(num_size, h=True): """文件大小数值变为 MB 的显示 :param num_size: 文件大小 :param h: 是否 human 显示 :return: {'value': 数值,'measure': 单位,'str': 字串, 'org_size': 原始大小} """ measure_list = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'] fsize = num_size i = 0 while (fsize >= 1) and (i < len(measure...
f3cf060b4015831381ab5d5b3ed236d8519746cc
3,628,642
def cartopy_ylim(var=None, geobounds=None, wrfin=None, varname=None, timeidx=0, method="cat", squeeze=True, cache=None): """Return the y-axis limits in the projected coordinates. For some map projections, like :class`wrf.RotatedLatLon`, the :meth:`cartopy.GeoAxes.set_extent` method d...
ea0b9f40730c19f9cc52e55e6f124a54df07b9f4
3,628,643
def get_user_csc_name(): """Get user csc name from saml userdata. Returns: [string] -- The users CSC username. """ if not is_authenticated() or not is_authenticated_CSC_user() or 'samlUserdata' not in session: return None csc_name = session.get('samlUserdata', {}).get(SAML_ATTRIBU...
17bcbc3b4ca2bfbb0a9de19b77f47aac94f2d089
3,628,644
def precision_Approximation(*args): """ * Returns the precision value in real space, frequently used by approximation algorithms. This function provides an acceptable level of precision for an approximation process to define adjustment limits. The tolerance of approximation is designed to ensure an acceptable com...
01dd6286509b69a875807bdaf4db59a34d7d5aad
3,628,646
import time def getEpoch( ): """ Return the Unix epoch divided by a constant as string. This function returns a coarse-grained version of the Unix epoch. The seconds passed since the epoch are divided by the constant `EPOCH_GRANULARITY'. """ return str(int(time.time()) / const.EPOCH_GRA...
649fb0dc8bb8a2bbd8294449ef1c3ffb64ca5aa1
3,628,649
def moveeffect_02C(score: int, move: Move, user: Pokemon, target: Pokemon, battle: AbstractBattle) -> int: """ Move Effect Name: Increases user's special attack and special defense (Calm Mind) """ if user.first_turn: score += 40 if user.boosts.get("spa", 0) == 6 and user.boosts.get("spd", ...
6bff14b50029af1a60c47c7e478766edbf033c9a
3,628,651
from typing import Optional from typing import Tuple from typing import Dict from typing import Hashable def get_dataset_subsampling_slices( dataset: xr.Dataset, step: int, xy_dim_names: Optional[Tuple[str, str]] = None ) -> Dict[Hashable, Optional[Tuple[slice, ...]]]: """ Compute subs...
0cef7a329bc33f124e3c5f7263a08cc9df8e9c37
3,628,654
import types import asyncio def loop_apply_coroutine(loop, func: types.FunctionType, *args, **kwargs) -> object: """ Call a function with the supplied arguments. If the result is a coroutine, use the supplied loop to run it. """ if asyncio.iscoroutinefunction(func): future = asyncio.ensure...
d77a70540237f690e712e30b93b53b363907b678
3,628,655
def zipmap(keys, vals): """ Return a ``dict`` with the keys mapped to the corresponding ``vals``. """ return dict(zip(keys, vals))
a058e5a4e462416f48d83b3c288a0cd8d6b000ef
3,628,656
def _create_thingy(sql_entity, session): """Internal call that holds the boilerplate for putting a new SQLAlchemy object into the database. BC suggested this should be a decorator but I don't think that aids legibility. Maybe should rename this though. """ session.add(sql_entity) #Note t...
4d50da3a15606c7adf61e2c9c09a4a3a9898edf9
3,628,657
import torch def mix_estimator(states, actions, disc_rewards, mask, policy, result='mean'): """ states: NxHxm actions: NxHx1 disc_rewards, mask: NxH """ upsilon_scores = policy.loc_score(states, actions) #NxHxm G = torch.cumsum(upsilon_scores, 1) #NxHxm sigma_scores = policy.scale_scor...
510e88bbd9b36e89853341951d67cfc254e68d61
3,628,658
def weighted_loss(func): """ A syntactic sugar for loss functions with dynamic weights and average factors. This method is expected to be used as a decorator. """ @wraps(func) def _wrapper(pred, target, weight=None, reduction='mean', ...
078ddd743e5f1e3b835ac86ea25966a3813001ce
3,628,659
def similarity(s, theta, axis, tx, ty, tz): """ Create a 4x4 similarity transformation matrix. Parameters: ----------- s: isotropic scaling ratio. theta: angle of rotation about `thetaaxis`. axis: a vector (not necessarily a unit vector along the axis of rotation. tx: translation in...
8303d2b2c988aae8e6217807a35afef1058c42dc
3,628,660
def compute_sequences_weight(alignment_data=None, seqid=None): """Computes weight of sequences. The weights are calculated by lumping together sequences whose identity is greater that a particular threshold. For example, if there are m similar sequences, each of them will be assigned a weight of 1/m. No...
b0da45ffb48526cbaaa2d976405323a6c41b6072
3,628,661
def parameter_bank_names(device, bank_name_dict=BANK_NAME_DICT): """ Determine the bank names to use for a device """ if device != None: if device.class_name in bank_name_dict.keys(): return bank_name_dict[device.class_name] else: banks = number_of_parameter_banks(device)...
3dbb95d35a7bb837208d812ba377bc546c986993
3,628,662
def maxsubarray(list): """ Naive approach to calculating max subarray Iterating all possible subarrays Complexity (n = list size) Time complexity: O(n^2) Space complexity: O(1) """ maxStart = 0 maxEnd = 0 maxSum = list[0] for i in range (len(list)): currentSum = 0 ...
71b4a12d02fab45fc14890ae4a34a0dc50d6a7b4
3,628,663
def deserialize_transaction_data(f): """ Deserialize transaction data More info: https://learnmeabitcoin.com/technical/transaction-data :param f: buffer, required :return: dict """ transaction = Transaction() start_transaction_data = f.tell() transaction.version = f.read(4)[::-1].he...
8231bca1dbf7dfb86f16dbd4a5ac30d1c80579e7
3,628,664
def parse_string(string: str) -> list: """Parsing specified string :param string: File content for parsing :type string: str :rtype: list :raises: ParseException """ parsed = create_grammar().parseString(string, parseAll=True) return parse_tokens(parsed)
0b94d3917cfb37b28d22c90a877cbe4df32b1d67
3,628,665
def reset_config(): """Reset the configuration. An endpoint that accepts a POST method. The json request object must contain the key ``reset`` (with any value). The method will reset the configuration to the original configuration files that were used, skipping the local (and saved file). .. ...
f4c8c7aeea43a7c2c8bc196855ce4fb8081ac31c
3,628,666
from typing import Sequence def is_sequence(obj): """Is the object a *non-str* sequence? Checking whether an object is a *non-string* sequence is a bit unwieldy. This makes it simple. """ return isinstance(obj, Sequence) and not isinstance(obj, str)
06129c6122fec0290edb34cadc75b68199738435
3,628,667
def make_exponential_statistics(state): """Make ExponentialMovingStatistics object from state.""" return ExponentialMovingStatistics.fromstate(state)
bf9df2841707e2c12d91e23f17bc6de52728e66d
3,628,669
import time import socket def DetectAio(timeout=1.1): """Detect AIO nodes on the network, present all options if none detected.""" sources = aio.aio_node_helper.Names() types = aio.message_type_helper.Names() client = aio.AioClient(types, timeout=0.1, allowed_sources=sources) ip_list = [] version_list = [...
805dc33200a6e774fc2d55032242ea79aa97c28f
3,628,670
def getAxisList(var): """ Returns a list of coordinates from: var """ return [var.coords[key] for key in var.dims]
eae9b971bcbf021ef2203dd6cb21df6343d0f19a
3,628,671
import functools def listify(fn=None, wrapper=list): """ From https://github.com/shazow/unstdlib.py/blob/master/unstdlib/standard/list_.py#L149 A decorator which wraps a function's return value in ``list(...)``. Useful when an algorithm can be expressed more cleanly as a generator but the functi...
d9fe22ffdda41938aa6029bbb3ac54aeda4b818b
3,628,672
def skip_nothing(name, dirpath): """Always returns :obj:`False`. """ return False
9e846b7060af43b2c4165e6530fcabc66415615b
3,628,673
def titlecase(string): """Titlecase all words in the string. Words with quote (') titlecased only in the beginning, as opposed to built-in ``str.title()``. Roman numerals are uppercased. """ def f(mo): roman_mo = ROMAN_PATTERN.match(mo.group()) if roman_mo: return mo.gro...
88140ff62db5601573227654f876b0310a343709
3,628,676
def register(key=None): """Returns a decorator registering a widget class in the widget registry. If no key is provided, the class name is used as a key. A key is provided for each core Jupyter widget so that the frontend can use this key regardless of the language of the kernel. """ def wrap(w...
c21246a30926f3e78c3e85c487de76affe776b72
3,628,677
import re def find(pattern): """ Find all instances where the pattern is in the running command .. code-block:: bash salt '*' nxos.cmd find '^snmp-server.*$' .. note:: This uses the `re.MULTILINE` regex format for python, and runs the regex against the whole show_run output....
b60aa06d973ec7725351276aa3898be45e73757e
3,628,679
import torch def get_center(arcs): """Centre of the arc Args: arcs: tensor [batch_size, num_arcs, 7] arcs[b, i] = [x_start, y_start, dx, dy, theta, sharpness, width] Returns: tensor [batch_size, num_arcs, 2] """ x_start = arcs[..., 0] y_start = arcs[..., 1] dx = arcs[...
665685e4cc17ab34732ad0928363c2f882bdc03e
3,628,680
import urllib from bs4 import BeautifulSoup def get_urls_towns(url_index_by_letter): """Provides from the page corresponding to a city index the pages corresponding to the cities of the index. Args: url_index_by_letter (string): Url corresponding to a city index e.g. : "https://elections.int...
3282a27a4ded8d80f020b2306ab5e62c56c07be9
3,628,681
def simple_app(global_config, **settings): """This function returns a Pyramid WSGI application.""" with Configurator(settings=settings) as config: config.set_security_policy(TestingSecurityPolicy()) apps = global_config.get('apps', '') if not isinstance(apps, (list, tuple)): ...
7aa1edead8a557f6b08cb9323440633684cea6ab
3,628,682
from typing import Optional import glob import tqdm import re from pathlib import Path import PIL def imgs_preds(model_config: tuple[Model, tuple[int, int]], path: str, slc: Optional[slice] = None) -> list[ list[str, str]]: """ Get the predicted class for each image :param model_config: model object ...
e81c0eaeaba9597656ba2e7459e4c5a316237540
3,628,684
def vertical_cross(in_field, lon, lat, line_points, npts=100): """ Interpolate 2D or multiple dimensional grid data to vertical cross section. :param in_field: 2D or multiple dimensional grid data, the rightest dimension [..., lat, lon]. :param lon: grid data longitude. :param ...
873985f361883992e23a8bc5142c5d0e469ca6c3
3,628,685
import csv def write_wordlist(wordlist): """ Write a wordlist to a temporary file. """ handler = NamedTemporaryFile("w", encoding="utf-8", delete=False) writer = csv.DictWriter( handler, delimiter="\t", fieldnames=list(wordlist[0].keys()) ) writer.writeheader() writer.writerow...
377bb1871afaed6109e24e502752f7223238dec6
3,628,686
def hasfield(model_cls, field_name): """ Like `hasattr()`, but for model fields. >>> from django.contrib.auth.models import User >>> hasfield(User, 'password') True >>> hasfield(User, 'foobarbaz') False """ try: model_cls._meta.get_field(field_name) return True e...
186b0754b3c87b5fb4c2b9a003221b57887160d1
3,628,687
def get_distance(point_a, point_b): """Receives two coordinates by parameter, and returns the geodesic distance between them (in km). Params: - point_a: tuple or list expected, first coordinate - point_b: tuple or list expected, second coordinate Returns: - Formatted string indicati...
5a897797d5b89448f0af1c7d09b1d7dc9fbd4942
3,628,688
def __substitute_controller_variables(config): """Substitute variables and set defaults for config Arguments: config {dict} Raises: Exception: [description] Returns: [dict] """ global_variables = config.get("variables", {}) set_master_password = global_variables.ge...
29f55775284a5d1f8bd2bbc6ba2dcb18a4b838ec
3,628,689
def CNOT_like_PTM(idx): """ Returns the pauli transfer matrix for gates of the cnot like class (q0) --C1--•--S1-- --C1--•--S1------ | -> | (q1) --C1--⊕--S1-- --C1--•--S1^Y90-- """ assert(idx < 5184) idx_0 = idx % 24 idx_1 = (idx // 24...
ff861d8490742a9982fbfdb68e89d487e881bf1c
3,628,691
def _random_binary_string_matrix(rows, cols, max_length): """Returns a list of lists of random strings""" return [[_random_binary_string_gen(max_length) for _ in range(cols)] for _ in range(rows)]
841ea51e2ae54da8d2381bcdc95c696f67ede17e
3,628,692
def comment_list_view(request, slug): """ Get post comments from a server Selects the post instance matching the comment slug and then gets all displayed comments that match that post instance. Then we pass the objects we want to use into the serializer. The serializer will take that informati...
f8c344d8c8e3fc1d7ca0f1c9db95adb7f0a8d174
3,628,694
def cos(x): """ Takes the cosine of a DualNumber object and returns a DualNumber object with updated value and derivatives. """ x = DualNumber.promote(x) output = x.promote(np.cos(x.value)) # real part of the first parent distributes for k1 in x.derivatives: output.derivativ...
4f20588ae91891287f334243d1db4be5cc29bc9d
3,628,695
def get_defense_strategy(arg_dict, dataset_name, strategy_name, strategy_gpu_id, defense_desc, metric_bundle, field): """Take the strategy name and construct a strategy object.""" return built_in_defense_strategies[strategy_name]( arg_dict, dataset_name, strategy_gpu_id, defense...
1b0e4701ad1e85fd6fddf2ca174d30e2904b1c7b
3,628,696
def get_role_description(role: str) -> str: """Gets the description for a role. Args: role (str): The programmatic role name. Returns: str: The corresponding role description from the game-info json. """ return game_info_json['roles'][role.lower()]['description']
d6500f2b716938211aebbe11da10bcb6b93c6ce8
3,628,697
def pairwise_phase_pattern(module, window_type='voronoi', from_absolute=True, project_phases=False, full_window=False, sign='regular', length_unit='cm', palette=None): """ Convenience function to plot nice pairwise phase patterns ...
7262b594974214fb8b43be79ff837ae419591149
3,628,698
def centtoinch(cents): """Cents to inch.""" return .3937*cents
517142a29242246721abd05638c8ecbefcd888cb
3,628,699
def load_image(folder, test): """Load the data for a single letter label.""" image_files = glob.glob(folder + "*[0-9].tif") dataset = np.ndarray(shape=(len(image_files), FLAGS.image_size, FLAGS.image_size), dtype=np.float32) mask_train = [] print(folder) num_images = 0 for image_f...
83b824d7127cd2e0751578aadbde8ab4936ff909
3,628,700
def get_log_p_k_given_omega_int_analytic(k_train, k_bnn, interim_pdf_func): """Evaluate the log likelihood, log p(k|Omega_int), using kernel density estimation (KDE) on training kappa, on the BNN kappa samples of test sightlines Parameters ---------- k_train : np.array of shape `[n_train]` ...
83b4c43d86eddc6fd0a4f51deaec570889054d3f
3,628,701
import theano.tensor as T def LeakyReLU(a=0.33): """ Leaky rectified linear unit with different scale :param a: scale :return: max(x, a*x) """ def inner(x): return T.switch(x < a*x, a*x, x) return inner
5b9227f9e013fff14fbd49be77230dd1e9069525
3,628,702
def get_top_element_count(mol, top): """ Returns the element count for the molecule considering only the atom indices in ``top``. Args: mol (Molecule): The molecule to consider. top (list): The atom indices to consider. Returns: dict: The element count, keys are tuples of (elem...
f7293c1d154346c955052ceff0ee59483538bdc3
3,628,703
def load_data(filename, start=0.0, end=1.0, include_profiles=False): """ Wrapper function to load data from a file. Args: filename: The path of the file to load the data from. start: Fractional position from which to start reading the data. end: Fractional position up to which to re...
e234e037260ef31292f939cd39f20bc394197d31
3,628,704
def query_spf(domain: str) -> str: """ takes in a domain as a string and trys to find a spf with a query, if it finds one it returns the spf record if not returns an empty string. """ q = query(domain,'TXT') if not q: return "" for txtd in q.rrset: if txtd.strings[0].decode('utf-...
0c3bd664930445372cff2c9ffcd88ae1224ef6f8
3,628,705
def str_wire(obj): """Returns a string listing the edges of a wire.""" s = [] edges = obj.Edges() edge_count = len(edges) if edge_count == 1: s.append("Wire (1x Edge)\n") else: s.append("Wire (%dx Edges) " % (edge_count)) s.append("length:") s.append(_str_value(wi...
8434b804178e0e480b1804a2186f360c93c9fd4a
3,628,706
from typing import Tuple def calculate_approximate_ci( xs: np.ndarray, ratios: np.ndarray, confidence_ratio: float ) -> Tuple[float, float]: """ Calculate approximate confidence interval based on profile. Interval bounds are linerly interpolated. Parameters ---------- xs: The ...
d48133a5017e3e121c918ef1efc44d1bef2c21cd
3,628,708
import torch def transform_means(means, size, method='sigmoid'): """ Transforms raw parameters for the index tuples (with values in (-inf, inf)) into parameters within the bound of the dimensions of the tensor. In the case of a templated sparse layer, these parameters and the corresponding size tuple...
86bd46f2a10f01dc3a39e5b3e7c3003bb95641bb
3,628,710
def pull_if_not_exist(region: str=None, registry_prefix: str=None, repo: str=None, tag: str=None): """ Pull the image from the registry if it doesn't exist locally :param region: :param registry_prefix: :param repo: :param tag: :return: """ output = get_stdout('''{docker} images {re...
4826a31f41db9cac92b70f1b568dd5351ff2d0bd
3,628,711
import re def _remove_junk(plaintext, language): """ """ if language in {"zh", "ja", "fa", "iw", "ar"}: return plaintext lines = plaintext.splitlines() lines = [l for l in lines if re.findall(MEANINGFUL, l) or not l.strip() or l.startswith("<meta")] out = "\n".join(lines).strip() + "\n...
0d88d55021aa4b81eeb39f1ca21540b3112c6a08
3,628,712
def model_parallel_is_initialized(): """Check if model and data parallel groups are initialized.""" if _TENSOR_MODEL_PARALLEL_GROUP is None or _PIPELINE_MODEL_PARALLEL_GROUP is None or _DATA_PARALLEL_GROUP is None: return False return True
f60560130cbde971e340987064f58e66cd1b6855
3,628,713
def CV_IS_IMAGE(*args): """CV_IS_IMAGE(CvArr img) -> int""" return _cv.CV_IS_IMAGE(*args)
ca00c5f9614a59e037fbe1bd06d97f38f6c27b57
3,628,714
def fingerprint(samp): """A memory-efficient algorithm for computing fingerprint when wid is large, e.g., wid = 100 """ wid = samp.shape[1] d = np.r_[ np.full((1, wid), True, dtype=bool), np.diff(np.sort(samp, axis=0), 1, 0) != 0, np.full((1, wid), True, dtype=bool) ] ...
3b372b4480da2fc5fdfd89755b0dc7ec1408fbf3
3,628,715
def ldns_rr_list_compare(*args): """LDNS buffer.""" return _ldns.ldns_rr_list_compare(*args)
7a4414931578ec475bae6b1cf112e6eb8b8d564f
3,628,716
def at_least_one_shift_each(cur_individual): """ checks if there is at least one of each shift: 01, 10, 11 """ num_entrega = 0 num_recogida = 0 num_dual = 0 while cur_individual: shift = cur_individual[:2] cur_individual = cur_individual[2:] if shift == '01': num_...
070fe16e779ab30bcee7873ec01876962f30ec91
3,628,717
def generate_validate_yaml_for_python( artifact_name, top_level_imports, allowed=None, exclude_files=None, verbose=0, ): """Generate a validation YAML file from an artifact that is a python package. This function works in two stages. 1. It uses a default set of globs for python install...
074df24576fecabdd4d7d53faeacb09791556441
3,628,718