content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import torch def accuracy(output, target, topk=(1,), tok_groups=None, tok_group_labels=None, as_list=False): """Computes the accuracy over the k top predictions for the specified values of k""" mask = target != -1 output = output[mask] target = target[mask] maxk = max(topk) _, pred = output...
359c8993623d89c4e2b603eaf5ce262bbe9c47de
50,600
import warnings def deprecated(func): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emmitted when the function is used.""" def new_func(*args, **kwargs): warnings.simplefilter('always', DeprecationWarning) # turn off filter ...
e710d93dae4198e43862016c141750d40b70df5c
50,601
import subprocess import sys import errno def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) ...
9eb5bee349f4b002f817d949096a749d49b71aa2
50,602
import os import errno import functools import signal def timeout(seconds=10, error_message=os.strerror(errno.ETIME)): """ This decorator raise an TimeoutError exception if the function takes more than 'seconds' seconds to terminate From: https://stackoverflow.com/questions/2281850/ """ def d...
f46280146f0ee309f71100614bbc6d1afd38799d
50,603
def glove2dict(src_filename): """ GloVe reader. Parameters ---------- src_filename : str Full path to the GloVe file to be processed. Returns ------- dict Mapping words to their GloVe vectors as `np.array`. """ # This distribution has some words with spaces, so...
772a941df0d02703b627e64344f50895cca36c2c
50,604
import numpy import math def shear_matrix(angle, direction, point, normal): """Return matrix to shear by angle along direction vector on shear plane. The shear plane is defined by a point and normal vector. The direction vector must be orthogonal to the plane's normal vector. A point P is transforme...
511b33310f44bf9b95ebd7eee38393ec0f1235c1
50,605
def save_tiled_raster_images(tiled_img, filename): """ Save a a return value from `tile_raster_images` to `filename`. Returns ------- img : WRITEME The PIL image that was saved """ if tiled_img.ndim==2: ensure_Image() img = Image.fromarray( tiled_img, 'L') elif t...
331d286e79b83d83b8ff22c6051ab490139cdd78
50,606
import typing def two_points( reviewed_assertions: typing.List[ReviewedAssertion], ) -> typing.Optional[ReviewedAssertion]: """Extract two point ReviewedAssertion of possible.""" if not any(map(ReviewedAssertion.from_multiple, reviewed_assertions)): return None # is single => no two points el...
9e0adeb878de5b3ea0c75d7ec4049ca12b95819a
50,607
def _sigma_clip(data, threshold=3, cen_func='median', dev_func='mad_std', axis=None): """Create a mask of the sigma clipped pixels. This function will not change the array, instead, just output a mask for the masked elements. Parameters ---------- data: array_like Data ...
47ef3034950022afb08e726a52425ca53cd60548
50,608
def handler500(request, *args, **argv): """Error 500 configuration.""" return render(request, '{{cookiecutter.project_slug}}/404.html')
cda2b33df6c5ff61da14aea3660833524c800d69
50,609
def klucbGauss(x, level, sig2=1., lower=float("-inf"), upper=float("inf")): """returns u such that kl(x,u)=level for the Gaussian kl-divergence (can be done in closed form).""" if (upper==x): return x - np.sqrt(2*sig2*level) elif (lower==x): return x + np.sqrt(2*sig2*level) else: raise ValueError
4e1bd0fa6b6729f6c6699a986cf5944c9e0ed233
50,610
def base64_decode(data): """Decode a Base64 encodedstring""" return b64decode(data.encode('utf-8')).decode('utf-8')
ba768f2d0df2b3a42a80456396ae74185695014a
50,611
def movie(request, movie_id): """显示电影对应的所有场次""" one_movie = Movie.objects.get(movie_id=movie_id) comments = Movie_comment.objects.filter(movie_id=movie_id) score = False if len(comments) > 0: score = comments.aggregate(avg_score=Avg('score'))['avg_score'] cursor = connection.cursor() ...
f8d5d6d9722a55db02f8da4b69975b5f69d32e50
50,612
def load_file_to_dict(path): """ Takes a file path and loads it into a nested json dict following the format in json_form_schema.json The file may be a xls file or json file. If it is xls it is converted using xls2json. """ if path.endswith(".json"): name = _section_name(path) ...
7bfa1a3455e1cdba17b77ee0e7af49f72c193943
50,613
def UpdatePerfDataFiles(): """Updates the Chrome Endure graph data files with the latest test results. For each known Chrome Endure slave, we scan its latest test results looking for any new test data. Any new data that is found is then appended to the data files used to display the Chrome Endure graphs. R...
2d36c43f0451dc3d487ddbc7c00c37b518ee063c
50,614
from typing import Union def can_lead_to_object_uncertainty(gdatalog): """Figure out if a walked GDatalog[Δ] program can lead to object uncertainty. Object uncertainty happens when there is a rule in the program such that: - there exist an atom in the antecedent of the rule such that the ...
dea9d48fece0b6c3cb9eb5d57448c4e3c84f7eae
50,615
def averageRaDec(ra, dec): """Calculate average RA, Dec from input lists using spherical geometry. Parameters ---------- ra : `list` [`float`] RA in [radians] dec : `list` [`float`] Dec in [radians] Returns ------- float, float meanRa, meanDec -- Tuple of average R...
8af0cd4f9a612400a00af64e6a6bee5cb3383ff5
50,616
def onnx2str(model_onnx, nrows=15): """ Displays the beginning of an ONNX graph. See :ref:`onnxsklearnconsortiumrst`. """ lines = str(model_onnx).split('\n') if len(lines) > nrows: lines = lines[:nrows] + ['...'] return "\n".join(lines)
0bca645ab2882cde59788517cc9c8c02d208de2e
50,617
import argparse def create_cmd_arguments(aux): """ Use the `argparse` module to make the optional and required command-line arguments for the `wedap`. Parameters ---------- Returns ------- argparse.ArgumentParser: An ArgumentParser that is used to retrieve command line ar...
00185400cbf6c16707fc2d0437c6995d724725a7
50,618
def hessian (f, X, eps=1e-6): """ Check Hessian of function. checkgrad.hessian (f, X, eps=1e-6) Inputs: f Function, returns Y(X), d^2Y / dX^2. X [D1, ..., Dn] Y [E1, ..., Em] d^2Y/dX^2 [E1, ..., Em, D1,...
fc05e13e9fad5be88efcff5574dfd0bd370bf07c
50,619
def is_available(): """ Test whether YouCompleteMe plugin is available (was loaded). """ return 'g:loaded_youcompleteme' in vimp.var
219475c1405ec6fe132a9f1e94db0fa76028c1b9
50,620
import math import numpy as np def rs1_score(sequence): """ Generates a binary matrix for DNA/RNA sequence, where each column is a possible base and each row is a position along the sequence. Matrix column order is A, T/U, C, G """ seq = str(sequence).upper() seq = list(seq) matrix1 = np....
c23abc5ffe18034f26b88d7ea4c3ff7848250eb9
50,621
import copy def get_build_summary(results): """Prints to screen the complication results of example programs. Args: results - results of the compilation stage. which is the output of compile_repos() Returns: Numbers of failed results """ pass_table = PrettyTable() pass_table.field_na...
c4ab123ea89b8e8719fe48a663df99373c4dacf7
50,622
import binascii def s2n(s): """ String to number. """ if not len(s): return 0 return int(binascii.hexlify(s), 16)
21884827bf205bf98878d93b241855fbe4c0abcd
50,623
def diff_lists(old, new): """Returns sorted lists of added and removed items.""" old = set(old or []) new = set(new or []) return sorted(new - old), sorted(old - new)
1359a2c89c20993445491ff2a986a392eaee2aed
50,624
import csv from bs4 import BeautifulSoup import tqdm import urllib def save_csv_given_urls(urls, csv_filename='AAAI_tmp.csv'): """ write IJCAI papers' urls in one csv file :param urls: str, the urls of paper website, such as 'https://www.aaai.org/Library/AAAI/aaai20contents-issue01.php' :param csv_fil...
469e871d5e391e13b4b7bbab773e16be8d7c7ae1
50,625
def indicator_remove(_id, username=None): """ Remove an Indicator from CRITs. :param _id: The ObjectId of the indicator to remove. :type _id: str :param username: The user removing the indicator. :type username: str :returns: dict with keys "success" (boolean) and "message" (list) if failed...
e5e54198daaca2e92587fa0fe551c8e228dbe463
50,626
def get(github_repository, **args): """Send data and perform Core()""" return Core(github_repository, **args).get()
10b068ac4c0411ecee916aae5182da4ffd96f272
50,627
import requests def get_profile(login): """Get the GitHub profile from login""" print("get profile for %s" % (login,)) try: profile = get("https://api.github.com/users/%s" % login).json() except requests.exceptions.HTTPError: return dict(name=login, avatar_url=LOGO_URL, html_url="") ...
f3df77c82410fa4f5779c6892c225fdcc31d2dd1
50,628
def create_U_layer(mol, auxinfo): """ Creates a string with the positions of the atoms that bear unpaired electrons. The string can be used to complement the InChI with an additional layer that allows for the differentiation between structures with multiple unpaired electrons. The string is compose...
cc9b0e172feff70bb72a4bb3564b62c63ad2b6da
50,629
def result(product_id): """ Speak query result""" response = PhoneInterface() result = Product.query.get(product_id) response.speak(to_result(result)) response.speak('Is there anything else we can help you with?') response.listen('listenbot.done', 'yes, no') return str(response)
aa0c48dc77cb009ef94b411a3ac44063cac1e2c6
50,630
def key2board(key): """ Turn a key into a "Game of Life" board. We might add an arbitrary size parameter. """ Z = np.zeros((512 + 2, ((512 * 4) + 2)), int) Z[1:-1, 1:-1] = (np.frombuffer(hex2bin(key), 'u1') - ord('0')).reshape((512, 512 * 4)) return(Z)
46bc2a3f6ccd2895514a9181684c8f500e78574f
50,631
def PV(FV,i,n,m=1): """ future value interest years optional payments per year """ PV = FV / ((1 + i/m)**(m*n)) return PV
7b573f5338ad950295f2e03a584b544c3df81f82
50,632
def getCeleryApp(): """ Lazy loader for the celery app. Reloads anytime the settings are updated. """ global _celeryapp if _celeryapp is None: backend = Setting().get(PluginSettings.BACKEND) or 'amqp://guest:guest@localhost/' broker = Setting().get(PluginSettings.BROKER) or 'amqp://...
9bc201894ef92a13418e7bca8de7f844de802302
50,633
def get_gw_bytes_encoding(): """ get gateway encoding method :return: string """ return "utf-8"
44e23564f5feb086334d7d9c00a8f4283ae5273d
50,634
def build_py_ide_info(target, ctx): """Build PyIdeInfo.""" if not hasattr(target, "py"): return (None, set()) sources = sources_from_target(ctx) transitive_sources = target.py.transitive_sources py_ide_info = struct_omit_none( sources = sources, ) return (py_ide_info, transitive_sources)
05252876bc906f878b1522f9abf48feb90c27414
50,635
def factor_new_space(M): """ Given a new space `M` of modular symbols, return the decomposition into simple of `M` under the Hecke operators. INPUT: - ``M`` - modular symbols space OUTPUT: list of factors EXAMPLES:: sage: M = ModularSymbols(37).cuspidal_subspace() ...
e64f8e1b19f803fe92f3fa0a4cd1d959a8132cba
50,636
import tqdm import io def build_core_template(images, N=5, thresh=40, vb=True): """ Overlay images of core trays from e.g. a drillhole to calculate a template that is used for extracting individual core segments and is robust to data quirks (e.g. empty trays). All images must be identical dimensions a...
38e7f7af20265037163877378a84da647c78455c
50,637
from typing import Dict def cohort_tests(config: Dict, n_days: int) -> Dict[str, int]: """Determines the number of tests required per person for all cohorts. The number of tests required for a person in a cohort is approximately the number of testing days divided by the cohort's target testing interval. ...
3c68bde6016fa25f11c736c80460e7ef35398b46
50,638
def check_oversamplers_classifiers(oversamplers, classifiers): """Extract estimators and parameters grids.""" # Create estimators and parameter grids estimators, param_grids = [], [] for oversampler, classifier in product(oversamplers, classifiers): # Unpack oversamplers and classifiers ...
d8ceed380fd775968ad8f15662ff673c7753c5e2
50,639
import os def run_driver(): """ Run webdriver Chrome """ try: current_path = os.getcwd() options = Options() options.add_experimental_option("prefs", { "download.default_directory": current_path, "download.prompt_for_download": False, "download.direc...
e17cfe9e132fa610d13460362a5865175a741be4
50,640
def axiom_generator_have_arrow_ssa(t): """ Assert the conditions at time t under which the Agent has the arrow at time t+1 t := time """ "*** YOUR CODE HERE ***" axiom_str = state_have_arrow_str(t+1) + ' <=> (' + state_have_arrow_str(t) + ' & ~' + action_shoot_str(t) + ')' # Comment or...
db37c9365dfaf9016c7a47455ea2f07f9d6956cc
50,641
def map_(key, value, *tail) -> Expression: """ Creates a map of expressions. Example: :: >>> tab.select( >>> map_( >>> "key1", 1, >>> "key2", 2, >>> "key3", 3 >>> )) .. note:: keys and values should have the ...
8c0e4e50320b23d916e660c0d4baa78f9d781407
50,642
import os def CSPDarkNet53(input_shape=None, input_tensor=None, include_top=True, weights='imagenet', pooling=None, classes=1000, **kwargs): """Generate cspdarknet53 model for Imagenet classification.""" if not (weights in {'imagenet', N...
a412ac60d79c5af820966bd391c6315e03c7cdd4
50,643
def convert_coords(container: pygame.Rect, x: float, y: float) -> (int, int): """Converts the given coordinates for a simulation display purposes. :param container: the simulation surface :param x: the x position coordinate :param y: the x position coordinate :return: converted coordinates """ ...
3d103078658e904887f380425d3c7d3743103633
50,644
def _debug_warning(prod, txn, warning_table, vtec, segment, ets): """Get a more useful warning message for this failure""" cnt = txn.rowcount txn.execute( "SELECT ugc, issue at time zone 'UTC' as utc_issue, " "expire at time zone 'UTC' as utc_expire, " "updated at time zone 'UTC' as ...
93b91cc0643cc9036563eccb4b767f764128416d
50,645
def _parse_unit(unit_element, namespace): """returns a list of dicts that represent the values for a given unit or units element """ unit_dict = _element_dict(unit_element) tag_name = unit_element.tag.split('}')[-1] return_dict = {} if '1.0' in namespace: return_dict['name'] = unit_...
2b7b4333c9f0507e3c42528dbe8e19f498a5d6ac
50,646
def kw(sa: 'Atmosphere', frequency: float) -> Tensor1D_or_3D: """ :param frequency: частота излучения в ГГц :param sa: объект Atmosphere :return: весовая функция k_w (вода в жидкокапельной фазе). """ return wf.kw(frequency, sa.temperature)
5070cc2565b95fde5af77e0eb0f55604b2c8c629
50,647
def plot_lines(df: pd.DataFrame, cols: list = None, cols_like: list = None, x: str = None, h: int = 300, w: int = 1200, t_str: str = 'box_zoom,pan,hover,reset,save', x_type: str = 'datetime', show_p: bool = True, t_loc: str = 'right', out_path: str = None, return_p: bool = False, palette: ...
d45234fad9cb16e27e8d420437d95141bbe36423
50,648
import json def add_postgraduate_info(): """ 添加一条信息 :return:{'result': result} """ user_id = request.values.get('openid') # 用户微信openid subject = request.values.get('subject') # 考研方向 msg = request.values.get('msg') # 附加消息 phone = request.values.get('phone') # 联系电话 grade = reques...
9fe9af80063d4a717262c551985088a4aae9e880
50,649
def depth_first_traversal_for_node(node, callback, direction, obj=None): """ Executes a depth-first traversal from this node in a given direction. Raising a StopIteration will terminate the traversal. :type node: treestruct.Node :type callback: (treestruct.Node, treestruct.Node, object) -> () :...
638836150f81ed5261752c01ca9e506242c8cb71
50,650
def build_model(tparams, options): """ Construct computation graph for the whole model """ # inputs (image, sentence, contrast images, constrast sentences) im = tensor.matrix('im', dtype='float32') s = tensor.matrix('s', dtype='float32') cim = tensor.matrix('cim', dtype='float32') cs = t...
9caad070fffd6c2581a86d4226770fabd1fe3516
50,651
def default_slugifier(value, allow_unicode=False): """ Oscar's default slugifier function. When unicode is allowed it uses Django's slugify function, otherwise it uses cautious_slugify. """ if allow_unicode: return django_slugify(value, allow_unicode=True) else: return cautious_s...
e507934e3983816fb011f83e7a991eda13278a54
50,652
def extract_pos_tags(input_xls: str) -> dict: """ Read all post-tas from JUIZ column and returns a dictionary indexed by the sentence id with a list of all pos-tags. Parameters ---------- input_xls: str Input xls file. Returns ------- dict: Dict of sentence ids and ...
3df23b1e7da984b8ead1f27c530e9cef603fba30
50,653
def secure_atbd_version_lock( atbd_id: str, version: str, db: DbSession = Depends(get_db_session), override: bool = False, user: CognitoUser = Depends(require_user), principals=Depends(get_active_user_principals), ): """ Sets locked_by field of ATBD Version to current user. Succeeds ...
6ff5d5eb86e33e1b9ef278b3e319a4c6b6e2b6ff
50,654
from rdkit.sping.PDF import pidPDF from rdkit.piddle import piddlePDF def ClusterToPDF(cluster, fileName, size=(300, 300), ptColors=[], lineWidth=None, showIndices=0, stopAtCentroids=0, logScale=0): """ handles the work of drawing a cluster tree to an PDF file **Arguments** - cluster: t...
8fd99af1900e6f36b148d9c4cbf348e68348833d
50,655
def ants_move(space, pos, inv_distance, pheromones, alpha, beta, del_tau): """Moves the ants from starting position to cover all the nodes. Arguments: space {numpy.ndarray} -- The sample space pos {numpy.ndarray} -- The starting position of the ants inv_distance {numpy.ndarray} -- T...
46695e157efdc343be55f9bf1d85191808821a69
50,656
def list_to_tree(S: list) -> TreeNode: """ :param L: :return: """ L = [TreeNode(val) if val is not None else None for val in S] # print(L) tmp_list = [L[0]] cursor = 1 N = len(L) while tmp_list: n = len(tmp_list) next_cursor = cursor + n * 2 for i, node in...
65b9fa64673964c5e2af4d1923f947f97eb5e73f
50,657
def three_points_to_circle(p1, p2, p3): """ Function that calculates circle parameters defined by three points. Input: - p1 [float,float] : pair (x,y) of coordinates of the 1st point - p2 [float,float] : pair (x,y) of coordinates of the 2nd point - p3 [float,float] : pair (x,y) of coordinates of...
cc45cd43ec9d5555b469ed7001f46935d1bc16da
50,658
def dnlsim(system, u, t=None, x0=None): """Simulate output of a discrete-time nonlinear system. Calculate the output and the states of a nonlinear state-space model. x(t+1) = A x(t) + B u(t) + E zeta(x(t),u(t)) y(t) = C x(t) + D u(t) + F eta(x(t),u(t)) where zeta and eta are polynomials w...
81ede6bdbdaad7ad2ae1cae4d5b23b7e60f1fd98
50,659
import os import errno def get_cloudinit_instance(): """Return the current CloudInit instance ID.""" try: target = os.readlink('/var/lib/cloud/instance') except OSError as e: if e.errno != errno.ENOENT: raise return path, instance = os.path.split(target) return ...
3eff85599300c0d3a4ae18bc10f7501c3c9c2d25
50,660
def open_file(filename: str): """ >>> open_file("hello.txt") No such file or directory: hello.txt >>> import os >>> if os.path.exists("../LICENSE"): ... f = open_file("../LICENSE") ... _ = f is not None ... _ = f.readline().strip() == "Apache License" ... _ = f.readl...
fdc9f5746f61573014c4cb7b3631c2ce0ad10d4e
50,661
from typing import Tuple from typing import List def sanitize(report: str) -> Tuple[str, str, List[str]]: """Returns a sanitized report, remarks, and elements ready for parsing""" clean = sanitization.sanitize_report_string(report) data, remark_str = get_remarks(clean) data = core.dedupe(data) dat...
ae4159bb8b947c4e74ae2c63f9e49233b6c85c83
50,662
def matfromrcell(astar, bstar=None, cstar=None, alphastar=None, betastar=None, gammastar=None): """Make standard-orientation reciprocal cell matrix from reciprocal cell. """ if isinstance(astar, CellParam): cell = astar else: cell = fillCellParam(astar, bstar, cstar, alp...
2c3d0545a14f9b6337e0b4cc0e5e606832bb4ea3
50,663
from typing import List def list_octicons() -> List[str]: """List available octicon names.""" return list(get_octicon_data().keys())
5a48163e34ec17e5c51c82f0d4b7f06f093bd258
50,664
def sampler_params(scope="function"): """Common parameters for sampler test""" params = { "tag_type": "ner", "query_number": 4, "label_names": ["O", "PER", "LOC"], "token_based": False, "tagger": MagicMock(), "embeddings": MagicMock(), "kmeans_params": {"n...
5e16ca4a223363a8cc637b58625a2f3aa650a260
50,665
import os import errno def ocfn(filename, openMode='r+', binary=False): """Atomically open or create file from filename. If file already exists, Then open file using openMode Else create file using write update mode If not binary Else write update binary mode Returns file object ...
68099404963d28d205a5d916e6ea7b32dd4f4e65
50,666
def strip_xml(element): """ Recursively strip clean indentation from xml. Especially useful if you're using a template. For example, this is a bit of a mess: >>> xml_mess = ''' ... <help> How did ... ... <person>I ... </person> ... get to be so <cleanliness ...
e7938d19aa7202f1c8f4986b62a5556bb91fa6ac
50,667
import torch def add_gaussian(p, g_std): """add gaussian noise :param p: input tensor :param g_std: standard deviation of Gaussian :returns: tensor with added noise :rtype: tensor """ if g_std > 0: size = p.size() p += torch.normal(0, g_std, size=size) return p
025bfffca50463589619051f58b5d8e95341c0bd
50,668
def extension_supported(extension_name, request): """ this method will determine if nova supports a given extension name. example values for the extension_name include AdminActions, ConsoleOutput, etc. """ extensions = list_extensions(request) for extension in extensions: if extensio...
3087a0d9a5d9a64d4e4fc0b0f8b0c6ceafa577b6
50,669
from typing import Optional async def get_text( # https://fastapi.tiangolo.com/tutorial/query-params/ msg: Optional[str] = Query( ..., max_length=1500, min_length=2, # disallow one character message title="user's message", description="max. 5000 chars.", ), pre...
d6d33f2fcbb6425edce1f5daf4c44bec54a2f361
50,670
from typing import OrderedDict import re def parse_interactions(input_file): """ Parse through the interactions input file. @param[in] input_file The name of the input file. """ # Three dictionaries of return variables. Systems = OrderedDict() Interactions = OrderedDict() Globals = ...
630b2ee0d4c7e7c39e78ce62a0678e3b60f5a3ab
50,671
def get_rates_above_threshold(y_vals, rec_bins): """ Gives the total number of interactions above every given threshold The input is expected to be integrated rates over time. Thus, the total rate returned is counts/kg/t_full Parameters ---------- y_vals : `array` ...
9af8cae3cf85223cec769f44c6be3358a5aab03f
50,672
def stormpath_login(request): """ Verify user login. It uses django_stormpath to check if user credentials are valid. """ if settings.USE_ID_SITE: return redirect('sample:stormpath_id_site_login') if request.user.is_authenticated(): return redirect('sample:home') form = Au...
c2394c957c7393f590173e71d8b4b15cab932b1e
50,673
def chain(_input, funcs): """Execute recursive function chain on input and return it. Side Effects: Mutates input, funcs. Args: _input: Input of any data type to be passed into functions. funcs: Ordered list of funcs to be applied to input. Returns: Recusive call if any functi...
3f2d1490044f0eb35656bd7601d1569fb6f8a553
50,674
import sys def connect_mysql(options): """ Make connection to Mysql.""" try: con = mdb.connect( host = options.mysqlhost, user = options.mysqluser, passwd = options.mysqlpass, db = 'gold_cup_web', port = int(options.mysqlport), ) ...
1a02dd64024c36f886f74b75a229d3a2818dc057
50,675
def sample_circle(c, N=32): """ Sample points on a circle c Returns a 2D PointSet with N points """ assert len(c) == 3 # Get x, y and radius x, y, r = c # Sample N points, but add one to close the loop a = np.linspace(0,2*np.pi, N+1) # Prepare array pp = ...
357433b7d5fd228838c472b6132e282d95863c08
50,676
def turn_animation_into_updater2(animation, cycle=False, delay=0.0, **kwargs): """ Add an updater to the animation's mobject which applies the interpolation and update functions of the animation If cycle is True, this repeats over and over. Otherwise, the updater will be popped upon completion ...
7ce9e5a0ca6830b181de8503ed12e70e465f61e9
50,677
def all_levels(df, bucket_var, include_levels=None, ret_map=False): """ Assign each row of `df` to a bucket according to the unique values of `bucket_var`. bucket_var: Column name of the values to split on. Missing values will not be assigned to an interval. include_levels: Level value...
e16044f7a7cef4cade372938b29b48661dd2325c
50,678
import logging def loss_function(real, pred, loss_object): """ measure loss object in a logically consistent way :param real: :param pred: :param loss_object: :return: """ logging.info("loss_function") mask = tf.math.logical_not(tf.math.equal(real, 0)) loss_ = loss_object(real,...
1051ba1243698731131f9a42d1f10f2d6d19c475
50,679
def Z(theta=0, pulse_pars=None): """ Software Z-gate of arbitrary rotation. :param theta: rotation angle :param pulse_pars: pulse parameters (dict) :return: Pulse dict of the Z-gate """ if pulse_pars is None: raise ValueError('Pulse_pars is None.') else: ...
054133afad02dd15aceca4a5a60ad58c0d2783c5
50,680
def spend_separator_tx(tx_sep_tx, keys_for_sep_tx): """spends Transaction with scriptPubKey in form of: <pk1> OP_CHECKSIGVERIFY OP_CODESEPARATOR <pk2> OP_CHECKSIGVERIFY OP_CODESEPARATOR ... <pk N_signings> OP_CHECKSIG """ tx = CTransaction() tx.vin.append(CTxIn(COutPoint(tx_sep_tx.sha256, 0), b"",...
cb01f0ed7dc884fbc8dbb05a83a1748792f21b79
50,681
def get_nested_grid_bounds(land_cover_pth): """ Get the lat/lon bounds of the nested grid window (NA, EU, AS) for the inversion. The land cover file path specifies the window. """ if "NA" in land_cover_pth: if "GEOSFP" in land_cover_pth: minLat_allowed = 9.75 maxLat_...
49a2debbe5ee2cea9c74084d95a52f31313eb4b3
50,682
def get_resolution_HRF(): """Returns RIM_ONE_v2 resolution after post-processing.""" return (3504, 3504)
4d50b1a08a469f5790a7e59207fcde3956c4fa2d
50,683
import cv2 from matplotlib import pyplot as plt def crop_brain(image, n_top_areas = 5, max_scale_diff = 3, plot = False, dimensions = None, area = None): """ Crop image in order to only include square image of the "best" image of the brain """ image = normalize_img(image, use_min_max = True) if dimensio...
e4ff2742d45d40da67457d324daa3b7154fcdcb7
50,684
import string import random def generate_password(size=4, chars=string.ascii_uppercase + string.digits): """Randomly generate a password with length `size`. Args: size (int): Length of the password. chars (str): The char appeared in this string will be considered as one of the choice....
bb0230810ddf6d4946146798ea304f321c8b3ae4
50,685
def overlaps_bool(pred_roi, bbox): """ :param rois: regions of interest in format (y1, x1, y2, x2) :return: Boolean Example: [[ 99,325,135,363], [ 54,229,88,264], [ 53,230,94,266], [ 93,321,132,361]] -> [1, 2, 2, 1] """ l_1_y1 = pred_roi[0] l_1_x1 = pred_roi[1] r_1_y2 = pre...
c186026967b7016aba7ce21cd9d710b51af74d91
50,686
def angle_distance(innodes, name='angle_distance'): """ Returns the angle distance between two nodes. Angle distance is <x,y>/(||x||||y||) @param innodes: array of 2 tensorflow tensors with equal dimensions @param name: name of the subgraph. everything in this subgraph would be _[name], and the output...
258888d7aa45c561ddeaa7ea1ac80d499cd399e6
50,687
def spec_exists(notification: Notification) -> bool: """ Check whether the spec exists. Args: notification: The SNS notification. Returns: Whether the spec file in the SNS notification exists. """ response = S3_CLIENT.list_objects_v2( Bucket=notification.bucket_name, P...
851a29189e63b8d727a1fd73a65c8970350fad51
50,688
def person(request, pk): """ Retrieve, update or delete a code snippet. """ try: person = Personnel.objects.get(pk=pk) except Personnel.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = PersonnelSerializer(person) return JsonResponse(serializer.data) elif request.me...
1bf25578ef1acc020b2aab91e825c642babb3815
50,689
import os def is_ipython_frame(frame: FrameType) -> bool: """ Determine whether a frame is being executed by IPython. Args: frame (``types.FrameType``): the frame to examine Returns: ``bool``: whether the frame is an IPython frame """ filename = frame.f_code.co_filename p...
ee308a720fe7b9c9d263181c4ce5c0c3904d17ac
50,690
import re def underline_to_hump(underline_str): """ Transfer underline to hump Args: underline_str(string): underline code string """ sub = re.sub(r'(_\w)', lambda x: x.group(1)[1].upper(), underline_str) return sub
dbc59ced8306088f08b6997c305c468370b4631d
50,691
def get_query_workload(duration_sec, rate): """ Returns an array of query tuples (see get_next_query()) for the given duration and rate """ cur_time = 0.0 workload = [] while cur_time < duration_sec: q = get_next_query(rate, duration_sec) cur_time += q["dt"] workload.appe...
86e4b9e7e71b74400ffccf60317be5ae1a060aae
50,692
import os def _is_sound_file(name): """Returns: True if name is the name of an font file. Parameter name: A file name Precondition: NONE""" if type(name) != str: return False return os.path.exists(SOUND_PATH+'/'+name)
b8e480cfa53793c2d09a9316a1e6dca9afd2a797
50,693
def successor(node): """ 4.6 Successor: Write an algorithm to find the "next" node (i.e., in-order successor) of a given node in a binary search tree. You may assume that each node has a link to its parent. """ def get_min(node): if node.left != None: return get_min(node.left) ...
448342a8adcdf73ba73a5e6b4319cd299d1bc9a8
50,694
import traceback def get_length_audio(audiopath, extension): """ Returns length of audio in seconds. Returns None if format isn't supported or in case of error. """ try: audio = AudioSegment.from_file(audiopath, extension.replace(".", "")) except Exception: print(f"Error in get...
66408053a89a82b9ce9e0dc920ed91b990ac4158
50,695
import json def load_schema(data): """ Load Schema/Example data depending on its type (JSON, XML). If error in parsing as JSON and XML, just returns unloaded data. :param str data: schema/example data """ try: return json.loads(data) except Exception: # POKEMON! pass ...
13979ca2b649514524b12dc7a305c875a7140305
50,696
def netcdf_file_handler(index): """ Returns file info and phenomena information of a NETCDF file. """ fname = "file_%02d" % index fmeta = get_file_doc(fname) #fphen = get_file_phenomena() fphen = get_file_phenomena_i(index) return (fmeta, fphen)
b0a463a7cc6b6bcc8c80a3a47e248eb4dc637474
50,697
def get_reference_number_from_object_name(object_name_string): """ Given s3 object name: 'e23413582523--QUIDP.json' or 'e23413582523P.json': return just 'e23413582523' """ logger.debug(f"Received: {object_name_string}") if '--' in object_name_string: reference_number = object_name_st...
fd26fc3b5c64b70d695039b18a833b0f3656d90a
50,698
def calculate_transform(src, dst, model_class=AffineTransform): """Calculate transformation matrix from matched coordinate pairs. Parameters ---------- src : ndarray Matched row, column coordinates from source image. dst : ndarray Matched row, column coordinates from destination ima...
cbe4455d34753d6d7d0fb930a2b86a93d86dea1a
50,699