content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_curve_points( road: Road, center: np.ndarray, road_end: np.ndarray, placement_offset: float, is_end: bool, ) -> list[np.ndarray]: """ :param road: road segment :param center: road intersection point :param road_end: end point of the road segment :param placement_offset: o...
9bc22c1894332a70e904d4c543606c3f38606064
10,600
def default_inputs_folder_at_judge(receiver): """ When a receiver is added to a task and `receiver.send_to_judge` is checked, this function will be used to automatically set the name of the folder with inputs at judge server. When this function is called SubmitReceiver object is created but is not saved...
0f45a374a32feb19ffe17d394831123ca8af68c8
10,601
def remove_extension(string): """ Removes the extention from a string, as well as the directories. This function may fail if more than one . is in the file, such as ".tar.gz" Args: string: (string): either a path or a filename that for a specific file, with extension. (e.g. /usr/di...
8bdd3818696745c5955dfb5bd7725d87e1284103
10,602
def _theme_static(path): """ Serve arbitrary files. """ return static_app.static(path, 'theme')
c93815b041632c313961afbe7ef254117c4259de
10,603
def create_link(link: schemas.Link, db: Session = Depends(get_db)): """Create link """ # Check if the target already exists db_link = crud.get_link_by_target(db=db, target=link.target) if db_link: raise HTTPException(status_code=400, detail="link already registered") response = crud.cre...
b220403b6d054df0f0e6f0538573038b0f7895b3
10,604
def encode_rsa_public_key(key): """ Encode an RSA public key into PKCS#1 DER-encoded format. :param PublicKey key: RSA public key :rtype: bytes """ return RSAPublicKey({ 'modulus': int.from_bytes(key[Attribute.MODULUS], byteorder='big'), 'public_exponent': int.from_bytes(key[Att...
38b1c3b4ee361415fa8587df7dbfdd94d00fdbe1
10,605
def is_block_valid(new_block, old_block): """ simple verify if the block is valid. """ if old_block["Index"] + 1 != new_block["Index"]: return False if old_block["Hash"] != new_block["PrevHash"]: return False if caculate_hash(new_block) != new_block["Hash"]: ret...
8447ca7b7bbb75748601d4a79d97047ad7ef07ab
10,606
import urllib def add_get_parameter(url, key, value): """ Utility method to add an HTTP request parameter to a GET request """ if '?' in url: return url + "&%s" % urllib.urlencode([(key, value)]) else: return url + "?%s" % urllib.urlencode([(key, value)])
640de1f111ff9080386f855e220e8eaaad113a0a
10,607
def get_simple_match(text): """Returns a word instance in the dictionary, selected by a simplified String match""" # Try to find a matching word try: result = word.get(word.normalized_text == text) return result except peewee.DoesNotExist: return None
e8365b6129e452eb17696daf8638a573e8d0cb4b
10,608
def ipv_plot_df(points_df, sample_frac=1, marker='circle_2d', size=0.2, **kwargs): """Plot vertices in a dataframe using ipyvolume.""" if sample_frac < 1: xyz = random_sample(points_df, len(points_df), sample_frac) else: xyz = dict(x=points_df['x'].values, y=points_df['y'].values, z=points_d...
a957629bcf7b9acbff314f243a3cae9803bda69d
10,609
import subprocess def exec_command_stdout(*command_args, **kwargs): """ Capture and return the standard output of the command specified by the passed positional arguments, optionally configured by the passed keyword arguments. Unlike the legacy `exec_command()` and `exec_command_all()` functions,...
32552fed9fd250548c0826a8b2679fa46bd8bf14
10,610
def admin_login(): """ This function is used to show the admin login page :return: admin_login.html """ return render_template("admin_login.html")
495841f7cb352a07d8214f99b99ca8be7179839f
10,611
from sys import path def input_file_location(message): """ This function performs basic quality control of user input. It calls for a filepath with a pre-specified message. The function then checks if the given filepath leads to an actual existing file. If no file exists at the given location, the...
e0fd6c728c900c1eade36d9b03075ec3d79d22d4
10,612
def create_contact(): """ Get a contact form submission """ data = request.get_json(force=True) contact = ContactDAO.create(**data) return jsonify(contact.to_dict())
af2c5efbd06d3220faf3b16059ea9d612cece19e
10,613
import os import ntpath def make_my_tuple_video(LOGGER, image, width, height, frames, codec, metric, target, subsampling, param, uuid=None): """ make unique tuple for unique directory, primary key in DB, etc. """ (filepath, tempfilename) = os.path.split(image) filename, extension = os.path.splitext(te...
b37a38d6f76361fa85974d5ad56303d4f6ae308d
10,614
from typing import DefaultDict from typing import Tuple from typing import List import copy def separate_sets( hand: DefaultDict[int, int], huro_count: int, koutsu_first: bool = True ) -> Tuple[List[Tile], List[List[Tile]], Tile]: """Helper function for seperating player's remaining hands into sets. It sh...
894a712a739e16a98e2150c4461a3d66c759bace
10,615
def units(legal_codes): """ Return sorted list of the unique units for the given dictionaries representing legal_codes """ return sorted(set(lc["unit"] for lc in legal_codes))
85803ecb3d1f51c058c959b7e060c3cb5263f6a3
10,616
def resize_terms(terms1, terms2, patterns_to_pgS, use_inv): """ Resize the terms to ensure that the probabilities are the same on both sides. This is necessary to maintain the null hypothesis that D = 0 under no introgression. Inputs: terms1 --- a set of patterns to count and add to each other to de...
d422e3d5b32df55036afa3788cdb0bdd4aa95001
10,617
def get_network_list(): """Get a list of networks. --- tags: - network """ return jsonify([ network.to_json(include_id=True) for network in manager.cu_list_networks() ])
6a54b76091160fc28cd45502aea4c54d2862a588
10,618
def bfixpix(data, badmask, n=4, retdat=False): """Replace pixels flagged as nonzero in a bad-pixel mask with the average of their nearest four good neighboring pixels. :INPUTS: data : numpy array (two-dimensional) badmask : numpy array (same shape as data) :OPTIONAL_INPUTS: n : int ...
ae6b6c44e82dc70f998b31d9645cf74fef92c9fd
10,619
import re def parse_discount(element): """Given an HTML element, parse and return the discount.""" try: # Remove any non integer characters from the HTML element discount = re.sub("\D", "", element) except AttributeError: discount = "0" return discount
658f8a6bef8ba4bf82646a10c495904c03a717c7
10,620
import bisect def read_files(allVCFs): """ Load all vcfs and count their number of entries """ # call exists in which files call_lookup = defaultdict(list) # total number of calls in a file file_abscnt = defaultdict(float) for vcfn in allVCFs: v = parse_vcf(vcfn) # disa...
8518eac3c43772016fd5cbe0fd6c423a1e463ebc
10,621
def parse_dat_file(dat_file): """ Parse a complete dat file. dat files are transposed wrt the rest of the data formats here. In addition, they only contain integer fields, so we can use np.loadtxt. First 6 columns are ignored. Note: must have a bims and info file to process completely. Para...
3b84730a347075c5be1e0ebe5a195338a86ed0c6
10,622
import argparse import warnings def parse_cmd_arguments(mode='split_audioset', default=False, argv=None): """Parse command-line arguments. Args: mode (str): The mode of the experiment. default (optional): If True, command-line arguments will be ignored and only the default values...
e518cc9d9e643db349b9c3b7c34e6cfbd8ddc039
10,623
from hypothesis.provisional import domains import string def emails(): """A strategy for generating email addresses as unicode strings. The address format is specific in :rfc:`5322#section-3.4.1`. Values shrink towards shorter local-parts and host domains. This strategy is useful for generating "user...
b6a07ee114827e48873ab4ea3dc6679c88ae1c00
10,624
from typing import List def next_whole_token( wordpiece_subtokens, initial_tokenizer, subword_tokenizer): """Greedily reconstitutes a whole token from a WordPiece list. This function assumes that the wordpiece subtokens were constructed correctly from a correctly subtokenized CuBERT tokenizer, but ...
d26f4da0932030242c2209bc998bc32b6ce98cdf
10,625
import os def parse_tracks(filename="tracks.csv"): """ Builds the tracks matrix #tracks x #attributes (20635 x 4) where attributes are track_id,album_id,artist_id,duration_sec """ with open(os.path.join(data_path, filename), "r") as f: # Discard first line lines = f.readlines()[1:]...
2734e7f509e208394049b149f88ec90cb35e1e57
10,626
def match_seq_len(*arrays: np.ndarray): """ Args: *arrays: Returns: """ max_len = np.stack([x.shape[-1] for x in arrays]).max() return [np.pad(x, pad_width=((0, 0), (0, 0), (max_len - x.shape[-1], 0)), mode='constant', constant_values=0) for x in arrays]
2cd8715eb634e0b3604e1d5c305a5209bb0ae03d
10,627
import torch import math def get_cmws_5_loss( generative_model, guide, memory, obs, obs_id, num_particles, num_proposals, insomnia=1.0 ): """Normalize over particles-and-memory for generative model gradient Args: generative_model guide memory obs: tensor of shape [batch_si...
5e2b87a7d19eab1f09e5207f4c16c8e4a56b2225
10,628
import sys import os def chemin_absolu(relative_path): """ Donne le chemin absolu d'un fichier. PRE : - POST : Retourne ''C:\\Users\\sacre\\PycharmProjects\\ProjetProgra\\' + 'relative_path'. """ base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__))) correct = ba...
15f69eed0bbdb9ba09375d1485daba6a4fa8097f
10,629
import torch def to_float_tensor(np_array): """ convert to long torch tensor :param np_array: :return: """ return torch.from_numpy(np_array).type(torch.float)
84512d8383999bf22841c0e7e1fc8048bcba9a1a
10,630
def display_heatmap(salience_scores, salience_scores_2=None, title=None, title_2=None, cell_labels=None, cell_labels_2=None, normalized=True, ui=False): """ A utility funct...
8229db9630c8553567f0f93f8320c71397180ced
10,631
import re def _cleanse_line(line, main_character): """ Cleanse the extracted lines to remove formatting. """ # Strip the line, just in case. line = line.strip() # Clean up formatting characters. line = line.replace('\\' , '') # Remove escape characters. line = line.replace('[mc]...
87177c557ab89b77c63cc1df10874e52606258a7
10,632
def require_pandapower(f): """ Decorator for functions that require pandapower. """ @wraps(f) def wrapper(*args, **kwds): try: getattr(pp, '__version__') except AttributeError: raise ModuleNotFoundError("pandapower needs to be manually installed.") r...
35b0e5a5f9c4e189d849e3a6ba843b6f9e6b49b1
10,633
def optimal_path_fixture(): """An optimal path, and associated distance, along the nodes of the pyramid""" return [0, 1, 2, 3], 10 + 2 + 5
10c4e436907ecb99740a2514c927f05fd8488cf4
10,634
import timeit def evaluate_DynamicHashtablePlusRemove(output=True): """ Compare performance using ability in open addressing to mark deleted values. Nifty trick to produce just the squares as keys in the hashtable. """ # If you want to compare, then add following to end of executable statements: ...
243b5f4972b8eaa2630b6920c2d640d729feae61
10,635
def closest(lat1, lon1): """Return distance (km) and city closest to given coords.""" lat1, lon1 = float(lat1), float(lon1) min_dist, min_city = None, None for city, lat2, lon2 in CITIES: dist = _dist(lat1, lon1, lat2, lon2) if min_dist is None or dist < min_dist: min_dist, ...
4227e357f41619b6e2076bdcf3bb67b92daa9c4a
10,636
def get_previous_term(): """ Returns a uw_sws.models.Term object, for the previous term. """ url = "{}/previous.json".format(term_res_url_prefix) return Term(data=get_resource(url))
a261bc9d744f8f0b70ac76ac596f922b63ea9a46
10,637
from re import T def used(obj: T) -> T: """Decorator indicating that an object is being used. This stops the UnusedObjectFinder from marking it as unused. """ _used_objects.add(obj) return obj
33d241fe4a0953352ecad2ba306f915a88500d46
10,638
import scipy def fit_double_gaussian(x_data, y_data, maxiter=None, maxfun=5000, verbose=1, initial_params=None): """ Fitting of double gaussian Fitting the Gaussians and finding the split between the up and the down state, separation between the max of the two gaussians measured in the sum of the st...
65a54120e2d244301d36d0bba1e25fc711a9d6bb
10,639
def _set_advanced_network_attributes_of_profile(config, profile): """ Modify advanced network attributes of profile. @param config: current configparser configuration. @param profile: the profile to set the attribute in. @return: configparser configuration. """ config = _set_attribute_of_pr...
f5254f5f055865bf43f0e97f2dcf791bbbe61011
10,640
import os def Environ(envstring): """Return the String associated with an operating system environment variable envstring Optional. String expression containing the name of an environment variable. number Optional. Numeric expression corresponding to the numeric order of the environment string in t...
9972a427017dcae2917ea01d679d3fbc89ced0a7
10,641
def ring_bond_equal(b1, b2, reverse=False): """Check if two bonds are equal. Two bonds are equal if the their beginning and end atoms have the same symbol and formal charge. Bond type not considered because all aromatic (so SINGLE matches DOUBLE). Parameters ---------- b1 : rdkit.Chem.rdchem.B...
e0c5ab25d69f5770dcf58dd284519b3ed593ad33
10,642
import _warnings def survey_aligned_velocities(od): """ Compute horizontal velocities orthogonal and tangential to a survey. .. math:: (v_{tan}, v_{ort}) = (u\\cos{\\phi} + v\\sin{\\phi}, v\\cos{\\phi} - u\\sin{\\phi}) Parameters ---------- od: OceanDataset oceandata...
c506f8ca5db1ed6045ac02fb1988900f0ae10451
10,643
def insertion_sort(numbers): """ At worst this is an O(n2) algorithm At best this is an O(n) algorithm """ for index in xrange(1, len(numbers)): current_num = numbers[index] current_pos = index while current_pos > 0 and numbers[current_pos - 1] > current_num: numb...
d32a73b156f8b469cfcbdda70f349c7f3173d6a9
10,644
def ratio_shimenreservoir_to_houchiweir(): """ Real Name: Ratio ShiMenReservoir To HouChiWeir Original Eqn: Sum Allocation ShiMenReservoir To HouChiWeir/Sum Allcation From ShiMenReservoir Units: m3/m3 Limits: (None, None) Type: component """ return sum_allocation_shimenreservoir_to_hou...
e49969f53d6641a02b6cea5d3010ac34eb0739fd
10,645
import torch def torch_profiler_full(func): """ A decorator which will run the torch profiler for the decorated function, printing the results in full. Note: Enforces a gpu sync point which could slow down pipelines. """ @wraps(func) def wrapper(*args, **kwargs): with torch.autog...
7a92eb75d0131c6d151c9908fdcf2e84f6499468
10,646
def bias_add(x, bias, data_format=None): """Adds a bias vector to a tensor. # Arguments x: Tensor or variable. bias: Bias tensor to add. data_format: string, `"channels_last"` or `"channels_first"`. # Returns Output tensor. # Raises ValueError: In one of the tw...
1b783bbd6f685be336b565d7e5db9c5aa91a1f16
10,647
def get_news_with_follow(request, user_id): """ 获取用户关注类型的前30条,未登录300未登录 :param request: 请求对象 :return: Json数据 """ data = {} try: user = User.objects.get(pk=user_id) follow_set = user.follow_type.value_list('id').all() follow_list = [x[0] for x in follow_set] n...
41e9c8cb20c9c1757a8633d584f738b6a64e4f2b
10,648
import os def get_ngd_dir(config, absolute = False): """Returns the ngd output directory location Args: config (dictionary): configuration dictionary absolute (boolean): False (default): Relative to project base True: Absolute Returns: (string): string rep...
1d3ccdc83eaa1b29a8dc86ed0ad9150510ab1398
10,649
def trigger(): """Trigger salt-api call.""" data = {'foo': 'bar'} return request('/hook/trigger', data=data)
6aa469468711c3c94e0b5a20d9825fc9c0a73d83
10,650
from typing import List import math def fitness_function(cams: List[Coord], pop: List[Coord]) -> int: """ Function to calculate number of surveilled citizens. Check if all the cameras can see them, if any can score increases """ score = [] for cit in pop: test = False for cam ...
d10c02a7b182a8c38d8db37f13aec5b4c9def593
10,651
import requests def scrape_opening_hours(): """"scrape opening hours from https://www.designmuseumgent.be/bezoek""" r = requests.get("https://www.designmuseumgent.be/bezoek") data = r.text return data
297a35f3bc4e10d453da495e031fae5ce79ca643
10,652
import torch def _demo_mm_inputs(input_shape=(1, 3, 256, 256)): """Create a superset of inputs needed to run test or train batches. Args: input_shape (tuple): input batch dimensions """ (N, C, H, W) = input_shape rng = np.random.RandomState(0) imgs = rng.rand(*input_shap...
abef4e006fe6e530c5ca372904a40eecc3dbb5b7
10,653
import random def compute_one_epoch_baseline(): """ Function to compute the performance of a simple one epoch baseline. :return: a line to display (string reporting the experiment results) """ best_val_obj_list = [] total_time_list = [] for nb201_random_seed in nb201_random_seeds: ...
1bc3b03d49f0bbb8e2213acb31c64367b577aed2
10,654
import string import random def generate_random_string( length ): """Generate a random string of a given length containing uppercase and lowercase letters, digits and ASCII punctuation.""" source = string.ascii_lowercase + string.ascii_uppercase + string.digits + string.punctuation return ''.join( random....
9bb1ee7e21f27231e498f48bff505d963565f582
10,655
import shlex import psutil def start_cmd(cmd, use_file=False): """Start command and returns proc instance from Popen.""" orig_cmd = "" # Multi-commands need to be written to a temporary file to execute on Windows. # This is due to complications with invoking Bash in Windows. if use_file: ...
bdb6c5eef6a9e0a2fc2da16bfa88737410be477a
10,656
from typing import Mapping from typing import Sequence def pretty_table(rows, header=None): """ Returns a string with a simple pretty table representing the given rows. Rows can be: - Sequences such as lists or tuples - Mappings such as dicts - Any object with a __dict__ attribute (most pla...
1b4707932b27277ef22f17631e7a5778a38f99eb
10,657
def interpolate_trajectory(world_map, waypoints_trajectory, hop_resolution=1.0): """ Given some raw keypoints interpolate a full dense trajectory to be used by the user. Args: world: an reference to the CARLA world so we can use the planner waypoints_trajectory: the current coarse trajectory...
df544616954868aaa25c86b50420202bea860d9b
10,658
def import_data(filepath="/home/vagrant/countries/NO.txt", mongodb_url="mongodb://localhost:27017"): """ Import the adress data into mongodb CLI Example: salt '*' mongo.import_data /usr/data/EN.txt """ client = MongoClient(mongodb_url) db = client.demo address_col = db.address ...
8f80343c60000a8ab988c02bac54e2f748e346b9
10,659
import async_timeout import requests async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Enphase Envoy sensor.""" ip_address = config[CONF_IP_ADDRESS] monitored_conditions = config[CONF_MONITORED_CONDITIONS] name = config[CONF_NAME] username = confi...
07e762a8fbcc987b57d38bc8a10d3f51e6fa58a4
10,660
from .register import PIPING_SIGNS from .verb import Verb import ast def _get_piping_verb_node(calling_node: ast.Call) -> ast.Call: """Get the ast node that is ensured the piping verb call Args: calling_node: Current Call node Returns: The verb call node if found, otherwise None """ ...
2f6be9b382f2bf2e31d39ff9682f5b26618aa1af
10,661
def slot(**kwargs): """Creates a SlotConfig instance based on the arguments. Args: **kwargs: Expects the following keyed arguments. in_dist: Distribution for inbound in msec. Optional in_max_bytes: Optional. Ignored when in_dist is missing. in_max_pkts: Optional. Ign...
4b26f7a805b88a7a6bd03f7d23db7a14d7979eeb
10,662
def get_agent_type(player): """ Prompts user for info as to the type of agent to be created """ print('There are two kinds of Agents you can initialise.') print(' 1 - <Human> - This would be a totally manually operated agent.') print(' You are playing the game yourself.') print(' ...
3d0fce9faafaa6c993cb2b5b54a1480268c22ab3
10,663
def _try_match_and_transform_pattern_1(reduce_op, block) -> bool: """ Identify the pattern: y = gamma * (x - mean) / sqrt(variance + epsilon) + beta y = x * [gamma * rsqrt(variance + eps)] + (beta - mean * [gamma * rsqrt(variance + eps)]) x --> reduce_mean --> sub --> square --> reduce_mean --> a...
f1baecfc53daf731c5b518aadcc11c88508258e3
10,664
import click def cli_resize(maxsize): """Resize images to a maximum side length preserving aspect ratio.""" click.echo("Initializing resize with parameters {}".format(locals())) def _resize(images): for info, image in images: yield info, resize(image, maxsize) return _resize
f0695940531c45a88ff1722c002dacc6103962e0
10,665
import numpy def _fetch_object_array(cursor): """ _fetch_object_array() fetches arrays with a basetype that is not considered scalar. """ arrayShape = cursor_get_array_dim(cursor) # handle a rank-0 array by converting it to # a 1-dimensional array of size 1. if len(arrayShape) == 0: ...
7c84306c0b84a126f401e51bac5896203357380a
10,666
def sldParse(sld_str): """ Builds a dictionary from an SldStyle string. """ sld_str = sld_str.replace("'", '"').replace('\"', '"') keys = ['color', 'label', 'quantity', 'opacity'] items = [el.strip() for el in sld_str.split('ColorMapEntry') if '<RasterSymbolizer>' not in el] sld_items = [] ...
888a2ee3251a0d1149b478d32ccb88ff0e309ec3
10,667
def x_ideal(omega, phase): """ Generates a complex-exponential signal with given frequency and phase. Does not contain noise """ x = np.empty(cfg.N, dtype=np.complex_) for n in range(cfg.N): z = 1j*(omega * (cfg.n0+n) * cfg.Ts + phase) x[n] = cfg.A * np.exp(z) return x
87e4df7cbbfe698e5deb461642de72efb6bfffad
10,668
def _wrap_stdout(outfp): """ Wrap a filehandle into a C function to be used as `stdout` or `stderr` callback for ``set_stdio``. The filehandle has to support the write() and flush() methods. """ def _wrap(instance, str, count): outfp.write(str[:count]) outfp.flush() retu...
f7d773890b17b18855d2d766bd147c67ac7ade3b
10,669
def svn_fs_apply_textdelta(*args): """ svn_fs_apply_textdelta(svn_fs_root_t root, char path, char base_checksum, char result_checksum, apr_pool_t pool) -> svn_error_t """ return _fs.svn_fs_apply_textdelta(*args)
d8d228415d8768ec297415a42113e0eb2463163f
10,670
def find(x): """ Find the representative of a node """ if x.instance is None: return x else: # collapse the path and return the root x.instance = find(x.instance) return x.instance
5143e9d282fb1988d22273996dae36ed587bd9d2
10,671
def convert_shape(node, **kwargs): """Map MXNet's shape_array operator attributes to onnx's Shape operator and return the created node. """ return create_basic_op_node('Shape', node, kwargs)
7d4414eac78208b0c35d7ab5a9f21ab70a0947ae
10,672
import logging import os def _UploadScreenShotToCloudStorage(fh): """ Upload the given screenshot image to cloud storage and return the cloud storage url if successful. """ try: return cloud_storage.Insert(cloud_storage.TELEMETRY_OUTPUT, _GenerateRemotePath(fh), fh.GetAbs...
0f77dc93f0cd708e36e157d9aee664c20536b486
10,673
import time def get_timestamp(prev_ts=None): """Internal helper to return a unique TimeStamp instance. If the optional argument is not None, it must be a TimeStamp; the return value is then guaranteed to be at least 1 microsecond later the argument. """ t = time.time() t = TimeStamp(*tim...
89751c53679f11efd26b88609887c4a2ed475418
10,674
def get_element_as_string(element): """ turn xml element from etree to string :param element: :return: """ return lxml.etree.tostring(element, pretty_print=True).decode()
f62945ff4bdd3bea2562ba52a89d8d01c74e0b10
10,675
import sys import glob import os def get(dirPath): """指定したパスのファイル一覧を取得する""" if sys.version_info.major != 3: print("Error!!\nPython 3.x is required.") exit() if sys.version_info.minor >= 5: # python 3.5以降 fileList = [] fileList = glob.glob(dirPath, recursive=True) ...
a9b66504f1103f094930386a75afbcb8847dacbd
10,676
def _select_ports(count, lower_port, upper_port): """Select and return n random ports that are available and adhere to the given port range, if applicable.""" ports = [] sockets = [] for i in range(count): sock = _select_socket(lower_port, upper_port) ports.append(sock.getsockname()[1]) ...
2f92cb7e4ab26c54bc799369cd950c4269049291
10,677
def is_solution_quad(var, coeff, u, v): """ Check whether `(u, v)` is solution to the quadratic binary diophantine equation with the variable list ``var`` and coefficient dictionary ``coeff``. Not intended for use by normal users. """ reps = dict(zip(var, (u, v))) eq = Add(*[j*i.xrepla...
b19d7678c725a41df755352f5af1ce322f3efad7
10,678
def is_callable(x): """Tests if something is callable""" return callable(x)
72584deb62ac5e34e69325466236792c5299a51b
10,679
def validate_version_argument(version, hint=4): """ validate the version argument against the supported MDF versions. The default version used depends on the hint MDF major revision Parameters ---------- version : str requested MDF version hint : int MDF revision hint Retur...
e29342f78236f043b079cf5e4473f6dccb29d35c
10,680
import torch def roc_auc(probs, labels): """ Computes the area under the receiving operator characteristic between output probs and labels for k classes. Source: https://github.com/HazyResearch/metal/blob/master/metal/utils.py args: probs (tensor) (size, k) labels (tensor...
9ae79a4ff5cbf93d2187857c8ac62014c6fa98f0
10,681
from typing import Collection def show_collection(request, collection_id): """Shows a collection""" collection = get_object_or_404(Collection, pk=collection_id) # New attribute to store the list of problems and include the number of submission in each problem collection.problem_list = collection.probl...
a23efc449258839a7d7bfa0c0a73d889a6891a0f
10,682
from typing import Union from typing import Callable from typing import List def alpha( data: np.ndarray, delta: Union[Callable[[int, int], float], List[List[float]], str] = "nominal", ): """Calculates Krippendorff's alpha coefficient [1, sec. 11.3] for inter-rater agreement. [1] K. Krippendorff,...
98c86120287d9d4b2c7f10ad074702c2088ade8d
10,683
def enforce(action, target, creds, do_raise=True): """Verifies that the action is valid on the target in this context. :param creds: user credentials :param action: string representing the action to be checked, which should be colon separated for clarity. O...
16cdefe38bfc56f529a735b8517d94ade7db780d
10,684
from operator import and_ from operator import or_ def query_data(session, agency_code, period, year): """ Request A file data Args: session: DB session agency_code: FREC or CGAC code for generation period: The period for which to get GTAS data year: The ye...
0eb856f699eebf95bf10ff2d3dd6c9a72ec0843a
10,685
def vocublary(vec_docs): """ vocabulary(vec_docs) -> tuple: (int avg_doc_len, updated vec_docs, corpus Vocabulary dictionary {"word": num_docs_have__this_term, ...}) vec_docs = list of documents as dictionaries [{ID:"word_i word_i+1 ..."} , {ID:"word_i word_i+1"}, ...}] """ vocabulary = {} count_v...
4e6f4df1e36c2fdf3d7d1d20750d74f91a0214b6
10,686
import os import traceback def main(unused_argv): """Main entry. Args: * unused_argv: unused arguments (after FLAGS is parsed) """ try: # setup the TF logging routine tf.logging.set_verbosity(tf.logging.INFO) # set the learning phase to 'inference'; data format may be changed if needed se...
7f1af5f6055629b9c80ff9144713ca146ce9b9ed
10,687
import warnings def _build_type(type_, value, property_path=None): """ Builds the schema definition based on the given type for the given value. :param type_: The type of the value :param value: The value to build the schema definition for :param List[str] property_path: The property path of the curr...
7033e5f8bc5cd5b667f25b8554bfe3296191762f
10,688
def lidar_2darray_to_rgb(array: np.ndarray) -> np.ndarray: """Returns a `NumPy` array (image) from a 4 channel LIDAR point cloud. Args: array: The original LIDAR point cloud array. Returns: The `PyGame`-friendly image to be visualized. """ # Get array shapes. W, H, C = array.shape assert C == 2 ...
69e2de793b9280b269ac8ab9f3d313e51c932c8c
10,689
import argparse def args(): """ --all (some subset that is useful for someone) --packages (maybe positional?) """ parser = argparse.ArgumentParser("serviced-tests") parser.add_argument("-v", "--verbose", action="store_true", help="verbose logging") types = parser.add_argument_group("Test...
b2a6b83b1ee02fc5ae2ba3130757ca50d9d954fe
10,690
from typing import Tuple from typing import Union from typing import List from typing import Dict import tqdm import torch def rollout(dataset: RPDataset, env: RPEnv, policy: Policy, batch_size: int, num_workers: int = 4, disable_progress_bar: bool = False, ...
1b88ff01b86d567de2c78d4450825e4fd1120311
10,691
def regex_ignore_case(term_values): """ turn items in list "term_values" to regexes with ignore case """ output=[] for item in term_values: output.append(r'(?i)'+item) return output
5dbf5fba758fe91fb0bbfaed6ab3cfa5f05357eb
10,692
from typing import Callable def importance_sampling_integrator(function: Callable[..., np.ndarray], pdf: Callable[..., np.ndarray], sampler: Callable[..., int], n: int = 10000, s...
14b6abfaa38f37430ec0e9abcd330f1392543978
10,693
from apex.amp._amp_state import _amp_state import torch def r1_gradient_penalty_loss(discriminator, real_data, mask=None, norm_mode='pixel', loss_scaler=None, use_apex_amp=F...
d142375d89f39ae2510575d0615a878bd67e9574
10,694
import json import re def visualize(args): """Return the visualized output""" ret = "" cmd_list = json.load(args.results)['cmd_list'] cmd_list = util.filter_cmd_list(cmd_list, args.labels_to_include, args.labels_to_exclude) (cmd_list, label_map) = util.translate_dict(cmd_list, args.label_map) ...
8a9e655adfc9713785f96ab487d579a19d9d09b2
10,695
def send_request(apikey, key_root, data, endpoint): """Send a request to the akismet server and return the response.""" url = 'http://%s%s/%s/%s' % ( key_root and apikey + '.' or '', AKISMET_URL_BASE, AKISMET_VERSION, endpoint ) try: response = open_url(url, data=...
aea5ac8eb0b8b91002e680376c6f2647a631e58c
10,696
def request_set_bblk_trace_options(*args): """ request_set_bblk_trace_options(options) Post a 'set_bblk_trace_options()' request. @param options (C++: int) """ return _ida_dbg.request_set_bblk_trace_options(*args)
728d7e2a7a0ef0085d4bb72763b2a019d89896ec
10,697
def range_str(values: iter) -> str: """ Given a list of integers, returns a terse string expressing the unique values. Example: indices = [0, 1, 2, 3, 4, 7, 8, 11, 15, 20] range_str(indices) >> '0-4, 7-8, 11, 15 & 20' :param values: An iterable of ints :return: A string of u...
85dedc97342b07dcb2a8dda753768309aa31ed43
10,698
import json def analyze(request): """ 利用soar分析SQL :param request: :return: """ text = request.POST.get('text') instance_name = request.POST.get('instance_name') db_name = request.POST.get('db_name') if not text: result = {"total": 0, "rows": []} else: soar = Soa...
a033774727242783357a35a6608d7154f77bc016
10,699