content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
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
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
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
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 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 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
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
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 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 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
from typing import Union import re def import_maxquant_data( file: str, sample: Union[str, list, None] = None ) -> pd.DataFrame: """Import peptide level data from MaxQuant. Args: file (str): The name of a file. sample (Union[str, list, None]): The unique raw file name(s) to filter the...
28238068b0703388909a5f90ca651ce5ebc74e06
37,200
def get_z_from_freq(obs_freq): """ Convert observed frequency to (measured) redshift Parameters ========== obs_freq: float Observation (central) frequency in units of Hz ! Return ====== z: float Measured redshift """ z = ( _HI_RESTFREQ / obs_freq ) - 1. return ...
ad7f7d24a8dd1e8aa858563ba27be5c7f829378d
37,201
import array def R_to_orientstring(R): #************************ """ Purpose: Convert transformation matrix to 3-character string defining orientation (e.g., RAI, LPI etc) Arguments: R: 4x4 transformation matrix Returns: orientation: A 3-character string. """ #LPI ...
4687919dac1dd743d2aa096fa8a569263577211d
37,202
def get_executor(): """ Gets executor from the current event thread if applicable. If not, starts a new one. Returns ------- executor : ``ExecutorThread`` or ``ClaimedExecutor`` """ loop = current_thread() if isinstance(loop, EventThread): executor = loop.claim_executor() ...
3d0e60f159896ff5c94d9c01d75e7c4101045cbd
37,203
def shape4(tik_instance, input_x, res, dtype): """input shape (32, 8, 28, 28, 16)""" zero = tik_instance.Scalar(dtype="float16", init_value=0) with tik_instance.for_range(0, 32, block_num=32) as block_idx, tik_instance.for_range(0, 2) as cc1_db, \ tik_instance.for_range(0, 2, thread_num=2) as db...
5150f7637e495d74f7a858eca4a59b25b425e219
37,204
def parse_person(elt): """Parse a person type response element into nested dictionaries http://developer.healthvault.com/sdk/docs/urn.com.microsoft.wc.thing.types.person.1.html """ return dict( name = elt.find('name').text, organization = text_or_none(elt, 'organization'), profe...
2429102554e09e2b5fc8297c6f86e903db366826
37,205
def to_absolute_coordinates(keypoints, height, width, check_range=True, scope=None): """Converts normalized keypoint coordinates to absolute pixel coordinates. This function raises an assertion failed error when the maximum keypoint coordinate value is larger than 1.01 (in which case ...
c337fd7b332b2c9a5ef9ca0a6dd59b9c937bbbef
37,206
def get_zygosity(call): """Check if a variant position qualifies as a variant 0,1,2,3==HOM_REF, HET, UNKNOWN, HOM_ALT""" zygdict = dict([(0, "nocall"), (1, "het"), (2, "nocall"), (3, "hom")]) return zygdict[call]
aff88ed481beeb6406261822eca482430494b6f6
37,207
def discrete_mutual_info(mus, ys): """Compute discrete mutual information.""" num_codes = mus.shape[0] num_factors = ys.shape[0] print(mus.shape,ys.shape) m = np.zeros([num_codes, num_factors]) for i in range(num_codes): for j in range(num_factors): m[i, j] = sklearn.metrics.mutual_info_score(ys[j...
dcc81d137bcce2f358bb5e796ba034641aed7e56
37,208
import torch def create_batch(sentences, params, dico): """ Convert a list of tokenized sentences into a Pytorch batch args: sentences: list of sentences params: attribute params of the loaded model dico: dictionary returns: word_ids: indices of the tokens lengths...
c08430651ea20f633169187f62f7b22e09bbd17e
37,210
def path_label_squeeze(paths): """Returns a weights sum of paths solutions, for visualization.""" v_range = tf.range(1, tf.shape(paths)[-1] + 1, dtype=paths.dtype) return tf.einsum('ijkn,n->ijk', paths, v_range)
cd2300b83abd8294cb78800142c1616ae918df7a
37,211
def _Hz2Semitone(freq): """_Hz2Semitone.""" A4 = 440 C0 = A4 * pow(2, -4.75) name = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"] if freq == 0: return "Sil" # silence else: h = round(12 * log2(freq / C0)) octave = h // 12 n = h % 12 r...
9ca4fe4cad8e01971756d5c09c9cefd6ad62b69f
37,212
def uCSIsCatLt(code): """Check whether the character is part of Lt UCS Category """ ret = libxml2mod.xmlUCSIsCatLt(code) return ret
a4c95edf37dd9d9a462ce3176d8cfd5ed152b878
37,213
def export_file(isamAppliance, path, name, filename, check_mode=False, force=False): """ Exporting a file from the runtime template files directory :param isamAppliance: :param path: :param name: :param check_mode: :param force: :return: """ warnings = [] check_file = _check...
c7b71462b3aab32b34fa24153bad502764f155c4
37,214
from typing import List def make_pos_array_and_diff(trials: List[dict]) -> List[dict]: """ Parameters ---------- trials : Non-filtered refinement trials Returns ------- A list of dictionaries with updated position and difference of neighbours """ _trials = trials[:] for i, c...
ebdb0a63d9399985d11b06ec28d4032a54b22f89
37,215
def a(O, R_r, E, aggregator='sum', include_v=True): """ Applies and returns the aggregating function of the Interaction Network Parameters ---------- O : numpy.ndarray Object matrix R_r : numpy.ndarray Binary matrix that indexes the receiver objects E : numpy.ndarray Predict...
d54caf23ec9090edbacab012a494798fa3875f79
37,217
def coords_json_to_api_pan(ang_clockwise): """converts from robot coordinates to API coordinates.""" return ang_clockwise
6511b7cf196a171095b184d48281f25f97fc6792
37,218
import copy import six import warnings from typing import Iterable def polnum2str(num, x_orientation=None): """ Convert polarization number to str according to AIPS Memo 117. Uses 'pI', 'pQ', 'pU' and 'pV' to make it clear that these are pseudo-Stokes, not true Stokes Parameters ---------- ...
5d6fab5d1e2c66db6d9dedd966a826090791c954
37,219
async def delete_me(twofa: Code2FA, user: UserPass = Depends(is_connected_pass)) -> User: """Delete your user.""" if user.totp is not None: if twofa.code is None or not twofa.verify(user): raise HTTPException( status.HTTP_401_UNAUTHORIZED, "Un code de double a...
c17a4eec312d9e6ad4a2ec8ef936d26d5a60b853
37,220
from typing import Type def should_unwrap(obj: Type[ObjectT]) -> bool: """Test whether we should use the __args__ attr for resolving the type. This is useful for determining what type to use at run-time for coercion. """ return (not isliteral(obj)) and any(x(obj) for x in _UNWRAPPABLE)
9a8c391b692c22fd836f01cf6f186ccdcaa16ae2
37,221
def normalize(net,nodesToIndices=None,layersToIndices=None,nodeStart=0,layerStart=0): """Returns a copy of the network with layer and node indices as integers. In network with n nodes the nodes are renamed so that they run from 0 to n-1. In network has b_a elementary layers in aspect a, the layers are rena...
37e494ded554b5a6dbbb366066bedf6b8ec033e8
37,222
def dict_other_json(imagePath, imageData, shapes, fillColor=None, lineColor=None): """ :param lineColor: list :param fillColor: list :param imageData: str :param imagePath: str :return: dict"" """ # return {"shapes": shapes, "lineColor": lineColor, "fillColor": fillColor, "imageData": im...
3742664276d70ce5f037ba99994c8c2e61114107
37,223
import numpy def draw_dot_singlearrows(fname, epsilon, invepsilon, morph_by_state, axs, ays, L_max, all_digits = False, save_dot = True): """ This function draws the .dot file associated with the epsilon-transducer stored in epsilon+invepsilon. This version works with *memoryful* transducers, where we assume ...
3d915f855ae2bd1050553b1f75d95d1ed8eacb82
37,224
import requests def get_post(post_id): """ Get the post. """ # Returns: (post_title, post_body, user_tuple) route = '{}/api/v2.0/posts/' +\ '{}?key={}&filter=MLLKIHJMHIHKKFMJLLHGMKIMMGOKFFN' response = requests.get(route.format(ms_config["ms_host"], post_id, ms_config["api_key"])) tr...
a3a0027d6f83da7ef343a4e87b45cb6c3e9dd6c4
37,225
def track_from_filename(filename, filetype = None, timeout=DEFAULT_ASYNC_TIMEOUT, force_upload=False): """ Create a track object from a filename. NOTE: Does not create the detailed analysis for the Track. Call Track.get_analysis() for that. Args: filename: A string containing the path to t...
929ba302f05b975fd0ee42988a8835aa13ac6f4b
37,226
from typing import List def create_sectors_from_entities( entities: List[Entity], created_by: Identity ) -> List[Identity]: """Create sectors from entities.""" sectors = [] for entity in entities: sector = create_sector_from_entity(entity, created_by) if sector is None: co...
256b3296420454514d938882f577b0a5bd005686
37,227
def minor1d(array1d, i): """Accept 1D array and return a new array with element i removed.""" range1 = list(range(i)) + list(range(i+1, array1d.shape[0])) return array1d[np.array(range1)]
63ef3f3093e9619d09079af71e0fb1ce769dea23
37,228
def get_ast_field_name(ast): """Return the normalized field name for the given AST node.""" replacements = { # We always rewrite the following field names into their proper underlying counterparts. '__typename': '@class' } base_field_name = ast.name.value normalized_name = replacemen...
c5cf0acbca963e7dc0d853064a2599b732d6b0d1
37,229
def public_api(host_uri): """ Note: unlike the authenticated variant, this helper might get called even if the API isn't going to be used, so it's important that it doesn't try to actually connect to the API host or something. """ conf = fatcat_openapi_client.Configuration() conf.host = host...
e35e4528e06d817f89ef6950590518745e06c76d
37,230
def convex_hull_3d(input, inputmsk=None, outhull=None, inhull=None, copy=False, copyoutside=True): """ Calculates 3D convex hull of non-masked voxels of an image. By default, returns an image where inside-hull-voxels have value :samp:`inhull` and outside-hull-voxels have value :samp:`outhull`. :typ...
d7a6a9adb15b258ba737518a187db546a735a945
37,233
from typing import Any def liquid_filter(_filter: FilterT) -> FilterT: """A filter function decorator that wraps `TypeError` in `FilterArgumentError`.""" @wraps(_filter) def wrapper(val: object, *args: Any, **kwargs: Any) -> Any: try: return _filter(val, *args, **kwargs) excep...
1b6ed4bb26013af1cfe638e3e5cd36cce20c822a
37,234
def end(): """ Terminates a PyNGL script, flushes all buffers, and closes all internal files. Ngl.end() """ NhlClose() return None
072f8c4757492407d93a2eec6ce6607a2c823b00
37,235
def check_home(): """ Checks the button that is clicked from the home screen and returns the corrseponding values.Returns 1 if Play button is clicked, 3 if Instructions button is clicked, and 4 if About button is clicked """ global value, right_click value = 0 mouse = pygame.mouse.get_pos() if 370 <= mouse[...
fe10c9fbd15775c43fa2fafe87cef518b4db4a3a
37,237
def olivine(piezometer=None): """ Data base for calcite piezometers. It returns the material parameter, the exponent parameter and a warn with the "average" grain size measure to be use. Parameter --------- piezometer : string or None the piezometric relation References ---------- ...
387ea9413acdf551abe108ba5ba7dda51e162c51
37,238