content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def build_tree(train, max_depth, min_size, n_features): """build_tree(创建一个决策树) Args: train 训练数据集 max_depth 决策树深度不能太深,不然容易导致过拟合 min_size 叶子节点的大小 n_features 选取的特征的个数 Returns: root 返回决策树 """ # 返回最优列和相关的信息 root = get_sp...
5afd343436f14d9ab704636eb480d92a31d59f04
5,000
import pprint def delete_bucket(bucket_name: str, location: str, verbose: bool) -> bool: """Delete the specified S3 bucket Args: bucket_name (str): name of the S3 bucket location (str): the location (region) the S3 bucket resides in verbose (bool): enable verbose output Returns: ...
79c225c9f8caa0d8c3431709d3f08ccaefe3fc1c
5,001
import re def generate_ordered_match_str_from_subseqs(r1, subseqs_to_track, rc_component_dict, allow_overlaps=False): """Generates an ordered subsequences match string for the input se...
202f228b40b73518342b1cc2419ca466626fc166
5,002
def combination(n: int, r: int) -> int: """:return nCr = nPr / r!""" return permutation(n, r) // factorial(r)
6cf58428cacd0e09cc1095fb120208aaeee7cb7c
5,003
def _extract_operator_data(fwd, inv_prep, labels, method='dSPM'): """Function for extracting forward and inverse operator matrices from the MNE-Python forward and inverse data structures, and assembling the source identity map. Input arguments: ================ fwd : ForwardOperator ...
6daded6f6df4abbd3dea105927ca39e02e64b970
5,004
def create_new_containers(module, intended, facts): """ Create missing container to CVP Topology. Parameters ---------- module : AnsibleModule Object representing Ansible module structure with a CvpClient connection intended : list List of expected containers based on following ...
d173c49a40e6a7a71588618e18378260c05018c6
5,005
from prompt_toolkit.interface import CommandLineInterface from .containers import Window from .controls import BufferControl def find_window_for_buffer_name(cli, buffer_name): """ Look for a :class:`~prompt_toolkit.layout.containers.Window` in the Layout that contains the :class:`~prompt_toolkit.layout.co...
7912cc96365744c3a4daa44a72f272b083121e3c
5,006
def create_pilot(username='kimpilot', first_name='Kim', last_name='Pilot', email='kim@example.com', password='secret'): """Returns a new Pilot (User) with the given properties.""" pilot_group, _ = Group.objects.get_or_create(name='Pilots') pilot = User.objects.create_user(username, email, password, first_na...
6c173a94a97d64182dcb28b0cef510c0838a545f
5,007
def dict_to_datasets(data_list, components): """add models and backgrounds to datasets Parameters ---------- datasets : `~gammapy.modeling.Datasets` Datasets components : dict dict describing model components """ models = dict_to_models(components) datasets = [] for...
e021317aae6420833d46782b3a611d17fb7156dc
5,008
def of(*args: _TSource) -> Seq[_TSource]: """Create sequence from iterable. Enables fluent dot chaining on the created sequence object. """ return Seq(args)
eb8ea24c057939cf82f445099c953a84a4b51895
5,009
def find_anagrams(word_list: list) -> dict: """Finds all anagrams in a word list and returns it in a dictionary with the letters as a key. """ d = dict() for word in word_list: unique_key = single(word) if unique_key in d: d[unique_key].append(word...
5e3514344d396d11e8a540b5faa0c31ae3ee6dab
5,010
import itertools def resolver(state_sets, event_map): """Given a set of state return the resolved state. Args: state_sets(list[dict[tuple[str, str], str]]): A list of dicts from type/state_key tuples to event_id event_map(dict[str, FrozenEvent]): Map from event_id to event Re...
90b8f78e46e13904a9c898cda417378964667ff8
5,011
def parse_study(study): """Parse study Args: study (object): object from DICOMDIR level 1 object (children of patient_record) Returns: children_object appending_keys """ #study_id = study.StudyID study_date = study.StudyDate study_time = study.StudyTime ...
d0e85d991e4f2f13e6f2bd87c0823858ea9c83bc
5,012
def list_organizational_units_for_parent_single_page(self, **kwargs): """ This will continue to call list_organizational_units_for_parent until there are no more pages left to retrieve. It will return the aggregated response in the same structure as list_organizational_units_for_parent does. :param sel...
73e942d59026830aac528b9dd358f08ebe8a66b3
5,013
def daemon(target, name=None, args=None, kwargs=None, after=None): """ Create and start a daemon thread. It is same as `start()` except that it sets argument `daemon=True`. """ return start(target, name=name, args=args, kwargs=kwargs, daemon=True, after=after)
27d608c9cc5be1ab45abe9666e52bbbf89a1f066
5,014
import threading def add_image_to_obj(obj, img, *args, **kwargs): """ """ # skip everything if there is no image if img == None: return None # find out of the object is an artist or an album # then add the artist or the album to the objects objs = {} if isinstance(obj, Artist)...
60b2f9eb871e5b4943b4ab68c817afdd8cf47cab
5,015
from datetime import datetime def rr_category_ad(context, ad_zone, ad_category, index=0): """ Returns a rr advert from the specified category based on index. Usage: {% load adzone_tags %} {% rr_category_ad 'zone_slug' 'my_category_slug' 1 %} """ to_return = {'random_int': randint(1000000...
db78853ebdf64267e2cca217589ac309706333a1
5,016
def decoderCNN(x, layers): """ Construct the Decoder x : input to decoder layers : the number of filters per layer (in encoder) """ # Feature unpooling by 2H x 2W for _ in range(len(layers) - 1, 0, -1): n_filters = layers[_] x = Conv2DTranspose(n_filters, (3, 3), strides...
9c48c5242b0793c71385f9137729393d17d2db06
5,017
import torch def binary_dice_iou_score( y_pred: torch.Tensor, y_true: torch.Tensor, mode="dice", threshold=None, nan_score_on_empty=False, eps=1e-7, ignore_index=None, ) -> float: """ Compute IoU score between two image tensors :param y_pred: Input image tensor of any shape ...
9d4b751dbdd9c3b7e5f2490c7f7cd8ac08868233
5,018
def get_uname_arch(): """ Returns arch of the current host as the kernel would interpret it """ global _uname_arch # pylint: disable=global-statement if not _uname_arch: _uname_arch = detect_uname_arch() return _uname_arch
b30946675f6cad155eab3f81b711618551b49f44
5,019
from typing import Tuple def _getSTSToken() -> Tuple[str, BosClient, str]: """ Get the token to upload the file :return: """ if not Define.hubToken: raise Error.ArgumentError('Please provide a valid token', ModuleErrorCode, FileErrorCode, 4) config = _invokeBackend("circuit/genSTS",...
553844ce8530911bab70fc823bdec65b058b70a4
5,020
import os async def get_thumb_file(mass: MusicAssistant, url, size: int = 150): """Get path to (resized) thumbnail image for given image url.""" assert url cache_folder = os.path.join(mass.config.data_path, ".thumbs") cache_id = await mass.database.get_thumbnail_id(url, size) cache_file = os.path....
fe9a10e6460453b44e8509f2b2b42b30639be48b
5,021
import pickle def load_pickle(filename): """Load Pickfle file""" filehandler = open(filename, 'rb') return pickle.load(filehandler)
f93b13616f94c31bc2673232de14b834a8163c5f
5,022
import json def columnize(s, header=None, width=40): """Dump an object and make each line the given width The input data will run though `json.loads` in case it is a JSON object Args: s (str): Data to format header (optional[str]): Header to prepend to formatted results width (op...
36343f682677f04d0b3670882539e58b48146c46
5,023
def create_eeg_epochs(config): """Create the data with each subject data in a dictionary. Parameter ---------- subject : string of subject ID e.g. 7707 trial : HighFine, HighGross, LowFine, LowGross Returns ---------- eeg_epoch_dataset : dataset of all the subjects with different con...
a33abcb056b9e94a637e58a42936b886e90a94f2
5,024
def to_newick(phylo): """ Returns a string representing the simplified Newick code of the input. :param: `PhyloTree` instance. :return: `str` instance. """ return phylo_to_newick_node(phylo).newick
814610413223e37a6417ff8525262f0beb2e8091
5,025
import functools def pipe(*functions): """ pipes functions one by one in the provided order i.e. applies arg1, then arg2, then arg3, and so on if any arg is None, just skips it """ return functools.reduce( lambda f, g: lambda x: f(g(x)) if g else f(x), functions[::-1], ...
f58afedd5c7fe83edd605b12ca0e468657a78b56
5,026
import logging def remove_news_update(removed_update_name: str, expired: bool) -> None: """Removes any expired news articles or any articles that have been manuallyremoved by the user. If an update has expired, a loop is used to find the update and remove it from the global list of updates. Otherwise...
a8a01af22ef2377265f49f35f288f6eebabef3f0
5,027
import torch def initialize_graph_batch(batch_size): """ Initialize a batch of empty graphs to begin the generation process. Args: batch_size (int) : Batch size. Returns: generated_nodes (torch.Tensor) : Empty node features tensor (batch). generated_edges (torch.Tensor) : Empty edge fe...
f7ae56b3a0d728dd0fd4b40a3e45e960f65bcf31
5,028
def TimestampFromTicks(ticks): """Construct an object holding a timestamp value from the given ticks value (number of seconds since the epoch). This function is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. :rtype: :class:`datetime.datetime` """ return ...
ccb377b793d600d1a98363e35fc6cd041517b50a
5,029
from typing import Counter def extract_object_token(data, num_tokens, obj_list=[], verbose=True): """ Builds a set that contains the object names. Filters infrequent tokens. """ token_counter = Counter() for img in data: for region in img['objects']: for name in region['names']: ...
c35ea7a9eaa2f259c9b38b47e3c982b9ee11682b
5,030
def test_lambda_expressions(): """Lambda 表达式""" # 这个函数返回两个参数的和:lambda a, b: a+b # 与嵌套函数定义一样,lambda函数可以引用包含范围内的变量。 def make_increment_function(delta): """本例使用 lambda 表达式返回函数""" return lambda number: number + delta increment_function = make_increment_function(42) assert increm...
e727df25b2165bb0cd7c9cce47700e86d37a2a1a
5,031
def _generate_with_relative_time(initial_state, condition, iterate, time_mapper) -> Observable: """Generates an observable sequence by iterating a state from an initial state until the condition fails. Example: res = source.generate_with_relative_time(0, lambda x: True, lambda x: x + 1, lambda x: 0...
d3f5549f94125065b387515299014b5701411be8
5,032
def is_prime(num): """判断一个数是不是素数""" for factor in range(2, int(num ** 0.5) + 1): if num % factor == 0: return False return True if num != 1 else False
c0e8435b046a87dd15278149f5e1af7258634a01
5,033
def ptcorr(y1, y2, dim=-1, eps=1e-8, **kwargs): """ Compute the correlation between two PyTorch tensors along the specified dimension(s). Args: y1: first PyTorch tensor y2: second PyTorch tensor dim: dimension(s) along which the correlation is computed. Any valid PyTor...
140cad4de4452edeb5ea0fb3e50267c66df948c1
5,034
import typing def discretize_time_difference( times, initial_time, frequency, integer_timestamps=False ) -> typing.Sequence[int]: """method that discretizes sequence of datetimes (for prediction slices) Arguments: times {Sequence[datetime] or Sequence[float]} -- sequence of datetime ...
871726102dbdedfbc92570bff4f73faf1054e986
5,035
def pathlines(u_netcdf_filename,v_netcdf_filename,w_netcdf_filename, startx,starty,startz,startt, t, grid_object, t_max,delta_t, u_netcdf_variable='UVEL', v_netcdf_variable='VVEL', w_netcdf_variable='WVEL', u_gri...
2c7da1a6de8157c690fb6ea57e30906108728711
5,036
def firing_rate(x, theta=0.5, alpha=0.12): """ Sigmoidal firing rate function Parameters ---------- x : float Mean membrane potential. theta : float Inflection point (mean firing activity) of sigmoidal curve (default value 0.12) alpha : float Steepness of si...
ddb4ce078f8613a088971d4ed0a4a71d746772b5
5,037
def map_points(pois, sample_size=-1, kwd=None, show_bbox=False, tiles='OpenStreetMap', width='100%', height='100%'): """Returns a Folium Map displaying the provided points. Map center and zoom level are set automatically. Args: pois (GeoDataFrame): A GeoDataFrame containing the POIs to be displayed. ...
cb8e2a32b62ca364e54c90b94d2d4c3da74fc12a
5,038
def read_data_file(): """ Reads Data file from datafilename given name """ datafile = open(datafilename, 'r') old = datafile.read() datafile.close() return old
5aa6aa7cbf0305ca51c026f17e29188e472e61f3
5,039
def squared_loss(y_hat, y): """均方损失。""" return (y_hat - y.reshape(y_hat.shape))**2 / 2
4f796ed753de6ed77de50578271a4eca04fc1ffb
5,040
import re def normalize_string(string, lowercase=True, convert_arabic_numerals=True): """ Normalize the given string for matching. Example:: >>> normalize_string("tétéà 14ème-XIV, foobar") 'tetea XIVeme xiv, foobar' >>> normalize_string("tétéà 14ème-XIV, foobar", False) ...
b6772b47f4cc049e09d37c97710a4f37e5a50a7c
5,041
from typing import Sequence def find_sub_expression( expression: Sequence[SnailfishElement], ) -> Sequence[SnailfishElement]: """Finds the outermost closed sub-expression in a subsequence.""" num_open_braces = 1 pos = 0 while num_open_braces > 0: pos += 1 if expression[pos] == "[":...
11d91c38c66fc8c9ce1e58297fcfbb290c18b968
5,042
import tempfile import os import logging import subprocess def run_tha_test(manifest, cache_dir, remote, max_cache_size, min_free_space): """Downloads the dependencies in the cache, hardlinks them into a temporary directory and runs the executable. """ cache = Cache(cache_dir, remote, max_cache_size, min_free...
340bbc2daf4f28b1574ca0729575d5abdb5848d4
5,043
import importlib def get_rec_attr(obj, attrstr): """Get attributes and do so recursively if needed""" if attrstr is None: return None if "." in attrstr: attrs = attrstr.split('.', maxsplit=1) if hasattr(obj, attrs[0]): obj = get_rec_attr(getattr(obj, attrs[0]), attrs[1]...
a6831d48c79b8c58542032385a5c56373fd45321
5,044
def _get_message_mapping(types: dict) -> dict: """ Return a mapping with the type as key, and the index number. :param types: a dictionary of types with the type name, and the message type :type types: dict :return: message mapping :rtype: dict """ message_mapping = {} entry_index = ...
a098e0386aa92c41d4d404154b0b2a87ce9365ce
5,045
import sys import os def _get_default_config_files_location(): """Get the locations of the standard configuration files. These are Unix/Linux: 1. `/etc/pywps.cfg` 2. `$HOME/.pywps.cfg` Windows: 1. `pywps\\etc\\default.cfg` Both: 1. `$PYWPS_CFG environment variable` ...
a359c0ac95092200cf346768e6db8ea7e2753416
5,046
def cd(path): """ Change location to the provided path. :param path: wlst directory to which to change location :return: cmo object reference of the new location :raises: PyWLSTException: if a WLST error occurs """ _method_name = 'cd' _logger.finest('WLSDPLY-00001', path, class_name=_c...
fbb8d9ac0a9a4c393d06d0c15bfd15154b0a5c0a
5,047
def plt_roc_curve(y_true, y_pred, classes, writer, total_iters): """ :param y_true:[[1,0,0,0,0], [0,1,0,0], [1,0,0,0,0],...] :param y_pred: [0.34,0.2,0.1] , 0.2,...] :param classes:5 :return: """ fpr = {} tpr = {} roc_auc = {} roc_auc_res = [] n_classes = len(classes) fo...
5e02d83f5a7cd4e8c8abbc3afe89c25271e3944e
5,048
def get_deps(sentence_idx: int, graph: DependencyGraph): """Get the indices of the dependants of the word at index sentence_idx from the provided DependencyGraph""" return list(chain(*graph.nodes[sentence_idx]['deps'].values()))
9eb00fc5719cc1fddb22ea457cc6b49a385eb51d
5,049
import functools def incr(func): """ Increment counter """ @functools.wraps(func) def wrapper(self): # Strip off the "test_" from the function name name = func.__name__[5:] def _incr(counter, num): salt.utils.process.appendproctitle("test_{}".format(name)) ...
036ae9eac9d223a34871737a7294fad027c2d3c9
5,050
import operator def index(a: protocols.SupportsIndex) -> int: """ Return _a_ converted to an integer. Equivalent to a.__index__(). Example: >>> class Index: ... def __index__(self) -> int: ... return 0 >>> [1][Index()] 1 Args: a: """ ...
52f2fbdb8d65b12cb53761647b2c13d3cb368272
5,051
def col_to_num(col_str): """ Convert base26 column string to number. """ expn = 0 col_num = 0 for char in reversed(col_str): col_num += (ord(char) - ord('A') + 1) * (26 ** expn) expn += 1 return col_num
d6bb00d3ef77c48338df635a254cf3ca5503bb73
5,052
def process_chunk(chunk, verbose=False): """Return a tuple of chunk kind, task-create links, task-create times, task-leave times and the chunk's graph""" # Make function for looking up event attributes get_attr = attr_getter(chunk.attr) # Unpack events from chunk (_, (first_event, *events, last_ev...
f2430377bc592b2a317b6db627cc39c185f64177
5,053
def delazi_wgs84(lat1, lon1, lat2, lon2): """delazi_wgs84(double lat1, double lon1, double lat2, double lon2)""" return _Math.delazi_wgs84(lat1, lon1, lat2, lon2)
3ced7e7dc3fd8dd7ced621a536c43bfb9062d89d
5,054
def clipped_zoom(x: np.ndarray, zoom_factor: float) -> np.ndarray: """ Helper function for zoom blur. Parameters ---------- x Instance to be perturbed. zoom_factor Zoom strength. Returns ------- Cropped and zoomed instance. """ h = x.shape[0] ch = int(np...
befbe10493bd4acc63c609432c1c00ac3eeab652
5,055
def NextFchunk(ea): """ Get next function chunk @param ea: any address @return: the starting address of the next function chunk or BADADDR @note: This function enumerates all chunks of all functions in the database """ func = idaapi.get_next_fchunk(ea) if func: return func.s...
b70136da02d6b689fdc3ce7e946aeff87841cb46
5,056
def share_to_group(request, repo, group, permission): """Share repo to group with given permission. """ repo_id = repo.id group_id = group.id from_user = request.user.username if is_org_context(request): org_id = request.user.org.org_id group_repo_ids = seafile_api.get_org_group...
20cdd294692a71e44a635f5fb9dd8ab3a77f95c4
5,057
def change_config(python, backend, cheatsheet, asciiart): """ Show/update configuration (Python, Backend, Cheatsheet, ASCIIART). """ asciiart_file = "suppress_asciiart" cheatsheet_file = "suppress_cheatsheet" python_file = 'PYTHON_MAJOR_MINOR_VERSION' backend_file = 'BACKEND' if asciiart...
b76f40546981c66f8b068c12fa1c1701b532ee7f
5,058
def get_memcached_usage(socket=None): """ Returns memcached statistics. :param socket: Path to memcached's socket file. """ cmd = 'echo \'stats\' | nc -U {0}'.format(socket) output = getoutput(cmd) curr_items = None bytes_ = None rows = output.split('\n')[:-1] for row in rows:...
fcabd77bbf0186498753a4630c50ed7fd900cf96
5,059
def dataset_config(): """Return a DatasetConfig for testing.""" return hubs.DatasetConfig(factory=Dataset, flag=True)
15d8c33e5706c07c03589adb945bdaee3b1dd18a
5,060
import itertools def combinations(): """Produce all the combinations for different items.""" combined = itertools.combinations('ABC', r=2) combined = [''.join(possibility) for possibility in combined] return combined
501060cf9c7de9b4b4453940e017ad30cec2f84f
5,061
from evohomeclient2 import EvohomeClient import logging def setup(hass, config): """Create a Honeywell (EMEA/EU) evohome CH/DHW system. One controller with 0+ heating zones (e.g. TRVs, relays) and, optionally, a DHW controller. Does not work for US-based systems. """ evo_data = hass.data[DATA_EV...
2baf2286e4f08ac0ffb452c8d089951fcede8688
5,062
def geo_exps_MD(n_nodes, radius, l_0, l_1, K=40, thinRatio=1, gammas=10, max_iter=100, nSamp=50, Niid=1, seed=0): """Solves the Connected Subgraph Detection problem and calculates AUC using Mirror Descent Optimisation for a random geometric graph. Parameters ---------- n_nodes...
9e3831975915b6dffecbb1142dbd01cd26a255ca
5,063
from typing import Tuple def validate_sig_integrity(signer_info: cms.SignedData, cert: x509.Certificate, expected_content_type: str, actual_digest: bytes) -> Tuple[bool, bool]: """ Validate the integrity of a signature for a part...
36e64173d8612c9ca3e95cb0566222140c56c17d
5,064
def linemod_dpt(path): """ read a depth image @return uint16 image of distance in [mm]""" dpt = open(path, "rb") rows = np.frombuffer(dpt.read(4), dtype=np.int32)[0] cols = np.frombuffer(dpt.read(4), dtype=np.int32)[0] return (np.fromfile(dpt, dtype=np.uint16).reshape((rows, cols)) / 1000....
e2538520ba3bd82ada339b816c4d1a067bbd4000
5,065
from typing import Iterable from typing import Optional def findNode(nodes: Iterable[AstNode], name: str) -> Optional[SExpr]: """ Finds a node with given name in a list of nodes """ for node in nodes: if isinstance(node, Atom): continue if len(node.items) == 0: ...
5b3f53e98269e6d00cb2dc11dd75d81dfed98f30
5,066
def search(keywords=None, servicetype=None, waveband=None): """ execute a simple query to the RegTAP registry. Parameters ---------- keywords : list of str keyword terms to match to registry records. Use this parameter to find resources related to a particular topic. ser...
855e00f2a001995de40beddb6334bdd8ddb8be77
5,067
import os def _get_credentials(vcap_services, service_name=None): """Retrieves the credentials of the VCAP Service of the specified `service_name`. If `service_name` is not specified, it takes the information from STREAMING_ANALYTICS_SERVICE_NAME environment variable. Args: vcap_services (di...
a72f3e7b6be56ab6c66252cd8063fd0207aac02b
5,068
def all_are_independent_from_all(program, xs, ys): """ Returns true iff all xs are statistially independent from all ys, where the xs are from the current iteration and the ys are from the previous iteration. """ for x in xs: if not is_independent_from_all(program, x, ys): return...
50f091530e322b741465b222da70080463e4f142
5,069
import sys import traceback import string def get_exc_short(): """Print only error type and error value. """ exType, exValue, exTb = sys.exc_info() resL1 = traceback.format_exception_only(exType, exValue) return string.join(resL1, "")
5dc21b813fd3317544f06512e8c1160599aa6955
5,070
def is_str_str_dict(x): """Tests if something is a str:str dictionary""" return isinstance(x, dict) and all( isinstance(k, str) and isinstance(v, str) for k, v in x.items() )
ce6230714c0526764f2cc67e4dedf598acd28169
5,071
def _ensureListLike(item): """ Return the item if it is a list or tuple, otherwise add it to a list and return that. """ return item if (isinstance(item, list) or isinstance(item, tuple)) \ else [item]
1c602a1fcf8dd6a5b4583264e63e38747f5b0d50
5,072
import io def get_file_from_gitlab(gitpkg, path, ref="master"): """Retrieves a file from a Gitlab repository, returns a (StringIO) file.""" return io.StringIO(gitpkg.files.get(file_path=path, ref=ref).decode())
7eccad01a538bdd99651b0792aff150f73e82cdd
5,073
def tsne(x, no_dims=2, initial_dims=50, perplexity=30.0, max_iter=1000): """Runs t-SNE on the dataset in the NxD array x to reduce its dimensionality to no_dims dimensions. The syntaxis of the function is Y = tsne.tsne(x, no_dims, perplexity), where x is an NxD NumPy array. """ # Check inputs ...
348c83048190830dd10982e9fa1426db06e983fc
5,074
def add_corp(): """ 添加投顾信息页面,可以让用户手动添加投顾 :by zhoushaobo :return: """ if request.method == 'GET': fof_list = cache.get(str(current_user.id)) return render_template("add_corp.html", fof_list=fof_list) if request.method == 'POST': name = request.form['name'] alia...
9d70ac010bdf5a3102635eaf1acf75f43689f82e
5,075
def nll_loss(output: Tensor, target: Tensor): """ Negative log likelihood loss function. ## Parameters output: `Tensor` - model's prediction target: `Target` - training sample targets ## Example usage ```python from beacon.tensor import Tensor from beacon.functional import functio...
339ef1300c42ad6923e044e7011615b934923e23
5,076
from typing import List from typing import Optional async def album_upload(sessionid: str = Form(...), files: List[UploadFile] = File(...), caption: str = Form(...), usertags: Optional[List[Usertag]] = Form([]), location: Opti...
303aba7ee57e61082197fe18330663c5c0c51c76
5,077
def mocked_requests_get(*args, **kwargs): """Mock requests.get invocations.""" class MockResponse: """Class to represent a mocked response.""" def __init__(self, json_data, status_code): """Initialize the mock response class.""" self.json_data = json_data sel...
41a54452593cd23e8ea86f1fbdc0c5e92845482f
5,078
def count_disordered(arr, size): """Counts the number of items that are out of the expected order (monotonous increase) in the given list.""" counter = 0 state = { "expected": next(item for item in range(size) if item in arr), "checked": [] } def advance_state(): state...
bb708e7d862ea55e81207cd7ee85e634675b3992
5,079
from typing import Iterable import collections from sys import flags def lookup_flag_values(flag_list: Iterable[str]) -> collections.OrderedDict: """Returns a dictionary of (flag_name, flag_value) pairs for an iterable of flag names.""" flag_odict = collections.OrderedDict() for flag_name in flag_list: if n...
591f0e877a71388de8ad0111f624246ea7a2dc5b
5,080
def test_alignment(): """Ensure A.M. cosine's peaks are aligned across joint slices.""" if skip_all: return None if run_without_pytest else pytest.skip() N = 1025 J = 7 Q = 16 Q_fr = 2 F = 4 # generate A.M. cosine ################################################### f1, f2 = ...
a0f664a153c1af5942d39d54c75bcb8a3b3b660a
5,081
import base64 def request_text(photo_file, max_results=5): """ Request the Google service to find text in an image :param photo_file: The filename (or path) of the image in a local directory :param max_results: The requested maximum number of results :return: A list of text entries found in the im...
3af646e81fb71f89ffab2a9f20f979cdbaaf29a6
5,082
def config(request): """render a ProsperConfig object for testing""" return p_config.ProsperConfig(request.config.getini('app_cfg'))
4222d7d2a56020883e0a196f4c531b44d2f50dd5
5,083
def flatatt(attrs): """ Convert a dictionary of attributes to a single string. The returned string will contain a leading space followed by key="value", XML-style pairs. It is assumed that the keys do not need to be XML-escaped. If the passed dictionary is empty, then return an empty string. ...
03175fd9b2d0574bd3634d43821e38177924ed0e
5,084
import json def json_io_dump(filename, data): """ Dumps the the JSON data and returns it as a dictionary from filename :arg filename <string> - Filename of json to point to :arg data - The already formatted data to dump to JSON """ with open(filename, encoding='utf-8', mode='w') as json_file: ...
e0ae7187ac29669330109ae39ebcac33c1e30ab6
5,085
import requests import json def get_restaurants(_lat, _lng): """緯度: lat 経度: lng""" response = requests.get(URL.format(API_KEY, _lat, _lng)) result = json.loads(response.text) lat_lng = [] for restaurant in result['results']['shop']: lat = float(restaurant['lat']) lng = float(restau...
35884258210174cca0ffcf73dc3451dae07d5712
5,086
def geomfill_GetCircle(*args): """ :param TConv: :type TConv: Convert_ParameterisationType :param ns1: :type ns1: gp_Vec :param ns2: :type ns2: gp_Vec :param nplan: :type nplan: gp_Vec :param pt1: :type pt1: gp_Pnt :param pt2: :type pt2: gp_Pnt :param Rayon: :ty...
f00ade1b203e819c6ae946c31c8c9821f2a79744
5,087
def dwconv3x3_block(in_channels, out_channels, stride, padding=1, dilation=1, bias=False, activation=(lambda: nn.ReLU(inplace=True)), activate=True): """ 3x3 depthwise vers...
eb2330206510369f8d81d0fc58d2578cf212a1df
5,088
import json def predict() -> str: """ Creates route for model prediction for given number of inputs. :return: predicted price """ try: input_params = process_input(request.data) print(input_params) predictions = regressor.predict(input_params) return json.dumps({"p...
ee58cbecf6d44a65f94cb3becd4d6cfe2d30ef30
5,089
def all_h2h_pairs_all_lanes(matches_df, file_name=''): """Produces all head to head win rates for all lane matchups -- even across different lanes (eg. TOP_SOLO Renekton vs MID_SOLO Xerath).""" df = pd.DataFrame() lanes = dc.get_lanes_roles() for lane1 in lanes: print(lane1) for lane...
f6ffd40985455515767c1aa6286dc9998b7bdb7d
5,090
import requests def reload_rules(testcase, rest_url): """ :param TestCase self: TestCase object :param str rest_url: http://host:port :rtype: dict """ resp = requests.get(rest_url + "/rest/reload").json() print("Reload rules response: {}".format(resp)) testcase.assertEqual(...
e747668ba8ad5f58f0307194b0008469dd3593c1
5,091
def encryptMessage(key: str, message: str) -> str: """Vigenère cipher encryption Wrapper function that encrypts given message with given key using the Vigenère cipher. Args: key: String encryption key to encrypt with Vigenère cipher. message: Message string to encrypt. Returns: ...
428372d8443579ac691d43a5542de850b49966ce
5,092
def rae(label, pred): """computes the relative absolute error (condensed using standard deviation formula)""" #compute the root of the sum of the squared error numerator = np.mean(np.abs(label - pred), axis=None) #numerator = np.sum(np.abs(label - pred), axis = None) #compute AE if we were to ...
bff280ba243fd494347643233870524c008c7473
5,093
def subset_sum(arr, target_sum, i, cache): """ Returns whether any subset(not contiguous) of the array has sum equal to target sum. """ if target_sum == 0: return True, {} if i < 0: return False, {} if target_sum in cache[i]: return cache[i][target_sum] # Either inclu...
aa90d7eb4ffa3a457a5f27733de56a82df450861
5,094
from typing import Type import types from typing import Optional def set_runtime_parameter_pb( pb: pipeline_pb2.RuntimeParameter, name: Text, ptype: Type[types.Property], default_value: Optional[types.Property] = None ) -> pipeline_pb2.RuntimeParameter: """Helper function to fill a RuntimeParameter ...
4c6394f60774c42b0a6be8d55b57a67b8fc6b1d5
5,095
def get_loader(content_type): """Returns loader class for specified content type. :type content_type: constants.ContentType :param content_type: Content type. :returns: Loader class for specified content type. :raise ValueError: If no loader found for specified content type. """ for loader_...
0d7e37ff17a48e8bed3a4abb7ce9734579fe9100
5,096
from typing import List from typing import Dict import torch def get_basis_script(max_degree: int, use_pad_trick: bool, spherical_harmonics: List[Tensor], clebsch_gordon: List[List[Tensor]], amp: bool) -> Dict[str, Tensor]: """ ...
9afbe8973541b8b1562f2d336d13b19dae9245fc
5,097
def get_iterative_process_for_minimal_sum_example(): """Returns an iterative process for a sum example. This iterative process contains the fewest components required to compile to `forms.MapReduceForm`. """ @computations.federated_computation def init_fn(): """The `init` function for `tff.templates.I...
40ea1b07f2eeccaaff3cc0657207ef445985f795
5,098
def get_r_port_p_d_t(p): """玄関ポーチに設置された照明設備の使用時間率 Args: p(int): 居住人数 Returns: ndarray: r_port_p_d_t 日付dの時刻tにおける居住人数がp人の場合の玄関ポーチに設置された照明設備の使用時間率 """ return get_r_i_p_d_t(19, p)
abdc6f9201594ca946ff2deb25cdf8c1e1d98839
5,099