content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Union from typing import List def count(obj: Union[int, List]) -> int: """Return the number of integers in obj. >>> count(27) 1 >>> count([4, 1, 8]) 3 >>> count([4]) 1 >>> count([]) 0 >>> count([4, [1, 2, 3], 8]) 5 >>> count([1, [2, 3], [4, 5, [6, 7]...
d982b3096dc9c7776b32bab765e2a17769d128e9
37,100
def kmeans(x, n_clusters=20, random_state=42, **sklearnArg): """Given a set of different 1D functions (represented in matrix form where each row contains the function values on a given grid), this method clusters those functions and tries to find typical function structures. Args: x (numpy matr...
2671a7d40f339cc8e45c28381e65c8f8ceed474e
37,101
def GetClientSecretFlag(): """Anthos auth token client-secret flag, specifies the Client Secret is the shared secret between OIDC client application and OIDC provider.""" return base.Argument( '--client-secret', required=False, help='Client Secret is the shared secret between OIDC client applicati...
7d01e32208f51299e793359458ecef1da5e5bae6
37,102
def login(request): """ Fonction idantifiant les gens et/ou renvoyant le formulaire. """ message = None form = None topThree = [] if request.method == 'POST': if request.session.test_cookie_worked(): request.session.delete_test_cookie() form = LoginForm(reque...
7e3dfe056e690c5830053a6e05f86b74e37e0fec
37,103
def start_instance_pool(instance_pool_id: str, configuration: Configuration = None, secrets: Secrets = None) -> OCIResponse: """Start the given OCI Compute instances.""" client = oci_client(ComputeManagementClient, configuration, secrets, ...
462f76cad9c9c7c7817ccaf6ed4715c7fb5caed1
37,104
def label_rank(label, scores, label_order) -> int: """ Add Labels based on Rank :param label: Label to assign to item :param scores: Score to rank item :param label_order: Order of Labels :return: Return Index """ loc = label_index(label, label_order) if loc is None: return ...
06d5bb4d01f7b8194555f978be66ddb238b03360
37,105
def _single_quote_string(name: str) -> str: # pragma: no cover """Single quote a string to inject it into f-strings, since backslashes cannot be in double f-strings.""" return f"'{name}'"
39868168862f3bd60d8da6168503cbc51fcbda84
37,106
import tempfile import os import yaml def parse_override_config_and_write_file(namespace): """ Parse the command line for overriding the defaults and create an override file. """ overrides = parse_override_config(namespace) try: tmp_dir = tempfile.mkdtemp() override_config_file = os.path.join(tmp_...
607466e20bbd5a64c14883e5515c19c04cc9e7ac
37,107
def compute_rel_rois(num_rel, rois, relations): """ union subject boxes and object boxes given a set of rois and relations """ rel_rois = np.zeros([num_rel, 5]) for i, rel in enumerate(relations): sub_im_i = rois[rel[0], 0] obj_im_i = rois[rel[1], 0] assert(sub_im_i == obj_im...
4fcdf1fe57557a73c3da476e327f1632ea217d6d
37,108
from pyparsing import ( srange, oneOf, Forward, Optional, Suppress, Word, ZeroOrMore, dblQuotedString, pythonStyleComment ) def from_gml(text): """ Return the list of graphs read from `text`, a string in GML format. This function assumes that the input follows the GML specification, p...
d223438d6b38d1b1c62c2e9a734a6a08b94e1721
37,109
import typing from unittest.mock import patch def parse(type_string: str, *, func=None): """Parse the given type string. Args: type_string (str): The type string to be parsed. func (function): The function to which the type string belongs (optional). This causes the t...
485d0d5dd2edb63873464e3e02d67c202947d78b
37,110
from threading import Thread def run(data, inFile="", encrypt=False, method=3, aad="", key=config.KEY): """ Run encryption of decryption. data: file name with extension encrypt: False to decrypte method: Block cyphering method """ if len(data) > 100000: thread = Thread(target=wa...
3884592005f72a2e2375da2698f37a61e7bc6aa3
37,111
def convert_str_version_number(version_str): """ Convert the version number as a integer for easy comparisons :param version_str: str of the version number, e.g. '0.33' :returns: tuple of ints representing the version str """ version_numbers = version_str.split('.') if len(version_number...
b550b7d07d9b226800de261f792bf0995ac21738
37,112
import torch def valid_simulation(_state, _params): """ AW - valid_simulation - return a binary variable per simulation indicating whether or not that simulation satifies the desired policy outcome. :param _state: tensor (N x D): tensor of the state trajectory. :return: tensor (N, ), bool: ten...
6eb82ec744cbab353f649e63d54c0d95236f1699
37,113
def computeA(diameter): """Computes area of circle""" radius = diameter / 2.0 return np.pi * (radius**2)
d78b596a3df0e82cf93b5e0318b9ba53c3dc1b6c
37,114
def RemoveFromLinuxKernelCmdline(option): """ Remove 'option' to the kernel boot options of the grub configuration. """ if FindInLinuxKernelCmdline(option): src = r'^(.*?' + MyDistro.grubKernelBootOptionsLine + r'.*?)(' + option + r')(.*?)("?)$' rep = r'\1\3\4' try: R...
798c803d3fb7d2ac9d525e8ea67e858c518e4e2d
37,115
def get_maximum_weight(G, S, T): """ Given a networkx graph G and two subsets of vertices S and T, this method returns the maximum weight of an edge e, having one endpoint in S and the other in T :param G: A networkx graph :param S: A subset of vertices in G :param T: A subset of vertices in G ...
8cb40045a303845b070760aad3c9d66815827a3d
37,116
def create_volume_snapshot(session, cg_id, display_name, return_type=None, **kwargs): """ Creates a new snapshot for the specified volume. Manually initiated snapshots will fall under the "On Demand" snapshot policy. :type session: zadarapy.session.Session :param session...
caf9fdbdb5ddb26c3b271f3c568f3e49b5c5acd2
37,117
def parse_elem(elem): """Determine element type and dispatch to other parse functions.""" if len(elem) == 0: return parse_text(elem) if not elem[0].attrib: return parse_list(elem) if elem[0].get('Name') == 'Key': return parse_key_value_dict(elem) return parse_attrib_dict(elem...
c6195c8f8389b0ea93e8f48a827d0e212eb5aa42
37,118
from typing import Optional def configured_version_for(artifact_name: str) -> Optional[str]: """Given the name of an artifact, retrieves the version of that artifact from the current stack configuration. Returns `None` if no version has been specified for that artifact. In general, we will have versi...
90e6bd5f09aa53ff33fefda5027c3b110d923578
37,119
def filtered_cumulative_sum(df, columns, latest_date, reference_column_name="covid_vacc_date"): """ This calculates cumulative sums for a dataframe, and when given a set of characteristics as columns, produces a dictionary of dataframes. Args: df (Dataframe): pandas dataframe. At the very least...
5bcb2d79fdfb2e8f26868ef3d411163b3d73f8e3
37,120
def handover_results(): """ Endpoint to get a list of all the handover by release This is using docstring for specifications --- tags: - handovers operationId: handovers parameters: - name: release in: query type: string description: get handover list for ...
a15b0b69b5ddf4654311d0940a37fac548c5dcf4
37,121
def safezip(*args): """make sure *args* are equal len before zipping""" Nx = len(args[0]) for i, arg in enumerate(args[1:]): if len(arg) != Nx: raise ValueError(_safezip_msg % (Nx, i + 1, len(arg))) return list(zip(*args))
f8d2a1c3bbe33903b896e1dbf64ffd1c0804d849
37,122
from typing import Union def chaid_to_graphviz( tree: dict, classes: Union[list, np.ndarray] = [], classes_color: list = [], round_pred: int = 2, percent: bool = False, vertical: bool = True, node_style: dict = {}, arrow_style: dict = {}, leaf_style: dict = {}, **kwds, ): "...
e48dc9611b9208b99daa631217320d644d02a769
37,123
import copy def process_dataset(dataset, func): """Calculate things here using the dataset, then return a dictionary containing names and values for each calculated quantity.""" new_dataset = copy.copy(dataset) del new_dataset["val"] new_dataset.update(func(dataset)) return new_dataset
b38b2edd1abe9a990d8f524b78b38e8abadc7c55
37,124
def cosine_beta_schedule(timesteps, s = 0.008): """ cosine schedule as proposed in https://openreview.net/forum?id=-NEXDKk8gZ """ steps = timesteps + 1 x = np.linspace(0, steps, steps) alphas_cumprod = np.cos(((x / steps) + s) / (1 + s) * np.pi * 0.5) ** 2 alphas_cumprod = alphas_cumprod...
703c78956b9d0e1ca00dbe2d1b3a7025aa955623
37,125
def _infinity(name): """ Create a single instance of an class with a given name. """ return type(name + "Type", (object, ), { '__repr__': lambda self: "{0}.{1}".format(self.__module__, name), '__str__': lambda self: name, '__unicode__': lambda self: name, })()
bd6cbda227e9d97938ab9ed7c2d2e97b95dc5080
37,126
def allocate_packs(packs, tracks, pack_refs, num_silent_tracks): """Allocate tracks to channels and packs. This is intended to be used on a subset of tracks referenced by an audioObject, or on all tracks if there is no programme/content/object hierarc...
05c1c0c99633904f8c38255410f0517c5dec8eb7
37,127
def edit_settings(request): """Edit user settings.""" user = request.user if user.groups.filter(name='Mozillians').exists(): raise Http404 form = forms.EditSettingsForm(request.POST or None, instance=user.userprofile) if request.method == 'POST' and form.is...
3a933ad9ded228bfccac92e6ab1ce9d2535d9fe2
37,128
def calculate_priority(priority_table_uri): """Create dictionary mapping each land-cover class to their priority weight. Args: priority_table_uri (str): path to priority csv table Returns: priority_dict (dict): land-cover and weights_matrix """ LOGGER.info("Creating land-cover prio...
7e78ac80a388c7337f2ecd0b13e5149adee7c0d7
37,129
def create_virtual_cdrom_spec(client_factory, datastore, controller_key, file_path, cdrom_unit_number): """Builds spec for the creation of a new Virtual CDROM to the VM.""" config_spec = clien...
8f62c70c432c368f0f94b3c1dc48f38d75093b07
37,130
def read_image_from_file(file_path: str) -> np.ndarray: """Read image data from a file and return as is.""" img = cv2.imread(file_path, cv2.IMREAD_UNCHANGED) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) return img
dccee146e26b4eb99ac02f392dc4769666dd2a98
37,131
def get_line(x, camera_id, camera_param): """Get line in world""" # x: n * 2 x_tmp = np.concatenate((x, np.ones((len(x), 1)).astype(np.float32)), axis=1) new_x = (x_tmp - camera_param[camera_id]['C']) * camera_param[camera_id]['FInv'] sample_num = len(new_x) cam_origin = np.array([[0, 0, 0]...
6467767026bcb556d83709c4b63d3b0e3eeba2ed
37,132
def get_cca_data_as_matrices(data_set="train"): """ Normalizes data and returns data and labels as separate lists. Args: data_set: data set to retrieve Returns: data: list of data vectors labels: list of vectors """ X_scores, labels = CCA_reduction(data_set=data_set) dat...
6e580dd6738f46cb5fa0cb11e865538989a622ad
37,133
def shard_query(query, shard_count): """ Given a datastore.Query object and a number of shards, return a list of shards where each shard is a pair of (low_key, high_key). May return fewer than `shard_count` shards in cases where there aren't many entities. """ OVERSAMPLING_MULTIPLIER = 32 #...
118ef5ba64a3ea58ba0676982062e3261ae4e2ed
37,134
def get_bindings(keysToObtain=None): """Returns a dict struct with the direct input equivalent of the necessary elite keybindings""" if keysToObtain is None: keysToObtain = keys_to_obtain direct_input_keys = {} latest_bindings = get_latest_keybinds() bindings_tree = parse(latest_bindings) ...
284f6eb8eac18079ad2d3de050758a2cbe528380
37,135
def add_intercept(A): """ Adds an intercept (column of ones) to a supplied array A such that the intercept is the first (leftmost) column """ n = A.shape[0] intercept = ones(n).reshape(n, 1) return hstack((intercept, A))
64149664398b153dcf2927a8d4543b3de0e4b8a3
37,136
from sys import path import logging def predict_adjacent_stop(departure_stop_num, arrival_stop_num, features, num_predictions): """ Predict the time to travel between two adjacent stops on the same route trip. This method uses stop numbers and not stop IDs since stop IDs are not available in the histo...
1376da584f9aee4ffb9b7996df5932223c202bb1
37,137
def _cut_open_ended_intervals(intervals): """Keep only one open interval If there are multiple open intervals keep only the latest open; cut others so they no longer intersect each other. :param intervals: [Interval] :return: processed intervals: [Interval] """ filtered_intervals = [] ...
1a4b5ae772a4a0bc092b1b61387c91dd32236b6d
37,138
def get_content_type(obj): """ Returns the content type for ``obj``. """ return ContentType.objects.get_for_model(obj)
71ee7ee109ce15f966446f7d86666c5737f80171
37,139
def spark_random_split(data, ratio=0.75, seed=42): """Spark random splitter. Randomly split the data into several splits. Args: data (pyspark.sql.DataFrame): Spark DataFrame to be split. ratio (float or list): Ratio for splitting data. If it is a single float number it splits d...
0a250f72e99ea81d2660d888276340a467e4af88
37,140
import os def get_test_suite_kwargs(args): """Set and return test suite kwargs based on options.""" kwargs = vars(args) del kwargs['verbose'] ydk_root = get_ydk_root() default_profile = ydk_root + '/profiles/test/ydktest.json' default_test_root = os.path.join(ydk_root, 'test', 'test-cases') ...
8f1f5ea592b24f4be64fa7d333a9ccf4093fdd24
37,141
def unique_all(x: Array, /) -> UniqueAllResult: """ Array API compatible wrapper for :py:func:`np.unique <numpy.unique>`. See its docstring for more information. """ values, indices, inverse_indices, counts = np.unique( x._array, return_counts=True, return_index=True, ...
a6946861799c51a4499d94dc003316ecfbfb1802
37,142
def tail(filepath, n): """Similate Unix' tail -n, read in filepath, parse it into a list, strip newlines and return a list of the last n lines""" with open(filepath) as f: file = f.read() tail_result = file.split('\n')[-n:] return tail_result
a91b1111c7943f9b9ac3e63032a43f3a18fbda59
37,143
import argparse def parse_args(): """ Parse the command line arguments and return an object representing the command line (as returned by argparse's parse_args()). Returns ------- The commandline argparse namespace. """ parser = argparse.ArgumentParser(description='Utility for lis...
3f58a22f11418c79479f28ee9b4fd7cb8832b77c
37,144
def test_flag_robots(app, mock_user_ctx, request_headers, objects): """Test flag_robots preprocessor.""" def build_event(headers): with app.test_request_context(headers=headers): event = file_download_event_builder({}, app, objects[0]) return flag_robots(event) assert build_even...
f5b5cd6698bdf99d6b1caff38c07c8f53ee75fb8
37,145
def plot_mean_and_CI(axes, mean, lb, ub, label, freqs, linestyle='-'): """ Plot mean and confidence boundaries. Args: axes: plt.axes mean: np.ndarray lb: np.ndarray ub: np.ndarray label: string freqs: list linestyle: string Returns: plt.axes ...
77b7ecaa6dddae474495c0a65efafbf08717584c
37,146
def messages(request): """ Display some messages """ adjax.success(request, "This is your first success") adjax.info(request, "This is your first info") adjax.warning(request, "This is your first warning") adjax.error(request, "This is your first error") adjax.debug(request, "This is your first ...
a7a339712e905d109c19d73ab60059869b149b74
37,147
def locked(acquire, release): """Decorator taking two methods to acquire/release a lock as argument, returning a decorator function which will call the inner method after having called acquire(self) et will call release(self) afterwards. """ def decorator(f): def wrapper(self, *args, **kwarg...
92f8ae3b36375d14962997436bc1d210510b4cdb
37,148
from api_x.zyt.evas.payment.config import PaymentScene def app_checkout_entry_info(source, sn): """app支付info接口 deprecated之前只有lvye_skiing接入 """ return redirect(config.HOST_URL + url_for('biz_entry.pay_info', sn=sn, payment_scene=PaymentScene.lvye_skiing))
27654aff3e1a178d97889d2f649bc4ba46bad256
37,149
def linreg(X, Y): """ Summary Linear regression of y = ax + b Usage real, real, real = linreg(list, list) Returns coefficients to the regression line "y=ax+b" from x[] and y[], and R^2 Value """ if len(X) != len(Y): raise ValueError("unequal length") N = len(...
379ec60fdbf33d9ea5c544cc04ecfd8257813c47
37,150
import torch def _handle_row_wise_sharding_sharded_tensor( input, world_size, weight, local_shard_t, bias, pg ): """ Entry-point function to handle the logic of row-wise sharding of weight for Linear when the input is a sharded tensor. (Detailed explanations of the logic can be found in the commen...
e5e709d7cc101adf1d31efbc3195136accbbc73d
37,151
def put_tags(new_tag_list, cgx_dict): """ This function looks at a CloudGenix config object, and puts tags. :param new_tag_list: List of tags to add if not already present. :param cgx_dict: CloudGenix config dict, expects "tags" keys supported in root. :return: CloudGenix config dict with added tags...
70ff682995a17d2e27d4a4fabcb32c545bb7bcfe
37,152
def perturb_actions(states, actions, perturbations, limits=None): """Create state-action pairs by perturbing the actions. Parameters ---------- states : ndarray An (N x n) array of states at which we want to generate state-action pairs. actions : ndarray An (N x m) array of ...
6a7152027004a4520057dcfaf82d1cde21f81dc2
37,153
import time def median(image_set, size=None): """ Applies a median filter to the image set. This function is a wrapper around scipy.ndimage.filters.median_filter """ if size is None: print('Please set a filter size. Defaulting to size = 3.') size = 3 print('Applying median f...
3fd0c47ec3bafabbe93584c2c011e7245003ed48
37,154
def conditional_demographic_parity_ratio(labels, pred, attr, groups): """ Calculate conditional demographic parity by calculating the average demographic parity ratio across bins defined by `groups`. """ ratios = [] for group in set(groups): mask = groups == group ratios.append...
523a70684f303822f05d14874011a56741161e05
37,155
def calculate_ddx_G2(neighborindices, neighborpositions, eta, Rc, Rs, i, m, l): """ Calculates coordinate derivative of G2 symmetry function for atom at index i and position Ri with respect to coordinate x_{l} of atom index m. Parameters --------- neighborindices : list of int List ...
affc094b6ecacb17c451989460bbde8c9939aadf
37,156
def _correct_module_lettercase(module: str): """ 修正模块的大小写. 示例: 'qtquick-window' -> 'QtQuick.Window' 'qtgraphicaleffects' -> 'QtGraphicalEffects 注意: 存在一些特殊情况: 'qt-labs-animation' -> 'Qt.labs.animation' 思路: 1. 我们需要把模块的名字按照词来拆分: 'qtgraphicaleff...
bb520055cf181b07cf39cef5adba33af60fab77f
37,157
def normalize(x, axis=None, degree = 2, avoid_nans = False): """ Normalize array x. :param x: An array :param axis: Which axis to normalize along :param degree: Degree of normalization (1 for L1-norm, 2 for L2-norm, etc) :param avoid_nans: If, along an axis, there is a norm of zero, then normali...
5b356936a6943f1490e6c8a6d6d93e3b2a8fb003
37,158
def get_default_curriculum_env_config(method, env_config=None): """Get default curriculum env config. Args: method: The method used in curriculum learning. env_config: Optional. The env config. If None, use the default env config file. Default, None. Returns: A curriculum env config. """ i...
cf2d7166ae66a8342f2e574bf921f5e27105afb5
37,159
import ctypes def _get_libc(): """Load the lib-C for unix systems.""" libc = _system_libraries.get("libc") if libc is None: libc_name = find_library("c") if libc_name is None: # pragma: no cover return None libc = ctypes.CDLL(libc_name, mode=_RTLD_NOLOAD) _syst...
6e233d6e8af013d48e0751325f40ca9ef95d7d19
37,160
def try_multiple_dec_s3(func): """An S3 specific adapter to @try_multiple_dec To decorate func to try multiple times after some sleep upon encountering some intermittent error from S3 """ return try_multiple_dec( ntrials=4, duration=2., increment_type...
711c30c85cc5ca66484ddc27426afc1e151e86de
37,161
def standardize_education_level(education_column): """This function aims at standardizing the education level. The column has mixed types (ints and categories, with overlapping categories). Args: education_column (pd.Series): column in which we will replace the identified matching values. ...
8a8cc237b8123a5c48b52a918d5e8d5de660ce4b
37,162
def neutral_key_state(game: Game): """ Logic to execute when no relevant key is pressed. Returns updated neutral_count """ player = game.player previous_orientation = player.orientation if player.is_moving_up(): player.reset_speed() player.orientation = DIRECTIONS.get(0) game.sc...
4f2a7542385e5e575dcb46e5be5b02987b528743
37,163
def reshape_from_matrix(output_tensor, orig_shape_list): """Reshapes a rank 2 tensor back to its original rank >= 2 tensor.""" if len(orig_shape_list) == 2: return output_tensor output_shape = get_shape_list(output_tensor) # output_shape = tf.shape(output_tensor) orig_dims = orig_shape_list[0:-1] widt...
de9344c0cf09cdd0a3f33db39fcb1b7a72fe00e5
37,164
def compute_unconstrained_optimization_weights(cov, mean, market_return, rfr, market_var, l=None): """ """ # risk aversion if l is None: l = (market_return - rfr) / market_var return np.dot(np.linalg.inv(l*cov), mean)
0a11d920db8bb28e13484d3138a33b7233103327
37,165
import os def get_coordinates_partition_path(coordinates_dir: str, partition_type: utils.PartitionType) -> str: """Gets the path to the coordinates for the provided partition file. Args: coordinates_dir: A directory containing coordinates files. partiti...
2aee18e77eeaf85fe552be622e8370f924b1077b
37,166
def setup_animation(tracks, step_interval): """ Set up data structures and a matplotlib FuncAnimation instance for animating a list of track DataFrames. :param tracks: list of track DataFrames :param step_interval: step interval for animation (e.g., '15S') :return: FuncAnimation instance """...
8e296f35395f2a815309b3a15c43933a41791f90
37,167
def eval_standard(ner_model, examples, label=None): """ Evaluates the model using the standard evaluation metrics If label parameter is not defined, the scores will be calculated for the whole document, otherwise it will calculate the scores for the selected label only Parametres ------------- ...
68e2d372369a69fb3bee5f0dde767873021347ae
37,168
def calc_E_G_C_hs_d_t(): """冷房設備機器のガス消費量(MJ/h)(23b)を計算する Args: Returns: ndarray: 冷房設備機器のガス消費量(MJ/h) """ return calc_E_G_C_hs_MR_d_t() + calc_E_G_C_hs_OR_d_t()
c9eff01fd51590850d8c2f01aae90c04315eb4d7
37,169
def Keplerian1D_neg(x, mass=1., v0=0., r0=0.): """Computes the keplerian velocity at requested distances. Args: x (array_like): Distances to the central object. mass (float, optional): Mass of the central object. v0 (float, optional): Velocity offset ...
edbb693de44d73420c9874efa4366a7ea39c4ecb
37,170
import os def process_modules_csv(drcty): """ Separate out MFG from model and append these columns to base data frame """ dp = os.path.join(os.getcwd(), drcty) fp = os.path.join(dp, 'CEC Modules.csv') df = pd.read_csv(fp, index_col=0, skiprows=[1,2]) names = list(df.index.values) mfgs...
405c4d185ed829ce6619147804ac19a0da85b487
37,171
def create_sample_table(word_count): """ Create negative sample table for vocabulary, words with higher frequency will have higher occurrences in table. """ table = [] frequency = np.power(np.array(word_count), 0.75) sum_frequency = sum(frequency) ratio = frequency / sum_frequency co...
9c8c1e05d2d493b4c8ace51772effa776c732e61
37,172
from typing import Dict import torch def create_supervised_evaluator( model: nn.Module, metrics: Dict, device, dtype, output_transform=lambda x, y, y_pred: (y_pred, y,)): """ Factory function for creating an evaluator for supervised models. Args: model (`torch.nn.Module`): the model to tr...
56def95b6491b16ca15ae386f3d58d2798433e36
37,173
import logging def post(activity: dict, collection_id=None, **kwargs): """Celery task to deal with data post processing.""" execution = execution_from_collection(activity, collection_id=collection_id, activity_type=post.__name__) collection = execution.activity.collection scene_id = activity['scenei...
bdef84b97d6fe4883f24953a990bd5dd7b610f89
37,174
import functools import operator def feed_forward_cnn_small_categorical_fun(action_space, config, observations): """Small cnn network with categorical output.""" obs_shape = common_layers.shape_list(observations) x = tf.reshape(observations, [-1] + obs_shape[2:]) with tf.variable_scope("network_parameters"): ...
bdd25c95c30d66976dc1d84b596ebc08cab4abad
37,175
def check_next_in_request(request): """ Проверяет наличие слова 'next' в объекте запроса request методе POST :param request: :return: """ return True if 'next' in request.POST else False
b70ba54fa32234798b842ffcb24834fdcd95c827
37,176
from typing import List from typing import Callable def build_data_pipeline( chain: List[Callable], kwargs: DataFuncKwargs, args_mut: DataFuncArgsMut ): """ Higher order function :param chain: array of callable :param **kwargs: any kwargs you like """ for call in chain: # note: ret...
252d7aa1a5238a770a589623bddeb36fa8d21bd7
37,177
import tokenize def tokenize_by_word(text, deacc): """Tokenize input text. Before tokenizing transforms text to lower case and removes accentuation and acronyms set :const:`~gensim.summarization.textcleaner.AB_ACRONYM_LETTERS`. Parameters ---------- text : str Given text. Returns ...
eab6b61f178b6a388a5f5357e0f31c818ca74750
37,178
def overlap_slices(large_array_shape, small_array_shape, position): """ Modified version of `~astropy.nddata.utils.overlap_slices`. Get slices for the overlapping part of a small and a large array. Given a certain position of the center of the small array, with respect to the large array, tuples o...
ef86928b3ef619f209247bb72e2e391d14d541c4
37,179
import torch def mrr(scores: torch.Tensor) -> np.float: """ Tested | Accepts one (n,) tensor """ ranks = (torch.argsort(scores, dim=0) == 0).nonzero()[0] recirank = 1.0 / (ranks + 1).float() return recirank.detach().cpu().numpy().item()
33f185d0465bd6bf89a933d3a849e49414e7e423
37,180
import os import subprocess import logging def write_to_raveler(sps, sp_to_segment, segment_to_body, directory, gray=None, raveler_dir='/usr/local/raveler-hdf', nproc_contours=16, body_annot=None): """Output a segmentation to Raveler format. Arguments: - sps: ...
95c063139addc53be505932050ba1fc4bd7b6528
37,181
import numpy def rotmat(x, origin=(0, 0, 0), upvector=(0, 0, 1)): """ Given a position vector x, find the rotation matrix to r,h,v coordinates. """ x = numpy.asarray(x) - numpy.asarray(origin) nr = x / numpy.sqrt((x * x).sum()) nh = numpy.cross(upvector, nr) if all(nh == 0.0): nh =...
519d7aaa15dd48bb31aed0059c01f365f4e8118b
37,182
def curry(func): """Curry a function, but keep the docstring Args: func: a function to curry Returns: a curried function >>> def add(a, b): ... '''Add stuff''' ... return a + b >>> curry(add)(1)(2) 3 >>> print(curry(add).__doc__) Add stuff """ retur...
7fed40c2794496a78ff629f1e391206ab5c3b241
37,183
def score_func(house_data, venue_data): """Function for calculating location-based score of a house. Function gets a house and venues within 1 km radius of that house, calculates each venue's influential score on that house with dividing venue's check-in count with the distance. With that division,...
d1f3f5596316cfb958edf9672fcbc9665f53fa9c
37,184
def bold(s): """Return the string bold. Source: http://stackoverflow.com/a/16264094/2570866 :param s: :type s: str :return: :rtype: str """ return r'\textbf{' + s + '}'
f7b791ea59852f5ab268ff67535c2f4b26d0f078
37,185
def train( n_layer, init_scale=1, scale_upper_bound=128, accum_upper_bound=4096, method="approx_range", update_per_n_iteration=1, warmup_attr_ratio=None, warmup_n_epoch=None, n_class=10, manual_seed=0, train_batch=128, device=-1, learnrate=0.1, ): """ Train functi...
3bcb26a2ffc23b4af97e8fa78fcc5ee86a27649e
37,186
def verify_access_key(key): """ Confirm that the access key is valid. :param str key: Access key string. """ try: access_key = models.AccessKey.objects.get(key=key) except models.AccessKey.DoesNotExist: return None return access_key
682e644fe420d17142d89c734e976db91bfce3c9
37,187
def send_sns_message(sns_client, payload, sns_topic_arn): """Publishes the message to sns. Arguments: sns_client (client): The boto3 client for SQS payload (dict): the payload to post to SNS sns_topic_arn (string): the arn for the SNS topic """ dumped_payload = get_escaped_json...
0398ebf26314a2efe532b072dd2c9696a188644d
37,188
def filter_first_altloc(atoms, altloc_ids): """ Filter all atoms, that have the first *altloc* ID appearing in a residue. Structure files (PDB, PDBx, MMTF) allow for duplicate atom records, in case a residue is found in multiple alternate locations (*altloc*). This function is used to r...
baa8e0b3588523d4af194091bd161873fdebaa4f
37,189
import scipy import numpy def dlqr(A, B, Q, R, optimal_cost_function=False): """Solves for the optimal lqr controller. x(n+1) = A * x(n) + B * u(n) J = sum(0, inf, x.T * Q * x + u.T * R * u) """ # P = (A.T * P * A) - (A.T * P * B * numpy.linalg.inv(R + B.T * P *B) * (A.T * P.T * B).T + Q # 0.5...
17149079f1eae11f07184170c4a91a46fa2787bb
37,190
def add_single_scale_rpn_losses(model): """Add losses for a single scale RPN model (i.e., no FPN).""" # Spatially narrow the full-sized RPN label arrays to match the feature map # shape model.net.SpatialNarrowAs( ['rpn_labels_int32_wide', 'rpn_cls_logits'], 'rpn_labels_int32' ) if cfg.T...
367917906613f688f68d629063a6a80ea05ceafe
37,191
def product(data): """ Generate the product for the entries specified by the data. """ return "tRNA-{aa} ({anticodon})".format( aa=data["metadata"]["isotype"], anticodon=data["metadata"]["anticodon"], )
5f347cfa1fd7d7030fb1b1a5d2e88eb664c831ae
37,192
def _pad_image(image, factor=2): """Enlarges the image canvas, filling new pixels with colors at the edge. :param image: An RGB image :param factor: A scalar representing the factor in which the canvas is to be enlarged. A factor of 2 will double the canvas, a factor of 1 will keep it ...
de45488de1b8de449d4c9ba8db9e7b1572f5d88c
37,193
def change_multi_asset_mode(self, multiAssetsMargin: str, **kwargs): """ | | **Change Multi-Assets Mode (TRADE)** | *Change user's Multi-Assets mode (Multi-Assets Mode or Single-Asset Mode) on Every symbol* :API endpoint: ``POST /fapi/v1/multiAssetsMargin`` :API doc: https://binance-docs.github...
03935ac6efb09b9a4e5923f9aab8ef1edfca5426
37,194
import base64 def get_image_data(docx_file_path, image_name): """ Return base 64 encoded data for the image_name that is stored in the docx_file_path. """ with ZipFile(docx_file_path) as f: images = [ e for e in f.infolist() if e.filename == 'word/media/%s' % image_...
77776dfc43c8a31c371b9ec87f4fcdedda8c0441
37,195
async def get_a_user(user_id): """ Get a single user --- /api/users/{user_id}: get: summary: Buscar um usuário pelo ID security: - APIKeyHeader: [] tags: - User parameters: - in: path name: user_id required: true schema: ...
48fe262763872d0f394bdb9bb9a3ed553cae7ee2
37,196
def extract_string_from_tensor(input_ids: Tensor, mode="single",config = None, tokenizer = None): """ Args: input_ids(Tensor): input tensor of sequence index. Shape: (self.batchsize,self.seq_length) mode(str): "pair","single"and "CBT", "pair" for tasks with paired inputs, such ...
91eb9f11b338592d365e062312ad70f5d0ab5ce8
37,197
async def create_deliverer_keyboard( customer_tg_id, button_text: str, callback_action: str, ) -> InlineKeyboardMarkup: """Creates a keyboard for delivery man.""" keyboard = [ [ InlineKeyboardButton( text=button_text, callback_data=f'{callback_acti...
71f15a2b061f235a12f3a211732054718d45c76b
37,198
def get_trial_id(): """Trial id for the corresponding trial of this Trainable. For function API use only. Do not call this method in the Class API. Use `self.trial_id` instead. """ _session = get_session() return _session.trial_id
69c40d2a5d3541e0568ddcbfddf65fc848801097
37,199