content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def concept_uri(lang, text, *more): """ `concept_uri` builds a representation of a concept, which is a word or phrase of a particular language, which can participate in relations with other concepts, and may be linked to concepts in other languages. Every concept has an ISO language code and a text...
4c9ff7c10b6ddb86a782ca1b878f63db6601d165
61,306
def baby_names_collapsed_from_list(a_baby_names_list): """ a_baby_names_list is a list of lists, each element [name, rank] Collapse list element to a string """ print('baby_names_collapsed_from_list') baby_names_collapsed = [] for baby_element in a_baby_names_list: baby_names_collap...
f874c1fb205e0a86e46db8a3e2c0002712db82cb
61,307
from typing import Union def deserialize_timestamp(timestamp: Union[int, str, FVal]) -> Timestamp: """Deserializes a timestamp from a json entry. Given entry can either be a string or an int. Can throw DeserializationError if the data is not as expected """ if timestamp is None: raise Des...
7a787164a4a6f4730fea9b23d8ce341d1d1aae46
61,308
def exp_lr_scheduler(optimizer,init_lr,epoch,lr_decay=2): """Decay learning rate by a factor of 0.1 every lr_decay_epoch epochs.""" lr = init_lr * (0.1**(epoch // lr_decay)) for param_group in optimizer.param_groups: param_group['lr'] = lr return optimizer
c18885263fab2b6cab39a2147465f3f71f9514a0
61,309
import copy def check_output(output, expected_output): """ Return True if output and expected_output contains the same lists, False otherwise. Note that the ordering of the list is not important. Examples: check_output([ [0, 1], [1, 0] ] ], [ [1, 0], [0, 1] ]) returns True ​ Args: ...
c09a9aaa2fb226318e2d0a71f3da08d5772a9a8d
61,310
from typing import Sequence import torch def pretty_print_double(contents1: dict, contents2: dict, args): """ Prints a nice summary of the top-level contens in a checkpoint dictionary. """ col_size = max(max(len(str(k)) for k in contents1), max(len(str(k)) for k in contents2)) common_keys = list(contents1...
795a902f7ffcd48338b48c57c0e708f3b255e12f
61,311
def HeadingStr(heading): """ Gives a heading string given the heading float """ headstr = "?" if heading != None: if heading < 22.5 or heading >= 337.5: headstr = "N" elif heading >=22.5 and heading < 67.5: headstr = "NE" elif heading >= 67.5 and heading < 112.5: headstr = "E" elif heading >= 112....
1f1276e3f8f9c963703ced42d9391d1ee0598e3e
61,312
def test_then_compute_adds_computation_result_to_behaviour(result_ready_behaviour_builder, behaviour): """ :type result_ready_behaviour_builder: BehaviourBuilder :type behaviour: Behaviour """ def function(*args, **kwargs): return None result_ready_behaviour_builder.then_compute(functio...
d725fc25d0a588b447bf5aa0d3cc8df5c6e8ed3f
61,313
def counting_sort(arr: list, max_value: int = None, place_value: int = None) -> list: """Sort a list using counting sort Args: arr (list): the list to be sorted Returns: list: the sorted list """ size = len(arr) # Get the max value if max_value is None: max_value =...
590b4f84d3cc7675f907f28182326c2f46b82326
61,314
def make_context(source, frmat='table'): """Return a new context from source string in the given format. >>> c = make_context(''' ... |male|female|adult|child| ... man | X | | X | | ... woman| | X | X | | ... boy | X | | | X | ... girl | | X ...
93e00d7a95e96f7d0efa02a5cded1bff32b4c4e8
61,315
import pickle import requests import json def room_list(campus): """/user/room/list campus 1=建工/2=燕巢/3=第一/4=楠梓/5=旗津 get campus room list In this function, without use cache_ap_query use webap_crawler.query and use GUEST account. Returns: [str]: result type is json error:...
bf859231c9dfa86360ae173d4dbf3f09eae3a32e
61,316
def polyval(p,x): """ Replacement for the polyval routine in numpy. This version doesnt check the input variables to make sure they are array_like. This means that when masked arrays are treated correctly when they are passed to this routine. Parameters ---------- p : a 1D array of coeffi...
7887e504aef74f35bc014462e9bb0eb2c4548971
61,317
def _authorize_package_action(method, context, data_dict): """ Authorize access to core CKAN package actions, to ensure that these actions are not used directly for modifying metadata records. :param method: 'create' | 'update' | 'delete' :param context: should include 'invoked_action' to indicate ...
bde4452b43a33be332152d80a18c751552210efd
61,318
from pathlib import Path import fnmatch def apply_path_wildcard(stats, path_wildcard): """Filter the given DirectoryListing object using the given PathWildcard.""" paths = Paths(tuple(Path(normpath(join(path_wildcard.symbolic_path, basename(s.path))), s) for s in stats.dependencies ...
c69f32f10c409dcbf03e208864681bf3b0029477
61,319
def get_kappa_log_weights_vectorized(k_bnn, omega_post_samples, log_p_k_given_omega_int): """Evaluate the log weights used to reweight individual kappa posteriors Parameters ---------- k_bnn : np.array of shape `[n_test, n_samples]` omega_post_samples : np.array of shape `[n_omega, 2]` log_p_k_...
93d17a773ef7b84e82abf717aafb42d2ad23541a
61,320
def getMatches(sku=None, division=None, round=None, instance=None, matchnum=None, scheduled=None, field=None, team=None, scored=None, season=None, get_all=False): """Return a list of matches matching the given criteria. For sets of criteria that match a la...
f57dd6cb63e4172d20f5cd4d457686de2e3d13e0
61,321
def minimum_bounding_circle(geometry, **kwargs): """Computes the minimum bounding circle that encloses an input geometry. Parameters ---------- geometry : Geometry or array_like **kwargs For other keyword-only arguments, see the `NumPy ufunc docs <https://numpy.org/doc/stable/refere...
bc5d1218f79ec7ea2e46ee752ab14fe07a17ec51
61,322
def dict_of_dict_to_columns(main_df, dict_column, dict_key): """Converts a dictionary entry of a dictionary defined in string format into columns""" if isinstance(main_df[dict_column][0], dict): # Already of type dict pass else: # Convert unicode to dict in dict_column ...
601f797770b5c726bbd0c41798d6dd9153152fd4
61,323
def foobar_unstructured(module, name): """ 텐서 내 다른 모든 항목들을 제거하여 `module` 에서 `name` 이라는 파라미터에 대해 가자치기 기법을 적용 다음 내용에 따라 모듈을 수정 (또는 수정된 모듈을 반환): 1) 가지치기 기법에 의해 매개변수 `name` 에 적용된 이진 마스크에 해당하는 명명된 버퍼 `name+'_mask'` 를 추가합니다. `name` 파라미터는 가지치기 기법이 적용된 것으로 대체되며, 가지치기 기법이 적용되지 않은 기존의 파라미터는 `...
44a3c7ec5f631e8d414208ddde3e046260cb3b39
61,324
def generateBnode(name=None, prefix=''): """ Generates blank nodes (bnodes), AKA anonymous resources """ global _bNodeCounter, _sessionBNodeUUID _bNodeCounter += 1 name = name or str(_bNodeCounter) return BNODE_BASE + prefix + _sessionBNodeUUID + name
5cfb1c3a3fb717877100a412ecae33f5ad197628
61,325
def get_user_by_email(email, db_model): """Take an email from request and return user object if existed. """ return db_model.query.filter(db_model.email == email).first()
656ccd8b7fc66141a1e2023ebcfda84dd1caea16
61,326
def handler_get_user_interests_from_id(userID): """Get the interests of the user with the given ID. .. :quickref: Users; Get the interests of the user with the given ID. :param int userID: The ID of the user to retrieve the collection from :status 200: The list was correctly retrieved :status ...
41a706234e188d0538ea90f1a82739a0e8e161f9
61,327
def validate(data_home=None, silence=False): """Validate if the stored dataset is a valid version Args: data_home (str): Local path where the dataset is stored. If `None`, looks for the data in the default directory, `~/mir_datasets` Returns: missing_files (list): List of file ...
cf7de1084957b55ef0a8a46c826199fae76bbe5e
61,328
import collections def get_nbest(prelim_predictions, features, example, n_best_size, do_lower_case): """get nbest predictions""" _NbestPrediction = collections.namedtuple( "NbestPrediction", ["text", "start_logit", "end_logit"]) seen_predictions = {} nbest = [] for pred in prelim_predicti...
a793a5cf29c0ead2a247a33435e8e6f61ee65867
61,329
from collections import defaultdict def E(): """ Сеть компании состоит из серверов. Серверы соединены друг с другом в кластеры. Каждый сервер может скачивать файлы только с серверов в его кластере. Составьте программу, которая сообщать, из каких источников определённый сервер может скачать необход...
c5ce5e64f2be3c25e63d3f413970b13c1a094725
61,330
import secrets def random_key(length: int = 16) -> str: """Generate a random key of specified length from the allowed secret characters. Args: length: The length of the random key. """ secret_allowed_chars = ( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~" )...
a50daa81f3a01430a211299ae7123196a4b34264
61,331
import re def fetch(name: str, **kwargs): """ """ func = f"""_fetch_{re.sub("[_-]+dict", "", name.lower()).replace("-", "_")}""" retval = eval(f"{func}(**kwargs)") return retval
62fbe0e478bbb81955e7aa5205b9ddf5197d7fe5
61,332
def running(): """Running Note: Endpoint to check if API is running. Returns: flask.jsonify: {'detail': 'Running...'} """ return flask.jsonify({'detail': 'Running...'}), 200
496f7dd30651895fc9d9674c69a57299dbafd8d7
61,333
from typing import Union def peekStep(x:Union[Header, Message], n:int=0) -> Step: """Returns the nth Step in x""" if isinstance(x, Message): return peekStep(x.header, n) else: if len(x.steps) > n: return x.steps[n] else: return Step()
d3f0ec880f1615d6092a0c13c1e174240fff20d6
61,334
def plot_alpha_vs_width(widths=[pi/24,pi/12,pi/9,pi/6,pi/4,pi/2], tlim=(-5,5), ax=None, norm=True, legend=True, **kwargs): """Plot alpha (phase error) across time for different cue sizes (widths) Additional keyword arguments are passed to error.alpha(). """ widths = np.asarray(widths) if a...
25d0975d4e620479c5cf3ef97597faa56671417a
61,335
def create_hparams(hparams_string=None, verbose=False): """Create model hyperparameters. Parse nondefault from given string.""" hparams = contrib.training.HParams( ################################ # Experiment Parameters # ################################ epochs=50000, ...
064d8911db2889ecfabfbc053d0c4f22452bd4d5
61,336
from typing import Optional import re def extract_issue_number_from_ref(ref: str) -> Optional[int]: """从 Ref 中提取议题号""" match = re.search(rf"{BRANCH_NAME_PREFIX}(\d+)", ref) if match: return int(match.group(1))
7f570ef1b914816b405892bf75a85e6b62b2cd66
61,338
def get_edge_weights_canny_mask( image, mask, dilate_kernel_size=11, erode_kernel_size=11, w_edge=1.0, canny_thr=3.0, ): """ Args: image: NCHW mask: N1HW """ edge_map = get_canny_edge_tensor(image, canny_thr, device=image.device) mask_edge_weight = compute_mas...
aa4308e6de1b4eb966b8c98e2b5ad3798fe79491
61,339
def money_to_decimal(money: Money): """ 测试自定义的Money类型,会转换成Decimal :param money: 金额 :return: """ return money
62e24b7f45f4f2383d5d38bd0c303693a36e5363
61,342
def merge_molecules_xyz(protein_xyz, ligand_xyz): """Merges coordinates of protein and ligand. """ return np.array(np.vstack(np.vstack((protein_xyz, ligand_xyz))))
86b19d4b78feaa98e24d37f60bb71338918cb5aa
61,343
def get_authenticated_session(): """Return a :py:class:`requests.Session` object authenticated to introspect tokens. The return value is cached. """ cached_session = getattr(get_authenticated_session, '_cached', None) if cached_session is not None: return cached_session get_authenticate...
eac3fd839f216aaf5d0e81b111167421de4d74e2
61,344
import re def commit_message_contains_query(message, query_terms): """ Check if the commit message contains the query terms @param message: The commit message @param query_terms: The terms that we look for in the message @return: """ tester = r'\b(' + '|'.join(query_terms) + ')' has_re...
b701dac00971658be13a6b7207f8685c3388609e
61,345
def updateContact(request): """ 연동회원의 담당자 정보를 수정합니다. - https://docs.popbill.com/message/python/api#UpdateContact """ try: # 팝빌회원 사업자번호 CorpNum = settings.testCorpNum # 팝빌회원 아이디 UserID = settings.testUserID # 담당자 정보 updateInfo = ContactInfo( ...
1912b4a2b19be68e7fb3102d5d7640fdde349b81
61,346
from typing import Dict def convert_relus_to_fat(module: Module, **kwargs) -> Dict[str, FATReLU]: """ Replace all of the ReLUs in a module with FATReLU instances. Note: only works if the ReLUs are layers in the module, will not work with torch.functional ones. :param module: the module to replac...
ff89ebbe7e7c78db47e481b61c94c7a75ad28fb6
61,347
def gradient(initial_theta, X, y, initial_lambda): """ 求梯度,其实就是求偏导 :param initial_theta: :param X: :param y: :param initial_lambda: :return: """ m = len(y) h = sigmoid(np.dot(X, initial_theta)) theta1 = initial_theta.copy() theta1[0] = 0 grad = np.zeros((initial_theta...
2a6bb32371aec1e9b277bb597d6bd1263d479e5b
61,348
def get_event_role(bot, guild): """Return the event role, if it exists""" result = bot.db.get_event_role_id(guild.id) if result: for role in guild.roles: if role.id == result.get('event_role_id'): return role
85656ee6b65896762197008108c7b09830a5a4a8
61,349
def wbrykmap(anchors: tuple[float, float, float] = (1/4, 1/2, 3/4) ) -> LinearSegmentedColormap: """ Custom colormap that goes from white to blue to red to yellow to black inspired by http://paulbourke.net/fractals/juliaset/ Parameters ---------- anchors : tuple[float, float, floa...
65a85ef19233542c81b3430c6f7384981c9b061f
61,350
def create_dataloader(dataset, trans_fn=None, mode='train', batch_size=1, batchify_fn=None): """ Creats dataloader. Args: dataset(obj:`paddle.io.Dataset`): Dataset instance. trans_fn(obj:`callable`, opti...
2b1b5d3c83b1406e7239a759c37b908776248a92
61,351
from typing import Dict from typing import List from typing import Set from typing import Tuple def create_majority_digraph(profile: Dict[str, List[Set[str]]]) -> Tuple[Set[str], Edges]: """ :param profile: :return: """ alternatives: Set[str] = determine_alternatives(profile) edge_list: List[...
476477323bd961ba62c24b399f3b941c6f92a699
61,352
def laser(asteroid_angles): """ Takes list of relative asteroid positions with manhattan distances and relative angles from (0,1), sorted in order of increasing angle and increasing distance where angles are equal. Simulates firing a laser from 0 radians (along (0,1)) to 2 pi radians and de...
80947e23f1c01d60d73a2fc2f41fa5304b9b1ab4
61,353
def _plug_compass_ex_east(area, widget, frame, guide): """ Create a east tab widget from the widget and frame. """ return _tabify_helper(area, widget, frame, QDockTabWidget.East)
85af5f3069c1574d63b022451b489381d18369a5
61,354
def get_buildings_on_street(city, min_house_area, nodelist_buildings): """ Get all building with the same address. Using "streets". This is a list of the street names in the city, which was created in the function "get_lists(city)". :param city: str, cit...
73a9e14e9f747562818178c0900363207687c1b3
61,355
def get_team_iterations(team, timeframe=None, organization=None, project=None, detect=None): """List iterations for a team. :param team: The name or id of the team. :type team: str :param timeframe: A filter for which iterations are returned based on relative time. Only Current is supported current...
73178fa498f3600fbb0dad5f34c675f1d8eada67
61,357
def start_pb_type( tile_name, pin_assignments, input_wires, output_wires, root_pb_type, root_tag='pb_type' ): """ Starts a pb_type by adding input, clock and output tags. """ pb_type_xml = ET.Element( root_tag, { 'name': add_vpr_tile_pr...
2de94e7adbdb2cb1aa51b5c63d5c5673b41e0246
61,362
import csv def get_shipping(f): """Get shipping costs function.""" shipping = {} with open(f, 'rb') as csvfile: reader = csv.reader(csvfile, delimiter=',') for row in reader: row[1] = float(row[1]) shipping[row[0]] = row[1] return shipping
1af402c2e62cb7fba76aff333ddd0f873b3ed7f6
61,363
def adjusted_mutual_information(labels_true, labels_pred, n_jobs = -1, emi_method="parallel", use_cython=True, average_method='arithmetic'): """Adjusted Mutual Information. Adjusted Mutual Information (AMI) is an adjustment of the Mutual Information (MI) score to account for c...
e32e767bfed1cfea5605748aabcb12da7b2cddde
61,364
from typing import Optional from typing import Dict from typing import Any def commit_draft( access_key: str, url: str, owner: str, dataset: str, *, draft_number: int, title: str, description: Optional[str] = None, ) -> Dict[str, str]: """Execute the OpenAPI `POST /v2/datasets/{own...
395070863b678892ca1004de20ac1b163d6e2da8
61,366
def is_polygon(f, e): """ checks if the shape of the points in f is the convex hull of the eigenvalues e @param f: numpy complex array with points representing the numerical range @param e: array of the eigenvalues of the matrix @return: true if the numerical range is a polygon that is the convex hu...
a1ec18da0b638be4c6b71a4ee19e3a5fbf288e76
61,368
def wielding(weapon): """ Make a character to wield a weapon """ action = WieldAction(weapon) return action
b0859c84f789cb5edf9bc90c3ae68d469c11c508
61,369
def DotProduct_DML(feat, M, query=None, is_sparse=False, is_trans=False): """ DotProduct distance with DML. """ if query is None: query = feat return -query.dot(M).dot(feat.T)
7a1d1173e351d6f621755fe5dfc64bcbdcc95b97
61,370
def _truncated_svd(A, rank=None): """Private helper function for calculating truncated singular value decompositions. Given a matrix A and a rank K computes the truncated singular value decomposition U, S, V of A where the K largest singular values are kept and the rest are truncated to zero. If A ...
a204a74c4433c4ed78abab43d70098517f2c8f13
61,372
def default_load(*args, **kwargs): """Do default deserialize.""" return _DEFAULT_LOAD(*args, **kwargs)
b41f4a7c8eda2a8436f472f7a35cfb42fddc88be
61,373
def random_combination(iterable, r): """Return a random *r* length subsequence of the elements in *iterable*. >>> random_combination(range(5), 3) # doctest:+SKIP (2, 3, 4) This equivalent to taking a random selection from ``itertools.combinations(iterable, r)``. """ pool = tuple(...
13434b86aba68300be8e09ca9098d1c813b802f0
61,374
def zncc(var1, var2): """Zero-Normalized Cross-Correlation ZNCC (normalized correlation of deviation from mean) """ N = var1.shape[0] * var1.shape[1] sigma_1 = np.std(var1) sigma_2 = np.std(var2) mu_1 = np.mean(var1) mu_2 = np.mean(var2) return 1/N * np.sum(1/(sigma_1 * sigma_2) * (v...
fa1e2c7b9bfb0e641479f005f46d0fdd376a31b6
61,376
import random def create_fake_risk(data): """ Since the raw data had almost only 'unknown_risk' values and I wanted to have my visualisations look cool, I decided to do a Diederik Stapeltje and make up the data myself. ¯\_(ツ)_/¯ """ risks = [] # for a specific amount of times, add the di...
c42edc03a57913d96701cc8b36c388d42c1c9bfc
61,377
from typing import Mapping from typing import Union import yaml def read_solutions_from_yaml( filename: str ) -> Mapping[str, Union[SolutionI, SolutionII]]: """Reads the solutions(s) contained in a YAML file. Args: filename: name of the YAML file to read, it has to have the extension ``....
3c395cd57fece19addbfd34393d3a4c9d46766a7
61,379
def prepareuser_dict(user_dict: dict) -> dict: """ Prepare the dict before saving it to redis. Converts data to str or int. :param user_dict: User data taken from user.to_dict() :return: dict """ d = {} for k, v in user_dict.items(): d[k] = makesafe(v) return d
3e8acf611f4b0bdedbecd757ccc1c7500304ab35
61,380
import random def capnp_id() -> str: """ Generates a valid id for a capnp schema. Returns: str -- capnp id """ # the bitwise is for validating the id check capnp/parser.c++ return hex(random.randint(0, 2 ** 64) | 1 << 63)
55ae4e112c3ba223168627d7d06fab327a0d4f82
61,381
def linspace(start,stop,np): """ Emulate Matlab linspace """ return [start+(stop-start)*i/(np-1) for i in range(np)]
b1be58298ff9983f6e2f6c5156cb4497ef8668d9
61,382
def zScoreStep(**kwargs): """ Parameters ---------- kwargs: axis: on which axis to apply the z-score, default to None Returns ------- data after z-score """ data = kwargs['data'] axis = setDefaultVal(kwargs, 'axis', None) return data.map(lambda x: zscore(x, axis=axis))
a40aebe55bea66c3bb32719863d43ea690441465
61,383
def allow_logged_in(*args, **kwargs): """Permission that checks if the community owner is making the request.""" def can(self): """Check that the current user is the community's owner.""" return current_user.is_authenticated return type('AllowCommunityOwner', (), {'can': can})()
42b1a137f0924a7c637f6cbafbc3e54d6c0bf0f1
61,384
def make_clf(): """ Takes no argument, and return a pipeline of linear classifier, containing a scaler and a linear estimator """ clf = [] clf.append(('vectorizer',Vectorizer())) # vectorize the 3D matrix along the last 2 dimensions clf.append(('scaler',StandardScaler())) estimator = SVC(ker...
bef25a3fe95a4569be621f983e361a350e245f0d
61,385
import pandas def _coerce_numeric(table): """Coerce a table into numeric values.""" for i in range(table.shape[1]): table.iloc[:, i] = pandas.to_numeric(table.iloc[:, i], errors='coerce') return table
cba1a224655e3536e361212569b7d6397a58786e
61,386
from cacao_accounting.database import Entidad def entidades(): """Listado de entidades.""" CONSULTA = Entidad.query.order_by(Entidad.entidad.desc()).paginate( request.args.get("page", default=1, type=int), MAXIMO_RESULTADOS_EN_CONSULTA_PAGINADA, False ) TITULO = "Listado de Entidades - " + AP...
f0d8de42b5fa87e037a6b0354f2c7924e583ab87
61,387
def motion_plot( uv_motion_field, plot_type="quiver", ax=None, geodata=None, axis="on", plot_kwargs=None, map_kwargs=None, step=20, ): """ Function to plot a motion field as arrows (quiver) or as stream lines (streamplot). .. _`quiver_doc`: https://matplotlib.org/api/_as_gen...
e45d74050a00b0eade3b6d1dee1ac1d0f2ec05cf
61,388
def get_token_from_auth_header(header_string): """Obtains the Access Token from the Authorization Header """ if not header_string: raise AuthError( { "code": "authorization_header_missing", "description": "Authorization header is expected", }, ...
22f3021d96f580abbff5bdd202d1837b9772ec66
61,389
from pathlib import Path def parse_yaml(filename): """ Given input path filename, parse YAML file. """ inf = Path(filename) yml = ruamel.yaml.YAML() return yml.load(inf)
01cd38f35a4392d09ac4100fd17abca5aedb8305
61,390
def get_scene_model(point_cloud, is_training, num_class, sigma, bn_decay=None, weight_decay = None): """ Semantic segmentation PointNet, input is BxNx3, output Bxnum_class """ batch_size = point_cloud.get_shape()[0].value num_point = point_cloud.get_shape()[1].value end_points = {} l0_xyz = point_c...
3cd3f1a5b71cc4eafa5403e5ab714a7d684323c2
61,391
def vgg16(**kwargs): """ VGG-16 model from 'Very Deep Convolutional Networks for Large-Scale Image Recognition,' https://arxiv.org/abs/1409.1556. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.torch/mo...
c05ed87aecc689b69750fabeb075582b960e86d7
61,392
from typing import Tuple def to_mido_note_on_note_off( note: Note, channel: int, use_note_off_message: bool = False ) -> Tuple[Message, Message]: """Return a Note object as mido Message objects. Timing is in absolute time, NOT in delta time. Parameters ---------- note : :class:`muspy.Note` o...
e8fd486046dba34c7773a9885e7688cbf5e949eb
61,393
def plot_exposures(pointings, Aeff_fact, index=1, lat=0., lon=np.radians(260.), Earth=True, antiEarth=False, NSIDE=32, doplot=True): """Short descrtiption of this function. Parameters ---------- pointings : dictionary Dictionary with the pointings of the detectors. Aeff...
2584411db280b9c7ab5ab87a1fe6303c7f1cd0de
61,394
from typing import Any def get_user_if_token_user(user: Any): """ Support for django-rest-framework-simplejwt TokenUser. Makes sure to always use the actual user model with save capability. Returns None for anonymous users """ if user: if not user.is_authenticated: return N...
100a4970bea67d5b2709b964f5b462094ab201e7
61,396
def assert_normalized(probs, tolerance=0.01, raise_error=True): """ Normalize probs so they sum to one. The probability should already so to ~1, but not exactly 1 due to rounding. :param probs: A list of probabilities :param tolerance: The maximum tolerance (i.e. should sum to 1. +- tolerance) ...
bb9dd8797c21b5067f7bc66800683c9d5e44c132
61,397
def add_ta_features(df, ta_settings): """Add technial analysis features from typical financial dataset that typically include columns such as "open", "high", "low", "price" and "volume". http://mrjbq7.github.io/ta-lib/ Args: df(pandas.DataFrame): original DataFrame. ta_settings(dic...
2c435fb98fe1326a08a093c28f53e5eee1515762
61,398
def dm_to_npy(dm_path): """ Converts a dm3 or dm4 image to a uint8 numpy array with a contrast limit suggested in the dm file. """ # Load the dm4 file and extract the image data. signal = dm.file_reader(dm_path)[0] image_data = signal['data'] # get the contrast limits from the file m...
e619a8c386aa8ac6af4785e1d3510a4735686256
61,399
import math def depair(z): """ Inverse of Cantor pairing function """ w = math.floor((math.sqrt(8 * z + 1) - 1) / 2) t = (w**2 + w) / 2 y = int(z - t) x = int(w - y) return x, y
92695c635ddbb60540d07e59ff1f495844e5e516
61,400
def _berkowitz_vector(M): """ Run the Berkowitz algorithm and return a vector whose entries are the coefficients of the characteristic polynomial of ``M``. Given N x N matrix, efficiently compute coefficients of characteristic polynomials of ``M`` without division in the ground doma...
c2cf5430c4ceeb6ff669f894264f71e1a4575208
61,401
def peppers(): """Peppers. Notes ----- This image was downloaded from the Signal and Image Processing Institute at the University of Southern California. <http://sipi.usc.edu/database/database.php?volume=misc&image=11#top> No known copyright restrictions, released into the public domain. ...
60f3c8ac71432e77f12b69cd74e06a8d721f7b3f
61,402
import socket def get_gateway_socket(gateway): """Takes a gateway address string and returns a non-blocking UDP socket to communicate with its NAT-PMP implementation on NATPMP_PORT. e.g. addr = get_gateway_socket('10.0.1.1') """ if not gateway: raise NATPMPNetworkError...
7b45cc2fa5b3dc54b08fcfc388f9547fa108e496
61,403
def get_lla_to_enu_R_matrix(lat, lng): """ Get a East, North, Up rotation matrix Parameters ---------- lat : float, latitude in degrees [-90, 90] lng : float, longitude in degrees [-180, 180] h : float, height in meters geoid : the ellipsoid model Returns ------- rotation_m...
13089802ffed4cbe7a771930a6e086bcaf227464
61,405
from typing import List def parse_sentence_to_word(sentence: str, stopwords: List[str]) -> List[str]: """read sentence, remove stopwords, and tokenize it into words""" words = [] for word in jieba.cut(sentence): if word not in stopwords and word != ' ': words.append(word) return words
61c5d502a1c26eef4b5846376c0296b148977f86
61,406
def calc_likelihood(clazz, attribute_counts, test_data): """ Calculates total likelihood for all attributes in test data according to attribute_count """ likelihoods = [] for idx in range(len(test_data)): likelihoods.append(attribute_counts[idx][test_data[idx]] / len(clazz)) return ...
d0c392aebb3076c09730a21bfeb913eee98d0bff
61,407
def break_after_nth_tick(ax, n, axis="x", occHeight=None, occWidth=None, where=0.5): """Visually break an axis x or y spine after the nth tick. Places a white occluding box and black diagonals onto the axis. Axis ticklabels must be changed manually. Parameters ---------- ax : matplotlib.axis ...
d55cdb102a49eacb119e4f2a0df5682a7a2154e6
61,408
def getisofill(Gfi_name_src='default'): """%s :param Gfi_name_src: String name of an existing isofill VCS object :type Gfi_name_src: `str`_ :returns: The specified isofill VCS object :rtype: vcs.isofill.Gfi """ # Check to make sure the argument passed in is a STRING if not isinstance(...
c9ed6433f02816e31cfc2754fd710ec8d326ecef
61,412
def add_cell_annotations(adata, var_index): """ This function adds annotation to anndata: cell level: total_counts, log10_total_counts, n_genes_detected, mito_frac, ribo_frac, compl(exity) gene_level: n_cells Arguments: adata - anndata object, raw (unnormalized!) ...
7fa6f8667715dae6c2571a27881c992f90f23553
61,413
def mean_image_subtraction(image, means): """Subtracts the given means from each image channel. For example: means = [123.68, 116.779, 103.939] image = _mean_image_subtraction(image, means) Note that the rank of `image` must be known. Args: image: a tensor of size [height, width, C] or [batch, heigh...
f95ed824c4925c4ef66c3a382014ca7812cd46e0
61,414
def apply_standard_scaler(dfs, scaler=None): """ apply sklearn standard scaler """ idx=pd.IndexSlice multiindex_rolling_features= pd.MultiIndex.from_product((['measurement'], SURVEY_ROLLING_FEATURES+SURVEY_BASELINE_FEATURES+['weekofyear']*args.weekofyear)) # for item in multiindex_rolling_f...
3a8b2dbf3dca49b7001201952ad764fb5a71cf3c
61,415
def auto_correlation(mag, magerr): """The autocorrelation integral calculates the correlation of a given signal as a function of the time delay of each measurement. Has been employed in previous research as a metric to differentitate between lightcurve classes. See: (SIDRA: a blind algorithm for signal ...
d4fdb3cefa2d907ec381d382ba94d181f03c9b4f
61,416
def generate_wiki_redirect_text(redirect_name: str) -> str: """Generate wikitext for redirect.""" return f'#REDIRECT [[{redirect_name}]]'
f6e55fa20004d836ea601a1d3966d070273df237
61,417
from typing import Union def check_text_file(file_path: str, filename) -> Union[pd.DataFrame, str]: """Check user submitted results file.""" check_read_file = _read_text_file(file_path, filename) # Check if file cannot be read and throw error if isinstance(check_read_file, str): return check_...
0b2fd70def10b3f9ea92608a0c95c2184a39a018
61,418
import random def calibrate_file(data_filename, output_level=2): """ Given an input file, calibrate it and return a new file. Parameters ---------- data_filename: str Fully specificied filename of the non-calibrated file (data level < 2) output_level: int The requested data le...
777b5e38995de7cfb6448d2670b854e107e4a579
61,419
def _process_image_annotations(image): """Helper for processing annotation types from protobuf. :type image: :class:`~google.cloud.grpc.vision.v1.image_annotator_pb2.\ AnnotateImageResponse` :param image: ``AnnotateImageResponse`` from protobuf. :rtype: dict :returns: Dictionary p...
942a8a414eeff48de1dbc4efc3d971ee029f23b0
61,420
def _chpi_locs_to_times_dig(chpi_locs): """Reformat chpi_locs as list of dig (dict).""" dig = list() for rrs, gofs in zip(*(chpi_locs[key] for key in ('rrs', 'gofs'))): dig.append([{'r': rr, 'ident': idx, 'gof': gof, 'kind': FIFF.FIFFV_POINT_HPI, 'coord_fram...
3fbbcdaee74eeb72a2c21bde0c11c3f491656ed1
61,421
import six def flatten(nested_dict, separator="_", root_keys_to_ignore=set()): """ Flattens a dictionary with nested structure to a dictionary with no hierarchy Consider ignoring keys that you are not interested in to prevent unnecessary processing This is specially true for very deep objects ...
5c011109bcd89449f0350528a908bcd0fcd6eb7d
61,422
def generate_filtered_query(model, path, emitted_keys): """ Generate a query filtered on the primary key of the last model in path. :param model: A :ref:`declarative <sqla:declarative_toplevel>` class. :param str path: :param dict emitted_keys: A `dict` containing the key value ...
a3689bb4ef79db7bc7de02bf969f725191f417bd
61,423