content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def build_stats(loss, eval_result, time_callback): """Normalizes and returns dictionary of stats. Args: loss: The final loss at training time. eval_result: Output of the eval step. Assumes first value is eval_loss and second value is accuracy_top_1. time_callback: Time track...
cddde6bf9bd2797c94bc392be77f7be19a46271e
26,700
import random def random_resource_code2() -> str: """One random book name chosen at random. This fixture exists so that we can have a separate book chosen in a two language document request.""" book_ids = list(bible_books.BOOK_NAMES.keys()) return random.choice(book_ids)
04ea455fa85eea32c2c7e9d7d3a3dc98759b937b
26,701
def _to_str(value): """Helper function to make sure unicode values are converted to UTF-8. Args: value: String or Unicode text to convert to UTF-8. Returns: UTF-8 encoded string of `value`; otherwise `value` remains unchanged. """ if isinstance(value, unicode): return value.encode('utf-8') ret...
46186757a475c2b5fa877e8fb62c32a27770e6b7
26,702
def get_loss(loss_name): """Get loss from LOSS_REGISTRY based on loss_name.""" if not loss_name in LOSS_REGISTRY: raise Exception(NO_LOSS_ERR.format( loss_name, LOSS_REGISTRY.keys())) loss = LOSS_REGISTRY[loss_name] return loss
d91bde7ce34e2d4fe38a5c86a93ba96d153eb7c1
26,703
def collate_fn(batch): """ Data collater. Assumes each instance is a dict. Applies different collation rules for each field. Args: batches: List of loaded elements via Dataset.__getitem__ """ collated_batch = {} # iterate over keys for key in batch[0]: try: ...
718a6945d71a485fd4dbbbeaac374afbb9256621
26,704
def _rec_eval_in(g, a, v, i, j, K): """Recursive helper for :func:`dmp_eval_in`.""" if i == j: return dmp_eval(g, a, v, K) v, i = v - 1, i + 1 return dmp_strip([ _rec_eval_in(c, a, v, i, j, K) for c in g ], v)
51fbd9a45b4e1722ef98a5ab543575980d56b66b
26,705
def normalize(array): """ Normalize a 4 (or Nx4) element array/list/numpy.array for use as a quaternion :param array: 4 or Nx4 element list/array :returns: normalized array :rtype: numpy array """ quat = np.array(array) return np.squeeze(quat / np.sqrt(np.sum(quat * quat, axis=-1, keep...
020b1fb9b1050192254274ac3d716e655a5ff003
26,706
def dose_class_baseline(dose_num, df_test, df_targets): """Calculate the PR- baseline for each dose treatment""" dose_cpds_index = df_test[df_test['dose'] == dose_num].index df_class_targets = df_targets.loc[dose_cpds_index].reset_index(drop = True) class_baseline_score = calculate_baseline(df_class_targets) ...
0e0178573fc3ccfb08c8f898d264efa84fd10962
26,707
def xrange(mn: int, mx: int = None) -> list: """Built-in range function, but actually gives you a range between mn and mx. Range: range(5) -> [0, 1, 2, 3, 4] XRange: xrange(5) -> [0, 1, 2, 3, 4, 5]""" return list(range(0 if mx is None else mn, mn + 1 if mx is None else mx + 1))
4ab3059a51966cefd43008c4aa4c50cf42cb8fa2
26,708
import os def stage_per_sample_specific_statics(opts, sample_ids): """Items like the Latex templates Parameters ---------- opts : dict A dict of relevant opts. sample_ids : Iterable of str A list of sample IDs of interest Returns ------- dict A dict containing...
038dd67ed235d133bd7abb14800214de54f34bb2
26,709
def sous_tableaux(arr: list, n: int) -> list: """ Description: Découper un tableau en sous-tableaux. Paramètres: arr: {list} -- Tableau à découper n: {int} -- Nombre d'éléments par sous-tableau Retourne: {list} -- Liste de sous-tableaux Exemple: >>> sous_ta...
4f0a627ea00beafb5b6bc77490e71631e8a55e28
26,710
def get_previous_tweets(date_entry): """Return details about previous Tweets. Namely, retrieve details about the date_entry-th Tweets from 7 days ago, 30 days ago, and a random number of days ago. If a given Tweet does not exist, its corresponding entry in the output will be empty. Args: ...
a4b91b87f3cc897e720f745a1c0ad1097292774b
26,711
def changed_cat_keys(dt): """Returns keys for categories, changed after specified time""" return [root_category_key()]
fbc4d0380bb1deaf7f1214d526d1c623cceb4676
26,712
def create_client(CLIENT_ID, CLIENT_SECRET): """Creates Taboola Client object with the given ID and secret.""" client = TaboolaClient(CLIENT_ID, client_secret=CLIENT_SECRET) return client
bea955f5d944e47f11c74ae97c5472dc3c512217
26,713
def set_values_at_of_var_above_X_lat_2_avg(lat_above2set=65, ds=None, use_avg_at_lat=True, res='0.125x0.125', var2set=None, only_consider_water_boxes=True, ...
6040523af84f5046af373de2aa22447e66aef181
26,714
def vzc_dict(svy): """ vizier column dictionary dictionary for NVSS, TGSS column using vizier TODO: add column for errors too """ columns = {'tgss': ['RAJ2000', 'DEJ2000', 'Maj', 'Min', 'PA'], 'nvss': ['RAJ2000', 'DEJ2000', 'MajAxis', 'MinAxis', 'PA', '+NVSS'] } ...
fa431d490da440cd3d95e5026892c38da8743988
26,715
def _plot_xkcd(plot_func, *args, **kwargs): """ Plot with *plot_func*, *args* and **kwargs*, but in xkcd style. """ with plt.xkcd(): fig = plot_func(*args, **kwargs) return fig
a4bc526c115c54f37c5171b82639adf0c0a3f888
26,716
import requests def unfollow_user(): """UnfollowUser""" auth = request.headers user = request.args.get('userId') req = requests.post( '/api/v1/IsAuthenticated', {'id': auth['Authorization']} ) req.json() if req.authenticated: cur = MY_SQL.connection.cursor() ...
8e40b633b960070a4d433610f4f0d4e7f8b89a12
26,717
def isOverlaysEnabled(): """Returns whether or not the current client's quality overlay system is currently enabled. Returns: bool: True (1) if overlays are currently enabled. """ return False
d433b86b38bfa3c3ed28705888ef12710aaf4f96
26,718
def load_image(path, size=None, grayscale=False): """ Load the image from the given file-path and resize it to the given size if not None. """ # Load the image using opencv if not grayscale: # BGR format image = cv2.imread(path) else: # grayscale format image = cv2.imread(...
2d3d4a625a690800c2d5db8f8577e9c06a36001a
26,719
def brent_min(f, bracket, fnvals=None, tolerance=1e-6, max_iterations=50): """\ Given a univariate function f and a tuple bracket=(x1,x2,x3) bracketing a minimum, find a local minimum of f (with fn value) using Brent's method. Optionally pass in the tuple fnvals=(f(x1),f(x2),f(x3)) as a parameter. """ x1, x2, x3 = b...
ef4010e00ca67d1751b7f8eea497afc59e76364c
26,720
def best_validity(source): """ Retrieves best clustering result based on the relative validity metric """ # try: cols = ['min_cluster_size', 'min_samples', 'validity_score', 'n_clusters'] df = pd.DataFrame(source, columns = cols) df['validity_score'] = df['validity_score'].fillna(0) bes...
ba830ccca8c9f62758ecd8655576efb58892cdbc
26,721
import json def normalize_cell_value(value): """Process value for writing into a cell. Args: value: any type of variable Returns: json serialized value if value is list or dict, else value """ if isinstance(value, dict) or isinstance(value, list): return json.dumps(value)...
8ef421814826c452cdb6528c0645133f48bd448a
26,722
import numpy def _ancestry2paths(A): """Convert edge x edge ancestry matrix to tip-to-tip path x edge split metric matrix. The paths will be in the same triangular matrix order as produced by distanceDictAndNamesTo1D, provided that the tips appear in the correct order in A""" tips = [i for i i...
732ef3bbccff4696650c24a983fdbc338f1d8e24
26,723
def geometric_mean(x, axis=-1, check_for_greater_than_zero=True): """ Return the geometric mean of matrix x along axis, ignore NaNs. Raise an exception if any element of x is zero or less. """ if (x <= 0).any() and check_for_greater_than_zero: msg = 'All elements of x (except NaNs...
485780f7766857333a240d059d2bb1c526d3f5a8
26,724
def mongodb(): """ Simple form to get and set a note in MongoDB """ return None
a6de90429bb3ad3e23191e52e1b43484435747f9
26,725
def get_single_blog(url): """Получить блог по указанному url""" blog = Blog.get_or_none(Blog.url == url) if blog is None: return errors.not_found() user = get_user_from_request() has_access = Blog.has_access(blog, user) if not has_access: return errors.no_access() blog_dic...
b4a32278681af7eecbebc29ed06b88c7860a39c0
26,726
def test_section(): """Returns a testing scope context to be used in 'with' statement and captures testing code. Example:: with autograd.train_section(): y = model(x) compute_gradient([y]) with autograd.test_section(): # testing, IO, gradient upda...
6bcbc9aaaaeee5a9b5d8b6a3307f1fb69bf726ae
26,727
from typing import Optional import select async def get_installation_owner(metadata_account_id: int, mdb_conn: morcilla.core.Connection, cache: Optional[aiomcache.Client], ) -> str: """Load the native user ID who in...
925780ce87c14758cf98191cf39effcaf09a8aaa
26,728
def get_cflags(): """Get the cflag for compile python source code""" flags = ['-I' + get_path('include'), '-I' + get_path('platinclude')] flags.extend(getvar('CFLAGS').split()) # Note: Extrat cflags not valid for cgo. for not_go in ('-fwrapv', '-Wall'): if not_go in flags: ...
f1c171d5a70127bda98a3ef7625c60336641ea1f
26,729
import requests def request_post_json(url, headers, data): """Makes a POST request and returns the JSON response""" try: response = requests.post(url, headers=headers, data=data, timeout=10) if response.status_code == 201: return response.json() else: error_mess...
82d7ce423024ca1af8a7c513f3d689fbc77c591a
26,730
import random def get_rand_number(min_value, max_value): """ This function gets a random number from a uniform distribution between the two input values [min_value, max_value] inclusively Args: - min_value (float) - max_value (float) Return: - Random number between this range (float) ...
0eec094d05b291c7c02207427685d36262e643e5
26,731
def detect_callec(tree): """Collect names of escape continuations from call_ec invocations in tree. Currently supported and unsupported cases:: # use as decorator, supported @call_ec def result(ec): # <-- we grab name "ec" from here ... # use directly on a literal...
e55f1e1080c3872e664c1c50411a282a5c4958e5
26,732
import copy def _get_good_pport_list(sriov_adaps, pports, capacity, redundancy, check_link_status, redundant_pports=None): """Get a list of SRIOV*PPort filtered by capacity and specified pports. Builds a list of pypowervm.wrappers.iocard.SRIOV*PPort from sriov_adaps such that: ...
a8f4fa0b618605f3f434e3c793e8b97c0c72f385
26,733
def read(string): """ Given a single interval from a GFFv2 file, returns an Interval object. Will return meta lines if they start with #, track, or browser. """ if string.startswith(metalines): return interval(_is_meta=True, seqname=string) values = [] cols = string.split(delimiter) fo...
e4651216c9694935bc879c012b1fe74f529cb41d
26,734
from typing import Union from pathlib import Path from typing import Dict def average_results(results_path: Union[Path, str], split_on: str = " = ") -> Dict[str, float]: """ Average accuracy values from a file. Parameters ---------- results_path : Union[Path, str] The file to read results...
28b896d567d6ef18662766a2da64c6bdb262f3d7
26,735
import sys import os def absPath(myPath): """Get absolute path to resource, works for dev and for PyInstaller""" try: # PyInstaller creates a temp folder and stores path in _MEIPASS base_path = sys._MEIPASS lprint("found MEIPASS: %s " % os.path.join(base_path, os.path.basename(myPath)...
7bfbee7dd9e566aed3449cb7c6b514f307af875f
26,736
def dict_collection_only(method): """ Handles the behavior when a group is present on a clumper object. """ @wraps(method) def wrapped(clumper, *args, **kwargs): if not clumper.only_has_dictionaries: non_dict = next(d for d in clumper if not isinstance(d, dict)) rais...
a84c3588942378157674e6862d2f1a8c785ba569
26,737
def country_name(country_id): """ Returns a country name >>> country_name(198) u'Spain' """ if country_id == '999': #Added for internal call - ie flag/phone.png return _('internal call').title() try: obj_country = Country.objects.get(id=country_id) return obj...
fdb44061d795e42d9e312bc25f8335a41c91ca11
26,738
import sys def parse_mjinfo(): """List up game history stored in Flash cache directory Returns ------- dict Key : str File name in which data are stored Value : list of dict Information of logs. See :func:`parse_sol`. """ if sys.platform == 'darwin': ...
44f0471738ac7a8c03ab4fad727f1f31227f4613
26,739
import copy def multiply(input_op_node: cc_dag.OpNode, output_name: str, target_col_name: str, operands: list): """ Define Multiply operation. :param input_op_node: Parent node for the node returned by this method. :param output_name: Name of returned Multiply node. :param target_col_name: Name o...
68effc870a5a53cf123b763cbca87eaec83ff35d
26,740
from typing import Dict from pathlib import Path import os import shutil import subprocess def download_clip_wrapper( row, label_to_dir, trim_format, tmp_dir, existing_files: Dict[str, Path] = {} ): """Wrapper for parallel processing purposes.""" output_filename = construct_video_filename(row, label_to_di...
4a589627259fd370b7f5f35200bbe8ad21646935
26,741
import os def list_subdir(path): """ list all subdirectories given a directory""" return [o for o in os.listdir(path) if os.path.isdir(path / o)]
d99760b6ec914d59cdbf5b8f4bc2bb8b0a30f9e8
26,742
def update_jira(vulnerability_dictionary, config): """ Feeds JIRA with issues based on the vulnerability dictionary. :param vulnerability_dictionary: dictionary of vulnerabilities :param config: confiture object that contains the quart configuration. :return: int, number of issues created/updated to...
eaee30bf93e03d7e777e7372a4fdd105c977e771
26,743
def KLdist(P,Q): """ KLDIST Kullbach-Leibler distance. D = KLDIST(P,Q) calculates the Kullbach-Leibler distance (information divergence) of the two input distributions. """ P2 = P[P*Q>0] Q2 = Q[P*Q>0] P2 = P2 / np.sum(P2) Q2 = Q2 / np.sum(Q2) D = np.sum(P2*np.log(P2/Q2)) ...
380796f3688c5ad8483ba50ddc940eb797e4a973
26,744
import argparse def get_args(): """Get arguments from CLI""" parser = argparse.ArgumentParser( description="""\nRuns Stacks process_radtags on each plate in barcodes.txt file""") parser.add_argument( "--Read1", required=True, action=FullPaths, he...
3b3564a404e882281ec3603924fed3729ae33893
26,745
def homepage(request: HttpRequest) -> HttpResponse: """ Render the home page of the application. """ context = make_context(request) person = get_person(TARGET_NICK) if not person: return render(request, "404.html", status=404) context["person"] = person technology_set = person.technol...
42f749a38543b456b603b5b7b923d5637ab84abe
26,746
def _call_rmat(scale, num_edges, create_using, mg): """ Simplifies calling RMAT by requiring only specific args that are varied by these tests and hard-coding all others. """ return rmat(scale=scale, num_edges=num_edges, a=0.1, b=0.2, c...
cf68a7e436919ad5296438708898eeb233112651
26,747
def value_loss(old_value): """value loss for ppo""" def loss(y_true, y_pred): vpredclipped = old_value + K.clip(y_pred - old_value, -LOSS_CLIPPING, LOSS_CLIPPING) # Unclipped value vf_losses1 = K.square(y_pred - y_true) # Clipped value vf_losses2 = K.square(vpredclipped -...
0888a411be6fa7e41469d15a2798cbebda46db01
26,748
import torch import warnings def split_by_worker(urls): """Selects a subset of urls based on Torch get_worker_info. Used as a shard selection function in Dataset.""" urls = [url for url in urls] assert isinstance(urls, list) worker_info = torch.utils.data.get_worker_info() if worker_info i...
1ddcf436fecc4359367b783f9c1c62fe84782468
26,749
import os import psutil import sys import math def cpu_count(): """Get the available CPU count for this system. Takes the minimum value from the following locations: - Total system cpus available on the host. - CPU Affinity (if set) - Cgroups limit (if set) """ count = os.cpu_count() ...
1e89fdf5660ac4e86d1acbc98db1ef8f4c8a5fc6
26,750
def runge_kutta4(y, x, dx, f): """computes 4th order Runge-Kutta for dy/dx. Parameters ---------- y : scalar Initial/current value for y x : scalar Initial/current value for x dx : scalar difference in x (e.g. the time step) f : ufunc(y,x) Callable function ...
0f79962a3bd7bbe49bd3ae3eff6d5496182fbea8
26,751
def genBinaryFileRDD(sc, path, numPartitions=None): """ Read files from a directory to a RDD. :param sc: SparkContext. :param path: str, path to files. :param numPartition: int, number or partitions to use for reading files. :return: RDD with a pair of key and value: (filePath: str, fileData: Bina...
85ef3c657b932946424e2c32e58423509f07ceae
26,752
import requests def generate(): """ Generate a classic image quote :rtype: InspiroBotImageResponse :return: The generated response """ try: r = requests.get("{}?generate=true".format(url())) except: raise InsprioBotError("API request failed. Failed to connect") if r.st...
bc9a49909d9191f922a5c781d9fc68c97de92456
26,753
import pickle def inference_lstm(im_path, model_path, tok_path, max_cap_len=39): """ Perform inference using a model trained to predict LSTM. """ tok = pickle.load(open(tok_path, 'rb')) model = load_model( model_path, custom_objects={'RepeatVector4D': RepeatVector4D}) encoder =...
81cec1407b6227d7f65a697900467b16b2fce96e
26,754
def iterative_proof_tree_bfs(rules_dict: RulesDict, root: int) -> Node: """Takes in a iterative pruned rules_dict and returns iterative proof tree.""" root_node = Node(root) queue = deque([root_node]) while queue: v = queue.popleft() rule = sorted(rules_dict[v.label])[0] if n...
c7ce6f1e48f9ac04f68b94e07dbcb82162b2abba
26,755
def get_host_buffer_init(arg_name, num_elem, host_data_type, host_init_val): """Get host code snippet: init host buffer""" src = get_snippet("snippet/clHostBufferInit.txt") src = src.replace("ARG_NAME", arg_name) src = src.replace("NUM_ELEM", str(num_elem)) src = src.replace("HOST_DATA_TYPE", host_d...
7f94d2727a3c6f861f5c6402c5c8d2211d32dd71
26,756
def get_setting(setting, override=None): """Get setting. Get a setting from `muses` conf module, falling back to the default. If override is not None, it will be used instead of the setting. :param setting: String with setting name :param override: Value to use when no setting is available. D...
7e4a05ee3b077023e04693a37d3cbeaaa6025d8d
26,757
def extract_year_month_from_key(key): """ Given an AWS S3 `key` (str) for a file, extract and return the year (int) and month (int) specified in the key after 'ano=' and 'mes='. """ a_pos = key.find('ano=') year = int(key[a_pos + 4:a_pos + 8]) m_pos = key.find('mes=') month...
b52dc08d393900b54fca3a4939d351d5afe0ef3c
26,758
def depolarize(p: float) -> DepolarizingChannel: """Returns a DepolarizingChannel with given probability of error. This channel applies one of four disjoint possibilities: nothing (the identity channel) or one of the three pauli gates. The disjoint probabilities of the three gates are all the same, p /...
247dd040844cdd3cd44336ca097b98fcf2f3cac3
26,759
import re def verilog_to_circuit( netlist, name, infer_module_name=False, blackboxes=None, warnings=False, error_on_warning=False, fast=False, ): """ Creates a new Circuit from a module inside Verilog code. Parameters ---------- netlist: str Verilog code. ...
4dc8e59ff8bea29f32e64219e3c38ed7bfec4aef
26,760
def load_all_channels(event_id=0): """Returns a 3-D dataset corresponding to all the electrodes for a single subject and a single event. The first two columns of X give the spatial dimensions, and the third dimension gives the time.""" info = load_waveform_data(eeg_data_file()) locs = load_channel_l...
17dd6dfc196a3f88f4bf7f0128da1a0b027f9072
26,761
def parentheses_cleanup(xml): """Clean up where parentheses exist between paragraph an emphasis tags""" # We want to treat None's as blank strings def _str(x): return x or "" for em in xml.xpath("//P/*[position()=1 and name()='E']"): par = em.getparent() left, middle, right = _st...
b5a476cd6fd9b6a2ab691fcec63a33e6260d48f2
26,762
import numpy def filter_atoms(coordinates, num_atoms=None, morphology="sphere"): """ Filter the atoms so that the crystal has a specific morphology with a given number of atoms Params: coordinates (array): The atom coordinates num_atoms (int): The number of atoms morphology (str):...
9763f2c7b14a26d089bf58a4c7e82e2d4a0ae2bd
26,763
def predict_timeslice_single(vis: Visibility, model: Image, predict=predict_2d, remove=True, gcfcf=None, **kwargs) -> Visibility: """ Predict using a single time slices. This fits a single plane and corrects the image geometry. :param vis: Visibility to be predicted :param...
b09fe0d93c42a56372450f29e92731203bd4a1d4
26,764
def weekly(): """The weekly status page.""" db = get_session(current_app) #select id, user_id, created, strftime('%Y%W', created), date(created, 'weekday 1'), content from status order by 4, 2, 3; return render_template( 'status/weekly.html', week=request.args.get('week', None), ...
b5c1e5a8d981fb217492241e8ee140898d47b633
26,765
from typing import List import pathlib from typing import Sequence def parse_source_files( src_files: List[pathlib.Path], platform_overrides: Sequence[str], ) -> List[LockSpecification]: """ Parse a sequence of dependency specifications from source files Parameters ---------- src_files : ...
47a6e66b56ca0d4acd60a6b388c9f58d0cccbb2c
26,766
def delete_registry( service_account_json, project_id, cloud_region, registry_id): """Deletes the specified registry.""" # [START iot_delete_registry] print('Delete registry') client = get_client(service_account_json) registry_name = 'projects/{}/locations/{}/registries/{}'.format( ...
baa8cad0d324f2e564052822f9d17f45a581a397
26,767
def bundle(cls: type) -> Bundle: """ # Bundle Definition Decorator Converts a class-body full of Bundle-storable attributes (Signals, other Bundles) to an `hdl21.Bundle`. Example Usage: ```python import hdl21 as h @h.bundle class Diff: p = h.Signal() n = h.Signal() ...
bf1b68791dbdc5b6350d561db4d784ff92c0bbae
26,768
import time import calendar def previousMidnight(when): """Given a time_t 'when', return the greatest time_t <= when that falls on midnight, GMT.""" yyyy, MM, dd = time.gmtime(when)[0:3] return calendar.timegm((yyyy, MM, dd, 0, 0, 0, 0, 0, 0))
0821eb46115a1e5b1489c4f4dbff78fab1d811b5
26,769
def compute_net_results(net, archname, test_data, df): """ For a given network, test on appropriate test data and return dataframes with results and predictions (named obviously) """ pretrain_results = [] pretrain_predictions = [] tune_results = [] tune_predictions = [] for idx in r...
b971f269bbee7e48f75327e3b01d73c77ec1f06c
26,770
def _distance_along_line(start, end, distance, dist_func, tol): """Point at a distance from start on the segment from start to end. It doesn't matter which coordinate system start is given in, as long as dist_func takes points in that coordinate system. Parameters ---------- start : tuple ...
2f168b068cc434fe9280e2cdf84ae3f0f93eb844
26,771
import argparse import sys import logging import tempfile import shutil def top_level_cli(fragment, *pos_args, **kwargs): """ Runs a default CLI that assists in building and running gateware. If the user's options resulted in the board being programmed, this returns the fragment that was programm...
6163d73863521a432f74b980f69ae54057b7d32c
26,772
def exploits_listing(request,option=None): """ Generate the Exploit listing page. :param request: Django request. :type request: :class:`django.http.HttpRequest` :param option: Action to take. :type option: str of either 'jtlist', 'jtdelete', 'csv', or 'inline'. :returns: :class:`django.htt...
941ab4e3da6273f17f4a180aebe62d35f7133080
26,773
from typing import Sequence from typing import Tuple def find_command(tokens: Sequence[str]) -> Tuple[Command, Sequence[str]]: """Looks up a command based on tokens and returns the command if it was found or None if it wasn't..""" if len(tokens) >= 3 and tokens[1] == '=': var_name = tokens[0] ...
4b46b03f6dd0fb4a6cbcda855029d0a42958a49f
26,774
def clean(df: pd.DataFrame, completelyInsideOtherBias: float = 0.7, filterCutoff: float = 0.65, algo: str = "jaccard", readFromFile: bool = True, writeToFile: bool = True, doBias: bool = True) -> pd.DataFrame: """Main function to completely clean a restaurant dataset. Args: df: a pa...
6c7873958c61bab357abe1d099c57e681c265067
26,775
def create_list(value, sublist_nb, sublist_size): """ Create a list of len sublist_size, filled with sublist_nb sublists. Each sublist is filled with the value value """ out = [] tmp = [] for i in range(sublist_nb): for j in range(sublist_size): tmp.append(value) out....
1ecf6c88390167584d1835430c359a7ed6d6b40b
26,776
import os def before_folder_option(location): """location: folder full path""" if not os.path.exists(location): rpc.create_folder(location) # 如果不存在,通过RPC创建文件夹 rpc.chmod(location, '777', recursive=True) # 通过RPC更改文件夹权限 return True
65e110e10a98cee41fd0af314d9918f4d1daa334
26,777
from datetime import datetime import re def parse_time(date_str: str) -> datetime: """ Parses out a string-formatted date into a well-structured datetime in UTC. Supports any of the following formats: - hh:mm In this format, we treat the value of the hh section to be 24hr format. I...
6009342d1e9c1c3f9b255758adf685e4fe7ca2f0
26,778
def gen_r_cr(): """ Generate the R-Cr table. """ r_cr = [0] * 256 for i in range(256): r_cr[i] = int(1.40199 * (i - 128)) return r_cr
43e014bb62c40d038c5fbd124e834e98e9edb5e3
26,779
def fallible_to_exec_result_or_raise( fallible_result: FallibleProcessResult, description: ProductDescription ) -> ProcessResult: """Converts a FallibleProcessResult to a ProcessResult or raises an error.""" if fallible_result.exit_code == 0: return ProcessResult( stdout=fallible_result...
6b46a78897f0fcbd10e4a0c9b733f1834f638af0
26,780
def tf_pose_to_coords(tf_pose): """Convert TransformStamped to Coordinates Parameters ---------- tf_pose : geometry_msgs.msg.Transform or geometry_msgs.msg.TransformStamped transform pose. Returns ------- ret : skrobot.coordinates.Coordinates converted coordinates. """ ...
3bfaf7d566e90c9ac0c0d8a34060497e2c0c0f78
26,781
def make_graph_indep_graphnet_functions(units, node_or_core_input_size, node_or_core_output_size = None, edge_input_size = None, edge_output_size = None, global_input_size = None, global_output_size = None, aggregation_function = 'mean', **kwargs): "...
63694e7765896d0b369b65d4362edca29b6592d0
26,782
import typing def is_generic(t): """ Checks if t is a subclass of typing.Generic. The implementation is done per Python version, as the typing module has changed over time. Args: t (type): Returns: bool """ # Python 3.6, 3.5 if hasattr(typing, "GenericMeta"): ...
b085d7799ffe034b4bdeccea250d36f4ff372aea
26,783
def getGpsTime(dt): """_getGpsTime returns gps time (seconds since midnight Sat/Sun) for a datetime """ total = 0 days = (dt.weekday()+ 1) % 7 # this makes Sunday = 0, Monday = 1, etc. total += days*3600*24 total += dt.hour * 3600 total += dt.minute * 60 total += dt.second return(tot...
16caa558741d8d65b4b058cf48a591ca09f82234
26,784
from re import T def make_support_transforms(): """ Transforms for support images during inference stage. For transforms of support images during training, please visit dataset.py and dataset_fewshot.py """ normalize = T.Compose([ T.ToTensor(), T.Normalize([0.485, 0.456, 0.406], [...
38d17b780fc8faf6a77074c53ef36733feb1f756
26,785
def single_label_normal_score(y_pred, y_gold): """ this function will computer the score by simple compare exact or not Example 1: y_pred=[1,2,3] y_gold=[2,2,3] score is 2/3 Example 2: it can also compute the score same way but for each label y_pred=[1,2,3,2,3] y_gold=[2,2,3,1,3...
3f906aca6cc5280b932c2dc0a73bfcedad63bd65
26,786
def get_tuning_curves( spike_times: np.ndarray, variable_values: np.ndarray, bins: np.ndarray, n_frames_sample=10000, n_repeats: int = 10, sample_frac: float = 0.4, ) -> dict: """ Get tuning curves of firing rate wrt variables. Spike times and variable values are both in mill...
ecdc4a71cc5a65dbb51dd69ef7a710c8ff596fec
26,787
import functools def _accelerate_update_fn(forward_and_backward_fn, optimizer, n_devices, accelerate=True): """Accelerate the given forward_and_backward_fn function.""" if n_devices == 1: def single_device_update_fn( weights...
2fb96a6d17d5d28882a04914885eacb4f43fac15
26,788
def get_custom_feeds_ip_list(client: PrismaCloudComputeClient) -> CommandResults: """ Get all the BlackListed IP addresses in the system. Implement the command 'prisma-cloud-compute-custom-feeds-ip-list' Args: client (PrismaCloudComputeClient): prisma-cloud-compute client. Returns: ...
bcaf44dcefe0fda10943b29cae5e9ba72e561e27
26,789
from typing import Optional import sys import os def get_dist_egg_link(dist: Distribution) -> Optional[str]: """Is distribution an editable install?""" for path_item in sys.path: egg_link = os.path.join(path_item, dist.project_name + '.egg-link') if os.path.isfile(egg_link): egg_li...
07c49687c7b627e9d511dff9787897b1a562ef22
26,790
import logging def setup_new_file_handler(logger_name, log_level, log_filename, formatter, filter=None): """ Sets up new file handler for given logger :param logger_name: name of logger to which filelogger is added :param log_level: logging level :param log_filename: path to log file :param fo...
1ffd48250d17232eea94f13dd52628993ea04c2e
26,791
import hashlib def _gen_version(fields): """Looks at BotGroupConfig fields and derives a digest that summarizes them. This digest is going to be sent to the bot in /handshake, and bot would include it in its state (and thus send it with each /poll). If server detects that the bot is using older version of th...
0052c655ca355182d0e962e37ae046f63d1a5066
26,792
import os def server_factory(device, count): """ Generate a virtusb server """ controller = VirtualController() controller.devices = [device() for _ in range(count)] server = UsbIpServer(controller) if os.getuid() == 0: #pylint: disable=line-too-long LOGGER.warning('Super user per...
80c58906077e07362275bb6db0eeb27431572c4c
26,793
import logging def get_callee_account(global_state, callee_address, dynamic_loader): """ Gets the callees account from the global_state :param global_state: state to look in :param callee_address: address of the callee :param dynamic_loader: dynamic loader to use :return: Account belonging to ...
28a95b2155b1f72a2683ac7c7029d1d5739305f3
26,794
from typing import Iterable def get_products_with_summaries() -> Iterable[ProductWithSummary]: """ The list of products that we have generated reports for. """ index_products = {p.name: p for p in STORE.all_dataset_types()} products = [ (index_products[product_name], get_product_summary(pr...
0d9e23fecfebd66ba251bc62b750e2d43b20c7fa
26,795
import json import logging from datetime import datetime import asyncio async def events_handler(value: str) -> None: """Consume scan complete events and mark the execution status as FINISHED.""" try: event = json.loads(value) if event["eventId"] != EventId.SCAN_COMPLETE: return No...
e0d7079d83e102f95dbad7549c13202dcc35b17a
26,796
def _round_to_4(v): """Rounds up for aligning to the 4-byte word boundary.""" return (v + 3) & ~3
c79736b4fe9e6e447b59d9ab033181317e0b80de
26,797
import os import sys def cli(dry_run, force, find_links, index_url, extra_index_url, no_index, quiet, user_only, src_files): """Synchronize virtual environment with requirements.txt.""" if not src_files: if os.path.exists(DEFAULT_REQUIREMENTS_FILE): src_files = (DEFAULT_REQUIREMENTS_FILE,)...
33a3253c68dfa315e430684accd9366ba51fff64
26,798
def bool_like(value, name, optional=False, strict=False): """ Convert to bool or raise if not bool_like Parameters ---------- value : object Value to verify name : str Variable name for exceptions optional : bool Flag indicating whether None is allowed strict : b...
42d16ae228140a0be719fbd238bdc25dafc1cb64
26,799