content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import TextIO from typing import Set def observe_birds(observations_file: TextIO) -> Set[str]: """Return a set of the bird species listed in observations_file, which has one bird species per line. >>> file = StringIO("bird 1\\nbird 2\\nbird 1\\n") >>> birds = observe_birds(file) >>> 'bird...
e3ea90e8da4488121ec1ae75c4aa116646db08f5
18,200
def convert_sheet(sheet, result_dict, is_enum_mode=False): """ 转换单个sheet的数据 Args: sheet: openpyxl.worksheet.worksheet.Worksheet result_dict: [dict]结果都存在这里, key为data_name,value为sheet_result is_enum_mode: [bool]是否为enum导表模式 Returns: bool, 是否成功 """ if is_enum_mode: ...
284f470844b6722941d0e4725e4c23b1473b08df
18,201
from __main__ import __file__ as main_script_path import os def _nsimage_from_file(filename, dimensions=None, template=None): """Take a path to an image file and return an NSImage object.""" try: _log('attempting to open image at {0}'.format(filename)) with open(filename): pass ...
079556d6959c6344feb8fa25db3467d4468124d0
18,202
def bytes_to_int(b: bytes, order: str = 'big') -> int: """Convert bytes 'b' to an int.""" return int.from_bytes(b, order)
c959683787e03cc956b5abffc814f98cf4722397
18,203
def fit_model(params,param_names,lam_gal,galaxy,noise,gal_temp, feii_tab,feii_options, temp_list,temp_fft,npad,line_profile,fwhm_gal,velscale,npix,vsyst,run_dir, fit_type,output_model): """ Constructs galaxy model by convolving templates with a LOSVD given by a specified set of velocity parameters. ...
44cd0bc61a4472c6a5c3c7b190ee5be96f4bdb1a
18,204
import random def generate_numbers(): """ Function to generate 3 random digits to be guessed. Generate 3 random in a list in order to be compare to the user's digits. Return: str_digits (Array): List with 3 random digits converted to String """ # List comprehension to generate num...
8efd0f579a3a0b3dc5021cd762f9ad2f5774f6be
18,205
def get_media(): """Retrieves metadata for all of this server's uploaded media. Can use the following query parameters: * max: The maximum number of records to return * page: The page of records """ error_on_unauthorized() media = Upload.query.order_by(Upload.id) total_num = media.cou...
754417b47f5b9c28427b04ace88bf9ca5c9a5a47
18,206
def summate2(phasevec): """Calculate values b'(j^vec) for combining 2 phase vectors. Parameter: phasevec: tuple of two phasevectors Example: On input (([b_1(0),b_1(1),...,b_1(L-1)], L), ([b_2(0),b_2(1),...,b_2(L'-1)], L')) give output [b_1(0)+b_2(0), b_1(0)+b_2(1),..., b_1(1)+b_2(0),...,b_1(L-...
5150c2ee29a31438bf16104eaadeb85a01f54502
18,207
def get_children(): """ Return IDs of LIST which currently is zero-based index Modelled after treeview for future alphabetic IDs TODO: Should probably return list of all DICT? """ iid_list = [] #read() #print('location.get_children() LIST count:',len(LIST)) for i, ndx in enumera...
14e855df5c2b218c68e900709fd548d3431c4a8b
18,208
def makeTracker( path, args = (), kwargs = {} ): """retrieve an instantiated tracker and its associated code. returns a tuple (code, tracker). """ obj, module, pathname, cls = makeObject( path, args, kwargs ) code = getCode( cls, pathname ) return code, obj
bc23e21bb53357bcf74e6194656cfbea4b24c218
18,209
from typing import Tuple def get_anchor_generator(anchor_size: Tuple[tuple] = None, aspect_ratios: Tuple[tuple] = None): """Returns the anchor generator.""" if anchor_size is None: anchor_size = ((16,), (32,), (64,), (128,)) if aspect_ratios is None: aspect_ratios = ((0.5, 1.0, 2.0),) * le...
e9eef959c009062d5866558d00674c1afa033260
18,210
import torch def tensor_to_longs(tensor: torch.Tensor) -> list: """converts an array of numerical values to a tensor of longs""" assert tensor.dtype == torch.long return tensor.detach().cpu().numpy()
ba1788be8e353936cfc3d604d940b78a96990fd4
18,211
def test_fixed(SNRs): """ Fixed (infinite T1) qubit. """ fidelities = [] numShots = 10000 dt = 1e-3 for SNR in SNRs: fakeData = create_fake_data(SNR, dt, 1, numShots, T1=1e9) signal = dt*np.sum(fakeData, axis=1) fidelities.append(fidelity_est(signal)) return fidelities
70ca68f475beed73a47722c719811544ae1bfccb
18,212
def setup(app): """ Add the ``fica`` directive to the Sphinx app. """ app.add_directive("fica", FicaDirective) return { "version": __version__, "parallel_read_safe": True, "parallel_write_safe": True, }
996e568ab58634e64a845b34bf38082658b58889
18,213
from typing import Tuple import torch def get_binary_statistics( outputs: Tensor, targets: Tensor, label: int = 1, ) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor]: """ Computes the number of true negative, false positive, false negative, true negative and support for a binary classification pro...
e0c81b404f6da77f40c1e4f3810d699fdef1e6a4
18,214
def threshold_and_mask(min_normed_weight, W, Mc, coords): # =np.arange(Wc.shape[0])*stride + start): """Normalize the weights W, threshold to min_normed_weight and remove diagonal, reduce DX and DY to the columns and rows still containing weights. Returns ------- coords : array_like the in...
78d361cf2125cd0d3ac1a3985933e39b09538b18
18,215
import csv def readCGcsv(filename, levels): """ Read a .csv file of a callgraph into a dictionary keyed by callgraph level. """ cgdict = {} with open(filename, "r") as cgcsv: cgreader = csv.DictReader(cgcsv) for row in cgreader: lvl = int(row['Level']) if (lvl < l...
ec5dbc3d064a0cf784bfd764b996eb36677642a9
18,216
def use_colors(tones, i=None): """ Use specific color tones for plotting. If i is specified, this function returns a specific color from the corresponding color cycle For custom color palettes generation check: http://colorbrewer2.org/#type=sequential&scheme=YlGnBu&n=8 Args: tones : 'hot' or 'co...
e36cce208c89178af8199662edb336c2455bdc37
18,217
def fill_form(forms, form): """Fills a given form given a set or known forms. :param forms: A set of known forms. :param form: The form to fill. :return: A mapping from form element IDs to suggested values for the form. """ forms = list(forms) new_form = {} def rec_fill_form(form, lab...
3e6c1f623facb67602fa5e057080a08d0de9926d
18,218
def read_sky_model_from_csv(path: str) -> SkyModel: """ Read a CSV file in to create a SkyModel. The CSV should have the following columns - right ascension (deg) - declination (deg) - stokes I Flux (Jy) - stokes Q Flux (Jy): if no information available, set to 0 - stokes U Flux (Jy): i...
b649bd1cfd218a924c573bf90b26fa18f62c3cb4
18,219
def integer_to_vector(x, options_per_element, n_elements, index_to_element): """Return a vector representing an action/state from a given integer. Args: x (int): the integer to convert. n_options_per_element(int): number of options for each element in the vector. n_elements (int): the n...
2649359d6a62b047f70bfe72f8403e8343a231ab
18,220
def samples_for_each_class(dataset_labels, task): """ Numbers of samples for each class in the task Args: dataset_labels Labels to count samples from task Labels with in a task Returns """ num_samples = np.zeros([len(task)], dtype=np.float32) i = 0 for label ...
96bc2c794fd955110864f59ddb96c5df1c33b8ed
18,221
def requiredOneInGroup(col_name, group, dm, df, *args): """ If col_name is present in df, the group validation is satisfied. If not, it still may be satisfied, but not by THIS col_name. If col_name is missing, return col_name, else return None. Later, we will validate to see if there is at least one...
de46a4ef2f3e45381644db41d617d8c4c0845877
18,222
def persist(session, obj, return_id=True): """ Use the session to store obj in database, then remove obj from session, so that on a subsequent load from the database we get a clean instance. """ session.add(obj) session.flush() obj_id = obj.id if return_id else None # save this before obj i...
a308931f418616417d10d3115b0f370352778533
18,223
from unittest.mock import patch def test_bittrex_query_asset_movement_int_transaction_id(bittrex): """Test that if an integer is returned for bittrex transaction id we handle it properly Bittrex deposit withdrawals SHOULD NOT return an integer for transaction id according to their docs https://bittrex.gi...
83e3ce3d8f82b159191c6b9068b54321d06bfa9a
18,224
from typing import Sequence import logging def _fixed_point( searcher: 'AbstractSearcher', parsed: parsed_file.ParsedFile, initial_substitutions: Sequence[substitution.Substitution], start: int, end: int, max_iterations: int, ): """Repeatedly apply searcher until there are no more changes.""...
676102d43f965750d497dbbbbc3e87264de7a6d2
18,225
from operator import sub def masker(mask, val): """Enforce the defined bits in the <mask> on <val>.""" ones = sub(r"[^1]", "0", mask) val |= int(ones,2) zeros = sub(r"[^0]", "1", mask) val &= int(zeros,2) return val
68b3edd542b295ca7aade0eb9829e310e4c0ed2d
18,226
def ct_lt_u32(val_a, val_b): """ Returns 1 if val_a < val_b, 0 otherwise. Constant time. :type val_a: int :type val_b: int :param val_a: an unsigned integer representable as a 32 bit value :param val_b: an unsigned integer representable as a 32 bit value :rtype: int """ val_a &= 0xf...
6816fd1e9633c0c3035d68ac657f3cb917f24527
18,227
import typing async def is_banned(ctx: Context, user: typing.Union[discord.Member, discord.User]) -> bool: """Returns true if user is in guild's ban list.""" bans = await ctx.guild.bans() for entry in bans: if entry.user.id == user.id: return True return False
2807e2d9a296afb360efe9abf9618e0ebe19e796
18,228
from typing import List def _create_transformation_vectors_for_pixel_offsets( detector_group: h5py.Group, wrapper: nx.NexusWrapper ) -> List[QVector3D]: """ Construct a transformation (as a QVector3D) for each pixel offset """ x_offsets = wrapper.get_field_value(detector_group, "x_pixel_offset") ...
1504193d1a7731740a607f77c94a810561142c57
18,229
import random def buildIterator(spec_name, param_spec, global_state, random_selection=False): """ :param param_spec: argument specification :param random_selection: produce a continuous stream of random selections :return: a iterator function to construct an iterator over possible values """ i...
d86d2af9499117614a11796c17eeccba16149092
18,230
import logging def logged(obj): """Add a logger member to a decorated class or function. :arg obj: the class or function object being decorated, or an optional :class:`logging.Logger` object to be used as the parent logger (instead of the default module-named logger) :return: ...
5a7d53257ed7d68c53daf90dcf2d48943a430a4e
18,231
def outlier_removal_mean(dataframe, colname, low_cut, high_cut): """Replace outliers with the mean on dataframe[colname]""" col = dataframe[colname] col_numerics = col.loc[ col.apply( lambda x: isinstance(x, (int, float)) and (x >= low_cut and x <= high_cut) ) ]...
03d40bb8098d4313e468d5b4a929756354a7732c
18,232
def non_repeating(value, counts, q): """Finds the first non-repeating string in a stream. Args: value (str): Latest string received in the string counts (dict): Dictionary of strings containing the counts to determine if string is repeated q (Queue): Container for all strings in stream ...
fc5ec025cffa0d7230d814d3677ae640cd652349
18,233
def auth_optional(request): """ view method for path '/sso/auth_optional' Return 200 reponse: authenticated and authorized 204 response: not authenticated 403 reponse: authenticated,but not authorized """ res = _auth(request) if res: #authenticated, but can be aut...
06416fdce6a652ca0cdc169c48219e685c13cdad
18,234
def is_pip_main_available(): """Return if the main pip function is available. Call get_pip_main before calling this function.""" return PIP_MAIN_FUNC is not None
3d4243bb4336fbc9eb9e93b2a1cf9ec4cc129c03
18,235
import torch def energy_target(flattened_bbox_targets, pos_bbox_targets, pos_indices, r, max_energy): """Calculate energy targets based on deep watershed paper. Args: flattened_bbox_targets (torch.Tensor): The flattened bbox targets. pos_bbox_targets (torch.Tensor): Bounding...
84bed4cc1a8bf11be778b7e79524707a49482b39
18,236
def dashtable(df): """ Convert df to appropriate format for dash datatable PARAMETERS ---------- df: pd.DataFrame, OUTPUT ---------- dash_cols: list containg columns for dashtable df: dataframe for dashtable drop_dict: dict containg dropdown list for dashtable """ ...
39897244f81a5c6ac0595aac7cb219f59d6c5739
18,237
def other_identifiers_to_metax(identifiers_list): """Convert other identifiers to comply with Metax schema. Arguments: identifiers_list (list): List of other identifiers from frontend. Returns: list: List of other identifiers that comply to Metax schema. """ other_identifiers = []...
986c98d5a557fb4fb75ed940d3f39a9a0ec93527
18,238
def enforce_excel_cell_string_limit(long_string, limit): """ Trims a long string. This function aims to address a limitation of CSV files, where very long strings which exceed the char cell limit of Excel cause weird artifacts to happen when saving to CSV. """ trimmed_string = '' ...
9b8bcf4590dc73425c304c8d778ae51d3e3f0bf3
18,239
def gaussian_blur(image: np.ndarray, sigma_min: float, sigma_max: float) -> np.ndarray: """ Blurs an image using a Gaussian filter. Args: image: Input image array. sigma_min: Lower bound of Gaussian kernel standard deviation range. sigma_max: Upper bound of Gaussian kernel standard ...
2fd31d016e4961c6980770e8dd113ae7ad45a6ed
18,240
def get_number_of_pcs_in_pool(pool): """ Retrun number of pcs in a pool """ pc_count = Computer.objects.filter(pool=pool).count() return pc_count
812de24ad2cbc738a10258f8252ca531ef72e904
18,241
import tqdm import math def save_images(scene_list, video_manager, num_images=3, frame_margin=1, image_extension='jpg', encoder_param=95, image_name_template='$VIDEO_NAME-Scene-$SCENE_NUMBER-$IMAGE_NUMBER', output_dir=None, downscale_factor=1, show_progress=False, ...
37088294395539acd3b88543d1bdd4d05ef82ce5
18,242
from typing import List def get_used_http_ports() -> List[int]: """Returns list of ports, used by http servers in existing configs.""" return [rc.http_port for rc in get_run_configs().values()]
12982ff4d5b2327c06fef1cf874b871e2eee08c1
18,243
import io def get_img_from_fig(fig, dpi=180, color_cvt_flag=cv2.COLOR_BGR2RGB) -> np.ndarray: """Make numpy array from mpl fig Parameters ---------- fig : plt.Figure Matplotlib figure, usually the result of plt.imshow() dpi : int, optional Dots per inches of the image to save. Note...
dde9f35b78df436b30d4f9452b9964c93f924252
18,244
def split_data_by_target(data, target, num_data_per_target): """ Args: data: np.array [num_data, *data_dims] target: np.array [num_data, num_targets] target[i] is a one hot num_data_per_target: int Returns: result_data: np.array [num_data_per_target * num_targets...
d4425753b4d9892d2c593ec8e58e75bae0005c3d
18,245
def top_mutations(mutated_scores, initial_score, top_results=10): """Generate list of n mutations that improve localization probability Takes in the pd.DataFrame of predictions for mutated sequences and the probability of the initial sequence. After substracting the initial value from the values of the...
f574bf7f7569e3024a42866873c5bb589ff02095
18,246
def npmat4_to_pdmat4(npmat4): """ # updated from cvtMat4 convert numpy.2darray to LMatrix4 defined in Panda3d :param npmat3: a 3x3 numpy ndarray :param npvec3: a 1x3 numpy ndarray :return: a LMatrix3f object, see panda3d author: weiwei date: 20170322 """ return Mat4(npmat4[0, 0],...
7b58014d5d354aefac84786212b6ca190a983e48
18,247
import requests def is_at_NWRC(url): """ Checks that were on the NWRC network """ try: r = requests.get(url) code = r.status_code except Exception as e: code = 404 return code==200
b909a9087940eb70b569ea6c686ff394e84a6ed9
18,248
import torch def lmo(x,radius): """Returns v with norm(v, self.p) <= r minimizing v*x""" shape = x.shape if len(shape) == 4: v = torch.zeros_like(x) for first_dim in range(shape[0]): for second_dim in range(shape[1]): inner_x = x[first_dim][second_dim] ...
24bda333cdd64df9a0b4fa603211036bbdad7200
18,249
def _transform_index(index, func): """ Apply function to all values found in index. This includes transforming multiindex entries separately. """ if isinstance(index, MultiIndex): items = [tuple(func(y) for y in x) for x in index] return MultiIndex.from_tuples(items, names=index.na...
c642dd9330032ed784224b7ede6ee299b6d3ed67
18,250
def extractQualiTeaTranslations(item): """ # 'QualiTeaTranslations' """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol or frag) or 'preview' in item['title'].lower(): return None if 'Harry Potter and the Rise of the Ordinary Person' in item['tags']: return None i...
446b7f7598e118222c033bbfce074fa02340fd8e
18,251
def feature_norm_ldc(df): """ Process the features to obtain the standard metrics in LDC mode. """ df['HNAP'] = df['HNAC']/df['ICC_abs']*100 df['TCC'] = (df['ICC_abs']+df['DCC_abs'])/df['VOL'] df['ICC'] = df['ICC_abs']/df['VOL'] df['DCC'] = df['DCC_abs']/df['VOL'] return df
60e3ef31c0be07179854de3191c2c75f4ec2cb4d
18,252
def dice_jaccard(y_true, y_pred, y_scores, shape, smooth=1, thr=None): """ Computes Dice and Jaccard coefficients. Args: y_true (ndarray): (N,4)-shaped array of groundtruth bounding boxes coordinates in xyxy format y_pred (ndarray): (N,4)-shaped array of predicted bounding boxes coordinates...
ed3a043b53d843e05ff3e32954eb9dbc2939b6ca
18,253
def forward_pass(output_node, sorted_nodes): """ Performs a forward pass through a list of sorted nodes. Arguments: `output_node`: A node in the graph, should be the output node (have no outgoing edges). `sorted_nodes`: A topologically sorted list of nodes. Returns the output Node's v...
a91c5b7ebef98815a47b26d58a680b36098969d5
18,254
def qr_decomposition(q, r, iter, n): """ Return Q and R matrices for iter number of iterations. """ v = column_convertor(r[iter:, iter]) Hbar = hh_reflection(v) H = np.identity(n) H[iter:, iter:] = Hbar r = np.matmul(H, r) q = np.matmul(q, H) return q, r
94aa433e31e93dc36f67f579cb03f67930cfabc4
18,255
def main(args=None): """Main entry point for `donatello`'s command-line interface. Args: args (List[str]): Custom arguments if you wish to override sys.argv. Returns: int: The exit code of the program. """ try: init_colorama() opts = get_parsed_args(args) ...
1977a2bf8e537664a4eab2fb05d6300998a59977
18,256
import logging import torch import operator def build_detection_train_loader(cfg, mapper=None): """ A data loader is created by the following steps: 1. Use the dataset names in config to query :class:`DatasetCatalog`, and obtain a list of dicts. 2. Coordinate a random shuffle order shared among all p...
007b09ce00814264b3264798d4a0afd05c23d6eb
18,257
def discRect(radius,w,l,pos,gap,layerRect,layerCircle,layer): """ This function creates a disc that is recessed inside of a rectangle. The amount that the disc is recessed is determined by a gap that surrounds the perimeter of the disc. This much hangs out past the rectangle to couple to a bus waveguide.Calls sub...
1cb5f505fb868f31771fe6e48faa6399d8b051ad
18,258
def sub_factory(): """Subscript text: <pre>H[sub]2[/sub]O</pre><br /> Example:<br /> H[sub]2[/sub]O """ return make_simple_formatter("sub", "<sub>%(value)s</sub>"), {}
4f721d0713c1a2be496a45c1bf7abe8766572135
18,259
from typing import Tuple def train_test_split( structures: list, targets: list, train_frac: float = 0.8 ) -> Tuple[Tuple[list, list], Tuple[list, list]]: """Split structures and targets into training and testing subsets.""" num_train = floor(len(structures) * train_frac) return ( (structures[:...
279fbe353bf07aa9b9654f4be4c21cf248f2c8bb
18,260
def reset_password(token): """ Handles the reset password process. """ if not current_user.is_anonymous(): return redirect(url_for("forum.index")) form = ResetPasswordForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() expired...
c34d090b09a236eecfe101d66ec0daaf3c08eb87
18,261
def delete(vol_path): """ Delete a kv store object for this volume identified by vol_path. Return true if successful, false otherwise """ return kvESX.delete(vol_path)
5d120b6a509119587df5f2dc9f1436115b01a257
18,262
import uuid def get_tablespace_data(tablespace_path, db_owner): """This function returns the tablespace data""" data = { "name": "test_%s" % str(uuid.uuid4())[1:8], "seclabels": [], "spcacl": [ { "grantee": db_owner, "grantor": db_owner, ...
3272e9b941d6bfb426ed754eed7f956c4c0933f4
18,263
def join_chunks(chunks): """empty all chunks out of their sub-lists to be split apart again by split_chunks(). this is because chunks now looks like this [[t,t,t],[t,t],[f,f,f,][t]]""" return [item for sublist in chunks for item in sublist]
a5daf41ba3fa6e7dafc4f05b29cc5aeaa397d5a5
18,264
def urls_equal(url1, url2): """ Compare two URLObjects, without regard to the order of their query strings. """ return ( url1.without_query() == url2.without_query() and url1.query_dict == url2.query_dict )
f2cbcf111cd5d02fa053fbd373d24b2dab047dfc
18,265
def bytes_to_ints(bs): """ Convert a list of bytes to a list of integers. >>> bytes_to_ints([1, 0, 2, 1]) [256, 513] >>> bytes_to_ints([1, 0, 1]) Traceback (most recent call last): ... ValueError: Odd number of bytes. >>> bytes_to_ints([]) [] """ if len(bs) % 2 != 0:...
e8ac9ec973ff58973703e3e109da5b45d3f9d802
18,266
import logging import click import yaml def create_default_yaml(config_file): """This function creates and saves the default configuration file.""" config_file_path = config_file imgdb_config_dir = Config.IMGDB_CONFIG_HOME if not imgdb_config_dir.is_dir(): try: imgdb_config_dir.m...
786b3488b4400a66f44900811171df396b3ab3a9
18,267
import site def canRun(page): """ Returns True if the given check page is still set to "Run"; otherwise, returns false. Accepts one required argument, "page." """ print("Checking checkpage.") page = site.Pages[page] text = page.text() if text == "Run": print("We're good!") retur...
3cb1276d82ffeadb1a730bb2eb1c1f3427905e94
18,268
import os def parse_configs_for_multis(conf_list): """ parse list of condor config files searching for multi line configurations Args: conf_list: string, output of condor_config_val -config Returns: multi: dictionary. keys are first line of multi line config val...
faf9ea4a5ce40c31797a4d570f79826902bc05da
18,269
def _bgp_predict_wrapper(model, *args, **kwargs): """ Just to ensure that the outgoing shapes are right (i.e. 2D). """ mean, cov = model.predict_y(*args, **kwargs) if len(mean.shape) == 1: mean = mean[:, None] if len(cov.shape) == 1: cov = cov[:, None] return mean, cov
23bb62927e767057df94ef8b95b57874fc078d7f
18,270
import copy import json def create_waninterface(config_waninterface, waninterfaces_n2id, site_id): """ Create a WAN Interface :param config_waninterface: WAN Interface config dict :param waninterfaces_n2id: WAN Interface Name to ID dict :param site_id: Site ID to use :return: New WAN Interface...
f4de347a1e8120e1da8c38d16ed0054e13f13ae5
18,271
import numpy def max_pool(images, imgshp, maxpoolshp): """ Implements a max pooling layer Takes as input a 2D tensor of shape batch_size x img_size and performs max pooling. Max pooling downsamples by taking the max value in a given area, here defined by maxpoolshp. Outputs a 2D tensor of shape b...
acbbfb686f77dc6e05f385b2addc8f49e7f344d3
18,272
def rmean(A): """ Removes time-mean of llc_4320 3d fields; axis=2 is time""" ix,jx,kx = A.shape Am = np.repeat(A.mean(axis=2),kx) Am = Am.reshape(ix,jx,kx) return A-Am
39edcdca0cc4d411c579991086bf555d65686020
18,273
def default_pruning_settings(): """ :return: the default pruning settings for optimizing a model """ mask_type = "unstructured" # TODO: update based on quantization sparsity = 0.85 # TODO: dynamically choose sparsity level balance_perf_loss = 1.0 filter_min_sparsity = 0.4 filter_min_pe...
a81f153872a20eaaa5e654957ddf7b4a79ff42a9
18,274
def build_request_url(base_url, sub_url, query_type, api_key, value): """ Function that creates the url and parameters :param base_url: The base URL from the app.config :param sub_url: The sub URL from the app.config file. If not defined it will be: "v1/pay-as-you-go/" :param query_type: The query ...
ecf3ef0a3d7d5591b1f6aa9787f4f2984688f9f2
18,275
import re def snake_to_camel(action_str): """ for all actions and all objects unsnake case and camel case. re-add numbers """ if action_str == "toggle object on": return "ToggleObjectOn" elif action_str == "toggle object off": return "ToggleObjectOff" def camel(match): ...
c71745c02fc712e2b463e7bcb022bfca41c2efd4
18,276
from datetime import datetime def todayDate() -> datetime.date: """ :return: ex: datetime.date(2020, 6, 28) """ return datetime.date.today()
dc9dae8bbeaabf5c8d7d9e3509d1e331e2c609ff
18,277
def lookup_facade(name, version): """ Given a facade name and version, attempt to pull that facade out of the correct client<version>.py file. """ for _version in range(int(version), 0, -1): try: facade = getattr(CLIENTS[str(_version)], name) return facade ex...
eb76df1f7f3a9991c3e283643a52784c9d65f4f1
18,278
import time def create_service(netUrl, gwUrl, attributes, token): """ Create NFN Service in MOP Environment. :param netUrl: REST Url endpoint for network :param gwUrl: REST Url endpoint for gateway :param serviceAttributes: service paramaters, e.g. service type or name, etc :param token: see...
848f8375273ec4583a6c5d361c8a319ff43ba2a8
18,279
def _drawBlandAltman(mean, diff, md, sd, percentage, limitOfAgreement, confidenceIntervals, detrend, title, ax, figureSize, dpi, savePath, figureFormat, meanColour, loaColour, pointColour): """ Sub function to draw the plot. """ if ax is None: fig, ax = plt.subplots(1,1, figsize=figureSize, dpi=dpi) plt.rcParam...
43bf53cd4594c1ed58860a6127f40f6345bea6ba
18,280
def rename_columns(df): """This function renames certain columns of the DataFrame :param df: DataFrame :type df: pandas DataFrame :return: DataFrame :rtype: pandas DataFrame """ renamed_cols = {"Man1": "Manufacturer (PE)", "Pro1": "Model (PE)", "Man2"...
9c22747d7c6da20cab1593388db5575a38aa313f
18,281
import requests import json def get_github_emoji(): # pragma: no cover """Get Github's usable emoji.""" try: resp = requests.get( 'https://api.github.com/emojis', timeout=30 ) except Exception: return None return json.loads(resp.text)
533a56e2e59b039cbc45ab5acb7ab4e8487e4ad9
18,282
def transport_stable(p, q, C, lambda1, lambda2, epsilon, scaling_iter, g): """ Compute the optimal transport with stabilized numerics. Args: p: uniform distribution on input cells q: uniform distribution on output cells C: cost matrix to transport cell i to cell j lambda1: re...
584607e57b4d216633ef0a03c2cb06726b0f423f
18,283
def add(A: Coord, B: Coord, s: float = 1.0, t: float = 1.0) -> Coord: """Return the point sA + tB.""" return (s * A[0] + t * B[0], s * A[1] + t * B[1])
53c2f750199d785140154881fdc0ace31b9e2472
18,284
def from_binary(bin_data: str, delimiter: str = " ") -> bytes: """Converts binary string into bytes object""" if delimiter == "": data = [bin_data[i:i+8] for i in range(0, len(bin_data), 8)] else: data = bin_data.split(delimiter) data = [int(byte, 2) for byte in data] return bytes(da...
f16706da2d5b9ae5984a35a13ebd02ae94581153
18,285
def send_raw(task, raw_bytes): """Send raw bytes to the BMC. Bytes should be a string of bytes. :param task: a TaskManager instance. :param raw_bytes: a string of raw bytes to send, e.g. '0x00 0x01' :returns: a tuple with stdout and stderr. :raises: IPMIFailure on an error from ipmitool. :raise...
1f903f1942c5d1b673c9019f9023b1ddf7d2c07a
18,286
def one_on_f_weight(f, normalize=True): """ Literally 1/f weight. Useful for fitting linspace data in logspace. Parameters ---------- f: array Frequency normalize: boolean, optional Normalized the weight to [0, 1]. Defaults to True. Returns ------- weight: array...
54301aa7480e6f3520cbfcccfa463a2a02d34b9c
18,287
def PCSPRE1M2SOC(p0, meas_pcs, meas_pre, x_pcs ,y_pcs, z_pcs, \ x_pre ,y_pre, z_pre, wt_pcs=1.0, wt_pre=1.0, \ tol_pcs=None, tol_pre=None): """ Optimize two X-tensors and two PRE centres to two common sites @param p0: List containing initial guesses for (17 unknowns): ...
ec0f266ed1a8b1a45504c13057486bd26e3cc4a5
18,288
def load_randomdata(dataset_str, iter): """Load data.""" names = ['x', 'y', 'tx', 'ty', 'allx', 'ally', 'graph'] objects = [] for i in range(len(names)): with open("data/ind.{}.{}".format(dataset_str, names[i]), 'rb') as f: if sys.version_info > (3, 0): objects.append...
476a54078680bb711a77fc9e3900192a1ef3b811
18,289
def plot(figsize=None, formats=None, limit=100, titlelen=10, **kwargs): """Display an image [in a Jupyter Notebook] from a Quilt fragment path. Intended for use with `%matplotlib inline`. Convenience method that loops over supblots that call `plt.imshow(image.imread(FRAG_PATH))`. Keyword arguments...
f1b72c952d1c517ba4f09e03af8463a73d2c8759
18,290
def tresize(tombfile, keyfile, passphrase, newsize): """ Resize a tomb. Keyfile, passphrase and new size are needed. """ cmd = ['tomb', 'resize', tombfile, '-k', keyfile, '--unsafe', '--tomb-pwd', sanitize_passphrase(passphrase), '-s', ...
334a722b79aec80bc4a95c67a0b155653e29eb10
18,291
def auto_z_levels(fid, x, y, variable, t_idx, n_cont, n_dec): """ list(float) = auto_z_levels(fid, variable, t_idx, n_cont, n_dec) ... # contour lines ... # post . """ fig, ax = plt.subplo...
f80020c01a661412fb79d23f6081bdb94a471102
18,292
def canonicalize(curie: str): """Return the best CURIE.""" # TODO maybe normalize the curie first? norm_prefix, norm_identifier = normalize_curie(curie) if norm_prefix is None or norm_identifier is None: return jsonify( query=curie, normalizable=False, ) norm...
510b2d10170c674cc24090bf2bcd900912678acf
18,293
def _DefaultValueConstructorForField(field): """Returns a function which returns a default value for a field. Args: field: FieldDescriptor object for this field. The returned function has one argument: message: Message instance containing this field, or a weakref proxy of same. That function in...
3a468e2850aaf9707ee1229eeb009ef5c013f1b6
18,294
def clean_text(dirty_text): """ Given a string, this function tokenizes the words of that string. :param dirty_text: string :return: list input = "American artist accomplishments american" output = ['accomplishments', 'american', 'artist'] """ lower_dirty_text = dirt...
1df63ea0c9be5a518d2fd1f931772080962f878f
18,295
def GetCurrentUserController(AuthJSONController): """ Return the CurrentUserController in the proper scope """ class CurrentUserController(AuthJSONController): """ Controller to return the currently signed in user """ def __init__(self, toJson): """ Initialize with the Json ...
ee710cd4d65982cf01d17fba130b7bb83dffd617
18,296
import numpy def fft_in_range(audiomatrix, startindex, endindex, channel): """ Do an FFT in the specified range of indices The audiomatrix should have the first index as its time domain and second index as the channel number. The startindex and endinex select the time range to use, and the cha...
30ce104795d0809f054439ba32f47d33528ecbff
18,297
def drop_arrays_by_name(gt_names, used_classes): """Drop irrelevant ground truths by name. Args: gt_names (list[str]): Names of ground truths. used_classes (list[str]): Classes of interest. Returns: np.ndarray: Indices of ground truths that will be dropped. """ inds = [i fo...
67d711ae61f3c833fa9e8b33d4bf4bf6d99a34ad
18,298
def get_data_table_metas(data_table_name, data_table_namespace): """ Gets metas from meta table associated with table named `data_table_name` and namespaced `data_table_namespace`. Parameters --------- data_table_name : string table name of this data table data_table_namespace : string ...
8b4ee249112d399c429a33fed82d9cb01404d441
18,299