content
stringlengths
22
815k
id
int64
0
4.91M
def zip_dir(dir_path, zip_path): """ 压缩加密文件夹中的所有文件,以同步开始时间-结束时间命名,然后压缩到上传同步目录 :param dir_path: 目标文件夹路径 :param zip_path: 压缩后的文件夹路径 :return: """ try: zip = zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) for root, dirnames, filenames in os.walk(dir_path): file_...
5,326,200
def write_svg( output: TextIO, document: Document, page_size: Optional[Tuple[float, float]] = None, center: bool = False, source_string: str = "", layer_label_format: str = "%d", show_pen_up: bool = False, color_mode: str = "none", single_path: bool = False ) -> None: """Create a...
5,326,201
def get_elevation_data(lonlat, dem_path): """ Get elevation data for a scene. :param lon_lat: The latitude, longitude of the scene center. :type lon_lat: float (2-tuple) :dem_dir: The directory in which the DEM can be found. :type dem_dir: str """ datafi...
5,326,202
def iso8601(dt=None, aware=False): """ Returns string datetime stamp in iso 8601 format from datetime object dt If dt is missing and aware then use now(timezone.utc) else utcnow() naive YYYY-MM-DDTHH:MM:SS.mmmmmm which is strftime '%Y-%m-%dT%H:%M:%S.%f' Only TZ aware in python 3.2+ """ if dt...
5,326,203
def closeinstr(line, local_ns): """Close the specified instrument.""" name = line.strip() if not name: return logger.info('Closing {0}.'.format(name)) if name not in __instruments__: print('Unknown instrument {0}.'.format(name)) return inst = __instruments__[name] lis...
5,326,204
def parse_text(infile, xpath=None, filter_words=None, attributes=None): """Filter text using XPath, regex keywords, and tag attributes. Keyword arguments: infile -- HTML or text content to parse (list) xpath -- an XPath expression (str) filter_words -- regex keywords (list) attributes -- HTML t...
5,326,205
def say_date(tts): """ The AI gives current date. Parameters: tts (TextToSpeech) """ expression = "We are the " + str(date.today()) + "." say(ASSISTANT_NAME, expression, tts)
5,326,206
def _check_blacklist_members(rule_members=None, policy_members=None): """Blacklist: Check that policy members ARE NOT in rule members. If a policy member is found in the rule members, add it to the violating members. Args: rule_members (list): IamPolicyMembers allowed in the rule. poli...
5,326,207
def test_title_contains_both_axes_figure(pt_line_plt): """Check title_contains tester for combined axes + figure titles""" pt_line_plt.assert_title_contains( ["My", "Figure", "Plot", "Title"], title_type="either" ) plt.close()
5,326,208
def list_in_edges(node): """Handle Tuple here.""" assert isinstance(node, relay.Call) for src in list_in_nodes(node): yield (src, node)
5,326,209
def create_variable_weather(weather_data, original_epw_file, columns: list = ['drybulb'], variation: tuple = None): """ Create a new weather file adding gaussian noise to the original one. Parameters ---------- weather_data : opyplus.WeatherData Opyplus object with the weather for the simul...
5,326,210
def transform(func, geom): """Applies `func` to all coordinates of `geom` and returns a new geometry of the same type from the transformed coordinates. `func` maps x, y, and optionally z to output xp, yp, zp. The input parameters may iterable types like lists or arrays or single values. The output ...
5,326,211
def get_jit(policy_name, asc_location, resource_group_name): """Building query Args: policy_name: Policy name asc_location: Machine location resource_group_name: Resource name group Returns: dict: response body """ cmd_url = ( "/resourceGroups/{}/providers/M...
5,326,212
def rank_by_yield(df): """ Rank phenotypes by yield only. Parameters ---------- df : pd.DataFrame MAIZSIM yield output dataframe. df_sims or df_mature """ # Prep data groups = ['cvar', 'site'] how = 'mean' sim = 'dm_ear' mx_mean = agg_sims(df, groups, how, ...
5,326,213
def k2lc(epic): """ load k2 light curve """ prefix = epic[:4] id = epic[4:] c = "01" path = "data/c01/{0}00000/{1}".format(prefix, id) end = "kepler_v1.0_lc.fits" file = "{0}/hlsp_everest_k2_llc_{1}-c{2}_{3}".format(path, epic, c, end) x, y = process_data(file) return x, y
5,326,214
def caclulateHospitalBedsAvailability(): """ /** * @def caclulatHospitalBedsAvailability * @param sampleCaseData * @returns hospitalBedsByRequestedTime * @description This is the estimated a 35% bed availability in hospitals for severe COVID-19 positive patients. */ """ global sampleCaseDa...
5,326,215
def multi_leave_topics(multileaver, user_id, time): """Multileaves a number of suggested topics for a user and returns the results.""" topics = get_user_suggested_topics(user_id) if not topics: return None ranking, credit = multileaver.team_draft_multileave(topics) topic_recommendations...
5,326,216
def generate_age(sex): """Generate the age of a person depending on its sex Parameters ---------- sex : int Sex should be either 0 (men) or 1 (women). Raises ------ ValueError If sex is not 0 or 1. Returns ------- age : int Generated age of a perso...
5,326,217
def _extract_text_Wikilink(node: mwparserfromhell.nodes.wikilink.Wikilink) -> str: """ Wikilinks come in 2 formats, thumbnails and actual links. In the case of thumbnails, if posible pull out the nested caption. """ if node.title.startswith('File:') or node.title.startswith('Image:'): if nod...
5,326,218
def dict_zip(*dicts): """ Take a series of dicts that share the same keys, and reduce the values for each key as if folding an iterator. """ keyset = set(dicts[0]) for d in dicts: if set(d) != keyset: raise KeyError(f"Mismatched keysets in fold_dicts: {sorted(keyset)}, {sorte...
5,326,219
def process_command_line(): """ Parse command line arguments `argv` is a list of arguments, or `None` for ``sys.argv[1:]``. Return a Namespace representing the argument list. """ # Create the parser parser = argparse.ArgumentParser(prog='obflow_6_output', ...
5,326,220
def Ustagger_to_mass(U): """ U are the data on the left and right of a grid box A simple conversion of the U stagger grid to the mass points. Calculates the average of the left and right value of a grid box. Looping over all columns it reduces the staggered grid to the same dimensions as the mas...
5,326,221
def _linear(args, output_size, bias, bias_initializer=tf.zeros_initializer(), kernel_initializer=initializer(), scope=None, reuse=None): """Linear map: sum_i(args[i] * W[i]), where W[i] is a variable. Args: args: a 2D Tensor or a l...
5,326,222
def build_fpn_mask_graph(rois, feature_maps, image_size, num_classes, pool_size, train_bn=True): """Builds the computation graph of the mask head of Feature Pyramid Network. rois: [batch, num_rois, (y1, x1, y2, x2)] Proposal boxes in normalized coordinates. feature_maps: L...
5,326,223
def calculate_perf_counter_counter(previous, current, property_name): """ PERF_COUNTER_COUNTER https://technet.microsoft.com/en-us/library/cc740048(v=ws.10).aspx """ n0 = previous[property_name] n1 = current[property_name] d0 = previous["Timestamp_Sys100NS"] d1 = current["Timestamp_Sys1...
5,326,224
def event_edit(request, id): """Edit form for a particular event.""" event = get_object_or_404(Event, id=id) result = can_edit_event(event, request.user) if isinstance(result, http.HttpResponse): return result if request.user.has_perm('main.change_event_others'): form_class = forms.E...
5,326,225
def migrator(from_: str, to_: str) -> Callable[[MigratorF], MigratorF]: """Decorate function as migrating settings from v `from_` to v `to_`. A migrator should mutate a `NapariSettings` model from schema version `from_` to schema version `to_` (in place). Parameters ---------- from_ : str ...
5,326,226
def rawChipByLocation_query(): """ Get chips images by parcel id. Generates a series of extracted Sentinel-2 LEVEL2A segments of 128x128 (10m resolution bands) or 64x64 (20 m) pixels as list of full resolution GeoTIFFs --- tags: - rawChipByLocation responses: 200: descrip...
5,326,227
def load_adni_longitudinal_av45_pet(): """Returns paths of longitudinal ADNI AV45-PET """ # get file paths and description (subjects, subject_paths, description) = _get_subjects_and_description(base_dir='ADNI_av45_pet', prefix='I[0-9]*') ...
5,326,228
def build_settings( tmp_path: Path, template: str, *, oidc_clients: Optional[List[OIDCClient]] = None, **settings: str, ) -> Path: """Generate a test Gafaelfawr settings file with secrets. Parameters ---------- tmp_path : `pathlib.Path` The root of the temporary area. te...
5,326,229
def test_add_trcvr_init_error(): """Test error is raised if trcvr is the only input to init.""" pytest.raises(ValueError, DelaySpectrum, trcvr=9 * units.K)
5,326,230
def load_mnist(path, data_type='train'): """Load MNIST data from `path`""" labels_path = os.path.join(path, '%s-labels.idx1-ubyte' % data_type) images_path = os.path.join(path, '%s-images.idx3-ubyte' ...
5,326,231
def view(file_name: str, driver: str = "eida50", open_tab: bool = True, palette: str = "Viridis", port: int = 1234): """ FOREST Lite viewer A simplified interface to the FOREST Lite server tool """ port = scan_port(port) if open_tab: url = f"http://localhost:{port}" ...
5,326,232
def get_actions_matching_arn(arn): """ Given a user-supplied ARN, get a list of all actions that correspond to that ARN. Arguments: arn: A user-supplied arn Returns: List: A list of all actions that can match it. """ raw_arns = get_matching_raw_arns(arn) results = [] for...
5,326,233
def path_splitter(path): """ Split a path into its constituent parts. Might be better written as a recursive function. :param path: The path to split. :return: A list of the path's constituent parts. """ res = [] while True: p = os.path.split(path) if p[0] == path: ...
5,326,234
def _run_defp(mode,code,time_steps,error_model,decoder,error_probability,perm_rates,code_name,layout,measurement_error_probability, max_runs=None,max_failures=None,random_seed=None): """Implements run and run_ftp functions""" # assumptions assert (mode == 'ideal' and time_steps == 1) or mode == 'ft...
5,326,235
def api_retry(func, task_id): """ 添加api重试机制 :param func: 调用的api函数 :param task_id: 任务id :return: 重试结果 """ retry_flag, status_result = False, "" for i in range(TRANSPORT_RETRY_TIMES): time.sleep(TRANSPORT_RETRY_INTERVAL) retry_flag, status_result = func(task_id) if...
5,326,236
def _step_5(d, n_max, mp_max, Hwedge, Hv): """Recursively compute H^{m'−1, m}_{n}(β) for m'=−1,...,−n+1, m=−m',...,n using relation (50) resolved with respect to H^{m'−1, m}_{n}: d^{m'−1}_{n} H^{m'−1, m}_{n} = d^{m'}_{n} H^{m'+1, m}_{n} + d^{m−1}_{n} H^{m', m−1}_{n} ...
5,326,237
def test_bound_callables(): """Test that we can use a callable as a bound value.""" @magicgui(x={"bind": lambda x: 10}) def f(x: int = 5): return x assert f() == 10 f.x.unbind() assert f() == 5
5,326,238
def delete_role(user_id: str, role_id: str): """ Removes a role from a user """ print(user_id) print(role_id) return jsonify(), HTTPStatus.NO_CONTENT
5,326,239
def remove_degenerate_seqs( alignment_obj: BaseAlignment, identity_limit: int, show_id_array: bool = False ) -> BaseAlignment: """ Filter high similarity sequences from a list of Seq objects Returns: BaseAlignment """ import multiprocessing as mp from functools import partial from jinfo...
5,326,240
def api_add_resource(): """ The resource has multiple URLs and you can pass multiple URLs to the add_resource() method on the Api object. Each one will be routed to your Resource """ for url_pattern in URLPATTERNS: try: API.add_resource( get_resource(url_patte...
5,326,241
def get_domain(url): """ Get the domain from a URL. Parameters ---------- url : string HTTP URL Returns ------- domain : string domain of the URL """ o = urlparse(url) scheme = o.scheme if not o.scheme: scheme = "http" link = scheme + "://" + o...
5,326,242
def push_activations(activations, from_layer, to_layer): """Push activations from one model to another using prerecorded correlations""" inverse_covariance_matrix = layer_inverse_covariance(from_layer) activations_decorrelated = np.dot(inverse_covariance_matrix, activations.T).T covariance_matrix = laye...
5,326,243
def p_path_primary_0(p): """ path_primary : iri """ p[0] = p[1]
5,326,244
def pid_calibration_allfills(mydir='/Users/kocolosk/data/run5/hist-by-fill'): """generates a PDF of triple-Gaussian fits for all fills, plus a histogram of pion means""" allFiles = os.listdir(mydir) hfill = ROOT.TH1D('hfill','mean of pion Gaussian by RHIC Fill', len(allFiles), 0.5, len(allFiles)+0.5) ps...
5,326,245
def cross_val_score(estimator, X, y=None, groups=None, scoring=None, cv=None, n_jobs=1, verbose=0, fit_params=None, pre_dispatch='2*n_jobs'): """Evaluate a score using cross-validation Parameters ---------- estimator : estimator object implementing 'fit' The object to use to...
5,326,246
def test_empty(): """ Empty relevancy """ assert relevancy_to_adjust('') == list()
5,326,247
def load_graph(N, M): """ Builds an adjacency list representation of a graph with N vertices. Each graph[i][j] is the minimum length of an edge between vertice i and j. :rtype List[int, Dict[int, int]] """ graph = [dict() for i in range(0, N)] for i in range(0, M): (x, y, r) = read...
5,326,248
def quartile_range(arr): """ Find out the Interquartile Range """ #if it is odd if len(arr)%2 != 0: left=median(arr[:len(arr)/2]) right=median(arr[len(arr)/2 + 1:]) else: #if array is even left = median(arr[:len(arr)/2]) right = median(arr[len(arr)/2:]) ...
5,326,249
def border (surface, rect, data): """Fill with a border. Takes (border_width, border_colour, inner_colour). If inner_colour is omitted or width is 0, border colour is used for the whole tile. """ if len(data) == 2: border = data[1] width = 0 else: width, border, inner = data s...
5,326,250
def check_syntax(filename, raise_error=False): """Return True if syntax is okay.""" with autopep8.open_with_encoding(filename) as input_file: try: compile(input_file.read(), '<string>', 'exec', dont_inherit=True) return True except (SyntaxError, TypeError, UnicodeDecodeEr...
5,326,251
def test_process_image_pixels(): """Check the example how to implement convolution given in the docstring""" from astropy.convolution import convolve as astropy_convolve def convolve(image, kernel): '''Convolve image with kernel''' from ..utils import process_image_pixels images = d...
5,326,252
def im2vec(im, bsize, padsize=0): """ Converts image to vector. Args: im: Input image to be converted to a vector. bsize: Size of block of im to be converted to vec. Must be 1x2 non-negative int array. padsize (optional, default=0): Must be non-negative integers in a 1x2 array. Amou...
5,326,253
async def test_enable_service_call(hass): """Test enable service call with no Pi-hole named.""" mocked_hole = _create_mocked_hole() with _patch_config_flow_hole(mocked_hole), _patch_init_hole(mocked_hole): assert await async_setup_component( hass, pi_hole.DOMAIN, ...
5,326,254
def mobilenetV2_block( input_layer, filters: int = 32, dropout_ratio: float = DEFAULT_DROPOUT_RATIO, use_batchnorm: bool = False, prefix: str = "mobilenetV2_", initializer=DEFAULT_KERNEL_INITIALIZER, regularizer=DEFAULT_KERNEL_REGULARIZER, channels_index: ...
5,326,255
def test_regex(): """Runs simple tests on the Regex filter.""" filt = RegexFilter(pattern="foo") test_cases = { "foo.py": True, "bar/foo.py": True, "bar/foo": True, "bar/baz": False, "baz": False, "oof": False, } test_cases = [(FileItem(key=path), res...
5,326,256
def update_git_config_context_schemas(repository_record, job_result): """Refresh any config context schemas provided by this Git repository.""" config_context_schema_path = os.path.join(repository_record.filesystem_path, "config_context_schemas") if not os.path.isdir(config_context_schema_path): ret...
5,326,257
def _grid_archive(): """Deterministically created GridArchive.""" # The archive must be low-res enough that we can tell if the number of cells # is correct, yet high-res enough that we can see different colors. archive = GridArchive([10, 10], [(-1, 1), (-1, 1)], seed=42) archive.initialize(solution_...
5,326,258
def check_flush(hand): """Check whether the hand has a flush; returns a boolean.""" if len(hand) == len(hand.by_suit(hand[0].suit)): return True return False
5,326,259
def binary_accuracy(preds, y): """ Returns accuracy per batch :param preds: prediction logits :param y: target labels :return: accuracy = percentage of correct predictions """ # round predictions to the closest integer rounded_predictions = torch.round(torch.sigmoid(preds)) correct ...
5,326,260
def load_taxondump(idpath): """Importing the Acidobacteria taxon IDs""" taxons = {} with open(idpath) as csvfile: reader = csv.reader(csvfile, delimiter=',') for row in reader: taxons[row[1]] = row[0] return taxons
5,326,261
def _to_numeric_range(cell): """ Translate an Excel cell (eg 'A1') into a (col, row) tuple indexed from zero. e.g. 'A1' returns (0, 0) """ match = re.match("^\$?([A-Z]+)\$?(\d+)$", cell.upper()) if not match: raise RuntimeError("'%s' is not a valid excel cell address" % cell) col, ro...
5,326,262
def LUCroutDecompose(A): """ Implementação do método de Crout para decomposição LU. """ assert A.shape[0] == A.shape[1] and type(A) is matrix, "'A' deve ser NxN." L = zeros(A.shape) n = A.shape[0] U = L.copy() lib.LUDec(n, byref(ctypeslib.as_ctypes(A)), byref(ctypeslib.as_c...
5,326,263
def protocol(recarr, design_type, *hrfs): """ Create an object that can evaluate the FIAC Subclass of formulae.Formula, but not necessary. Parameters ---------- recarr : (N,) structured array with fields 'time' and 'event' design_type : str one of ['event', 'block']. Handles how...
5,326,264
def iter_children(param,childlist=[]): """ | Iterator over all sub children of a given parameters. | Returns all childrens names. =============== ================================= ==================================== **Parameters** **Type** **Description*...
5,326,265
def shell__shell_hook(callback: Callable[[int, WPARAM, LPARAM], Optional[str]]) -> Union[HHOOK, WindowsErrorMessage]: """ Adds a global shell hook, called when any key is pressed in any context. The callback is called directly in the thread that invoked this method. It is up to the callback to be as r...
5,326,266
def depth_first_graph_search(problem): """ [Figure 3.7] Search the deepest nodes in the search tree first. Search through the successors of a problem to find a goal. The argument frontier should be an empty queue. Does not get trapped by loops. If two paths reach a state, only use the first ...
5,326,267
def check_matrix_equality(A, B, tol=None): """ Checks the equality of two matrices. :param A: The first matrix :param B: The second matrix :param tol: The decimal place tolerance of the check :return: The boolean result of the equality check """ if len(A) != len(B) or len...
5,326,268
def about(topic): """Return a select function that returns whether a paragraph contains one of the words in TOPIC. Arguments: topic: a list of words related to a subject >>> about_dogs = about(['dog', 'dogs', 'pup', 'puppy']) >>> choose(['Cute Dog!', 'That is a cat.', 'Nice pup!'], about_d...
5,326,269
def calcBarycentricCoords(pt, verts): """calculate the Barycentric coordinates""" verts = np.array(verts) # vertices formed by N+1 nearest voxels pt = np.array(pt) # voxel of interest A = np.transpose(np.column_stack((verts, np.ones(verts.shape[0])))) b = np.append(pt, 1) retur...
5,326,270
def get_masked_fastas(bed): """create the masked fasta files per chromosome. needed to run bl2seq. and puts it into a dictionary seqid to path to genomic masked fasta""" f = bed.fasta.fasta_name fname = op.splitext(op.basename(f))[0] d = op.dirname(f) + "/%s_split" % fname try: os.mkdir(d) e...
5,326,271
def parse_regex(ctx, param, values): """Compile a regex if given. :param click.Context ctx: click command context. :param click.Parameter param: click command parameter (in this case, ``ignore_regex`` from ``-r|--ignore-regiex``). :param list(str) values: list of regular expressions to be compi...
5,326,272
def FileJustRoot(fileName): """ Gets just the root of the file name """ try: return os.path.splitext(fileName)[0] except: return ""
5,326,273
def generate_command(pbs_script, pbs_config, pbs_vars=None, python_exe=None): """Prepare a correct PBS command string""" pbs_env_init() # Initialisation if pbs_vars is None: pbs_vars = {} # Necessary for testing if python_exe is None: python_exe = sys.executable pbs_flags...
5,326,274
def get_query_string(**kwargs): """ Concatenates the non-None keyword arguments to create a query string for ElasticSearch. :return: concatenated query string or None if not arguments were given """ q = ['%s:%s' % (key, value) for key, value in kwargs.items() if value not in (None, '')] return ...
5,326,275
def check_bin(img): """Checks whether image has been properly binarized. NB: works on the assumption that there should be more background pixels than element pixels. Parameters ---------- img : np.ndarray Description of parameter `img`. Returns ------- np.ndarray A bina...
5,326,276
def add_quotes(path): """Return quotes if needed for spaces on path.""" quotes = '"' if ' ' in path and '"' not in path else '' return '{quotes}{path}{quotes}'.format(quotes=quotes, path=path)
5,326,277
def terminal(board): """ Returns True if game is over, False otherwise. """ if len(actions(board)) == 0: return True if winner(board) is not None: return True return False #raise NotImplementedError
5,326,278
def login(): """LogIn Page""" if request.method == "GET": return render_template("login.html") email = request.form.get("email") password = request.form.get("password") remember = bool(request.form.get("remember")) user = User.query.filter_by(email=email).first() if not user or not...
5,326,279
def apply_modifiers(membership: npt.ArrayLike, modifiers: List[str]) -> npt.ArrayLike: """ Apply a list of modifiers or hedges to a numpy array. :param membership: Membership values to be modified. :param modifiers: List of modifiers or hedges. >>> from fuzzy_expert.operators import apply_modifie...
5,326,280
def send_file_to_developers(filename): """ Loads a file to send data to the developers. @param filename: file to send @return: """ try: with open(filename, "r") as f: data = f.read() except: if data is None: return # There is no file, there is no dat...
5,326,281
def test_labels_new_label_unauthorized(client): """Tests adding a new label with an unauthorized key""" response = client.post( '/ny/panel/labels', headers={'X-AUTH': 'WRITE'}, json={'action': 'create', 'label': 'bar', 'icon': '🔮'}) assert(response.status_code == 401)
5,326,282
def unitY(m=1.0): """Return an unit vector on Y""" return np.array((0, m, 0))
5,326,283
def create_suction_model(radius): """Create a suction model""" hm = np.zeros((2 * radius + 1, 2 * radius + 1)) hm1 = np.tile(np.arange(-radius, radius + 1), (2 * radius + 1, 1)) hm2 = hm1.T d = np.sqrt(hm1**2 + hm2**2) return np.where(d < radius, 1, 0).astype(np.float64)
5,326,284
def model_entrypoint(model_name): """Fetch a model entrypoint for specified model name """ return _model_entrypoints[model_name]
5,326,285
def test_oais_fail_transfer(db): """Test the oais_fail_transfer function.""" # let's create a SIP sip = SIP.create() Archive.create(sip) db.session.commit() # we fail the transfer oais_fail_transfer(sip.id) assert Archive.query.count() == 1 ark = Archive.get_from_sip(sip.id) asse...
5,326,286
def _scan_duplicates(rootpath: str, files_dict: dict): """ Scan rootpath for duplicates. """ if not os.path.isabs(rootpath): rootpath = os.path.abspath(rootpath) for dirpath, _, filenames in os.walk(rootpath): for filename in filenames: absfilename = os.path.join(dirpath, filena...
5,326,287
def encrypt(data, password): """Enrcrypt data and return content in binary""" try: cipher = AES.new(password.encode(), AES.MODE_CBC) cypher_text_bytes = cipher.encrypt(pad(data.encode(), AES.block_size)) return b'' + cipher.iv + b':' + cypher_text_bytes except ValueError: p...
5,326,288
def change_datetime_to_str(input_time=None, str_format="%Y-%m-%d"): """ :param input_time: 指定需要转换的时间, 默认当前时间 :param str_format: 字符时间的格式, 默认%Y-%m-%d :return: """ spec_time = input_time or datetime.datetime.now() return spec_time.strftime(str_format)
5,326,289
def find_possible_words(word: str, dictionary: list) -> list: """Return all possible words from word.""" possible_words = [] first_character = word[0] last_character = word[len(word) - 1] for dictionary_entry in dictionary: if (dictionary_entry.startswith(first_character) and ...
5,326,290
def train(train_loader, model, criterion, optimizer, epoch): """ One epoch's training. :param train_loader: DataLoader for training data :param model: model :param criterion: MultiBox loss :param optimizer: optimizer :param epoch: epoch number """ model.train() # training...
5,326,291
def diag_multidim_gaussian_log_likelihood(z_u, mean_u, logvar_u, varmin): """Log-likelhood under a multidimensional Gaussian distribution with diagonal covariance. Returns the log-likelihood for the multidim distribution. """ return np.sum(diag_gaussian_log_likelihood(z_u, mean_u, logvar_u, varmin), axis=0)
5,326,292
def _shared_galaxy_properties(config_directory, kwds, for_tests): """Setup properties useful for local and Docker Galaxy instances. Most things related to paths, etc... are very different between Galaxy modalities and many taken care of internally to the container in that mode. But this method sets up ...
5,326,293
def copyPoses(nodeA, nodeB, emptyPoseValues=True): """Copy poses from nodeA to nodeB with the option to be blank or node for syncing nodes OF EQUAL LENGTH IN POSE INFO Args: nodeA (str): name of weightedNode nodeB (str): name of weightedNode emptyPoseValues (bool, optional): should ...
5,326,294
def get_method(java_object, method_name): """Retrieves a reference to the method of an object. This function is useful when `auto_field=true` and an instance field has the same name as a method. The full signature of the method is not required: it is determined when the method is called. :param ja...
5,326,295
def sentence_tokenize_cmd(lines: types.Lines, language: str) -> types.Sentences: """Tokenizes lines into sentences. Downloads nltk resources if they don't exist.""" try: nltk.data.find('tokenizers/punkt') except LookupError: nltk.download('punkt') line = '' try: for line in ...
5,326,296
def createRegionLabeledSet(setname, entity, label, mesh, format="Exodus II"): """Create a labeled set region. setname | string, name of the region entity | string, entity (see mesh_entity.py) label | string, label id in mesh file (note this is usually a string containing an integer) ...
5,326,297
def set_up_cube( zero_point_indices=((0, 0, 7, 7),), num_time_points=1, num_grid_points=16, num_realization_points=1, ): """Set up a cube with equal intervals along the x and y axis.""" zero_point_indices = list(zero_point_indices) for index, indices in enumerate(zero_point_indices): ...
5,326,298
def messageBox(self, title, text, icon=QMessageBox.Information): """ Working on generic message box """ m = QMessageBox(self) m.setWindowTitle(title) m.setText(text) m.setIcon(icon) # yesButton = m.addButton('Yes', QMessageBox.ButtonRole.YesRole) # noButton = m.addButton('No', QMess...
5,326,299