Dataset Viewer
Auto-converted to Parquet Duplicate
content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import re def remove_tags(text, which_ones=(), keep=(), encoding=None): """ Remove HTML Tags only. `which_ones` and `keep` are both tuples, there are four cases: ============== ============= ========================================== ``which_ones`` ``keep`` what it does ============== ==...
3aa9bcab068c35245df022c7b09652a016d5070f
0
def count_char(char, word): """Counts the characters in word""" return word.count(char) # If you want to do it manually try a for loop
363222f4876c5a574a84fe14214760c505e920b0
1
def run_on_folder_evaluate_model(folder_path, n_imgs=-1, n_annotations=10): """ Runs the object detector on folder_path, classifying at most n_imgs images and manually asks the user if n_annotations crops are correctly classified This is then used to compute the accuracy of the model If all images are s...
0c546194a76598d645cfc3cb7dc5fa1fc854aeca
2
def get_sos_model(sample_narratives): """Return sample sos_model """ return { 'name': 'energy', 'description': "A system of systems model which encapsulates " "the future supply and demand of energy for the UK", 'scenarios': [ 'population' ]...
885c251b8bbda2ebc5a950b083faed35c58f41cc
3
from typing import Dict from pathlib import Path from typing import Tuple import codecs def generate_gallery_md(gallery_conf, mkdocs_conf) -> Dict[Path, Tuple[str, Dict[str, str]]]: """Generate the Main examples gallery reStructuredText Start the mkdocs-gallery configuration and recursively scan the examples...
766d6b371b6a2930c546ccc191a00c1eb3009dc1
4
from typing import Union from typing import TextIO from typing import List import yaml def load_all_yaml(stream: Union[str, TextIO], context: dict = None, template_env = None) -> List[AnyResource]: """Load kubernetes resource objects defined as YAML. See `from_dict` regarding how resource types are detected. ...
b3be3b7eb82987849657165e67603b3c701e69cc
5
from typing import Optional from typing import Dict def parse_gridspec(s: str, grids: Optional[Dict[str, GridSpec]] = None) -> GridSpec: """ "africa_10" "epsg:6936;10;9600" "epsg:6936;-10x10;9600x9600" """ if grids is None: grids = GRIDS named_gs = grids.get(_norm_gridspec_name(s)...
4c0cc7dc8237a8232a8fb8d86109172d92678535
6
def make_quantile_normalizer(dist): """Returns f(a) that converts to the quantile value in each col. dist should be an array with bins equally spaced from 0 to 1, giving the value in each bin (i.e. cumulative prob of f(x) at f(i/len(dist)) should be stored in dist[i]) -- can generate from distribution ...
395314821be4349d0c5a3b13058db0d498b03ab5
7
def text(): """ Route that allows user to send json with raw text of title and body. This route expects a payload to be sent that contains: {'title': "some text ...", 'body': "some text ....} """ # authenticate the request to make sure it is from a trusted party verify_token(req...
7bf4a602d603508894c8f86b2febc6d2a6e8e3c3
8
def RPL_ENDOFINFO(sender, receipient, message): """ Reply Code 374 """ return "<" + sender + ">: " + message
02fc0ef666caf7921e4f4a78a908686fd3dded17
10
def combined_score(data, side_effect_weights=None): """ Calculate a top-level score for each episode. This is totally ad hoc. There are infinite ways to measure the performance / safety tradeoff; this is just one pretty simple one. Parameters ---------- data : dict Keys should incl...
9d0161f67de99f10e9d4900114ecf12462fac542
11
def volatile(func): """Wrapper for functions that manipulate the active database.""" def inner(self, *args, **kwargs): ret = func(self, *args, **kwargs) self.refresh() self.modified_db = True return ret return inner
bbd8107ecc6a2b36e3677254d2b26f4ef77c3eb3
12
def input_risk_tolerance(): """ This allows the user to enter and edit their risk tolerance. """ if g.logged_in is True: if g.inputs is True: risk_tolerance_id = m_session.query(model.User).filter_by( id=g.user.id).first().risk_profile_id risk_tolerance = ...
09f9ae246beb8e9a9e901e141e11c29e594cb9c7
13
def check_context(model, sentence, company_name): """ Check if the company name in the sentence is actually a company name. :param model: the spacy model. :param sentence: the sentence to be analysed. :param company_name: the name of the company. :return: True if the company name means a compan...
993c27924844b7cd0c570a9ce5fa404ef6d29b97
15
def getItemSize(dataType): """ Gets the size of an object depending on its data type name Args: dataType (String): Data type of the object Returns: (Integer): Size of the object """ # If it's a vector 6, its size is 6 if dataType.startswith("VECTOR6"): return 6 ...
2ab9c83bef56cd8dbe56c558d123e24c9da6eb0e
16
def replace_symbol_to_no_symbol(pinyin): """把带声调字符替换为没有声调的字符""" def _replace(match): symbol = match.group(0) # 带声调的字符 # 去掉声调: a1 -> a return RE_NUMBER.sub(r'', PHONETIC_SYMBOL_DICT[symbol]) # 替换拼音中的带声调字符 return RE_PHONETIC_SYMBOL.sub(_replace, pinyin)
a4c3d1a91fedf20016fb4c8b671326ad8cac008c
17
from pyclustering.cluster.kmeans import kmeans from pyclustering.cluster.center_initializer import kmeans_plusplus_initializer from pyclustering.cluster.elbow import elbow from pyclustering.cluster.kmeans import kmeans_visualizer def elbow_kmeans_optimizer(X, k = None, kmin = 1, kmax = 5, visualize = True): """k-...
53fe501367e85c3d345d0bebdfdccff17e8b93db
18
import time def FloatDateTime(): """Returns datetime stamp in Miro's REV_DATETIME format as a float, e.g. 20110731.123456""" return float(time.strftime('%Y%m%d.%H%M%S', time.localtime()))
115aef9104124774692af1ba62a48a5423b9dc2a
19
def xyz_to_rgb(xyz): """ Convert tuple from the CIE XYZ color space to the sRGB color space. Conversion is based on that the XYZ input uses an the D65 illuminate with a 2° observer angle. https://en.wikipedia.org/wiki/Illuminant_D65 The inverse conversion matrix used was provided by Bruce Lindbloo...
0c227f7d0ead08afdd0a3dd7946d45ad0cae011b
20
import numbers def _score(estimator, X_test, y_test, scorer, is_multimetric=False): """Compute the score(s) of an estimator on a given test set. Will return a single float if is_multimetric is False and a dict of floats, if is_multimetric is True """ if is_multimetric: return _multimetric...
1b3c136098e625968664518940769678d978aca4
21
import functools def asynchronous(datastore=False, obj_store=False, log_store=False): """Wrap request handler methods with this decorator if they will require asynchronous access to DynamoDB datastore or S3 object store for photo storage. If datastore=True, then a DynamoDB client is available to the handler as...
2bef0ba95993a4114ecb28b99a2952e2d269b54a
22
def get_translatable_models(): """ Get the translatable models according to django-modeltranslation !! only use to migrate from django-modeltranslation !! """ _raise_if_not_django_modeltranslation() return translator.get_registered_models()
b22ca513d3d29dfc7c2d3502cabdcf95e2e4bce9
23
def schedule_dense_arm_cpu(attrs, inputs, out_type, target): """dense arm cpu strategy""" strategy = _op.OpStrategy() isa = arm_isa.IsaAnalyzer(target) if isa.has_dsp_support: strategy.add_implementation( wrap_compute_dense(topi.nn.dense), wrap_topi_schedule(topi.arm_cpu....
45b800ceecc14dd62734159d05baa8273cc4c3ff
24
def default_select(identifier, all_entry_points): # pylint: disable=inconsistent-return-statements """ Raise an exception when we have ambiguous entry points. """ if len(all_entry_points) == 0: raise PluginMissingError(identifier) elif len(all_entry_points) == 1: return all_entry_...
331ca0108f05e97fcbec95e40111ca6eb5aa835b
25
import json def read_prediction_dependencies(pred_file): """ Reads in the predictions from the parser's output file. Returns: two String list with the predicted heads and dependency names, respectively. """ heads = [] deps = [] with open(pred_file, encoding="utf-8") as f: for line...
c8280c861d998d0574fb831cd9738b733fd53388
26
def add_new_ingredient(w, ingredient_data): """Adds the ingredient into the database """ combobox_recipes = generate_CBR_names(w) combobox_bottles = generate_CBB_names(w) given_name_ingredient_data = DB_COMMANDER.get_ingredient_data(ingredient_data["ingredient_name"]) if given_name_ingredient_data: ...
ea0cbc371502d84223aeec5c18e2f19a020e229a
27
def detect_entities(_inputs, corpus, threshold=None): """ Détecte les entités nommées sélectionnées dans le corpus donné en argument. :param _inputs: paramètres d'entrainement du modèle :param corpus: corpus à annoter :param threshold: seuils de détection manuels. Si la probabilité d'une catégorie d...
1d7dc2ef42a9961daee6260c9fb6b9b2f099e96f
28
def request_video_count(blink): """Request total video count.""" url = "{}/api/v2/videos/count".format(blink.urls.base_url) return http_get(blink, url)
d847d840892908a66f99fae95b91e78b8ddc7dcb
29
def version(): """Return a ST version. Return 0 if not running in ST.""" if not running_in_st(): return 0 return int(sublime.version())
d4f51b0a91301a8cdadff126931e7f0e72b8c850
30
def get_intervention(action, time): """Return the intervention in the simulator required to take action.""" action_to_intervention_map = { 0: Intervention(time=time, epsilon_1=0.0, epsilon_2=0.0), 1: Intervention(time=time, epsilon_1=0.0, epsilon_2=0.3), 2: Intervention(time=time, epsilo...
11c145efc3eb9e7bafc05943294232c161b59952
32
def draw_labeled_bboxes(img, labels): """ Draw the boxes around detected object. """ # Iterate through all detected cars for car_number in range(1, labels[1]+1): # Find pixels with each car_number label value nonzero = (labels[0] == car_number).nonzero() # Identify x and ...
7bf9a3a5a54a41c49845408d5e04dc5de67eea6c
33
def calc_diff(nh_cube, sh_cube, agg_method): """Calculate the difference metric""" metric = nh_cube.copy() metric.data = nh_cube.data - sh_cube.data metric = rename_cube(metric, 'minus sh ' + agg_method) return metric
3eb62be75af265bd2fa7323c6c23e3735e1c87be
35
def median_boxcar_filter(data, window_length=None, endpoints='reflect'): """ Creates median boxcar filter and deals with endpoints Parameters ---------- data : numpy array Data array window_length: int A scalar giving the size of the median filter window endpoints : str ...
1782998bad2ab02c628d8afbc456c1bea4c2533c
36
import ray import threading def test_threaded_actor_api_thread_safe(shutdown_only): """Test if Ray APIs are thread safe when they are used within threaded actor. """ ray.init( num_cpus=8, # from 1024 bytes, the return obj will go to the plasma store. _system_config={"max_direct...
f3fd0d4c2621e69c348b734040c7bd49f1f1578b
37
from typing import Optional def build_template_context( title: str, raw_head: Optional[str], raw_body: str ) -> Context: """Build the page context to insert into the outer template.""" head = _render_template(raw_head) if raw_head else None body = _render_template(raw_body) return { 'page...
38bf538c0c979b6e0aaba1367458140028332385
38
def inf_set_stack_ldbl(*args): """ inf_set_stack_ldbl(_v=True) -> bool """ return _ida_ida.inf_set_stack_ldbl(*args)
2b343bb66229f6ba5f834b3d543fcd75ad08875c
39
def _get_self_compatibility_dict(package_name: str) -> dict: """Returns a dict containing self compatibility status and details. Args: package_name: the name of the package to check (e.g. "google-cloud-storage"). Returns: A dict containing the self compatibility status and deta...
ca29593d3d5941f576a2d033f5754902828a1138
40
def checksum_md5(filename): """Calculates the MD5 checksum of a file.""" amd5 = md5() with open(filename, mode='rb') as f: for chunk in iter(lambda: f.read(128 * amd5.block_size), b''): amd5.update(chunk) return amd5.hexdigest()
80cd2bf43274ea060a4d5001d6a319fae59b1e94
41
def CleanGrant(grant): """Returns a "cleaned" grant by rounding properly the internal data. This insures that 2 grants coming from 2 different sources are actually identical, irrespective of the logging/storage precision used. """ return grant._replace(latitude=round(grant.latitude, 6), ...
648bb0a76f9a7cfe355ee8ffced324eb6ceb601e
42
def OpenRegistryKey(hiveKey, key): """ Opens a keyHandle for hiveKey and key, creating subkeys as necessary """ keyHandle = None try: curKey = "" keyItems = key.split('\\') for subKey in keyItems: if curKey: curKey = curKey + "\\" + subKey else...
d7555a752a08ed0e7bfedbb77583aed9e5b26fe1
43
import multiprocessing def eval_py(input_text: str): """Runs eval() on the input text on a seperate process and returns output or error. How to timout on a function call ? https://stackoverflow.com/a/14924210/13523305 Return a value from multiprocess ? https://stackoverflow.com/a/10415215/13523305 """...
1058f2877e00370fa4600cf2bcfb334149347cba
44
def trim(str): """Remove multiple spaces""" return ' '.join(str.strip().split())
ed98f521c1cea24552959aa334ffb0c314b9f112
45
def build_model_svr(model_keyvalue, inputs, encoder = None, context = None): """Builds model from, seal_functions, model params. model_keyvalue: key identifying model inputs: properly formatted encrypted inputs for model encoder: SEAL encoder object context: SEAL context object "...
0e36d94c5305aa55523d76d2f8afac17b9c7d9b0
46
def find_similar(collection): """ Searches the collection for (probably) similar artist and returns lists containing the "candidates". """ spellings = defaultdict(list) for artist in collection: spellings[normalize_artist(artist)].append(artist) return [spellings[artist] for artist in ...
c11f93d0da7ff27f89c51d1d255d75e31c6c539f
47
def vim_print(mse_ref, mse_values, x_name, ind_list=0, with_output=True, single=True, partner_k=None): """Print Variable importance measure and create sorted output. Parameters ---------- mse_ref : Numpy Float. Reference value of non-randomized x. mse_values : Numpy array. MSE's for r...
4c7eef9dc15d50b904dfe3df51586d77af70d776
48
def from_column_list( col_names, col_types=None, col_blobs=None, col_metadata=None ): """ Given a list of names, types, and optionally values, construct a Schema. """ if col_types is None: col_types = [None] * len(col_names) if col_metadata is None: col_metadata = [None] * le...
22fc57657bc144304ef0afbdd74acf9ed63faba0
49
import torch def get_optimizer(lr): """ Specify an optimizer and its parameters. Returns ------- tuple(torch.optim.Optimizer, dict) The optimizer class and the dictionary of kwargs that should be passed in to the optimizer constructor. """ return (torch.optim.SGD, ...
213090258414059f7a01bd40ecd7ef04158d60e5
50
def _from_list(data: any) -> dict: """Convert lists to indexed dictionaries. :arg data: An ordered map. :returns: An ordered map. """ if isinstance(data, list): return dict([(str(i), _from_list(v)) for i, v in enumerate(data)]) if isinstance(data, dict): return dict([(key, _fro...
06c757276edbc013c4094872f4063077cec2c589
51
def parse_date(ses_date): """This parses a date string of the form YYYY-MM-DD and returns the string, year, month, day and day of year.""" [yr,mn,dy] = ses_date.split('-') year = int(yr) month = int(mn) day = int(dy[:2]) # strip of any a or b DOY = day_of_year(year,month,day) return ses_date,year,month,...
a8105f9f39869402863f14a1d68ff37a7f25ed74
52
import requests import json def get_access_token(consumer_key, consumer_secret): """ :return: auth token for mpesa api calls """ oauth_url = "https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials" response = requests.get(oauth_url, auth=HTTPBasicAuth(consumer_key, consumer_s...
15d09439d0b6e135c4f87958fe116e686c38cca2
53
def create_feed_forward_dot_product_network(observation_spec, global_layers, arm_layers): """Creates a dot product network with feedforward towers. Args: observation_spec: A nested tensor spec containing the specs for global as well as per-arm observations. ...
ed4e95ce10859e976800fd88b6caceffd6ca09a2
54
import logging def check_collisions(citekeys_df): """ Check for short_citekey hash collisions """ collision_df = citekeys_df[['standard_citekey', 'short_citekey']].drop_duplicates() collision_df = collision_df[collision_df.short_citekey.duplicated(keep=False)] if not collision_df.empty: ...
b01b53323f7885a7375ba78b50222bcbe9980498
55
def get_user(module, system): """Find a user by the user_name specified in the module""" user = None user_name = module.params['user_name'] try: user = system.users.get(name=user_name) except ObjectNotFound: pass return user
f674352998e444a184ab2a2a6a2caedc35611e49
56
def appointments(request): """Page for users to view upcoming appointments.""" appointments = Appointment.objects.filter(patient=request.user.patient) context = { 'appointments': appointments } return render(request, 'patients/appointments.html', context)
ad7bab85db19f907631a8c9e25b65048abab7e6b
57
def _SignedVarintDecoder(mask): """Like _VarintDecoder() but decodes signed values.""" local_ord = ord def DecodeVarint(buffer, pos): result = 0 shift = 0 while 1: b = local_ord(buffer[pos]) result |= ((b & 0x7f) << shift) pos += 1 if not (b & 0x80): if result > 0x7fff...
de88a082cc90f6370674723173f4c75ee7025f27
58
def is_valid_msg_type(x): """ @return: True if the name is a syntatically legal message type name @rtype: bool """ if not x or len(x) != len(x.strip()): return False base = base_msg_type(x) if not roslib.names.is_legal_resource_name(base): return False # parse array indic...
ca6b6b2e62ffa26a795cbbccab01667a8ce9470e
59
def get_ascii_matrix(img): """(Image) -> list of list of str\n Takes an image and converts it into a list of list containing a string which maps to brightness of each pixel of each row """ ascii_map = "`^\",:;Il!i~+_-?][}{1)(|\\/tfjrxnuvczXYUJCLQ0OZmwqpdbkhao*#MW&8%B@$" brightness_matrix = get...
e8b6a160fc082a868267971937e56e2f6a1eb9e4
60
from typing import List from typing import Dict from typing import Any def to_scene_agent_prediction_from_boxes_separate_color( tracked_objects: TrackedObjects, color_vehicles: List[int], color_pedestrians: List[int], color_bikes: List[int] ) -> List[Dict[str, Any]]: """ Convert predicted observations int...
728d471fbc15957c57f4b3a6da68bfffdbf875ac
61
def stretch(snd_array, factor, window_size, h): """ Stretches/shortens a sound, by some factor. """ phase = np.zeros(window_size) hanning_window = np.hanning(window_size) result = np.zeros( len(snd_array) /factor + window_size) for i in np.arange(0, len(snd_array)-(window_size+h), h*factor): ...
aeb12b6da26de9630eec9ad84caf9f30bd6f1f71
62
def guess_encoding(text): """ Given bytes, determine the character set encoding @return: dict with encoding and confidence """ if not text: return {'confidence': 0, 'encoding': None} enc = detect_charset(text) cset = enc['encoding'] if cset.lower() == 'iso-8859-2': # Anomoaly -- ch...
f58d652b7a77652ace1c27b315fc81ac82726a03
63
def is_edit_end_without_next(line, configs): """ Is the line indicates that 'edit' section ends without 'next' end marker (special case)? - config vdom edit <name> ... end :param line: A str represents a line in configurations output :param configs: A stack (list) holding c...
0398fc86ee7911686bfdaa0cdf6431f53db1ccba
64
def get_live_args(request, script=False, typed=False): """ Get live args input by user | request --> [[str], [str]]""" arg_string = list(request.form.values())[0] if script: return parse_command_line_args(arg_string) if typed: try: all_args = parse_type_args(arg_string) ...
9e56043760e9ac263a737166c796640170a6174c
65
import codecs import csv def open_csv(path): """open_csv.""" _lines = [] with codecs.open(path, encoding='utf8') as fs: for line in csv.reader(fs): if len(line) == 3: _lines.append(line) return _lines
501ff4a2a1a242439c21d3131cecd407dcfa36af
66
from typing import Union from pathlib import Path from typing import Dict def parse_metadata(metadata_filepath: Union[str, Path]) -> Dict: """Parse the metadata file retreived from the BEACO2N site Args: metadata_filepath: Path of raw CSV metadata file pipeline: Are we running as part of the ...
321e9abb82172ee7d06423d2703ec2499aefbee9
67
def unit_norm(model,axis=0): """ Constrains the weights incident to each hidden unit to have unit norm. Args: axis (int):axis along which to calculate weight norms. model : the model contains weights need to setting the constraints. """ def apply_constraint(t: Tensor): w_d...
ffe517f2f883541d5d3736a2bb3263e6349ffe18
68
def responsive_units(spike_times, spike_clusters, event_times, pre_time=[0.5, 0], post_time=[0, 0.5], alpha=0.05): """ Determine responsive neurons by doing a Wilcoxon Signed-Rank test between a baseline period before a certain task event (e.g. stimulus onset) and a period after the tas...
10493948d8fc710a95e1267b4543bc63cdebc661
69
def create_link(seconds, image_name, size): """ Function returns temporary link to the image """ token = signing.dumps([str(timezone.now() + timedelta(seconds=int(seconds))), image_name, size]) return settings.SERVER_PATH + reverse("image:dynamic-image", kwargs={"token": token})
e0ede3b6a28e1bfa3a69d8019b0141cd85b77cce
70
def read_one_hot_labels(filename): """Read topic labels from file in one-hot form :param filename: name of input file :return: topic labels (one-hot DataFrame, M x N) """ return pd.read_csv(filename, dtype=np.bool)
df6f0be241c8f5016ff66d02a54c899298055bd7
71
def make_randint_list(start, stop, length=10): """ Makes a list of randomly generated integers Args: start: lowest integer to be generated randomly. stop: highest integer to be generated randomly. length: length of generated list. Returns: list of random numbers between sta...
6ac9a20b9c5c87d9eff2b13a461cf266381961e2
72
def merge(intervals: list[list[int]]) -> list[list[int]]: """Generate a new schedule with non-overlapping intervals by merging intervals which overlap Complexity: n = len(intervals) Time: O(nlogn) for the initial sort Space: O(n) for the worst case of no overlapping intervals ...
49a9d7d461ba67ec3b5f839331c2a13d9fc068d0
73
def df_drop_duplicates(df, ignore_key_pattern="time"): """ Drop duplicates from dataframe ignore columns with keys containing defined pattern. :param df: :param noinfo_key_pattern: :return: """ ks = df_drop_keys_contains(df, ignore_key_pattern) df = df.drop_duplicates(ks) return d...
babd7be3ef66cef81a5a2192cf781afd2f96aca9
74
def get_mediawiki_flow_graph(limit, period): """ :type limit int :type period int :rtype: list[dict] """ # https://kibana5.wikia-inc.com/goto/e6ab16f694b625d5b87833ae794f5989 # goreplay is running in RES (check SJC logs only) rows = ElasticsearchQuery( es_host=ELASTICSEARCH_HOST,...
c82976c24d80f7784f32e36666f791fed4ada769
75
def bsplslib_Unperiodize(*args): """ :param UDirection: :type UDirection: bool :param Degree: :type Degree: int :param Mults: :type Mults: TColStd_Array1OfInteger & :param Knots: :type Knots: TColStd_Array1OfReal & :param Poles: :type Poles: TColgp_Array2OfPnt :param Weight...
0fad8703881304c9d169feb4ce58f31b29d1703b
76
def genomic_del3_abs_37(genomic_del3_37_loc): """Create test fixture absolute copy number variation""" return { "type": "AbsoluteCopyNumber", "_id": "ga4gh:VAC.Pv9I4Dqk69w-tX0axaikVqid-pozxU74", "subject": genomic_del3_37_loc, "copies": {"type": "Number", "value": 2} }
ed417f1b0eba79a5db717bd16ca79dd85c55c381
77
def get_configinfo(env): """Returns a list of dictionaries containing the `name` and `options` of each configuration section. The value of `options` is a list of dictionaries containing the `name`, `value` and `modified` state of each configuration option. The `modified` value is True if the value d...
c96b784f389af7c043977fbc1707840ef56a6486
79
def given_energy(n, ef_energy): """ Calculate and return the value of given energy using given values of the params How to Use: Give arguments for ef_energy and n parameters *USE KEYWORD ARGUMENTS FOR EASY USE, OTHERWISE IT'LL BE HARD TO UNDERSTAND AN...
98095581bfaf4b8a6dbf59dce86b02e3f1fa6002
80
def sequence_sigmoid_cross_entropy(labels, logits, sequence_length, average_across_batch=True, average_across_timesteps=False, average_across_cla...
7eaea7dc8c416f0a37f0d6668ec175725f1fea04
81
import math import torch def stats(func): """Stats printing and exception handling decorator""" def inner(*args): try: code, decoded, res = func(*args) except ValueError as err: print(err) else: if FORMATTING: code_length = 0 ...
99e39e204238d09bd7275ac29089898ff3d22f6a
82
import asyncio async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" unload_ok = all( await asyncio.gather( *[ hass.config_entries.async_forward_entry_unload(entry, platform) for platform in PLATFORMS ...
f44f9d9f3a566794547571563ae94ce433082d6d
83
def get_ucp_worker_info(): """Gets information on the current UCX worker, obtained from `ucp_worker_print_info`. """ return _get_ctx().ucp_worker_info()
c40a0debcc769422b4cd8cd03018b57dd7efe224
84
from datetime import datetime def check_can_collect_payment(id): """ Check if participant can collect payment this is true if : - They have been signed up for a year - They have never collected payment before or their last collection was more than 5 months ago """ select = "SELECT time_sign_up...
a057b6599bfd5417a17de1672b4ccf2023991e6e
85
def plus_tensor(wx, wy, wz=np.array([0, 0, 1])): """Calculate the plus polarization tensor for some basis.c.f., eq. 2 of https://arxiv.org/pdf/1710.03794.pdf""" e_plus = np.outer(wx, wx) - np.outer(wy, wy) return e_plus
c5632dcfffa9990c8416b77ff0df728ae46c34bc
86
import json def duplicate_objects(dup_infos): """Duplicate an object with optional transformations. Args: dup_infos (list[dict]): A list of duplication infos. Each info is a dictionary, containing the following data: original (str): Name of the object to duplicate. ...
d8281eb6862cd7e022907bc479b03fc74cb3c78c
87
def _list_data_objects(request, model, serializer): """a factory method for querying and receiving database objects""" obj = model.objects.all() ser = serializer(obj, many=True) return Response(ser.data, status=status.HTTP_200_OK)
80f43efdf1d09e73fda7be8ee5f8e37a163892f7
88
import configparser def load_conf(file='./config', section='SYNTH_DATA'): """load configuration Args: file (str, optional): path to conf file. Defaults to './config'. section (str, optional): name of section. Defaults to 'SYNTH_DATA'. Returns: [str]: params of configurat...
a30240e98d9fd1cdc1bc7746566fdb07b842a8dc
89
import math def distance(a, b): """ Computes a :param a: :param b: :return: """ x = a[0] - b[0] y = a[1] - b[1] return math.sqrt(x ** 2 + y ** 2)
60b637771cd215a4cf83761a142fb6fdeb84d96e
90
def approve_pipelines_for_publishing(pipeline_ids): # noqa: E501 """approve_pipelines_for_publishing :param pipeline_ids: Array of pipeline IDs to be approved for publishing. :type pipeline_ids: List[str] :rtype: None """ pipe_exts: [ApiPipelineExtension] = load_data(ApiPipelineExtension) ...
e5ae4dfc0889fc95e3343a01111323eec43e1f93
91
def make_tokenizer_module(tokenizer): """tokenizer module""" tokenizers = {} cursors = {} @ffi.callback("int(int, const char *const*, sqlite3_tokenizer **)") def xcreate(argc, argv, ppTokenizer): if hasattr(tokenizer, "__call__"): args = [ffi.string(x).decode("utf-8") for x in a...
73f38b71f15b286a95a195296c5c265ba2da87f9
92
def looping_call(interval, callable): """ Returns a greenlet running your callable in a loop and an Event you can set to terminate the loop cleanly. """ ev = Event() def loop(interval, callable): while not ev.wait(timeout=interval): callable() return gevent.spawn(loop, in...
0df2a822c2eb56b8479224b0463bf9a2ad34f1e7
93
def rsquared_adj(r, nobs, df_res, has_constant=True): """ Compute the adjusted R^2, coefficient of determination. Args: r (float): rsquared value nobs (int): number of observations the model was fit on df_res (int): degrees of freedom of the residuals (nobs - number of model params...
8d466437db7ec9de9bc7ee1d9d50a3355479209d
94
def metadata_factory(repo, json=False, **kwargs): """ This generates a layout you would expect for metadata storage with files. :type json: bool :param json: if True, will return string instead. """ output = { "baseline_filename": None, "crontab": "0 0 * * *", "exclude_r...
8dc0cd4cb5aa194c915146efbe0a743b5047561d
95
from typing import Optional from typing import Sequence def inpand(clip: vs.VideoNode, sw: int, sh: Optional[int] = None, mode: XxpandMode = XxpandMode.RECTANGLE, thr: Optional[int] = None, planes: int | Sequence[int] | None = None) -> vs.VideoNode: """ Calls std.Minimum in order to shrink each pix...
67d05b2ef31fdc3b544d063a571d39a1c1a3ecf8
96
def _extract_aggregate_functions(before_aggregate): """Converts `before_aggregate` to aggregation functions. Args: before_aggregate: The first result of splitting `after_broadcast` on `intrinsic_defs.FEDERATED_AGGREGATE`. Returns: `zero`, `accumulate`, `merge` and `report` as specified by `can...
22aff3c077b94c5eae8841448c2a55bbfa311487
97
def _make_system(A, M, x0, b): """Make a linear system Ax = b Args: A (cupy.ndarray or cupyx.scipy.sparse.spmatrix or cupyx.scipy.sparse.LinearOperator): sparse or dense matrix. M (cupy.ndarray or cupyx.scipy.sparse.spmatrix or cupyx.scipy.sparse.LinearOperator): precond...
37d877dc8522a476c1ff0be34db01fe8d711dbb7
98
from typing import List def merge_intersecting_segments(segments: List[Segment]) -> List[Segment]: """ Merges intersecting segments from the list. """ sorted_by_start = sorted(segments, key=lambda segment: segment.start) merged = [] for segment in sorted_by_start: if not merged: ...
e18498d9a9695b2c5796fb6e006f375541f704c7
99
def change_log_root_key(): """Root key of an entity group with change log.""" # Bump ID to rebuild the change log from *History entities. return ndb.Key('AuthDBLog', 'v1')
465ab46b7e884d7f5e217861d6c451c491e04f07
100
import numpy def load_file(filename): """Loads a TESS *spoc* FITS file and returns TIME, PDCSAP_FLUX""" hdu = fits.open(filename) time = hdu[1].data['TIME'] flux = hdu[1].data['PDCSAP_FLUX'] flux[flux == 0] = numpy.nan return time, flux
50c777903b26c658c828346af53e3a659d1eb46b
101
def create_insight_id_extension( insight_id_value: str, insight_system: str ) -> Extension: """Creates an extension for an insight-id with a valueIdentifier The insight id extension is defined in the IG at: https://alvearie.io/alvearie-fhir-ig/StructureDefinition-insight-id.html Args: ...
72b000cdc3903308ca8692c815e562511fd50b91
102
def ReadNotifyResponseHeader(payload_size, data_type, data_count, sid, ioid): """ Construct a ``MessageHeader`` for a ReadNotifyResponse command. Read value of a channel. Sent over TCP. Parameters ---------- payload_size : integer Size of DBR formatted data in payload. data_type ...
5d088416f5fca6e0aeb3ef1f965ca7c00d8a6c90
103
def substitute_T5_cols(c, cols, nlu_identifier=True): """ rename cols with base name either <t5> or if not unique <t5_<task>> """ new_cols = {} new_base_name = 't5' if nlu_identifier=='UNIQUE' else f't5_{nlu_identifier}' for col in cols : if '_results' in col : new_cols[col] = n...
2820706faff786011abbd896551026c65bb0d848
104
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
35