content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_full_width(text, get_full_width_char, get_full_width_number, get_full_width_symbol): """ Get full width characters. :param text: original text. :param get_full_width_char: set True to get full width English letter. :param get_full_width_number: set True to get full width number. :param ...
9ea6b259d40a7d96dca1043d2009ee5d3fe69728
41,082
def polar_to_cartesian_2d(rho, phi): """Convert polar points to cartesian points. Convert polar coordinate points in 2D to cartesian coordinate points in 2D. This function uses the notation convention of ISO 80000-2:2009 and its related successors. Parameters ---------- rho : array_like ...
d749bc25010e7d426c42a05aa502f1bf92c35f6e
41,083
def ast_rotate_left_while_assoc_prec(ast): """Performs a left rotation of the AST around its root if associativity and precedence are not enforced yet. Args: ast: The AST dict. Returns: The new root of the rotated AST. """ if ("op" in ast) and (ast["op"] in all_op_data): if...
9f206ae1aa07c5fe7be8a7c657863395ef160a87
41,084
def memoryUsage(data, detail=1): """Got memory usage of dataset Parameters ---------- data: dataFrame """ if detail: display(data.memory_usage()) memory = data.memory_usage().sum() / (1024 * 1024) print("Memory usage : {0:.2f}MB".format(memory)) return memory
3c3ed920dea91c07eaa8d227fb9a7ae96ef03b2c
41,086
def settings_finish(update: Update, context: CallbackContext) -> int: """ Settings finish""" devotional_type = update.message.text chat_id = update.effective_chat.id update.message.reply_text( text=YOUR_CHOICE.replace("$choice", devotional_type), parse_mode=ParseMode.HTML ) if ...
4c6700f8768fc0cd73ad8f4af525ee4698246f61
41,087
def dataframe_to_thrift_struct(df, name, roffset, coffset, rows, cols, format): """ :type df: pandas.core.frame.DataFrame :type name: str :type coffset: int :type roffset: int :type rows: int :type cols: int :type format: str """ dim = len(df.axes) num_rows = df.shape[0] ...
8a2bac4a51637810396a82210c6cef6fff0911ea
41,088
import ast def collect_args(args: ast.arguments): """Collect function arguments.""" all_args = args.args + args.kwonlyargs all_args += [args.vararg, args.kwarg] return [arg for arg in all_args if arg is not None]
b8fdd180259aadd6a8d31a83503cf7da2b2c0bae
41,090
def getalllabels(): """Get a dictionary of label name -> SNES address.""" labeldatas = _getall(_asar.dll.asar_getalllabels) return {x.name.decode(): x.location for x in labeldatas}
ae053bc05be3bc689dffd2f5a636d9facf226bdf
41,091
def jinja2_enviroment(**options): """jinja2环境""" #创建环境 env = Environment(**options) #返回环境对象 env.globals.update({ "static":staticfiles_storage.url, #获取静态文件的前缀 "url":reverse, #反向解析 }) #自定义语法 : static. {{static{'静态文件相对路径') }} #return 对象 return env
5489deb7d7f98fccc7edf056e9f8bae60da49d2e
41,092
def pushmarker(repo, key, old, new): """Push markers over pushkey""" if not key.startswith('dump'): repo.ui.warn(_('unknown key: %r') % key) return 0 if old: repo.ui.warn(_('unexpected old value for %r') % key) return 0 data = base85.b85decode(new) lock = repo.lock() ...
9d43edfa3d98fc908f1e18555e3ae7189c0d6901
41,093
import logging def remove_images(): """Removes all dangling images as well as all images referenced in a dusty spec; forceful removal is not used""" client = get_docker_client() removed = _remove_dangling_images() dusty_images = get_dusty_images() all_images = client.images(all=True) for image...
fac5fb5819de5bd793fcb1f72c912ffd9647701c
41,094
def create_version_localization( version_id: str, locale: str, localization_attributes: VersionLocalizationAttributes, access_token: AccessToken, ): """Creates a new app store version localization.""" return fetch( method=FetchMethod.POST, path=f"/appStoreVersionLocalizations", ...
cbd64a70b15126dfa636d0cbf40d7aed73a5e91f
41,096
import shutil from pathlib import Path def clean_build(): """Remove build directory and recreate empty""" shutil.rmtree("site_build", ignore_errors=True) build_dir = Path("site_build") build_dir.mkdir(exist_ok=True) return build_dir
121e6ba5f06243654a3a38946a332efae43ce6c2
41,097
import click def print_markers(f): """A decorator that prints the invoked command before and after the command. """ @click.pass_context def new_func(ctx, *args, **kwargs): command = ctx.info_name assert command is not None command_name = ctx.command_path click_exten...
bee03bbdcfe7da134c21f9d4e5e9ea16a7b3b019
41,098
def gpsapi(): """(re)Generate and/or present API key.""" form = ApiForm(request.form) hasapi = ApiKey.query.filter_by(user_id=current_user.get_id()).all() # Handle regeneration of API key if request.method == "POST": if form.validate_on_submit(): apikey = strgen.StringGenerator("...
77a54a920f898b926900a519847abb4e70236f9e
41,099
def secret_exponent_to_wif(secret_exp, compressed=True, is_test=False): """Convert a secret exponent (correspdong to a private key) to WIF format.""" d = private_byte_prefix(is_test) + to_bytes_32(secret_exp) if compressed: d += b'\01' return b2a_hashed_base58(d)
8ac254b3dd650ab26d5be2ea0c889bba7cf930c7
41,102
def create_host(ec2_conn, ipa_client, image_id, count, domain, secgroup_ids, instance_type, subnet, disk, instance_vars, role=None, instance_profile=None, hostgroups=None, hostname=None, ip_address=None, eni=None, key=None, tags=None, spot=False, ...
3d2147940ad4f9023fe7b59f27aed8dd0f300324
41,103
def check_new_labels_var(self, labels_df): """Check the new annotations labels, then set the labels_df index""" if labels_df is None or labels_df.empty: return labels_df.index = self.get_var_index() if labels_df.index.name is None: labels_df.index.name = "index" # all labels must h...
600945f3049569417b9493e1e370e3e8ac4191dd
41,105
def ajax_delete_widget(request): """ Delete single widget """ if request.is_ajax(): if request.method == 'POST': widget_id = request.POST.get('widget_id', 0) if widget_id: delete_widget(widget_id) return HttpResponse(simplejson.dumps({'status':'succes...
d62fd59849c324f824f6c1acd4c0a8d222ffab13
41,106
from pathlib import Path async def post_pack_response(repo_path: Path, pack_type: str) -> Response: """ Make the response for handling exchange pack responses, uses 'BODY_TIMEOUT' for a timeout of a request. A matching route should be: '/<repo_name>.git/<pack_type>'. :param repo_path: Path t...
c5ed0b8635c2c4a1cb0fa4c5ea1188f627a47737
41,107
def get_geocoder_normalized_addr(address, addr_keys=ADDRESS_KEYS): # type: (Union[Mapping, str], Optional[Sequence]) -> dict """Get geocoder normalized address parsed to dict with addr_keys. :param address: string or dict-like containing address data :param addr_keys: optional list of address keys. sta...
b0c97f01b12fd80865f6c9722778f2775508f845
41,109
from typing import Dict from typing import Union from typing import List import csv def _read_csv(filepath: str, kwargs: Dict) -> Union[List, Dict]: """See documentation of mpu.io.read.""" if "delimiter" not in kwargs: kwargs["delimiter"] = "," if "quotechar" not in kwargs: kwargs["quotech...
dfc91fa4c9516a2f33d0e7d43124eaa78b434dc6
41,110
import torch def bbox_iou(box1, box2, x1y1x2y2=True): """ 计算IOU """ if not x1y1x2y2: b1_x1, b1_x2 = box1[:, 0] - box1[:, 2] / 2, box1[:, 0] + box1[:, 2] / 2 b1_y1, b1_y2 = box1[:, 1] - box1[:, 3] / 2, box1[:, 1] + box1[:, 3] / 2 b2_x1, b2_x2 = box2[:, 0] - box2[:, 2] / 2, b...
e492d3d98629f926d5de1627b563c25a6a99404d
41,111
def points_extraction(images, nx, ny): """ perform the extraction of object points and image points :param images: list of images :param nx: the number of inside corners in x :param ny: the number of inside corners in y :return: object points, image points and retvalues """ # Arrays to ...
c03520814d5599f0794bcce99da55862c5f3c3ca
41,113
def auto_delete_file_on_change(sender, instance, **kwargs): """ Deletes old file from filesystem when corresponding `Profile` object is updated with new file. """ if not instance.pk: return False try: old_avatar = Profile.objects.get(pk=instance.pk).avatar except Profile...
f78b78e106effaa04b67c2d23aab95ac89eb0c83
41,114
def get_user_id(username): """Convenience method to look up the id for a username.""" rv = User.query.filter_by(username=username).first() return rv.user_id if rv else None
d0a096f72ed0175238fcbd5756f5f70b3ae8f990
41,115
def clean_toc(toc: str) -> str: """Each line in `toc` has 6 unnecessary spaces, so get rid of them""" lines = toc.splitlines() return "\n".join(line[6:] for line in lines)
40a22200d04c12865e4bffae9cdd3bdc4ea827be
41,116
def separate_means_and_sigma(O: np.ndarray, D: int): """ Retreive means and sigma from the outputted O matrix of emission probabilities """ flat_sigma = O[D:] assert len(flat_sigma) == D*(D + 1) // 2 return O[:D], flat_sigma
73727c2884ddea1fcecfb3753a0757190ee2d573
41,117
import pickle def pickle_load(file_path): """ data = pickle_load(file_path) Load data from a pickle dump file inputs: file_path: str, path of the pickle file output: data: python object """ with open(file_path, 'rb') as file_ptr: data = pickle.load(file_ptr) r...
c9112881facc7a6a135893168fa9abf63309b392
41,118
import json async def account_add(request : VueRequest): """ 添加用户的接口 :param: :return: str response: 需要返回的数据 """ try: response = {'code': '', 'message': '', 'data': ''} request = rsa_crypto.decrypt(request.data) request = json.loads(request) username = req...
58773e7424a666142c0e01d45bef14602d3a9163
41,119
import socket def port_available(port): """ Check is port sent available currently. :return: {Tuple} """ status = False error = {} with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s: try: s.bind(('0.0.0.0', port)) status = True exce...
9a9b6daf94d6515f4358db5f557ea4d967a8a048
41,120
def vtk_points_to_polyline(vtk_points): """ creates a polyline, creating lines along point path :param vtk_points: :return: """ lines = vtk.vtkCellArray() for k in range(vtk_points.GetNumberOfPoints() - 1): line = vtk.vtkLine() line.GetPointIds().SetId(0, k) line.Ge...
f89296565ffa01acacb033dca38bc7ba82cb2b29
41,121
def getLayerThicknesses(vessel): """returns a dataframe with thicknesses of each layer along the whole vessel""" thicknesses = [] columns = ['lay{}_{:04.1f}'.format(i, angle) for i, angle in enumerate(getAnglesFromVessel(vessel))] for layerNumber in range(vessel.getNumberOfLayers()): vesselLayer...
84a9e80045b9c3c23ef0d8121c7e95b5187259c5
41,122
from typing import List def get_transcription_files_by_dataset( dataset: str, transcription_folder: str ) -> List[str]: """return paths of transcriptions from the given data set and the path of all of transcriptions""" train_set = get_data_list(f"splits/{dataset}") transcription_train_set = list( ...
e2a32614995c92706139a0a2c9d385b97918fb2f
41,123
def versiontuple(v): """Return the version as a tuple for easy comparison.""" return tuple(int(x) for x in v.split("."))
422d49818e2d6d34d0591c1c450d0c92b7fabc82
41,124
def validate_aliases(aliases): """Checks that each alias remains unique when converted to a valid filename.""" return len(set(get_valid_filename(s) for s in aliases)) == len(aliases)
fb866cfdc5c3f45c790468850a25aaa793659099
41,125
def apps(app_id=None): """Returns marathon apps together with corresponding tasks :param str app_id: application id """ marathon_addresses = _addresses() return _apps(marathon_addresses, app_id)
f99bd8ecdea5292a27e1092b4e5f64bea3e4102a
41,126
import re def find_checksum(s): """Accepts a manifest-style filename and returns the embedded checksum string, or None if no such string could be found.""" m = re.search(r"\b([a-z0-9]{32})\b", s, flags=re.IGNORECASE) md5 = m.group(1).lower() if m else None return md5
f0d9735833e257a3f133d2d51b01775e35408755
41,127
def data_null_check(df): """Prints out nulls of dataframe into a nice data frame format""" if type(df) == pd.core.frame.DataFrame: return df.isnull().sum()
5d18797d032799af30dca27f73f52946417c909c
41,128
def sum_up_nums(*nums): """(int or float) -> int or float Adds up as many numbers(separate arguments) as the caller can supply. Returns the sum of <*nums> """ cntr = 0 # Init sum zero for num in nums: cntr += num return cntr
8ed03f16d624ea24a90a20d42df30328b119edd7
41,129
from typing import Tuple from typing import List def _generate_random_example_for_one_session_and_one_marker( rng: np.random.Generator, ) -> Tuple[List[EventMetaData], List[int]]: """Generates a random marker extraction result for a single session and marker. Args: rng: a random number generator ...
4a770cd86de5ebab472492689f77ecc7d2e9dae3
41,130
def real_rowcol_in_hunk(hunk, relative_rowcol): # type: (str, RowCol) -> Optional[RowCol] """Translate relative to absolute row, col pair""" hunk_lines = split_hunk(hunk) if not hunk_lines: return None row_in_hunk, col = relative_rowcol # If the user is on the header line ('@@ ..') pre...
72968d95a52129e657e2f6565a99b4dc66381e98
41,131
def load_mrs_rsrf_file( filename ): """ Reads RSRF parameters from binary FITS table. """ # Read the RSRF data from file try: hdulist = pyfits.open(filename) fits_hdr_prim = hdulist[0].header fits_hdr_ext = hdulist[1].header #fitsdata = hdulist[1].data[0] ...
6af68cdeb2cc525ff7678767f91cf49d127b6092
41,132
import json def recipe(index): """ Return (GET) or delete (DELETE) one recipe """ try: if request.method == 'GET': return Response( json.dumps(recipebook.recipes[index].to_json_dict()), mimetype="application/json") elif request.method...
54787a5d0bdbec04ec76224090c41351e1b28ae0
41,133
def eval_numerical_gradient_blobs(f, inputs, output, h=1e-5): """ Compute numeric gradients for a function that operates on input and output blobs. We assume that f accepts several input blobs as arguments, followed by a blob into which outputs will be written. For example, f might be called like this: ...
6ce997d621df7915eb2f49ae747c0983ea7255e3
41,134
from re import S def poly_half_gcdex(f, g, *symbols): """Half extended Euclidean algorithm. Efficiently computes gcd(f, g) and one of the coefficients in extended Euclidean algorithm. Formally, given univariate polynomials f and g over an Euclidean domain, computes s and h, such that...
69c7c45480b0b59f32f89491fe3149959fbc2b90
41,135
def find_message(file_content): """Implmentation for Part 1.""" point_system = LightPointSystem(_parse_entry(entry) for entry in file_content) total_area = point_system.get_area() seconds = 0 while True: point_system.step_forward() new_area = poin...
6c25b2b6712bba70c68a717424a227041e137571
41,136
import collections def get_convert_rgb_channels(channels_info): """Get first available RGB(A) group from channels info. ## Examples ``` # Ideal situation channels_info: { "R": ..., "G": ..., "B": ..., "A": ... } ``` Result will be `("R", "G", "B", "A")`...
b2764811c3b929c51a6b4e9f735163c8aeb4abca
41,137
def create_choice(question, choice_text ): """ Creates a choice for question. """ return Choice.objects.create(question=question, choice_text=choice_text)
6a5e91eebeb7b13d04fee392d614b848e465a8f6
41,138
def GenerateTests(): """Generate all tests.""" filelist = [] ii = 0 for iTarget in range(len(_TARGETS)): for iFilter in range(len(_FILTERS)): for iFunc in range(len(_COMPARE_FUNCS)): item = _TARGETS[iTarget] + '_' + _FILTERS[iFilter] + '_' + _COMPARE_FUNCS[iFunc] filename = GenerateFil...
27d462c5a5adc5c6a1255fa51f46f1e04d338a03
41,139
def get_expts(context, expts): """Takes an expts list and returns a space separated list of expts.""" return '"' + ' '.join([expt['name'] for expt in expts]) + '"'
76cd216662a6f7a248b70351f79b52e3c47871aa
41,140
from datetime import datetime def to_timestamp(obj: datetime) -> int: """ 秒值 """ return int(obj.timestamp())
df4ed5659c96887b7d2b56c82c6431281f39ed0d
41,141
def make_model(model_type, dataset, from_logits=False): """Builds a model. XXX: from_logits=True is incompatible with expected gradient length. """ model = MODELS[model_type](dataset, to_proba=not from_logits) loss = keras.losses.CategoricalCrossentropy(from_logits=from_logits) # XXX doesn't st...
165331bd10e5842e7943a189fff26439064af7ad
41,142
def create_filename(last_element): """ For a given file, returns its name without the extension. :param last_element: str, file name :return: str, file name without extension """ return last_element[:-4]
3faaf647ed6e3c765321efb396b2806e7ef9ddf9
41,143
def ajax_popular_environment_external(request, form_acess, client): """ Method to call popular_environment_shared when use by external way """ return facade.popular_environment_shared(request, client)
6d8922477162364f6b3725f7802dc80d57a21e99
41,144
def cyclic_learning_rate(learning_rate, global_step, max_lr, step_size=10, mode='tri', name='CyclicLearningRate'): """ This function varies the learning rate between the minimum (learning_rate) and the maximum (max_lr). It returns the decayed learning rate. Parameters -----...
01447dd8979d480c1e36aca9f8842f4919e7bfd5
41,145
import yaml def fetch_local_config(default, config=None): """ Returns the content of a yml config file as a hash Parameters: - default: default file name to look for - config: override with this file name instead. (optional) Note: the pattern of using config is intended to make using this with OptionsP...
41639c401c6d33940b6098abaef9b26086615f74
41,146
from typing import Union def is_number(value: Union[int, str]) -> bool: """ Is thing a number """ return isinstance(value, int) or (isinstance(value, str) and value.isnumeric())
e69de261a45398eb970c00e9a5997a615c6fc7e6
41,149
import psutil def getCpuUsage(): """Find and return CPU Usage Returns: int -- Cpu Usage """ cpuUsage = psutil.cpu_percent() return int(cpuUsage)
3e063117731c0810fbb9a4faafee4c7299e5e2c4
41,150
def e_step(sigma,X, mask_var, mask_samp,n_ul = 0): """ E step for MTL algorithm. """ n = X.shape[0] n_tr = np.size(np.where(mask_samp == False)[0])-n_ul mask_var_c = ((mask_var+1)%2).astype(bool) mask_samp_c = ((mask_samp+1)%2).astype(bool) if n_ul>0: mask_samp_c[0:n_ul] =...
d324f082f7b8e491620246e524976c9567f982a7
41,151
def composite_coordinates_dictionary(dictified_values): """A dictionnary will be populated (or updated) with values from the 'dictified_values' dictionnary Parameters ---------- dictified_values : A dictionary of Sentinel-1 values coordinates_dictionary : A dictionnary matching...
cd80fc6ddaa20669eb84380659272ecea92a678c
41,153
def fruit_flow_through_fruit_development_stage(jth: int, number_Fruits, sum_canopy_t, last_24_canopy_t): """ Equation 9.31 number_flow_Fruit_j_Fruit_jplus = fruit_development_rate * FRUIT_DEVELOPMENT_STAGES_NUM * fruit_flow_inhibition_rate * number_fruit_j Returns: fruit flow through fruit development s...
f3a22ed089e9146c2cc05b1816a5806520936b43
41,154
def normalization(vector): """ Normalize scores in this vector """ x = vector[vector>0] beta = x.quantile(0.9) updated_vector = vector/beta return updated_vector
dfe403e8ec73ca3fab5492ce42a6390f1963f840
41,155
def emu(Omh2, ns, s8, fR0, n, z): """Returns the emulator prediction of Boost in power spectrum, for a redshift between 0 < z < 49 Parameters ---------- Omh2: float Physical matter density parameter (O_m h^2) in range [0.12, 0.15]. Here h = 0.67, a constant in the emulator design ns: floa...
a622982145fdd28a6935203c8f485da7d7fa58a6
41,157
def lp_visual(lp: LP, basic_sol: bool = True, show_basis: bool = True,) -> plt.Figure: """Render a figure visualizing the geometry of an LP's feasible region. Args: lp (LP): LP whose feasible region is visualized. basic_sol (bool): True if the entire BFS is shown. De...
a6e2643dfd598046524fe0c1db87dbdc09de186f
41,158
def _cofactor(M, i, j, method="berkowitz"): """Calculate the cofactor of an element. Parameters ========== method : string, optional Method to use to find the cofactors, can be "bareiss", "berkowitz" or "lu". Examples ======== >>> from sympy import Matrix >>> M = Matr...
9b87fae84e5b37303d5a606ac333b1a9e976934d
41,159
def separateResults(parallelResults, numThreads): """ Routine for separate each quality metric vector Parameters ---------- parallelResults: A tuple of quality of metrics, return of performCalc numThreads: 1D Numpy array ------- Return: A tuple of 3D Numpy Array [itera...
a0ab4810291bd1841dff3d3425ea529fa7247f5a
41,160
def _add_path(root_path, relative_path): """Add another level to an LDAP path. eg, _add_path('LDAP://DC=gb,DC=vo,DC=local', "cn=Users") => "LDAP://cn=users,DC=gb,DC=vo,DC=local" """ protocol = u("LDAP://") if relative_path.startswith(protocol): return relative_path ...
ad03442214f1611617b6dd28b1cd319b7d0f805c
41,162
def merge_scenarios_with_paths(scenarios): """ This will merge ScenarioWithPaths objects and return a ScenarioWithPaths objects which has the power generation vectors from all scenarios as well as the paths from all scenarios. We assume independence across the scenarios. Args: scenarios...
1daa4d428709f1e7c1956ad27888228abec45801
41,163
def adaptive_threshold(image: np.ndarray) -> np.ndarray: """ Wrapper for OpenCV's adaptive threshold algorithm. Parameters ---------- image : numpy.ndarray Image as numpy array Returns ------- numpy.ndarray Binarized image using adaptive threshold. Contribute -...
fc716fd04a8ea2cdcbebeca7fc51a7987bc14a6b
41,164
def quaternionInverse(*args): """ quaternionInverse(Quaternion pQua, Quaternion pQuaOut) quaternionInverse(Quaternion pQua) -> Quaternion """ return _almath.quaternionInverse(*args)
ff90abd6931659a4a23b89f351e75d75fbe3f1ff
41,165
import inspect import itertools import functools def get_common_base(cls_list): """ Get the most derived common base class of classes in ``cls_list``. """ # MRO in which "object" will appear first def rev_mro(cls): return reversed(inspect.getmro(cls)) def common(cls1, cls2): #...
a100f6259f773b0304fa67b7fd364ab4801db707
41,166
from operator import eq def l_inverse(L, check=False, verbose=False): """invert L (lower triangular, 1 on diagonal) """ m, n = L.shape assert m==n L1 = identity(m) # Work forwards for i in range(m): #u = L1[:, i] assert L[i, i] == 1 for j in range(i+1, m): ...
a5daa3fe776c6bac75d56d818fbf3ab88e3be0c2
41,168
def simplify_numpy_dtype(dtype): """Given a numpy dtype, write out the type as string Args: dtype (numpy.dtype): Type Returns: (string) name as a simple string """ kind = dtype.kind if kind == "b": return "boolean" elif kind == "i" or kind == "u": return "in...
c2370b2a08e58c9614ca43e3f14864782eef4100
41,169
import time import re def model_predict(year, month, day, country, dev=DEV, verbose=True): """ make predictions """ ## start timer for runtime time_start = time.time() ## load data datasets = engineer_features(training=False, dev=dev, verbose=verbose) ## load models ...
6ef8d43f68003ce5e85a8c6a6ca4980f2c321f24
41,170
import json def form2(req, key, slug): """ Show the bookmarklet form. """ s = good_session(key) if not s: return redirect('bookmarklet:form1', slug=slug) data = json.loads(s.data) scholar_url = data['scholar_url'] doi = data['doi'] event = OAEvent.objects.get(id=data['even...
455c15831dcd17abdc6017997b403b9eaa621b2a
41,171
def GetNetworkPerformanceConfig(args, client): """Get NetworkPerformanceConfig message for the instance.""" network_perf_args = getattr(args, 'network_performance_configs', []) network_perf_configs = client.messages.NetworkPerformanceConfig() for config in network_perf_args: total_tier = config.get('total...
2b2f0773fb01b7bbcda30af38d03ed845331f10c
41,172
def inv_lr_scheduler(param_lr, optimizer, iter_num, gamma=0.0001, power=0.75, init_lr=0.001): """Decay learning rate by a factor of 0.1 every lr_decay_epoch epochs.""" lr = init_lr * (1 + gamma * iter_num) ** (- power) i = 0 for param_group in optimizer.param_groups: param_g...
e3876633b34bc8e2135f9e8d82e64e8bba42a6da
41,173
def OpenFace(openface_features, PID, EXP): """ Tidy up OpenFace features in pandas data.frame to be stored in sqlite database: - Participant and experiment identifiers are added as columns - Underscores in column names are removed, because sqlite does not like underscores in column names. ...
684e74c159a3551e3fd6d9a80b134c2474759056
41,174
def auth(function): """Wrapper checking if the user is logged in.""" @wraps(function) def wrapper(*args, **kwargs): testing = app.config.get('TESTING') if (session.get('users') and session.get('logged_in')) or testing: return function(*args, **kwargs) return redirect(FLOW...
26bb3d97bbe56a632f4d97c5b45c87e2022a5719
41,175
def svd_solve(A, b=None, w_cut=1e-10): """ This function solves the system of equations Ax=b by calculating the inverse of A using the SVD method: x=A^(-1)*b; A^(-1)=V*S^(-1)*U' Inputs: A: 2D array of dimensions nxm (n>=m) b: 1D array of dimensions n w_cut: cut-off frequency for ...
fdf153836cba3ff5a618797505fbbb221fe29237
41,176
import re def get_bootstrap_game(self, default_game='SamplesProject'): """ :param self: Context :param default_game: Default game to set to if we cannot read bootstrap.cfg. :return: Name of the game enabled in bootstrap.cfg """ game = default_game project_folder_node = ge...
0f58438de8cfe18dcab446b68d9c178df03c8c87
41,177
def check_issue(name, checks, controls): """ Checks if a certain RWT issue needs to be suggested. Returns: list """ rwt = [] is_issue = False total_reasons = [] total_offenders = [] for check in checks: for control in controls: if control != []: f...
7e16b5d7fe2e674a4e91ccec70ca6a5f47784c49
41,178
def create_training_instances(all_tokens, vocab_words, max_seq_length, rng): """Create `TrainingInstance`s from raw text.""" rng.shuffle(all_tokens) instances = [] print('Process of "create_training_instances"') for tokens in all_tokens: instances.append(create_instances_from_sentence(token...
c94b588aa0a5b8d9c1a8dd9be203d62d6acbe060
41,179
def get_binary_result(probs): """ 将预测结果转化为二分类结果 Args: probs: 预测结果 Return: binary_result: 二分类结果 """ binary_result = [] for i in range(len(probs)): if float(probs[i][0]) > 0.5: binary_result.append(1) elif float(probs[i][0]) < 0.5: binary...
df0375b05abe2807a1568133f8ed0aa4a5fe3736
41,180
def _find_open_boundary_neighbors(neighbors, open_boundary_nodes): """Array of booleans that indicate if a neighbor is an open boundary.""" open_boundary_neighbors = neighbors[:, open_boundary_nodes] is_open_boundary_neighbor = np.in1d(open_boundary_neighbors, open_boundary_nodes) is_open_boundary_neigh...
a2705c964d11bda3d1784f5356f44090a1cf2e62
41,181
from datetime import datetime def _boto3_now(): """Get a ``datetime`` that's compatible with :py:mod:`boto3`. These are always UTC time, with time zone ``dateutil.tz.tzutc()``. """ if tzutc is None: raise ImportError( 'You must install dateutil to get boto3-compatible datetimes') ...
509fdca72c6ceea1b3e2723d5446f41a8e72c9ec
41,182
def pass_trigger(evt): """ # HLT_QuadJet40_IsoPFTau40 if (evt.run<165970 ) | ((evt.run>166782 & evt.run<171050)): if evt.HLT_QuadJet40_IsoPFTau40 == 1: return True else: return False # HLT_QuadJet45_IsoPFTau45 elif ((evt.run>=165970) & (evt.run<=166782)) | ((...
cd64eae12ce723f29f77d89bb544024605c1e830
41,183
def ricker(t,ts,fsavg): """ Ricker Pulse @param t time vector @param ts temporal delay @param fsavg pulse width parameter @return Output signal vector """ a = fsavg*pi*(t-ts) a2 = a*a return ((1.0-2.0*a2)*np.exp(-a2))
cf21218b114940dbfae2bc4d016757f0c83722a4
41,184
def read_avgint(dismod_file): """Read average integrand cases, translating to locations and covariates.""" avgint = dismod_file.avgint with_integrand = avgint.assign(integrand=avgint.integrand_id.apply(lambda x: IntegrandEnum(x).name)) with_location = with_integrand.merge(dismod_file.node, on="node_id",...
8964b5cf997b566d245aadbabef5ddf924ee74b6
41,185
def extendedMeasurementReport(): """EXTENDED MEASUREMENT REPORT Section 9.1.52""" a = TpPd(pd=0x6) b = MessageType(mesType=0x36) # 00110110 c = ExtendedMeasurementResults() packet = a / b / c return packet
a08b6afa7fb60a800ee9ca9848d575ce2222c216
41,186
def part1(data): """ >>> part1(read_input()) 6916 """ twos = 0 threes = 0 for label in data: if has_count(label, 2): twos += 1 if has_count(label, 3): threes += 1 return twos * threes
af4a5a5a971eafce264d4132b79df035c2153c38
41,187
def f_whist_jeu_real(request, record_id): """ Saisie du réalisé 0 1 2 """ crudy = Crudy(request, APP_NAME) obj = get_object_or_404(WhistJeu, id=record_id) title = "Réalisé de %s" % (obj.participant.joueur.pseudo.upper()) if obj.pari > 1: crudy.message = "**%s**, combien de plis as-tu réalisé...
d59a15550ce9539b97750f31e1db343f583033e2
41,188
def expected_min(x, m): """Compute unbiased estimator of expected ``min(x[1:m])`` on a data set. Parameters ---------- x : :class:`numpy:numpy.ndarray` of shape (n,) Data set we would like expected ``min(x[1:m])`` on. Require ``len(x) >= 1``. m : `int` or :class:`numpy:numpy.ndarray` with d...
c0aef9a8123f625194665aec88b034adaa59ef49
41,189
def _load_transforms(): """ Load the transform pairs into the module level variable for later lookup. Returns ------- :class:`dict` """ return { f: (globals().get(f), globals().get("inverse_{}".format(f))) for f in globals().keys() if "inverse_{}".format(f) in global...
45ef7c50aee54e6daa344809e603f7abf7bbe836
41,190
def scalarclip(polydata, arrayname, scalarvalue, insideout=True, ispointdata=True): """Clip vtkPolyData returning regions with value of array above a specified value.""" clipper = vtk.vtkClipPolyData() clipper.SetInput(polydata) if ispointdata: # array is pointdata clipper.Se...
912e5aaf1c911e61e39526f0e688f52fcfc4edd2
41,191
import copy def deep_merge_dict(base, priority): """Recursively merges the two given dicts into a single dict. Treating base as the the initial point of the resulting merged dict, and considering the nested dictionaries as trees, they are merged os: 1. Every path to every leaf in priority would be re...
5c527f45d4ddee00f1e905b09165bcd3551412f6
41,192
def class_oneshot(X, y, clmod, testsize = .2, randomstate=2342, score_method = 'AUC'): """ Store test measures from one-shot classification methods. Input: design matrix, X, response vector, y, a classification model, clmod, size of test set, testsize, random num...
d9e0428f16c9f7abe5d3ef1fbf1c287b0610837e
41,193
def _BuildUpgradeCandidateList(location_ref, image_version_id, python_version, release_track=base.ReleaseTrack.GA): """Builds a list of eligible image version upgrades.""" image_version_service = image_version_api_util.Imag...
46c6d2b753cba78cefe21d4f1e718c30dfa004e6
41,194
def pointer_gamut_visual_response(): """ Returns a *Pointer's Gamut* visual response. Returns ------- Response *Pointer's Gamut* visual response. """ args = request.args json_data = pointer_gamut_visual( colourspace_model=args.get('colourspaceModel', COLOURSPACE_MODEL),...
a6498ac6aa38ae559cfb5a98e3d671aa8ff5403d
41,195