content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_social_profile_provider_list(profile): """ """ sp = None sp = SocialProfileProvider.objects.filter(user=profile.user).order_by('provider', 'website',) return sp
9e157c97dfd0d7daa1a2d0ad80bd84add3dcc281
33,288
import socket import struct def ip2long(ip): """ Convert an IP string to long """ packedIP = socket.inet_aton(ip) return struct.unpack("!L", packedIP)[0]
fbcd7e6255590fa5f67c90bb077d2aa9858abf0a
33,290
def item_link_copy(request, op): """ Objekt zum Einblenden markieren """ if request.GET.has_key('id'): item_container = get_item_container_by_id(request.GET['id']) else: item_container = get_my_item_container(request, op) if item_container.parent_item_id != -1: #request.session['dms_link_copy_id'] =...
1696eaa219193f80d4f61a9b573d00c4a06f077b
33,291
def get_aggregation_fn_cls(rng): """Sample aggregation function for feature""" return rng.choice(AGGREGATION_OPERATORS)
843fc97c7216148e2bdfb40009da5a56f77b7008
33,292
def resnet_mvgcnn(depth, pretrained=False, **kwargs): """Constructs a MVGCNN based on ResNet-18 model.""" model = ResNetMVGCNN(BasicBlock, resnet_layers[depth], **kwargs) if pretrained: pretrained_dict = model_zoo.load_url( model_urls['re...
433b028c8af6c99a17b4cb35fc217bffaeee1439
33,293
def _smooth_samples_by_weight(values, samples): """Add Gaussian noise to each bootstrap replicate. The result is used to compute a "smoothed bootstrap," where the added noise ensures that for small samples (e.g. number of bins in the segment) the bootstrapped CI is close to the standard error of the me...
470c2263f81212daf56450e43f64b56d32b654a0
33,294
def lpc_ref(signal, order): """Compute the Linear Prediction Coefficients. Return the order + 1 LPC coefficients for the signal. c = lpc(x, k) will find the k+1 coefficients of a k order linear filter: xp[n] = -c[1] * x[n-2] - ... - c[k-1] * x[n-k-1] Such as the sum of the squared-error e[i] = ...
bd148dd367fa179933b7f318e071e1017fd707ce
33,295
def make_mpo_networks( action_spec, policy_layer_sizes = (300, 200), critic_layer_sizes = (400, 300), ): """Creates networks used by the agent.""" num_dimensions = np.prod(action_spec.shape, dtype=int) critic_layer_sizes = list(critic_layer_sizes) + [1] policy_network = snt.Sequential([ netw...
c52cb76f96390ab633ca05f33e1e40b20d78ae93
33,296
from typing import Callable from typing import Any def numgrad_x(f: Callable[[Any], Any], x: Tensor, eps: float = 1e-6) -> Tensor: """get numgrad with the same shape of x Args: f (Callable[[Any], Any]): the original function x (Tensor): the source x eps (float, optional): default error. Default...
fd8b680e122de3adaa3a3246f8d7f786bffd24a2
33,297
def throw_darts_serial(n_darts): """Throw darts at a square. Execute serially! Count how many end up in an inscribed circle. Approximate pi. Parameters ---------- n_darts : int Number of darts to throw Returns ------- pi_approx : float Approximation of pi ...
1aee3692af97eb2ac6d68ccfd573fa55e9e98a6c
33,298
def sample_category(user, name='Movie', slug='film'): """Create and return a sample ingredient""" return Category.objects.create(user=user, name=name, slug=slug)
c7291808b63244a74e97700819584d3630fd2f04
33,299
def get_all(): """ gets all genres. :rtype: list[GenreEntity] """ return get_component(GenresPackage.COMPONENT_NAME).get_all()
091ecec08926542df9d923a180a359c2adaa7a1c
33,300
def dist(node1, node2): """Calculate the distance between two vertices """ return np.sqrt(np.sum((node1 - node2)**2))
54458b1f32fc9af2bd426fa91711f802bdfb5d2c
33,301
def propagate_errors(f, x, dx, jac=None, n_samples=1e4, seed=42): """Propagates the errors over all the elements of the array x To see how the error propagation is performed see the documentation of dy Returns: [array]: Array with the same size of x with the errors """ return np.sqrt([...
cc0f790293fbfdccafded53cf182ab296df183a8
33,303
def getFibonacciIterative(n: int) -> int: """ Calculate the fibonacci number at position n iteratively """ a = 0 b = 1 for _ in range(n): a, b = b, a + b return a
19920a0dfc83f6dc17b5445294c206003ebe04f7
33,304
def louvain(graph, min_progress=1000, progress_tries=1): """Compute best partition on the `graph` by louvain. Args: graph (:class:`Graph`): A projected simple undirected graph. min_progress: The minimum delta X required to be considered progress, where X is the number of nodes ...
a79fee324f3f7a79cb568166f91adfa5af095ab4
33,305
def compat(data): """ Check data type, transform to string if needed. Args: data: The data. Returns: The data as a string, trimmed. """ if not isinstance(data, str): data = data.decode() return data.rstrip()
51d2d37b427e77b038d8f18bebd22efa4b4fdcce
33,306
from typing import Tuple def cascade(u: np.ndarray, balanced: bool = True, phase_style: str = PhaseStyle.TOP, error_mean_std: Tuple[float, float] = (0., 0.), loss_mean_std: Tuple[float, float] = (0., 0.)): """Generate an architecture based on our recursive definitions programmed to implement unitary :...
20fc298b8bd2c68ad46570c2815e674deb2d7020
33,307
def rsa_decrypt(cipher: int, d: int, n: int) -> int: """ decrypt ciphers with the rsa cryptosystem :param cipher: the ciphertext :param d: your private key :param n: your public key (n) :return: the plaintext """ return pow(cipher, d, n)
33822a0a683eca2f86b0e2b9b319a42806ae56cc
33,308
import json def ajax_update_report_findings(request): """ Update the ``position`` and ``severity`` fields of all :model:`reporting.ReportFindingLink` attached to an individual :model:`reporting.Report`. """ data = {"result": "error"} if request.method == "POST" and request.is_ajax(): p...
61c62d76e458bc7f752d6e9cecedd4cf5b941b91
33,309
def head_pos_to_trans_rot_t(quats): """Convert Maxfilter-formatted head position quaternions. Parameters ---------- quats : ndarray, shape (N, 10) MaxFilter-formatted position and quaternion parameters. Returns ------- translation : ndarray, shape (N, 3) Translations at eac...
9244452c59d132240a0b040effd35f68f80891df
33,311
def geo_to_h3(lats, lngs, res): """ Convert arrays describing lat/lng paris to cells. Parameters ---------- lats, lngs : arrays of floats res: int Resolution for output cells. Returns ------- array of H3Cells """ assert len(lats) == len(lngs) out = np.zeros(le...
acc004b6ecbc861e17e7e6421040fb3d36ca1e24
33,312
def create_roads(roads): """ Create roads information from roads reference data Args: roads: dataframe from roads reference data Returns: list of road curves for all roads """ road_curves = [] for _, row in roads.iterrows(): splitcoords = row["coordinates"].split(",") ...
764c8f77edb3603824c0de2bd50d71147b2e8abe
33,313
def set_extentions(doc): """No-param function. Sets 'frequency' and 'instance_list' variable for each token. The frequency is calculated by lemma_.lower() word of the noun phrase. And lemma_.lower() is used to add instance to instance list. Returns: None """ freq_count = defaultdict(int) i...
485f2afe1947144da38bb5cf5cf1c788a1a3adb1
33,314
import time def stream_occurrences(read_token, project_slug, last_id=None): """ read_token: Rollbar project_access_token with read_scope project_slug: The name of the project that this token is for last_id: The lowest occurence_id we are interested in returns: Occurrence list ...
9ede2738c9485047b807bb0917ac5c18f4d7a0a5
33,315
def git_describe(repos): """Try running git describe on the given repos""" return run(["git", "-C", str(repos), "describe", "--tags", "--abbrev=8"])
46faa032e08f09df3aeaa7c07478125fdac6b66f
33,316
def convertToModelZ(z): """ scale Z-axis coordinate to the model """ return z * SCALE_2_MODEL
b6a48f434bd9bebe57f724474bcc462647d55659
33,318
def opt_get_model_rest_api(model_id): """Retrieve model data """ model_id = Markup.escape(model_id) return retrieve_model_data(model_id)
2c69c4573736a455284df1098ef9b397588a7c35
33,319
import torch def tokenize(texts, context_length=77, truncate=False) -> Tensor: """ Returns the tokenized representation of given input string(s) Parameters ---------- texts : Union[str, List[str]] An input string or a list of input strings to tokenize context_length : int The c...
d6fbe8b863e4a1153a84f39851482f7211153dd9
33,320
import yaml def config_get_timesteps(filepath): """Get list of time steps from YAML configuration file. Parameters ---------- filepath : pathlib.Path or str Path of the YAML configuration file. Returns ------- list List of time-step indices (as a list of integers). "...
8a51e1437edbf2d73884cb633dbf05e9cfe5a98d
33,321
def join_expressions(positions, labels, sep="\t"): """Join mean expressions. Join expressions from different time points and return only those that are in all samples. """ dfs = [] for position, replicates in positions: dfs.append( get_mean_expression( replic...
48cc69bf02add561c3d5297b4d90f6e148117d18
33,322
def current_snapshot(id_or_symbol): """ 获得当前市场快照数据。只能在日内交易阶段调用,获取当日调用时点的市场快照数据。 市场快照数据记录了每日从开盘到当前的数据信息,可以理解为一个动态的day bar数据。 在目前分钟回测中,快照数据为当日所有分钟线累积而成,一般情况下,最后一个分钟线获取到的快照数据应当与当日的日线行情保持一致。 需要注意,在实盘模拟中,该函数返回的是调用当时的市场快照情况,所以在同一个handle_bar中不同时点调用可能返回的数据不同。 如果当日截止到调用时候对应股票没有任何成交,那么snapshot中的close, hig...
25c7493fdd380504854d4eb6be17af440966b639
33,323
def infection_rate_symptomatic_50x40(): """ Real Name: b'infection rate symptomatic 50x40' Original Eqn: b'Susceptible 40*Infected symptomatic 40x50*contact infectivity symptomatic 40x50*(self quarantine policy SWITCH self 40\\\\ * self quarantine policy 40+(1-self quarantine policy SWITCH self 40))/non con...
0ae1831493e02e413b0bd67d78f4fd88163ecd7e
33,324
def cut_limits(x_data: tuple, y_data: tuple, x_lims: tuple): """Selecting range of x/y data based on x_lims. Args: x_data (tuple): x axis data y_data (tuple): y axis values x_lims (tuple): limits to select range from x and y Raises: ValueError: If x_lims have wrong shape ...
144f47231e80c7bc00e6d7ea9038c2040748ff3b
33,327
import re def str_to_number_with_uncert(representation): """ Given a string that represents a number with uncertainty, returns the nominal value and the uncertainty. See the documentation for ufloat_fromstr() for a list of accepted formats. When no numerical error is given, an uncertainty of...
fbdafed553697c3052765afc5127fdfcc75e03f6
33,328
import json def saveRecipe(): """ Processing POST method from local for saving the new generated recipe :return: """ method = request.method if(method == "POST" and checkPassword(request, app.admin_password)): j = json.loads(request.json) fields = ['name','url', 'ingredients','...
922d4c1ec66e43bd0aa254ac561e5436cf9002ee
33,329
from typing import Dict from typing import Any def list_queues_command(client: Client, args: Dict[str, Any]) -> CommandResults: """ List queues in Azure storage account. Args: client (Client): Azure Queue Storage API client. args (dict): Command arguments from XSOAR. Returns: ...
7a54a290795d00d6c3594a78ace03fc3c3001961
33,330
def isUnsaturated(mol): """ Does the molecule have a bond that's not single? Eg. a bond that is double or triple or benzene """ cython.declare(atom1=Atom, atom2=Atom, bonds=dict, bond=Bond) for atom1 in mol.atoms: bonds = mol.getBo...
eaf58e2d958b02055e0eb969aec2fd983fcdd7cd
33,331
import random def run_with_fixed_seeds(count=128, master_seed=0x243F6A8885A308D3): """ decorator run test method w/ multiple fixed seeds. """ def builder(func): @wraps(func) def wrapper(*args, **kwds): rng = random.Random(master_seed) for _ in irange(count): ...
1b2c75b8e57e5c090cf25307189e86ba99a13589
33,332
def merge_cv_results(cv_results): """ Means across CV """ dtypes = ["train", "dev", "test"] props_l1 = ["mean_loss", "mean_accuracy", "mean_positive_f1", "UL-A", "Joint-A"] props_l2 = ["accuracy", "positive_f1"] merged_results = {} for dtype in dtypes: merged_results[dt...
854b0672ec31103136ad3c7285311f865a098159
33,333
from typing import List from typing import Tuple def _broads_cores(sigs_in: List[Tuple[str]], shapes: Tuple[Tuple[int, ...]], msg: str ) -> Tuple[List[Tuple[int, ...]], List[Tuple[int, ...]]]: """Extract broadcast and core shapes of arrays Parameters ...
228cbe06e4bc1e092cf92034255bfd60f01664c1
33,334
def batch_iou(boxes, box): """Compute the Intersection-Over-Union of a batch of boxes with another box. Args: box1: 2D array of [cx, cy, width, height]. box2: a single array of [cx, cy, width, height] Returns: ious: array of a float number in range [0, 1]. """ lr = np.maximum(np.min...
e7064a2f04370b5b3ffa78a585ab9341cd2321be
33,335
import random def createRandomIntID(length): """ Creates a random number.\n Useful for identifiers. """ global dict_of_ids final_id = '' for _ in range(length): final_id += str(random.randint(0,10)) if int(final_id) in dict_of_ids: final_id = createRandomIntID(length) ...
aebd025cf3275a5a07b303c1c296e86f1f17aac5
33,336
def get_all_colors(): """ :return: Color Options """ return color
2104c1195c6e70c20e595d25f369d99c6f00269f
33,337
import getpass def get_username(): """Get Windows username Get current logged in user's username :return: Username :Example: >>> get_username() 'Automagica' Keywords windows, login, logged in, lockscreen, user, password, account, lock, locked, freeze, hibernate, sleep Icon ...
91e5713317d72577d236e45963c7037446dad572
33,338
import json import logging def _ParseStepLogIfAppropriate(data, log_name): """PConditionally parses the contents of data, based on the log type.""" if not data: return None if log_name.lower() == 'json.output[ninja_info]': # Check if data is malformatted. try: json.loads(data) except Valu...
4f2ef1f451c271adf0285ae90f88cf10b6e8d9be
33,339
def RSIZJ(df, N=3, LL=6, LH=6): """ 相对强弱专家系统 :param df: :param N: :param LL: :param LH: :return: """ CLOSE = df['close'] LC = REF(CLOSE, 1) WRSI = SMA(MAX(CLOSE - LC, 0), N, 1) / SMA(ABS(CLOSE - LC), N, 1) * 100 ENTERLONG = CROSS(WRSI, LL) EXITLONG = CROSS(LH, WRSI) ...
563f4866ecb76dd732c9da192dc8a00a1ea44126
33,340
def autocomplete_service_env(actions, objects): """ Returns current service_env for object. Used as a callback for `default_value`. Args: actions: Transition action list objects: Django models objects Returns: service_env id """ service_envs = [obj.service_env_id fo...
04d75c96619cc60433d3df51c44f621c2a86df25
33,341
def SoftwareProvenanceConst_get_decorator_type_name(): """SoftwareProvenanceConst_get_decorator_type_name() -> std::string""" return _RMF.SoftwareProvenanceConst_get_decorator_type_name()
eda72a471a2baf9ecfc5937ec5f9a4151be1ef6d
33,342
import torch def collate_fn(batch, train=True): """ list of tensors to a batch tensors """ premise_batch, _ = pad_batch([row['premise'] for row in batch]) hypothesis_batch, _ = pad_batch([row['hypothesis'] for row in batch]) label_batch = torch.stack([row['label'] for row in batch]) # PyTorch RNN...
980beccc7eb84165a625ad1d58c28e00a095ac4f
33,343
def weights_and_neighbours(graph): """Compute weight and neighbors matrices from graph Parameters ---------- graph : scipy.sparse.csr_matrix sparse distance matrix representing an undirected graph Returns ------- weights : array_like (N,M) corresponding weights for N nodes ...
78c563fa52652d25f3bc408b8eff6c418a897aa6
33,344
def aabb_with_result(a: Rectangle, b: Rectangle, result: Rectangle) -> bool: """ Does Axis Aligned Bounding Box collision detection between two rectangles a and b. Also calculates the intersection rectangle. :param a: :param b: :param result: :return: """ # Horizontal amin = a.x ...
799348704e400ecc6b79ca15b76eee352062a7fe
33,346
from typing import List import pickle def make_visualizations_from_config(config: Config, extension: str = 'pdf') -> List[Figure]: """ Used to generate the embedding visualizations from a given Config object :param config: the Config used :param extension: the exten...
687bfa06bd18112ebc01b032c9f3b6f377c7b401
33,347
import re def get_intervals(bin_type, thresholds): """ Returns a list of interval objects. If bin_type is *within*, then intervals are formed by using each pair of consecutive thresholds. For bin_type below* the interval [-np.inf, threshold] is used and for bin_type above* the inveral [threshold, np.inf] ...
847c99e295c3200a1c10895b373083a49698d1ef
33,348
def shapely_formatter(_, vertices, codes=None): """`Shapely`_ style contour formatter. Contours are returned as a list of :class:`shapely.geometry.LineString`, :class:`shapely.geometry.LinearRing`, and :class:`shapely.geometry.Point` geometry elements. Filled contours return a list of :class:`shap...
d6e0951f2ed75c37ffcbd9d18ebaa65ca2e2368b
33,350
def _patch_redirect(session): # type: (requests.Session) -> None """Whether redirect policy should be applied based on status code. HTTP spec says that on 301/302 not HEAD/GET, should NOT redirect. But requests does, to follow browser more than spec https://github.com/requests/requests/blob/f6e13cc...
fc3e79475c86c9aeee6c780dc25ddd83d373a27b
33,351
def cal_rank_from_proc_loc(pnx: int, pi: int, pj: int): """Given (pj, pi), calculate the rank. Arguments --------- pnx : int Number of MPI ranks in x directions. pi, pj : int The location indices of this rank in x and y direction in the 2D Cartesian topology. Returns ------...
97146de9f69dd2f62173c19dfdb98d8281036697
33,352
import numpy def width_trailing(sdf): """Return the FWHM width in arcmin for the trailing tail""" # Go out to RA=245 deg trackRADec_trailing=\ bovy_coords.lb_to_radec(sdf._interpolatedObsTrackLB[:,0], sdf._interpolatedObsTrackLB[:,1], ...
a9fd52c584252470422fb39f555a64fe37a208e7
33,354
from typing import Optional def load_report_fn(report_path: gpath.GPath) -> Optional[ExperimentReport]: """Tries to load report from path, if it exists. Returns None otherwise.""" report = None if not gfile.Exists(report_path): print(f'File {report_path} does not exist.') return report try: repor...
a859751c3065eb03029c7fa11885421cfe025b29
33,355
from io import StringIO import csv from datetime import datetime def get_proposal_statistics_report(from_date, to_date, all_fields=False): """Gets the proposal statistics report from Cayuse""" # List of fields we want to retrieve from Cayuse and include in the CSV REPORT_FIELDS = ( 'application_t...
08148bd1dcc763d73477e13df56327c3bf639051
33,356
def emitter_for_format(construct_format): """ Creates a factory method for the relevant construct format. """ def _factory(): return ConstructEmitter(construct_format) return _factory
4472d4790f7469cc556a0c958003ec65673d0653
33,357
def get_client(settings): """Return a client for the Elasticsearch index.""" host = settings["elasticsearch_url"] kwargs = {} # nb. No AWS credentials here because we assume that if using AWS-managed # ES, the cluster lives inside a VPC. return Elasticsearch([host], **kwargs)
65260462e9154ee911b686ee66405fe7009f4add
33,358
def merge_model_predict( predict: TModelPredict, predict_append: TModelPredict ) -> TModelPredict: """Append model predictions to an existing set of model predictions. TModelPredict is of the form: {metric_name: [mean1, mean2, ...], {metric_name: {metric_name: [var1, var2, ...]}}) This...
bddff5101bd85de3a02087a48aa89f9acc4ebf52
33,359
def voucher_objects(states=voucher_states()): """ Build ``Voucher`` instances. """ return builds( Voucher, number=vouchers(), created=one_of(none(), datetimes()), expected_tokens=integers(min_value=1), state=states, )
4ffd0c9071fc375dd369f8c89e0312d0eeb4e346
33,360
from bs4 import BeautifulSoup import requests def fetch_events_sciencehistory(base_url='https://www.sciencehistory.org'): """ Fetch events from Science History Institute, https://www.sciencehistory.org/events """ events = [] page_soup = BeautifulSoup(requests.get( urljoin(base_url, '/event...
571586136255973baeb00598afddfb6f309e82b0
33,364
def _create_buffer(size): """Create a ctypes buffer of a given size.""" buftype = (CHAR * size) return buftype()
8aa09592ebea8d799c1cfa69edc35dd0b6f93ff9
33,366
from typing import Optional from typing import List from typing import Dict def collect_files(config: Config, files: Optional[List[str]] = None, method: Optional[str] = None) -> DFs: """Read a filtered memory map from a set of files.""" filenames = files if files else confi...
3870e4da457ba2a1780e262acdfd8aad81990115
33,367
def ModelInfoAddShader(builder, shader): """This method is deprecated. Please switch to AddShader.""" return AddShader(builder, shader)
69e21b53cc3c01b977115fd46f09d77f1499f3ef
33,368
def configuration(request): """Various things stored in settings.py""" return {"version": VERSION, "current_url": request.get_full_path(), "project_long_name": settings.project_long_name, "project_short_name": settings.project_short_name, "project_description": se...
02a0727c93c786305c1aa019fc79c624e7dd3f91
33,369
def percentile(event_collection, target_property, percentile, timeframe=None, timezone=None, interval=None, filters=None, group_by=None, max_age=None): """ Performs a percentile query Finds the percentile of a target property for events that meet the given criteria. :param event_collection:...
36208dae6b19b28b00ba311b5d15bef856fb0992
33,370
def MolAsMolWithQueryAtoms( mol: rdChem.Mol, strict: bool = False, includeIsotopes: bool = True ) -> rdChem.Mol: """If Mol contains Chem.Atoms, convert to Mol with Chem.QueryAtoms If Mol already is composed of QueryAtoms, returns the same object """ if all(isinstance(atom, rdChem.QueryAtom) for ato...
1a2d0e159294efa19686d2f442e8a8e223eb96d1
33,372
import pathlib from typing import Tuple from typing import List def find_images( directory: pathlib.Path, specs: specsmod.Specs) -> Tuple[List[pathlib.Path], List[str]]: """ Find all the sample images beneath the directory. :param directory: where to search :param specs: specification...
360743837c3da3142cb7060590102149adca24c4
33,373
def login(): """ Log in user --- tags: - Auth requestBody: content: application/x-www-form-urlencoded: schema: type: object properties: pin: description: Redirects to next page if login successful typ...
f89e9190c5e9a29e0629e16011c4332d16874996
33,374
def T_asy(x, beta): """Symmetry breaking transformation. .. math:: T_{asy}^{\\beta} (x_i) = \\begin{cases}x_i^{ 1 + \\beta \\frac{i-1}{D-1}\sqrt{x_i}} & \\text{if } x_i > 0\\\\ x_i & \\text{otherwise} \\end{cases} Parameters ---------- ...
671925fdbfc7d3fbc76acb1da3e9ff591207d131
33,375
def commonChecks(L0: float, Rtot: np.ndarray, KxStar: float, Kav: np.ndarray, Ctheta: np.ndarray): """ Check that the inputs are sane. """ Kav = jnp.array(Kav, dtype=float) Rtot = jnp.array(Rtot, dtype=float) Ctheta = jnp.array(Ctheta, dtype=float) assert Rtot.ndim <= 1 assert Rtot.size == Kav.s...
9007db3f77e2036d2db7af28d24ba40234e09168
33,376
def _threed_extract(step, var, walls=False): """Return suitable slices and coords for 3D fields.""" is_vector = not valid_field_var(var) hwalls = is_vector or walls i_x = conf.field.ix i_y = conf.field.iy i_z = conf.field.iz if i_x is not None or i_y is not None: i_z = None if i_...
a71310b0e735fabbee13ce1d4b71e3a8dbd9c809
33,377
def calc_temps(session,start_date, end_date): """TMIN, TAVG, and TMAX for a list of dates. Args: start_date (string): A date string in the format %Y-%m-%d end_date (string): A date string in the format %Y-%m-%d Returns: TMIN, TAVE, and TMAX """ return sessi...
e82dcfe895e39c37fceb490bb9fb7c832bc7a6c5
33,378
from typing import List def get_react_score(reactions: List[dict]) -> float: """ Returns score of the post according to reactions weights. :reactions: list of dictionaries containing post info """ react_score = 0 for react in reactions: react_score += reactions_dict[react.get("name"...
0ca3ce2abeed8f151e607dfec16591e5e3bae79a
33,379
import ast def _get_collections_abc_obj_id(node: ast.expr | None) -> str | None: """ If the node represents a subscripted object from collections.abc or typing, return the name of the object. Else, return None. >>> _get_collections_abc_obj_id(_ast_node_for('AsyncIterator[str]')) 'AsyncIterato...
f5cb701df687b90a0f3a247526cf5349e7b94d3e
33,380
def show_index(): """ main site, generating sections """ title = "Homepage" sql_query = 'SELECT categoryId, title FROM category' output = myDB.execute_sql(sql_query) sections = dict(output) return render_template("index.html", title=title,sections = sections)
b64d532810fc96e985b0291654e62e7d4e0e4b89
33,381
def generate_packed_decoder(wrapped_decoder): """Generate an decoder for a packer type from a base type decoder""" def length_wrapper(buf, pos): """Decode repeat values prefixed with the length""" length, pos = varint.decode_varint(buf, pos) end = pos+length output = [] w...
c213dcb49f63055dcd7ecf7ff75187c997f2a5e7
33,383
def create_ik_handle(name, start_joint, end_joint, solver_type=None, curve=None, **kwargs): """ Creates a new IK handle :param name: str :param start_joint: str :param end_joint: str :param solver_type: str :param curve: str :param kwargs: :return: str """ if solver_type is ...
b5f56cbea793201467146475ac266b95c4469982
33,384
import math def FinalFitness4(intermediate_outputs): """ Function: FinalFitness3 ======================== Compute global fitness of an individual. Intended when wanting to refine the fitness score. @param intermediate_outputs: the fitnesses of the tree over several s...
0e7337424a15439fbe1951b66fdfe52bc47edbbf
33,385
def create_with_deletion_protection(ledger_name): """ Create a new ledger with the specified name and with deletion protection enabled. :type ledger_name: str :param ledger_name: Name for the ledger to be created. :rtype: dict :return: Result from the request. """ logger.info("Let's cr...
2832988d222ab835984b2aeeabc4e9fc726e53c5
33,386
def run(command): """Execute command as user:<command>""" with hide('everything'), settings(warn_only=True): result = api.run(command) print("["+env.host+"] " + command) if result != '': print(result) return result
339b8d674da1962383314c66e3f8644f1427552e
33,387
def dummy_request(): """Fixture to return a single dummy request.""" return testing.DummyRequest()
7a4382ec76c2047a0b8cc7be4a6408c4000b5493
33,388
def refill(pop): """Get rid of duplicates.""" for lst in pop: lst[9] = sgn(lst[9]) lst[-1] = abs(lst[-1]) pop.sort() newpop = [0] * Npop i = 0 last = None for lst in pop: if lst != last: newpop[i] = lst i += 1 last = lst for j in ...
701fec91d9e59085bb0d9d1d26dfd0803f9dc42b
33,389
def parse_code(body): """ Parse the code from the body """ # Regex to match code block reddit comment regex = ur"^((?:(?:(?:[ ]{4}).*|)(?:[\r\n]+|$))+)" matches = re.findall(regex, body, re.MULTILINE) # remove all empty lines matches = [match for match in matches if match != "\n"] ...
3e978cfb55186946c1f6c577054349ff50914ec9
33,390
from polaris.integrations import registered_deposit_integration as rdi from typing import Tuple from typing import Optional def get_or_create_transaction_destination_account( transaction: Transaction, ) -> Tuple[Optional[Account], bool, bool]: """ Returns: Tuple[Optional[Account]: The account(s) f...
2bea36fbeed6a6cf1c6f95f46eb2f2220571cf81
33,392
from pathlib import Path def test_loading(tmpdir): """ Load an object. """ class A(FSObject): _config_file = 'a.json' def __init__(self,**kwargs): super().__init__(**kwargs) @property def state(self) -> dict: return {} @classmethod ...
add506c113f7fb518541a7151aa20a9d64c69097
33,393
from datetime import datetime import random def random_date(start=None, end=None): """Get a random date between two dates""" if start is None and end is None: end = datetime.datetime.now() start = end - datetime.timedelta(days=365) stime = date_to_timestamp(start) etime = date_to_tim...
67e4338808ccf6195fd786c50635371bdfcb49a4
33,394
def _chg_float(something): """ floatに変換できたらfloatに変換する """ try: f = float(something) return f except ValueError: pass return something
d0119c255b0842b2de4e60293c8037ff6f75b181
33,395
def get_seeding_programs(): """Returns the list of seeding program names""" try: seed_catalogs = read_plist(SEED_CATALOGS_PLIST) return list(seed_catalogs.keys()) except (OSError, IOError, ExpatError, AttributeError, KeyError) as err: log.warn(err) return ""
aad36b6ea85fa2d8a723a958281e8711e8d12af0
33,396
import re import requests import time def query_ols(iri): """ Gets the name field of measurementTechnique, infectiousAgent, infectiousDisease, and species in our nde schema ols api doc here: https://www.ebi.ac.uk/ols/docs/api Returns the formatted dictionary {name: ####, url: ####} if an url was ...
03f6a1d6088f74b9b8a13528d5e4709c236cfd5e
33,397
def cylinder( **named ): """Create a cylinder, adding to current scene""" return _newNode( geometry.VPCylinder, named )
5e012725d5787ffd802215f2ddbe549150a0429b
33,398
def mrr_finesse(a, r): """ description: Calculate the finesse of the MRR, i.e., finesse=FSR/FWHM=pi*sqrt(ra)/(1-ra) (Bogaerts et al., Silicon microring resonators, Laser and Photonics Review 2011, Eq.(21))\\ a {float} Attention coefficient\\ r {float} Self-coupling coefficient\\ return finesse {floa...
718bfe5a0a3d8a727a604bff7d21c1b6e3cb1715
33,399
import decimal def is_numeric(value): """ Check whether *value* is a numeric value (i.e. capable of being represented as a floating point value without loss of information). :param value: The value to check. This value is a native Python type. :return: Whether or not the value is numeric. :rtype: bool """ if...
4224e3a1af56e75256d5c6d7f7d990ea3ae9343a
33,400
def _position_to_features(sam_reader, allele_counter, region, position, exclude_contig): """Extracts the AlleleCount data from a given position.""" # We build the AlleleCount at the position. reads = sam_reader.query(region) for read in reads: allele_counter.add(read) counts = al...
7b430c6488a7f21661505a8ac9212f2fe2289744
33,401
def p_name(username): """ 根据用户名获取昵称 :param username: 用户名 :return: """ friend = itchat.search_friends(userName=username) if not friend: return '' return friend.get('RemarkName') or friend.get('NickName')
4a07df0a973f533bd740b6d8d11ca2eb981617d5
33,402
def user_profile(self): """Return this user's UserProfile, or None if one doesn't exist.""" try: return self.userprofile except UserProfile.DoesNotExist: return None
7ca38535ed779c591d7dc76b52861e6a9a126c8f
33,403