content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Dict from pathlib import Path from sys import path from typing import Counter def get_word_counts(filepath: str) -> Dict[str, int]: """ Return a dictionary of key-value pairs where keys are words from the given file and values are their counts. If there is no such file, return an em...
30fd14031b00766320ad0f1728042438cb05fd4e
13,800
import ctypes def getVanHoveDistances(positions, displacements, L): """ Compte van Hove distances between particles of a system of size `L', with `positions' and `displacements'. Parameters ---------- positions : (*, 2) float array-like Positions of the particles. displacements : ...
a66150cfe238b151f098733d4570c438f1c93906
13,801
from typing import Any from typing import Union from typing import List def plot_local_coordinate_system_matplotlib( lcs, axes: plt.Axes.axes = None, color: Any = None, label: str = None, time: Union[pd.DatetimeIndex, pd.TimedeltaIndex, List[pd.Timestamp]] = None, time_ref: pd.Timestamp = None...
2df77f0e3343f6ac541ff37991208fb894b44660
13,802
def saved_searches_list(request): """ Renders the saved_searches_list html """ args = get_saved_searches_list(request.user) return render('saved_searches_list.html', args, request)
a2f92c06733113f05501cb242d2ee2bad91917be
13,803
import os def upload(): """Upload files. This endpoint is used to upload "trusted" files; E.i. files created by CERT-EU E.g. CITAR, CIMBL, IDS signatures, etc. **Example request**: .. sourcecode:: http POST /api/1.0/upload HTTP/1.1 Host: do.cert.europa.eu Accept: applic...
5da57c64928c9212162667d036423070acbdb4f7
13,804
def get_active_loan_by_item_pid(item_pid): """Return any active loans for the given item.""" return search_by_pid( item_pid=item_pid, filter_states=current_app.config.get( "CIRCULATION_STATES_LOAN_ACTIVE", [] ), )
6922336876fddd72ce7655bf2cfee298fdc4a766
13,805
from typing import Set from re import X def _get_szymkiewicz_simpson_coefficient(a: Set[X], b: Set[X]) -> float: """Calculate the Szymkiewicz–Simpson coefficient. .. seealso:: https://en.wikipedia.org/wiki/Overlap_coefficient """ if a and b: return len(a.intersection(b)) / min(len(a), len(b))...
42d39edf9fa2465605717e0892bcbca05df7799b
13,806
def data_splitter( input: pd.DataFrame, ) -> Output(train=pd.DataFrame, test=pd.DataFrame,): """Splits the input dataset into train and test slices.""" train, test = train_test_split(input, test_size=0.1, random_state=13) return train, test
ddcc28b4430a8901fcde540cf321d4ea43f123d7
13,807
def reload(module, exclude=('sys', 'os.path', 'builtins', '__main__', 'numpy', 'numpy._globals')): """Recursively reload all modules used in the given module. Optionally takes a list of modules to exclude from reloading. The default exclude list contains sys, __main__, and __bu...
c97fd1942dae583ff236ed73d33b53b685cafd32
13,808
def get_words_for_board(words, board_size, packing_constant=1.1): """Pick a cutoff which is just beyond limit of the board size.""" # Order the words by length. It's easier to pack shorter words, so prioritize them. # This is SUPER hacky, should have a Word class that handles these representational differe...
e5f74806fa15c1f1fbe78e0ac218d6d808611dfe
13,809
def booleans(key, val): """returns ucsc formatted boolean""" if val in (1, True, "on", "On", "ON"): val = "on" else: val = "off" return val
f210a2ce6b998e65d2e5934f1318efea0f96c709
13,810
def merge_param_classes(*cls_list, merge_positional_params: bool = True) -> type(Params): """ Merge multiple Params classes into a single merged params class and return the merged class. Note that this will not flatten the nested classes. :param cls_list: A list of Params subcla...
c42907652f971d7cd6d208017b8faaacacddb5b2
13,811
import random import collections def make_pin_list(eff_cnt): """Generates a pin list with an effect pin count given by eff_cnt.""" cards = [1] * eff_cnt cards.extend([0] * (131 - len(cards))) random.shuffle(cards) deck = collections.deque(cards) pin_list = [] for letters, _ in KEY_WHEEL_DA...
2c15a09928231993f09a373354ee29723463280d
13,812
import select def drop(cols, stmt): """ Function: Drops columns from the statement. Input: List of columns to drop. Output: Statement with columns that are not dropped. """ col_dict = column_dict(stmt) col_names = [c for c in col_dict.keys()] colintention = [c.evaluate(stmt).name if i...
73ecf35077824281a5ebc4e26776b963e0cb378e
13,813
def ConvertVolumeSizeString(volume_size_gb): """Converts the volume size defined in the schema to an int.""" volume_sizes = { "500 GB (128 GB PD SSD x 4)": 500, "1000 GB (256 GB PD SSD x 4)": 1000, } return volume_sizes[volume_size_gb]
b1f90e5ded4d543d88c4f129ea6ac03aeda0c04d
13,814
def render_template_with_system_context(value): """ Render provided template with a default system context. :param value: Template string. :type value: ``str`` :param context: Template context. :type context: ``dict`` """ context = { SYSTEM_KV_PREFIX: KeyValueLookup(), } ...
6df2e7a652595b35919638791aae5465258edf0f
13,815
def ToTranslation(tree, placeholders): """Converts the tree back to a translation, substituting the placeholders back in as required. """ text = tree.ToString() assert text.count(PLACEHOLDER_STRING) == len(placeholders) transl = tclib.Translation() for placeholder in placeholders: index = text.find(PL...
36fca25dfc78e0f37ddc6193a17f2d29c6192228
13,816
import torch def complex(real, imag): """Return a 'complex' tensor - If `fft` module is present, returns a propert complex tensor - Otherwise, stack the real and imaginary compoenents along the last dimension. Parameters ---------- real : tensor imag : tensor Returns ...
272a293e3918e5e067f251a7dae10a4d2c56abf4
13,817
def get_snps(x: str) -> tuple: """Parse a SNP line and return name, chromsome, position.""" snp, loc = x.split(' ') chrom, position = loc.strip('()').split(':') return snp, chrom, int(position)
52672c550c914d70033ab45fd582fb9e0f97f023
13,818
def qr_match(event, context, user=None): """ Function used to associate a given QR code with the given email """ user_coll = coll('users') result = user_coll.update_one({'email': event["link_email"]}, {'$push': {'qrcode': event["qr_code"]}}) if result.matched_count == 1: return {"status...
7af48bc9fc97d34eb182eb8f429d93396079db87
13,819
def update_has_started(epoch, settings): """ Tells whether update has started or not :param epoch: epoch number :param settings: settings dictionary :return: True if the update has started, False otherwise """ return is_baseline_with_update(settings['baseline']) and epoch >= settings['updat...
d2d2c8d7d8de0a13414a116121fb3cec47bc1d3f
13,820
import torch def compute_i_th_moment_batches(input, i): """ compute the i-th moment for every feature map in the batch :param input: tensor :param i: the moment to be computed :return: """ n, c, h, w = input.size() input = input.view(n, c, -1) mean = torch.mean(input, dim=2).view(n...
2ab3b7bfd34b482cdf55d5a066b57852182b5b6a
13,821
def hs_online_check(onion, put_url): """Online check for hidden service.""" try: print onion return hs_http_checker(onion, put_url) except Exception as error: print "Returned nothing." print error return ""
19b7b2f45581e2bdb907d416be1885f569841a86
13,822
def plotfile(fname, cols=(0,), plotfuncs=None, comments='#', skiprows=0, checkrows=5, delimiter=',', names=None, subplots=True, newfig=True, **kwargs): """ Plot the data in a file. *cols* is a sequence of column identifiers to plot. An identifier is either an int or a string....
493fccdf7d3661b9acffd22dbfd5799126a3d4f8
13,823
import argparse def parse_options(): """Parses and checks the command-line options. Returns: A tuple containing the options structure. """ usage = 'Usage: ./update_mapping.py [options]' desc = ('Example: ./update_mapping.py -o mapping.json.\n' 'This script generates and stores a file that gives the\n...
7f7ee6a90e152023dbf6c6e163361a8c327108ae
13,824
def retrieve(object_type, **kwargs): """Get objects from the Metatlas object database. This will automatically select only objects created by the current user unless `username` is provided. Use `username='*'` to search against all users. Parameters ---------- object_type: string The ...
54d35c23dd92ad65c5911d8c451b5b1fcbd131da
13,825
def read_plot_pars() : """ Parameters are (in this order): Minimum box width, Maximum box width, Box width iterations, Minimum box length, Maximum box length, Box length iterations, Voltage difference """ def extract_parameter_from_string(string): #returns the part ...
c78dc8e2a86b20eb6007850a70c038de5bf9f841
13,826
import typing def create(subscribe: typing.Subscription) -> Observable: """Creates an observable sequence object from the specified subscription function. .. marble:: :alt: create [ create(a) ] ---1---2---3---4---| Args: subscribe: Subscription function. ...
79c149545475a7686f8f8dffaed8f343604dd4aa
13,827
def tocl(d): """Generate TOC, in-page links to the IDs we're going to define below""" anchors = sorted(d.keys(), key=_lower) return TemplateData(t='All The Things', e=[a for a in anchors])
8c27c42f05e4055a8e195d4d352345acc7821bae
13,828
def get_upper_parentwidget(widget, parent_position: int): """This function replaces this: self.parentWidget().parentWidget().parentWidget() with this: get_upper_parentwidget(self, 3) :param widget: QWidget :param parent_position: Which parent :return: Wanted parent widget ...
ff010f3d9e000cfa3c58160e150c858490f2412d
13,829
def DirectorySizeAsString(directory): """Returns size of directory as a string.""" return SizeAsString(DirectorySize(directory))
3e3d3b029da40502c2f0e7e5867786d586ad8109
13,830
def patch_is_tty(value): """ Wrapped test function will have peltak.core.shell.is_tty set to *value*. """ def decorator(fn): # pylint: disable=missing-docstring @wraps(fn) def wrapper(*args, **kw): # pylint: disable=missing-docstring is_tty = shell.is_tty shell.is_tty ...
77655d32a5572824978910a12378a54d83b7e81e
13,831
import torch import math def uniform_unit_scaling(tensor: torch.Tensor, nonlinearity: str = "linear"): """ An initaliser which preserves output variance for approximately gaussian distributed inputs. This boils down to initialising layers using a uniform distribution in the range `(-sqrt(3/dim[0]) * s...
aa14ec45c389c55c141d9bffd6ef370313fdf446
13,832
def get_results(elfFile): """Converts and returns collected data.""" staticSizes = parseElf(elfFile) romSize = sum([size for key, size in staticSizes.items() if key.startswith("rom_")]) ramSize = sum([size for key, size in staticSizes.items() if key.startswith("ram_")]) results = { "rom": ...
b60052f702e53655ab1a109ea2bb039e78aabaf5
13,833
def path_element_to_dict(pb): """datastore.entity_pb.Path_Element converter.""" return { 'type': pb.type(), 'id': pb.id(), 'name': pb.name(), }
2a4e757dedf6707dc412248f84b377c2f375e70c
13,834
import tempfile import os def copy_to_tmp(in_file): """Copies a file to a tempfile. The point of this is to copy small files from CNS to tempdirs on the client when using code that's that hasn't been Google-ified yet. Examples of files are the vocab and config files of the Hugging Face tokenizer. Argume...
97b98214df23079d5aa9ee0ece072204d36d2f33
13,835
def get_orr_tensor(struct): """ Gets orientation of all molecules in the struct """ molecule_list = get_molecules(struct) orr_tensor = np.zeros((len(molecule_list),3,3)) for i,molecule_struct in enumerate(molecule_list): orr_tensor[i,:,:] = get_molecule_orientation(molecule_struct) return or...
faf42cf76168191835d9dd354ae9bc03198829ad
13,836
def make_request_for_quotation(supplier_data=None): """ :param supplier_data: List containing supplier data """ supplier_data = supplier_data if supplier_data else get_supplier_data() rfq = frappe.new_doc('Request for Quotation') rfq.transaction_date = nowdate() rfq.status = 'Draft' rfq.company = '_Test Company...
ee0663231fc0bb06f6f43fa5abecdced048c1458
13,837
def mlrPredict(W, data): """ mlrObjFunction predicts the label of data given the data and parameter W of Logistic Regression Input: W: the matrix of weight of size (D + 1) x 10. Each column is the weight vector of a Logistic Regression classifier. X: the data matrix of siz...
a37359433b020eb625b37ea57cb15282c4f82c8d
13,838
import glob import filecmp import subprocess def write_urdb_rate_data(urdb_rate_data, urdb_filepath = './', overwrite_identical=True): """ Takes Pandas DataFrame containing URDB rate data and stores as .csv at urdb_filepath. The 'overwrite_identical' variable indicates whether 'urdb_rate_data' should...
cde6f16f4ba8abf2c744fb6ef579c0beddd407fd
13,839
def add(n): """Add 1.""" return n + 1
c62cee4660540ae62b5b73369bdeb56ccb0088d6
13,840
import psutil import os def get_system_status(memory_total=False, memory_total_actual=False, memory_total_usage=False, memory_total_free=False, all_pids=False, swap_memory=False, pid=Fal...
79b3b43a3e046c2fc1237cde103c6f416ae1f01b
13,841
def _area(x1, y1, x2, y2, x3, y3): """Heron's formula.""" a = np.sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2)) b = np.sqrt(pow(x3 - x2, 2) + pow(y3 - y2, 2)) c = np.sqrt(pow(x1 - x3, 2) + pow(y3 - y1, 2)) s = (a + b + c) / 2 return np.sqrt(s * (s - a) * (s - b) * (s - c))
456ffe56a76fbea082939c278b5f0f2ebaf8c395
13,842
def plot_coarray(array, ax=None, show_location_errors=False): """Visualizes the difference coarray of the input array. Args: array (~doatools.model.arrays.ArrayDesign): A sensor array. ax (~matplotlib.axes.Axes): Matplotlib axes used for the plot. If not specified, a new figure will...
e4a0d1fe4ab48b5050c55d44bd4ca4342cc9f9a9
13,843
def get_publicKey(usrID): # TODO: from barbican """ Get the user's public key Returns: Public key from meta-container (Keys) in meta-tenant """ auth = v3.Password(auth_url=AUTH_URL,username=SWIFT_USER,password=SWIFT_PASS,project_name='demo',project_domain_id="Default",user_domain_name='De...
545dec9826273830767f395903cae878df8213b0
13,844
def pad_sequence(sequences, batch_first=False, padding_value=0.0): """Pad a list of variable-length Variables. This method stacks a list of variable-length :obj:`nnabla.Variable` s with the padding_value. :math:`T_i` is the length of the :math:`i`-th Variable in the sequences. :math:`B` is the batch s...
449c7681d39edc0494269aefd488aa44548a68df
13,845
import urllib import yaml import requests def _fetch_global_config(config_url, github_release_url, gh_token): """ Fetch the index_runner_spec configuration file from the Github release using either the direct URL to the file or by querying the repo's release info using the GITHUB API. """ if c...
c436bfb7692ce0d100367691588d511ed95bce99
13,846
def parse_color(c, desc): """Check that a given value is a color.""" return c
ebabefbd56de120a753723f1dccb0f7c12af2fe6
13,847
import os def get_package_dir(): """ Gets directory where package is installed :return: """ return os.path.dirname(ndextcgaloader.__file__)
447b6ed962119787c3c11f457fcf81bc31b0ae0d
13,848
def __virtual__(): """Only load gnocchiv1 if requirements are available.""" if REQUIREMENTS_MET: return 'gnocchiv1' else: return False, ("The gnocchiv1 execution module cannot be loaded: " "os_client_config or keystoneauth are unavailable.")
5dc2a83ba6a93a37f037978bfe89edf6ec2fe103
13,849
def setup(): """Start headless Chrome in docker container.""" options = webdriver.ChromeOptions() options.add_argument('--no-sandbox') options.add_argument('--headless') options.add_argument('--disable-gpu') driver = webdriver.Chrome(options=options) driver.implicitly_wait(5) return driv...
79c135732b39513f270ac0f670ffddc89b576f75
13,850
import json def lambdaResponse(statusCode, body, headers={}, isBase64Encoded=False): """ A utility to wrap the lambda function call returns with the right status code, body, and switches. """ # Make sure the body is a json object if not...
0159ba871c38ce550752d47ffea536c33a5d6b3e
13,851
def singleton(class_): """ Specify that a class is a singleton :param class_: :return: """ instances = {} def getinstance(*args, **kwargs): if class_ not in instances: instances[class_] = class_(*args, **kwargs) return instances[class_] return getinstance
678205d133783f6b0720876546deed9ed7c59d72
13,852
from typing import Optional from typing import Union from typing import List from datetime import datetime def is_datetime( value: Scalar, formats: Optional[Union[str, List[str]]] = None, typecast: Optional[bool] = True ) -> bool: """Test if a given string value can be converted into a datetime object for...
642fbe509c7b13a905dc4c65b43dcec20f36fb7e
13,853
def sortkey(d): """Split d on "_", reverse and return as a tuple.""" parts=d.split("_") parts.reverse() return tuple(parts)
1d8f8864a3d0bfd7dae8711bca183317e0f3fc0e
13,854
def resolve_stream_name(streams, stream_name): """Returns the real stream name of a synonym.""" if stream_name in STREAM_SYNONYMS and stream_name in streams: for name, stream in streams.items(): if stream is streams[stream_name] and name not in STREAM_SYNONYMS: return name ...
48fe2f5eca72b30bd669477807c9b7476eb4ef18
13,855
def get_split_cifar100_tasks(num_tasks, batch_size,run,paradigm,dataset): """ Returns data loaders for all tasks of split CIFAR-100 :param num_tasks: :param batch_size: :return: datasets = {} # convention: tasks starts from 1 not 0 ! # task_id = 1 (i.e., first task) => start_class = 0, end_class = 4 cifar_...
003c74a55a4e9a1f645a6bc930abf65342abd0fc
13,856
def is_point_in_triangle(pt, v1, v2, v3): """Returns True if the 2D point pt is within the triangle defined by v1-3. https://www.gamedev.net/forums/topic/295943-is-this-a-better-point-in-triangle-test-2d/ """ b1 = sign(pt, v1, v2) < 0.0 b2 = sign(pt, v2, v3) < 0.0 b3 = sign(pt, v3, v1) < 0.0 ...
2ff58dfb4efe939513cc901772aa744296ebb960
13,857
def precomputed_aug_experiment( clf, auged_featurized_x_train, auged_featurized_y_train, auged_featurized_x_train_to_source_idxs, auged_featurized_x_test, auged_featurized_y_test, auged_featurized_x_test_to_source_idxs, aug_iter, train_idxs_scores,...
50f03f08c7ce0777658ca3f84691b940f190e4cd
13,858
def get_yahoo_data(symbol, start_date, end_date): """Returns pricing data for a YAHOO stock symbol. Parameters ---------- symbol : str Symbol of the stock in the Yahoo. You can refer to this link: https://www.nasdaq.com/market-activity/stocks/screener?exchange=nasdaq. start_date : s...
adc2a6186d96c76a75a62391c7f8d7534836f5bd
13,859
def first_n(m: dict, n: int): """Return first n items of dict""" return {k: m[k] for k in list(m.keys())[:n]}
57ccc9f8913c60c592b38211900fe8d28feffb4c
13,860
from typing import List from typing import Dict from typing import Union def listdictnp_combine( lst: List, method: str = "concatenate", axis: int = 0, keep_nested: bool = False, allow_error: bool = False, ) -> Dict[str, Union[np.ndarray, List]]: """Concatenate or stack a list of dictionaries ...
b4527342c8a3b90c797e7ef88326c97b4933d1b0
13,861
def find_pure_symbol(symbols, clauses): """Find a symbol and its value if it appears only as a positive literal (or only as a negative) in clauses. >>> find_pure_symbol([A, B, C], [A|~B,~B|~C,C|A]) (A, True) """ for s in symbols: found_pos, found_neg = False, False for c in claus...
657c011fb0ee865252e7deed4672cde08c6db2e9
13,862
def cross_entropy_emphasized_loss(labels, predictions, corrupted_inds, axis=0, alpha=0.3, beta=0.7, regularizer=None...
e4ebb4e3198dea085789c81388522130ed867e3f
13,863
def get_process_list(node: Node): """Analyse the process description and return the Actinia process chain and the name of the processing result :param node: The process node :return: (output_objects, actinia_process_list) """ input_objects, process_list = check_node_parents(node=node) output_o...
00f5e6c767975def09fbea800a8b74cfcd12f935
13,864
def _validate_image_formation(the_sicd): """ Validate the image formation. Parameters ---------- the_sicd : sarpy.io.complex.sicd_elements.SICD.SICDType Returns ------- bool """ if the_sicd.ImageFormation is None: the_sicd.log_validity_error( 'ImageFormatio...
b68c9a767e2499b8149389e2e207a0f05d20bf44
13,865
def handle_closet(player, level, reward_list): """ Handle a closet :param player: The player object for the player :param level: The level that the player is on :return reward: The reward given to the player """ # Print the dialogue for the closet print "You found a closet. It appears t...
ab170cb556fd688edeac80eac9bb7577df771a33
13,866
def module_path_to_test_path(module): """Convert a module locator to a proper test filename. """ return "test_%s.py" % module_path_to_name(module)
17997d17d64686deec97d4aa9f23a14f04ff5516
13,867
def inspect_bom(filename): """Inspect file for bom.""" encoding = None try: with open(filename, "rb") as f: encoding = has_bom(f.read(4)) except Exception: # pragma: no cover # print(traceback.format_exc()) pass return encoding
84da40bc941053c4e6d18934c27b3e1d63318762
13,868
from packaging.specifiers import SpecifierSet def parse_requirement(text): """ Parse a requirement such as 'foo>=1.0'. Returns a (name, specifier) named tuple. """ match = REQUIREMENT_RE.match(text) if not match: raise ValueError("Invalid requirement: %s" % text) name = match.gro...
95dab6f3dd6784bf73233e80cfb946f904984a1d
13,869
def H_split(k, N, eps): """Entropy of the split in binary search including overlap, specified by eps""" return (k / N) * (np.log(k) + H_epsilon(k, eps)) + ((N - k) / N) * (np.log(N - k) + H_epsilon(N - k, eps))
555d5e56550851084fdfa148dc7936c75649a197
13,870
def date_features(inputs, features_slice, columns_index) -> tf.Tensor: """Return an input and output date tensors from the features tensor.""" date = features(inputs, features_slice, columns_index) date = tf.cast(date, tf.int32) date = tf.strings.as_string(date) return tf.strings.reduce_join(date, ...
3362019b24a6f3104d858d2ddf17f0fae4060d7b
13,871
import pickle def save_calib(filename, calib_params): """ Saves calibration parameters as '.pkl' file. Parameters ---------- filename : str Path to save file, must be '.pkl' extension calib_params : dict Calibration parameters to save Returns ------- saved : bool Saved successfully. """ i...
6735c8a6e96158b9fc580b6e61609b5ae7733fe0
13,872
def context_to_dict(context): """convert a django context to a dict""" the_dict = {} for elt in context: the_dict.update(dict(elt)) return the_dict
b319c6be4efa83c91eefa249c8be90824bc0158f
13,873
def returnItemsWithMinSupport(itemSet, transactionList, minSupport, freqSet): """calculates the support for items in the itemSet and returns a subset of the itemSet each of whose elements satisfies the minimum support""" _itemSet = set() localSet = defaultdict(int) for item in it...
e1290778548f198f87fc210c8a78bbfadaf0de9f
13,874
def create_P(P_δ, P_ζ, P_ι): """ Combine `P_δ`, `P_ζ` and `P_ι` into a single matrix. Parameters ---------- P_δ : ndarray(float, ndim=1) Probability distribution over the values of δ. P_ζ : ndarray(float, ndim=2) Markov transition matrix for ζ. P_ι : ndarray(float, ndim=1)...
0afdef50c50563421bb7c6f3f928fa6b3e5f4733
13,875
import attrs def sel_nearest( dset, lons, lats, tolerance=2.0, unique=False, exact=False, dset_lons=None, dset_lats=None, ): """Select sites from nearest distance. Args: dset (Dataset): Stations SpecDataset to select from. lons (array): Longitude of sites to in...
ebf22cdeb30215a76312f2cdd8223a2d24bf6af6
13,876
import datasets def evaluate(dataset, predictions, gts, output_folder): """evaluate dataset using different methods based on dataset type. Args: dataset: Dataset object predictions(dict): each item in the list represents the prediction results for one image. gt(dict): Groun...
85c0232c53de091f2293d042b944fe8768a9ac91
13,877
from vlescrapertools import getAuthedSession def html_xml_save( s=None, possible_sc_link=None, table="htmlxml", course_presentation=None ): """Save the HTML and XML for a VLE page page.""" if not possible_sc_link: # should really raise error here print("need a link") if not s: ...
37bb86769c86d851e3fec8dabc17534dfdecde60
13,878
import os def app(request): """An instance of the Flask app that points at a test database. If the TEST_DATABASE environment variable is set to "postgres", launch a temporary PostgreSQL server that gets torn down at the end of the test run. """ database = os.environ.get('TEST_DATABASE', 'sqlite')...
52cac3b340ef0fb5a92449242644c1061a5cba2b
13,879
def htmr(t,axis="z"): """ Calculate the homogeneous transformation matrix of a rotation respect to x,y or z axis. """ from sympy import sin,cos,tan if axis in ("z","Z",3): M = Matrix([[cos(t),-sin(t),0,0], [sin(t),cos(t),0,0], [0,0,1,0], ...
b3941680f22b2eb48da15b2bb1a6e39c05e3b5c3
13,880
def vt(n, gm, gsd, dmin=None, dmax=10.): """Evaluate the total volume of the particles between two diameters. The CDF of the lognormal distribution is calculated using equation 8.12 from Seinfeld and Pandis. Mathematically, it is represented as: .. math:: V_t=\\frac{π}{6}∫_{-∞}^{∞}D_p^3n...
ba407dc86bbf3201bd597f729f2397ef9428e72b
13,881
def core_value_encode(origin): """ 转换utf-8编码为社会主义核心价值观编码 :param origin: :return: """ hex_str = str2hex(origin) twelve = hex2twelve(hex_str) core_value_iter = twelve_2_core_value(twelve) return ''.join(core_value_iter)
7b81540f7e7184ec60fb6820e3548201d67eec29
13,882
def user_query_ahjs_is_ahj_official_of(self, request, queryset): """ Admin action for the User model. Redirects the admin to a change list of AHJs the selected users are AHJ officials of. """ model_name = 'ahj' field_key_pairs = [field_key_pair('AHJPK', 'AHJPK')] queryset = AHJUserMaintains....
4d97f25f2647a92a9690bf3360bd3fd63b03d631
13,883
def get_cache_node_count( cluster_id: str, configuration: Configuration = None, secrets: Secrets = None ) -> int: """Returns the number of cache nodes associated to the cluster :param cluster_id: str: the name of the cache cluster :param configuration: Configuration :param secrets: Secrets :ex...
e4a4b3cd6d0bf7416ffe5a3d86725a614ad1c41c
13,884
import string def top_sentences(query, sentences, idfs, n): """ Given a `query` (a set of words), `sentences` (a dictionary mapping sentences to a list of their words), and `idfs` (a dictionary mapping words to their IDF values), return a list of the `n` top sentences that match the query, ranked ...
5533b96848baea5afa614e691d2d2ae07c4a16a9
13,885
def load_distribution(label): """Load sample distributions as described by Seinfeld+Pandis Table 8.3. There are currently 7 options including: Urban, Marine, Rural, Remote continental, Free troposphere, Polar, and Desert. Parameters ---------- label : {'Urban' | 'Marine' | 'Rural' | 'Remote C...
3dfd2fea5c165c331255e3b350e1f92a37919726
13,886
from typing import List def split_4d_itk(img_itk: sitk.Image) -> List[sitk.Image]: """ Helper function to split 4d itk images into multiple 3 images Args: img_itk: 4D input image Returns: List[sitk.Image]: 3d output images """ img_npy = sitk.GetArrayFromImage(img_itk) spa...
21ad4f6c0cbdb05cf6f67469e3d32e732d1500ee
13,887
from bs4 import BeautifulSoup def parse_results(html, keyword): """[summary] Arguments: html {str} -- google search engine html response keyword {str} -- search term Returns: pandas.DataFrame -- Dataframe with the following columns ['keyword', 'rank', 'title', 'link', 'domain'] ...
4c89e919b3f3285565efe5bdf5c4ec5b87664c79
13,888
def maybe_iter_configs_with_path(x, with_params=False): """ Like x.maybe_iter_configs_with_path(), but returns [(x, [{}])] or [(x, {}, [{}])] if x is just a config object and not a Tuner object. """ if is_tuner(x): return x.iter_configs_with_path(with_params=with_params) else: if wi...
947a62067f3eacb4d5c8ba419d8018ad2ab3320c
13,889
import typing def median(vals: typing.List[float]) -> float: """Calculate median value of `vals` Arguments: vals {typing.List[float]} -- list of values Returns: float -- median value """ index = int(len(vals) / 2) - 1 return sorted(vals)[index]
9f840d11409a570a718fdfe56d7a282af43bc798
13,890
def melody_mapper(notes): """ Makes a map of a melody to be played each item in the list 'notes' should be formatted using these chars: duration - length in seconds the sound will be played note - the note to play sleep - time in seconds to pause (note, duration) ...
cf4c8f7864e91e771d3a70bfc4d8a7f4edb38967
13,891
def sample_bounding_box_scale_balanced_black(landmarks): """ Samples a bounding box for cropping so that the distribution of scales in the training data is uniform. """ bb_min = 0.9 bb_old = image.get_bounding_box(landmarks) bb_old_shape = np.array((bb_old[2] - bb_old[0], bb_old[3] - bb_old[1])...
789cbe92803b77614ab8a018434745b2d9bba3a4
13,892
import glob import os def get_files(data_path): """ 获取目录下以及子目录下的图片 :param data_path: :return: """ files = [] exts = ['jpg', 'png', 'jpeg', 'JPG','bmp'] for ext in exts: # glob.glob 得到所有文件名 # 一层 2层子目录都取出来 files.extend(glob.glob(os.path.join(data_path, '*.{}'.form...
1a81aa7679eb2c70d29d3e80423c4b2e860c307d
13,893
def get_trainable_layers(layers): """Returns a list of layers that have weights.""" layers = [] # Loop through all layers for l in layers: # If layer is a wrapper, find inner trainable layer l = find_trainable_layer(l) # Include layer if it has weights if l.get_weights():...
2d3f00cb061a6c2ee7081468be564f0b8621441d
13,894
def outcome_from_application_return_code(return_code: int) -> outcome.Outcome: """Create either an :class:`outcome.Value` in the case of a 0 `return_code` or an :class:`outcome.Error` with a :class:`ReturnCodeError` otherwise. Args: return_code: The return code to be processed. Returns: ...
c5b786906e0f3fd99ed6660c55213b18139003c0
13,895
import re def group_by_scale(labels): """ Utility that groups attribute labels by time scale """ groups = defaultdict(list) # Extract scales from labels (assumes that the scale is given by the last numeral in a label) for s in labels: m = re.findall("\d+", s) if m: groups[m...
661ea03f8d463b1e0d5746df60e9e2cb969737ab
13,896
def FontMapper_GetEncodingDescription(*args, **kwargs): """FontMapper_GetEncodingDescription(int encoding) -> String""" return _gdi_.FontMapper_GetEncodingDescription(*args, **kwargs)
0f154eaa616c3b18bc8828f63137c26c75397d56
13,897
from typing import Counter def create_merged_ngram_dictionaries(indices, n): """Generate a single dictionary for the full batch. Args: indices: List of lists of indices. n: Degree of n-grams. Returns: Dictionary of hashed(n-gram tuples) to counts in the batch of indices. """ ngram_dicts = []...
bd313ea7eab835102e94f6c7d66fec8882531385
13,898
import base64 def compute_hash_base64(*fields): """bytes -> base64 string""" value = compute_hash(*fields) return base64.b64encode(value).decode()
b29b77b44a51417d63f8cae1970b5c1f4fb40317
13,899