content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import functools def action_logging(f): """ Decorator to log user actions """ @functools.wraps(f) def wrapper(*args, **kwargs): with create_session() as session: if g.user.is_anonymous: user = 'anonymous' else: user = g.user.username...
60a54aae190b111bf522c873e34126bdf964f154
48,700
def ClassifyWspecifier(wspecifier): """Interprets type / filenames / options for the given wspecifier. Args: wspecifier: A string indicating the wspecifier. Returns: (WspecifierType, archive_filename, script_filename, WspecifierOptions) for the given filename. Examples: ...
446ca165d4e028ab3be4eed21ff7f0e601d6f0a1
48,701
def canonicalize_instance_info(node): """ Convert what is returned from GCE into the butter standard format. """ return Instance( instance_id=node.uuid, public_ip=node.public_ips[0], private_ip=node.private_ips[0], state=node.state)
6c5760fb231822f2b3edfc3f76937fb2e82ea464
48,702
def get_track( track_id ): """Returns data of a track having `track_id` No request params. """ try: track = g.user.get_track( track_id ) data = { 'title' : track.title, 'path' : track.path, 'artist' : track.artist, ...
1def539d9065c562b61cb520848ec36ae4b120c3
48,703
def _is_rule_exists(nat_rules, rule_type, original_ip, original_port, translated_ip, translated_port, protocol): """ check if we already have some rule with same properties """ # gatewayNatRule properties may be None or string # convert to str, bacause por...
c6ad5920b789e18d357941d71dd9e08922aa26a0
48,704
def lsgan_loss_generator(prob_fake_is_real): """Computes the LS-GAN loss as minimized by the generator. Rather than compute the negative loglikelihood, a least-squares loss is used to optimize the discriminators as per Equation 2 in: Least Squares Generative Adversarial Networks Xudong Mao,...
a524108b8486111e475ad56fa4e910bb9283592c
48,705
from collections import defaultdict def split_by_x(points): """Partitions an array of points into two by x-coordinate. All points with the same x-coordinate should remain on the same side of the partition. All points in the right partition should have strictly greater x-coordinates than all points in ...
ff41bec793544a59791912c1d97b09ccb175e77e
48,706
import json def dumps(*args, **kwargs): """ See :func:`json.dumps()`. """ kwargs["ensure_ascii"] = True kwargs["cls"] = _ExtendedJsonEncoder return json.dumps(*args, **kwargs)
c3e06e4f06bf39b01fcde74a4924d6edc97035f4
48,707
def remove_quoted_text(line): """get rid of content inside quotes and also removes the quotes from the input string""" while line.count("\"") % 2 == 0 and line.count("\"") > 0: first = line.find("\"") second = line.find("\"", first+1) line = line[0:first] + line[second+1:] while ...
ef0776ddfd9d60474077fd106474728de10b9e8f
48,708
def ryu_from_jsondict(jsondict): """ Load a ryu object from a json dictionary jsondict: A dictionary loaded by json.load """ assert len(jsondict) == 1 for oftype, value in jsondict.items(): cls = getattr(parser, oftype) if issubclass(cls, parser.OFPFlowMod): value["d...
c9db51a0b026749b118eeb09bccc237a874f70f3
48,709
def conv_block( inp, cweight, bweight, reuse, scope, use_stride=True, activation=tf.nn.leaky_relu, pn=False, bn=False, gn=False, ln=False, scale=None, bias=None, class_bias=None, use_bias=False, ...
3699166a4c626c7520b7fa372a27735f19672949
48,710
from typing import Tuple import numpy def qa_statistics(raster, mask, blocks, confidence=None) -> Tuple[float, float]: """Retrieve raster statistics efficacy and not clear ratio, based in Fmask values. Notes: Values 0 and 1 are considered `clear data`. Values 2 and 4 are considered as `not cl...
cc45c084a9860414d66de893cf27387b4c55c7b7
48,711
from varappx.main.view_tools import authenticate as auth def user_activation(email_to_file=None, rank_required=ADMIN_LEVEL): """Activate a user's account""" # logger.info("Activate/deactivate user") if auto_process_OPTIONS(request): return auto_process_OPTIONS(request) username = request.form[...
03e688c10a618096d2e13d217cc1674cd75489f1
48,712
import re def remove_emoji_and_non_alphanumeric(word_list): """ Remove both emojis and non-alphanumeric tokens in the given word list parameters ----------- :param word_list: list of str :return: list of str """ filtered_list = [word for word in word_list if word not in emoji.UNICODE_...
d187a7ac23fde91cdbb5ce931050c4a5562a8564
48,713
import os import logging import json def _GetJsonFileCreator(name, json_object): """Creates a creator function for an extended source context file. Args: name: (String) The name of the file to generate. json_object: Any object compatible with json.dump. Returns: (callable()) A creator function that...
db74748d51303087fae6aec5b6b6f6deb7d665c0
48,714
def active_matrix_from_extrinsic_euler_zyx(e): """Compute active rotation matrix from extrinsic zyx Cardan angles. Parameters ---------- e : array-like, shape (3,) Angles for rotation around z-, y-, and x-axes (extrinsic rotations) Returns ------- R : array-like, shape (3, 3) ...
e4660706b7e2b651a2f3c02d6f9620ea4095becb
48,715
def get_index_of_feature(feature_list, item): """ Gets the index of the feature in the provided feature list :rtype : int :param feature_list: List of features to search from :param item: The feature to search :return: The index where the feature was founded, -1 otherwise """ # getting...
2f2d79d4caf953b60ecf841a23d86e8b4a00b937
48,716
import logging import pytz def get_timezone(WindowsZoneName=True): """ Get the TimeZone Name if WindowsZoneName is True, then it returns the name used by the Microsoft Windows Platform otherwise it returns the Olsen name (used by all other platforms) Note: this needs to get tested on Windows ...
e175aae37bc544d8ecd51ad7cafafbc88b5862f7
48,717
def fix_ghdx_birth_weights(df): """Ensure the child birth weight is in grams and is a legal value. The original survey allowed answers to weights to be coded in grams or kilograms. The GHDx data has recoded the values into grams. However, a few cases are clearly still coded in kilograms. The survey als...
a11e50a1a1db780389ad99051e7cf93a025155ae
48,718
def __virtual__(): """ Only load if boto is available. """ if "boto3_elasticache.cache_cluster_exists" in __salt__: return "boto3_elasticache" return (False, "boto3_elasticcache module could not be loaded")
d844dc256eaf81e5a368afd14ac7169969a4bab6
48,719
def parse_adjlist(lines, comments='#', delimiter=None, create_using=None, nodetype=None): """Parse lines of a graph adjacency list representation. Parameters ---------- lines : list or iterator of strings Input data in adjlist format create_using: NetworkX graph container...
b395366c1f5ae8a048b80f8d78de33e1dc234966
48,720
def get_slovakia(): """ gets all the data for Slovakia :return: object """ slovakia = Country('Slovak Republic') slovakia.get_gdp('https://www.quandl.com/api/v3/datasets/WWDI/SVK_' 'NY_GDP_PCAP_CD.json?api_key=2jhCWecEKmuxzVY9ifwp') slovakia.get_investment_inflows('https...
98c6febb03c088e0f614e60573898aa680169297
48,721
from scipy.optimize import linear_sum_assignment as linear_assignment def cluster_acc(y_true, y_pred): """ Calculate clustering accuracy. Require scikit-learn installed # Arguments y: true labels, numpy.array with shape `(n_samples,)` y_pred: predicted labels, numpy.array with shape `(n_sa...
de82c781709b6c147177f54ab7363edf7365ad85
48,722
def calc_rms_df(df, measured_tox_col, modeled_tox_col): """ Calculate the root mean square deviation for two columns of a DataFrame returns √[ ∑(x-y)² / n ] """ df_rms = df[[measured_tox_col, modeled_tox_col]].dropna() toxobs = df_rms[measured_tox_col].tolist() toxmod = df_rms[modeled_tox_co...
9160881aa3ce08164aae1613eddf282ba1b43375
48,723
def dist(p1, p2): """ Distance between two points represented by arrays. """ return distance(p1[0], p1[1], p2[0], p2[1])
52f1a59c6aa125adcde80398712c30d7d61f2164
48,724
def trim_motif(pfm, motif, min_ic=0.2, pad=0): """ Given the PFM and motif (both L x 4 arrays) (the motif could be the PFM itself), trims `motif` by cutting off flanks of low information content in `pfm`. `min_ic` is the minimum required information content. If specified this trimmed motif will be e...
ee8207336ff01c32f3e22bb6ea2bc1a2e53b4c1c
48,725
def org_search(): """ Organisation REST controller - limited to just search.json for use in Autocompletes - allows differential access permissions """ s3.prep = lambda r: r.representation == "json" and \ r.method == "search" return s3_rest_controller(modu...
6e74da5fbcaf8d48c4d39105a7d73d65e51b1419
48,726
def in_quiet_hours() -> bool: """Check whether the current time is within quiet hours. Returns: bool: True if within quiet hours Raises: AttributeError: if quiet hours weren't defined in config """ now = pendulum.now() hour = now.hour if config.QUIET_START > config.QUIET_E...
782ccf47b045f8ff23a63dd81f81f89b0a11a5cf
48,727
def int_to_smile(list_of_int): """ Convert the list of int to list of token according to the vocabulary :param list_of_int: list of int representing the SMILES :type list_of_int: list of int :return: list of token """ return [p.tokens[s] for s in list_of_int]
28475b1357e0de3304823840cc81482bf789b2f4
48,728
def searchLibary(keyword): """ Keyword based search for books, case insensitive in author and title Args: keyword (string): Keyword to search for Return: List of search results """ results = [] lk = keyword.lower() for bookid, book in library.LIBRARY.items(): ...
1bef76e977983ed13898a6f0ab4ffb80729e36a7
48,729
def emprestarLivro(livro): """ Emprestimo do livro """ return biblioteca_temp.emprestarLivro(livro)
835a6621e0fd1ccd52e03cd21a228d7a6c2068fb
48,730
from typing import Any from operator import lt def _heapify(items: list[Any], d: int, comp=lt) -> list[Any]: """Создать на месте кучу из списка за время O(log(len(items))). :param items: список элементов :param d: коэффициент ветвления (максимальное число потомков у одного элемента) :param comp: функ...
5c32093dc3beddaceea76e4e9c36839f31610f95
48,731
def build_generator_growth_layer_block(conv_layers, params, block_idx): """Builds generator growth block internals through call. Args: conv_layers: list, the current growth block's conv layers. params: dict, user passed parameters. block_idx: int, the current growth block's index. ...
192701b6282ac8bd53b40b71b54e647e8aa9ec81
48,732
def isfloat(s): """**Returns**: True if s is the string representation of a number :param s: the candidate string to test **Precondition**: s is a string """ try: x = float(s) return True except: return False
6967444007388793a70b9bd74d3153d6f88b6a4d
48,733
import random import string def generate_password(length=10): """Generate rnadom password of the given length. """ return ''.join( random.SystemRandom().choice( string.ascii_lowercase + string.ascii_uppercase + string.digits ) for _ in range(length) )
e4d65ea76bee72c68afbfbcc011676e9ae35c588
48,734
import numpy def reference_transit(samples, per, rp, a, inc, ecc, w, u, limb_dark): """Returns an Earth-like transit of width 1 and depth 1""" f = numpy.ones(tls_constants.SUPERSAMPLE_SIZE) duration = 1 # transit duration in days. Increase for exotic cases t = numpy.linspace(-duration * 0.5, duratio...
716ac7ecda59a608389d03c2a091434ebdef2bcf
48,735
import math def sol_rad_from_t(et_radiation, cs_radiation, temperature_min, temperature_max, coastal): """ Estimate incoming solar (or shortwave) radiation, *Rs*, (radiation hitting a horizontal plane after scattering by the atmosphere) from min and max temperature together with an empirical adjustmen...
6952aa6509897494551839e412d5a15e51b5e30c
48,736
def moving_avg(v, N): """ simple moving average. Parameters ---------- v : list data ta to average N : integer number of samples per average. Returns ------- m_avg : list averaged data. """ s, m_avg = [0], [] for i, x in enumerate(v, 1): ...
2e71eefb91ac694eaf06c2167e38ef497671145e
48,737
def solve(): """This method will compute and return the solution if it exists, as a list of (row, column) tuples, zero-based. Else, an exception will be raised stating a loop was detected and that no solution exists.""" robot = Robot(number_of_rows, number_of_columns, ball_location, goal_location, block...
c24be000f6004ba6d3295b56f85b0a5921eb83c0
48,738
def hashed_password(username: str, password: str) -> str: """ ハッシュ化したパスワードを返す。 """ tmp = adcconfig.SALT + username + password return sha256(tmp.encode('utf-8')).hexdigest()
c91fff9edaf1a6dd487a4d912b77aaa27c5f197f
48,739
def linierRegression(features, weights): """ Performs simple linier regression """ return np.dot(features, weights)
24791550134b5f1efa102b956fa44be81053b001
48,740
from typing import List def get_students(tas: List[str], gr:str)->List[str]: """ From the list of all TAs, find TAs matching the constraint string For example, gr could be "cs17|es18" this represents all the students whole roll numbers start from cs17 or es18 This function returns the list of TAs fr...
b952fa3688b3ff107a5a1289fc3216244f4f0554
48,741
def calculate_prototypes_from_labels(embedding, labels, max_label=None): """Calculates prototypes from labels. This function calculates prototypes (mean direction) from embedding features for each label. This function is also used as the m...
d085117b45ec236d36528cafeb352030d5fce858
48,742
def get_mask(pos, shape, radius, include_edge=True, return_masks=False): """ Create a binary mask that masks pixels farther than radius to all given feature positions. Optionally returns the masks that recover the individual feature pixels from a masked image, as follows: ``image[mask][masks_single[i]]...
2e46235cbd32ae5f4ae48fb1c7990d189c0464a9
48,743
def Volume(v,u,w): """Calculate volume of solid created by three vectors. Returns int Attributes ---------- v: Vector First Vector u: Vector Second Vector w: Vector Third Vector """ return abs(DotProduct(CrossProduct(v,u), w))
be1fc8285fa339820cc71e59390a2a5a92bc9ace
48,744
def is_admin(user_id): """ Retrieves a user's admin status from the permissions directory. """ perms = get_current_permissions() return user_id in perms["admins"]
610528eb3ea18370261aa34aabf9ff05811bc9c0
48,745
def _get_commits(output): """Returns the commits message in the output. All commits must have been made by `Alice Author` or `PY C` to be found. """ commits = [] save = False cnt = 0 for row in output.split("\n"): if row.strip() in ["Alice Author", "Alice Äuthòr", "PY C"]: ...
0514d0c3279c7e14810403412284e6d07eb03d16
48,746
import platform import glob def scan(): """scan for available ports. return a list of names""" system_name = platform.system() if system_name == 'Windows': available = [] for i in range(200): try: s = serial.Serial(i) available.append(s.portstr) ...
2737052aa0f69454354d0ecc72e634940799285e
48,747
def valid_value(value, quote=default_cookie_quote, unquote=default_unquote): """Validate a cookie value string. This is generic across quote/unquote functions because it directly verifies the encoding round-trip using the specified quote/unquote functions. So if you use different quote/unquote function...
19d5e46187701d187a81e9f38f35725052fad83d
48,748
import os def cmdLists(cmd): """ creates docker or singularity command(s) from either a single command or a list of commands. """ if os.environ.get('CAT_BINARY_MODE') == 'docker': if isinstance(cmd[0],list): docList = [] for e in cmd: docList.append(...
46fbe3e9e3cd94efd617651125523411150281b6
48,749
import struct def steg(in_path, out_path=None, data=None): """ The steg function (use the LSB of the color table entries to hide the data) """ # Must encode the length of the data so we know how much to read when extracting if data is not None: data_array = bytearray(data) data_ar...
1464dadec850816d20de9c13b5297b4c49fda59a
48,750
def _make_specific_identifier(param_name, identifier): # type: (str, str) -> str """ Only adds an underscore between the parameters. """ return "{}_{}".format(param_name, identifier)
5268d366f04c616d8180e7cc4167030efdec9070
48,751
import torch def resnet50(pretrained=False, pretrained_model_path=None, num_classes=None, expose_stages=None, dilations=None, stride_in_1x1=False): """Constructs a ResNet-50 model Args: pretrained (bool): if True, load pretrained model. Default: False pretrained_model_path (str, optional): onl...
634c3e0a2446fe1b470e0eba311d71cda6bb7cae
48,752
def ReadTag(buffer, pos): """Read a tag from the buffer, and return a (tag_bytes, new_pos) tuple. We return the raw bytes of the tag rather than decoding them. The raw bytes can then be used to look up the proper decoder. This effectively allows us to trade some work that would be done in pure-python (decodi...
91c0a1e86816066768b15a3a2e7b8a8468900661
48,753
def emptyStack(): """ Empties the stack while collecting each element as it is removed. Returns the collected elements. """ elements = "" while not stack.isEmpty(): if isOperator(stack.peek()): elements += stack.pop() elif stack.peek() == '(': raise ParensMism...
72be5b7c6752093c8a30063d36f0bfa70bc5fb8d
48,754
from typing import Union import re def get_brackets(title: str) -> Union[str, None]: """ Return the substring of the first instance of bracketed text. """ regex_brackets = re.search(r"\[(.*?)\]", title) if regex_brackets is None: return None else: return regex_brackets.group()
f1d985cf79ae881e8aca168c065d40e640a9c1ff
48,755
def stack_3rd_dimension_along_axis(u_jkir, axis): """ Take the 3D input matrix, slice it along the 3rd axis and stack the resulting 2D matrices along the selected matrix while maintaining the correct order. :param u_jkir: 3D array of the shape [JK, I, R] :param axis: 0 or 1 :...
db9e126503beb99b43032bea7df7ffb9cc432a07
48,756
from typing import Union from typing import List def _op_nodes( graph: Union[tf.Graph, testutils.GraphDef]) -> List[testutils.NodeDef]: """Return arithmetic/nn operation nodes from a graph""" graph_def = graph.as_graph_def() if isinstance(graph, tf.Graph) else graph def _op(node): return node.op n...
7e2d854a5bbdb3e2401d3df8ed8fbaa9f564acac
48,757
def _compositeImageToVideoSegment(compositeImage): """ :param compositeImage: :return: @type compositeImage: CompositeImage """ if compositeImage is None or compositeImage.videomasks is None: return [] return [segmentToVideoSegment(item) for item in compositeImage.videomasks]
b730e0f3152a512cb200436c4732abaed3c147e3
48,758
from bids import BIDSLayout import warnings def collect_sessions(bids_dir, session=None, strict=False, bids_validate=True): """ List the sessions under the BIDS root and checks that sessions designated with the participant_label argument exist in that folder. Returns the list of sessions to be finally...
6c905038d5eca24c57197d574d1efb8c4ccf0a66
48,759
def _dof(mean_tau, sd_tau2): """ Returns the degrees of freedom for the chi-2 distribution from the mean and variance of the uncertainty model, as reported in equation 5.5 of Al Atik (2015) """ return (2.0 * mean_tau ** 4.) / (sd_tau2 ** 2.)
9a4a395c9aea7b965a477550c7f254bf744cadc5
48,760
def stations(): """Return a list of stations.""" print("Received Station API Request.") # Query the station list station_data = session.query(Station).all() # Create a list of dictionaries station_list = [] for station in station_data: station_dict = {} station_dict["id"] ...
67ffb7a8691ea4f44420b0f0f0b4d4c4a2ecd3ba
48,761
from typing import Iterable import yaml def yaml_load(string): """Parse multiple strings as yaml data. Multiple dictionaries are combined togather.""" if isinstance(string, str): return ordered_load(string) if not isinstance(string, Iterable): raise TypeError('Invalid yaml_load argument t...
3310aa780d774d325cabbbf353d45062a1c243a5
48,762
import requests def get_checklist(identifier): """ Get the data for a checklist from its eBird web page. Args: identifier (str): the unique identifier for the checklist, e.g. S62633426 Returns: (dict): all the fields extracted from the web page. ToDo: * scrape entry comm...
87599c88523c303b29f34b3495576ef1e2523f3e
48,763
def check_tensors_dtype_same(data_dtype, value_dtype, op_name): """Check tensors data type same.""" if data_dtype in value_dtype: return True raise TypeError(f"For '{op_name}', the value data type '{value_dtype}' " f"is not consistent with assigned tensor data type {data_dtype}."...
f31e34dea4ccb83938319db82a7a679876505a75
48,764
import tqdm def generate_data(data_dirs, save_dir): """ Routine for generating train data in tfrecords Args: data_dirs: where simulation data is. save_dir: where tfrecords will go. Returns: list of tfrecords. """ def data_generator(): def _get_data(dir): ...
9a67f3219e32787016e726e4da6d1025b80fac3b
48,765
def to_categories(df, cat_map): """ Convert a dataframe to use categories, based on the category map created by table_category_map. :param df: CHIS Dataframe to convert, loaded from Metatab :param cat_map: category map, from table_category_map :return: """ df = df.copy() for col in df.c...
66fb82fdc9d0d91e063e08a912673ab6acf0ef17
48,766
import sys def hastty(): """ Whether (it looks like) a tty is available. """ try: return sys.stdin and sys.stdin.isatty() except Exception: # pragma: no cover return False
2baebe972f0c58f58d90cab133e4e5d774b2cb25
48,767
def xgcd(vals): """Calculate extended greatest commond divisor.""" _xgcd = Xgcd(vals) return _xgcd.run()
cf4956bec4141780b1a6c3eedd311a4e727df4ae
48,768
import os def _get_i18n_locale(locale_name, react=False): """Retrieve a locale in a Jed-compatible format.""" # Ensure we have a valid locale. en_GB is our source locale and thus always considered # valid, even if it doesn't exist (dev setup where the user did not compile any locales) # since otherwi...
1b8f496a39df735821b771f1f060ed7324414dbe
48,769
def find_bad_frames(ds, reindex=True): """ Find the frames that have fewer cells than the previous frame. Parameters ---------- ds : (S, T, ..., Y, X) DataSet reindex : bool, default: True Whether to reindex each frame as well. Returns ------- bad : list With entrie...
78ae0ff38834bf0bc29571e68b7cd1497e652fe9
48,770
import aiohttp import os async def get_steam_game_search(keyword: str) -> list: """ Return search result Args: keyword: Keyword to search(game name) Examples: get_steam_game_search("Monster Hunter") Return: [ str, MessageChain ] """ ...
3bc2ecb8d9ee121eb4006a8be615061d4417c4fa
48,771
def get_most_energetic_neutrino(particles): """Get most energetic neutrino. Parameters ---------- particles : ndarray of dtype I3PARTICLE_T Returns ------- most_energetic_neutrino : shape () ndarray of dtype I3PARTICLE_T """ return get_best_filter( particles=particles, fil...
54add5340ba911a2e836b1386fd4ca6b5f72e9c8
48,772
def cria_coordenada(linha,coluna): """int x int -> tuple Esta funcao recebe duas coordenadas do tipo inteiro, a primeira correspondente a linha e a segunda a coluna e devolve um elemento do tipo coordenada, ou seja, o tuplo (linha,coluna)""" if 1<=linha<=4 and 1<=coluna<=4 and isinstance(linha,int) and isin...
b2d216a11706e4234cf9943525cfca72118a98f8
48,773
def identify_groups(ref_labels, pred_labels, return_overlaps=False): """Which predicted label explains which reference label? A predicted label explains the reference label which maximizes the minimum of ``relative_overlaps_pred`` and ``relative_overlaps_ref``. Compare this with ``compute_association_...
b7c6588946c005c6507b5f486930514dd6b91864
48,774
def commit_config(node, raid_controller, reboot=False, realtime=False): """Apply all pending changes on a RAID controller. :param node: an ironic node object. :param raid_controller: id of the RAID controller. :param reboot: indicates whether a reboot job should be automatically crea...
eead48d5a8eeb6591343d598e6c232ad7bb437f5
48,775
from typing import Tuple from typing import Optional def link(g: Graph, subject: Node, predicate: URIRef) -> Tuple[Optional[URIRef], Optional[URIRef]]: """ Return the link URI and link type for subject and predicate :param g: graph context :param subject: subject of linke :param predicate: link pr...
3a329697413ebe0d6218d388d74306643590f3e3
48,776
def list_pages(page_obj: Page) -> Page: """ Gets a paginator page item and returns it with a list of pages to display like: [1, 2, "…", 17, 18, 19, "…" 41, 42] Currently not in use, simpler pages lists are implemented. """ last_page_number = page_obj.paginator.num_pages pages_list = [1, 2] ...
40b225f45fe4868c7b3ef361a7cc9df432efaf78
48,777
from typing import List import json def compare_apache_profiles(baseline_file, test_file, threshold=0.5) -> List: """ Compare baseline Apache access log profile against test profile. :param baseline_file: file containing baseline profile :param test_file: file containing test profile :param thresh...
0b94ad318fcb61be559767cbdba51def1b6db61f
48,778
import os import math import subprocess import re async def ping(target: str, count: int = 3, timeout: int = 1000, interval: float = 1.0): """ PING 目标网络, 获取延迟丢包 (备用) 调用 Windows/Linux 系统 PING 命令, 支持 IPv6 :param target: 目标地址 :param count: 发送的回显请求数 :param timeout: 超时时间, Windows 有效 :param int...
f1c3d8e136613972efc94e365c1503dad76fa0b5
48,779
def cyclic_sort(nums): """ 0 1 2 3 4 5 [1, 2, 3, 4, 5] ^ [1, 2, 3, 4, 5, 6] ^ """ for i in range(0, len(nums)): while nums[i] != i + 1: j = nums[i] - 1 nums[i], nums[j] = nums[j], nums[i] return nums
fc9f7061121d4509b260e03df4edeee63c0eb6b9
48,780
def _build_section_path_map(): """ Simple wrapper around Django's low level cache; stores and populates a list of all section urls using the low-level caching framework. """ paths = {} Section = app_settings.get_extending_model() for section in Section.objects.all(): paths[section.f...
e89657ec68e4c1dab31f172e4d5aa8f98681aa5e
48,781
def unfold_arrow(arrow): """Extract a list of types from an arrow type :param arrow: A type, preferably an arrow type :type arrow: :class:`discopy.closed.Ty` :return: A list of the arrow's components, or of the original type :rtype: list """ if isinstance(arrow, Under): return [arr...
365a35e87bdb0edcd81cba8e44c4151cf5cb701c
48,782
def test_step(X, m_pre, m_fp): """ Test step used for mini-search-validation """ X = tf.concat(X, axis=0) feat = m_pre(X) # (nA+nP, F, T, 1) m_fp.trainable = False emb_f = m_fp.front_conv(feat) # (BSZ, Dim) emb_f_postL2 = tf.math.l2_normalize(emb_f, axis=1) emb_gf = m_fp.div_enc(emb_f) ...
c444a0935640f09122999efa3c382be15daab833
48,783
import json def calc_sett_rewards(badger, periodStartBlock, endBlock, cycle, unclaimedRewards): """ Calculate rewards for each sett, and sum them """ # ratio = digg_btc_twap(periodStartBlock,endBlock) # diggAllocation = calculate_digg_allocation(ratio) rewardsBySett = {} noRewards = ["nati...
7fa93585fbe5b1f461b24dc6a9a7d655aca4f7a7
48,784
def get_detector_module_slices(detector): """ Helper function to read data_origin and data_size from the NXdetector_modules in a NXdetector. Returns a list of lists, where each sublist is a list of slices in slow to fast order. Assumes slices are stored in NeXus in slow to fast order. """ #...
a23e797579c0925b48b802e0189ce17d3f5bf12c
48,785
def main(**prepared_args): """ main conversion runner :param prepared_args kwargs: :return: """ conversion_result = None if prepared_args['conversion_type'] == 'csv_to_parquet': conversion_result = converter_csv_to_parquet(prepared_args['source_file_path'], ...
6c79bbd453e1b229329b0bb91e8b0b81e0b7d4a2
48,786
import json import sys def _format_json(data, theme): """Pretty print a dict as a JSON, with colors if pygments is present.""" output = json.dumps(data, indent=2, sort_keys=True) if pygments and sys.stdout.isatty(): style = get_style_by_name(theme) formatter = Terminal256Formatter(style=s...
e062338e4843cad1281b61ab92e36fe55328ab09
48,787
def get_tm_session(session_factory: sessionmaker, transaction_manager: TransactionManager) -> Session: """ Get a ``sqlalchemy.orm.Session`` instance backed by a transaction. This function will hook the session to the transaction manager which will take care of committing any changes. - When using ...
80ae17addd6f519d55234c11707b3e0311329e22
48,788
import tarfile import logging def get_test_from_anaconda(url): """ Given the URL of an anaconda tarball, return tests """ try: tarball = get_file_from_recipe_url(url) except tarfile.ReadError: return None try: metafile = tarball.extractfile('info/recipe/meta.yaml') ...
f9ad72251a450d7c24e7eedd84cd89bf670a6b6b
48,789
import numpy def calculate_reservoir_rate(var, surf_mask, surf_type=None): """Inputs are two maps (var and surf_mask). Whereas there may be scripts that calculate the masked means, this calculates the volume flow rate (ie, not the flux density, but the total flux. This is currently written to only ...
41c89b6fbdfd7a3234ec7f555e3c7c48d8181641
48,790
def get_schedules(filter_params, dbinfo=None, fields=None): """ Helper function to get schedule data for a request. :param filter_params: dict mapping constraint keys with values. Valid constraints are defined in the global ``constraints`` dict. :param dbinfo: optional. If provided, defines (connec...
4043cfd9d05321af043ed32ec99524ca92318430
48,791
async def get_forge_godly_description(message_content: str, message: discord.Message) -> str: """Returns the embed description for the forge_godly event""" user_name_string = 'exhausted' user_name_start = message_content.find(user_name_string) + len(user_name_string) + 1 user_name_end = message_content....
2b12ff6c5b9ecbcce83b19cf3bde017cde0b9fee
48,792
from userbot.modules.sql_helper.spam_mute_sql import unmute async def unmoot(unmot): """ For .unmute command, unmute the replied/tagged person """ # Admin or creator check chat = await unmot.get_chat() admin = chat.admin_rights creator = chat.creator # If not admin and not creator, return ...
523b60270ccb26ed1c148e068c2ec8f84968addd
48,793
def objective_value(x, w): """Compute the value of a cut. Args: x (numpy.ndarray): binary string as numpy array. w (numpy.ndarray): adjacency matrix. Returns: float: value of the cut """ X = np.outer(x, (1-x)) w_01 = np.where(w != 0, 1, 0) return np.sum(w_01 * X)
ed6963759cd8f9a77bc5fdfd42018fc32b8c0994
48,794
def setEncoding(encoding = None): """ 라이브러리용 엔코딩 설정 함수 기본 엔코딩 정보를 설정한다 인자값 목록 (모든 변수가 반드시 필요): encoding : 문자열 엔코딩 정보 결과값 : 현재 설정된 기본 엔코딩 정보 """ global _default_encoding try: str("dummy", encoding) except: return _default_encoding _default_encoding = encoding or _default_encoding return _defau...
a1b0cbe83d5d08ad16274dafa4f0c4965aa938a1
48,795
def _create_v2_request_with_keyranges( sql, new_binds, keyspace_name, tablet_type, keyranges, not_in_transaction): """Make a request dict from arguments. Args: sql: Str sql with format tokens. new_binds: Dict of bind variables. keyspace_name: Str keyspace name. tablet_type: Str tablet_type. ...
af3f539fee6646a3d97bd531f57f9203eb6dee91
48,796
def generate_meme(image_path, meme_text): """ Generate meme with image and text """ pic = Image.open(image_path).convert("RGBA") pic = pic.resize((600, 300), Image.LANCZOS) background = Image.new("RGBA", (900, 700), "white") Image.Image.paste(background, pic, (150, 200)) draw = ImageDr...
873468f16813a9e35af87523cf6f9578dd57c434
48,797
def shuffle(images, labels): """ Return shuffled data. """ permutation = np.random.permutation(images.shape[0]) return images[permutation], labels[permutation]
56b5fabd93b21f875976b236843e40a4a3136577
48,798
import math def Linear(input_size, hidden_size, with_bias=True): """tbd""" fan_in = input_size bias_bound = 1.0 / math.sqrt(fan_in) fc_bias_attr = paddle.ParamAttr(initializer=nn.initializer.Uniform( low=-bias_bound, high=bias_bound)) negative_slope = math.sqrt(5) gain = math.sqrt(2.0 / (1 +...
e5f387dcdabc174717f6e431ce7d4afb4a7e305d
48,799