content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import tqdm def convNodeToProblems(graphList,vecGraphList,masterEncoder,genre=["C","V"],targetParams=CF.targetParams): """ graphList: list of graphs (before vectorization) vecGraphList: list of vectorized graphs (of graphList) masterEncoder: masterEncoder genre: genre to make problems: C: compoun...
c8eaa40c1b178ef55419956a1a2013875fa7421a
3,638,500
import SimpleITK as sitk import os def create_white_edge_cost_image(t1_file, t2_file, gm_proba_file, out_file): """ This class represents a... :param t1_file: :param t2_file: :param gm_proba_file: :param out_file: :return: """ gm_proba = sitk.ReadImage(gm_proba_file) negative...
edc64e6c602b01b33dc99fb4a724bbc35f523063
3,638,501
import math def getDewPoint(temp, humidity): """ A utility function to get the temperature to which an amount of air must be cooled in order for water vapor to condense into water. This is only valid for: 1) temperatures between 0C and 60C, 2) relative humidity between 1% and 100%, and 3) dew poin...
0e67eef5a90d9e55f85906d57e6c2eb347044897
3,638,502
import json def get_result_handler(rc_value, sa_file=None): """Returns dict of result handler config. Backwards compatible for JSON input. rc_value (str): Result config argument specified. sa_file (str): SA path argument specified. """ try: result_handler = json.loads(rc_value) except...
83c6aa6e0cacdc64422553050072af5d8ea46bf6
3,638,503
def speedup_experiment_ts(args, model_iter_fn, model, example_inputs): """ Measure baseline performance (without using TorchDynamo) of TorchScript and optimize_for_inference. Writes to ./baseline_ts.csv """ return baselines( [ ("eager", model), ("ts", try_script(mode...
0936d5e24759ae5e04027f8e68e467caa24d5ccb
3,638,504
from typing import Tuple def my_polyhedron_to_label( rays: Rays_Base, dists: ArrayLike, points: ArrayLike, shape: Tuple[int, ...] ) -> npt.NDArray[np.int_]: """Convenience funtion to pass 1-d arrays to polyhedron_to_label.""" return polyhedron_to_label( # type: ignore [no-any-return] np.expand_di...
f967a963fcb47c964895da182a48568a2a8a8ee2
3,638,505
import tqdm from sys import stdout from sys import path def order_files_by_ranges(root_path: str, dest_path: str, date_ranges: list, *, save_unsorted: bool = True) -> list: """Copies all files (including subdirectories) from given path to destination path without any loss of data and groups them in...
93d382eb6c0bb08ee9a0fdccc21533e075238cf7
3,638,506
from typing import Optional def get_incident_comment(incident_comment_id: Optional[str] = None, incident_id: Optional[str] = None, operational_insights_resource_provider: Optional[str] = None, resource_group_name: Optional[str] = None, ...
c0fa6ec1bb7bcccc379455454296bc6a5814946f
3,638,507
def getOrElseUpdate(dictionary, key, opr): """If given key is already in the dictionary, returns associated value. Otherwise compute the value with opr, update the dictionary and return it. None dictionary are ignored. >>> d = dict() >>> getOrElseUpdate(d, 1, lambda _: _ + 1) 2 >>> print(d) {...
95454d7ca34d6ae243fda4e70338cf3d7584b827
3,638,508
from operator import add from operator import mul def gs_norm(f, g, q): """ Compute the squared Gram-Schmidt norm of the NTRU matrix generated by f, g. This matrix is [[g, - f], [G, - F]]. This algorithm is equivalent to line 9 of algorithm 5 (NTRUGen). """ sqnorm_fg = sqnorm([f, g]) ffgg ...
da30e1bac41cba3a6c051ba0159234aac5e6e3cc
3,638,509
from phaser import substructure def find_anomalous_scatterers(*args, **kwds): """ Wrapper for corresponding method in phaser.substructure, if phaser is available and configured. """ if (not libtbx.env.has_module("phaser")): if "log" in kwds: print("Phaser not available", file=kwds["log"]) retu...
0c88f0df336802fa798ac26966485b28105a6238
3,638,510
def OpChr(ea, n): """ @param ea: linear address @param n: number of operand - 0 - the first operand - 1 - the second, third and all other operands - -1 - all operands """ return idaapi.op_chr(ea, n)
39c2716ed7344fccd85edda2d27b7a7f305cb14b
3,638,511
def check_access(func): """ Check whether user is in policy owners group """ def inner(*args, **kwargs): keycloak = get_keycloak() if 'policy_id' in kwargs: current_user = kwargs['user'] group_name = f'policy-{kwargs["policy_id"]}-owners' group_list = ...
6655af97f11ae04587904f1aaf2a2225ace5b64d
3,638,512
def score_ranking(score_dict): """ 用pandas实现分组排序 :param score_dict: dict {'591_sum_test_0601': 13.1, '591_b_tpg7': 13.1, '591_tdw_ltpg6': 14.14} :return: DataFrame pd.DataFrame([['591_sum_test_0601', 13.10, 2.0, 0.6667], ['591_b_tpg7', 13.10, 2.0, 0.6667], ['591_tdw_ltpg6', 14.14, 3.0, 1.0]]...
d799576afe382c13124c703351b69b8bcb7393b2
3,638,513
def dock_widget(widget, label="DockWindow", area="right", floating=False): """Dock the given widget properly for both M2016 and 2017+.""" # convert widget to Qt if needed if not issubclass(widget.__class__, QObject): widget = utils.to_qwidget(widget) # make sure our widget has a name name =...
80ef6bde493585e0010a497dfb179600aae04e9e
3,638,514
def compute_benjamin_feir_index(bandwidth, steepness, water_depth, peak_wavenumber): """Compute Benjamin-Feir index (BFI) from bandwidth and steepness estimates. Reference: Serio, Marina, et al. “On the Computation of the Benjamin-Feir Index.” Nuovo Cimento Della Societa Italiana Di Fisica C, ...
2b3ef715a85a6dab837a36f86c3eeeaed05f8345
3,638,515
import sys def query_yes_no(question, default="yes"): """Ask a yes/no question via raw_input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits <Enter>. It must be "yes" (the default), "no" or None (meaning ...
058ab1b06f9b3179264e0dc46c131f3a089abfa9
3,638,516
def plaintext_property_map(name: str) -> Mapper: """ Arguments --------- name : str Name of the property. Returns ------- Mapper Property map. See Also -------- property_map """ return property_map( name, python_to_api=plaintext_to_noti...
9b909de0eba2d8f55375896bb2acbbb53c6d759f
3,638,517
def pooling_layer(net_input, ksize=(1, 2, 2, 1), strides=(1, 2, 2, 1)): """ TensorFlow pooling layer :param net_input: Input tensor :param ksize: kernel size of pooling :param strides: stride of pooling :return: Tensor after pooling """ return tf.nn.max_pool(net_input, ksize=ksize, strid...
4de6b7bdb5860cfa235975f799204522e77b9299
3,638,518
from typing import OrderedDict def set_standard_attrs(da): """ Add standard attributed to xarray DataArray""" da.coords["lat"].attrs = OrderedDict( [ ("standard_name", "latitude"), ("units", "degrees_north"), ("axis", "Y"), ("long_name", "latitude"), ...
21f83552466127928c9a30e9354e91c3031225aa
3,638,519
import os def find_git_repos(folder): """ Returns a list of all git repos within the given ancestor folder. """ return [root for root, subfolders, files in os.walk(folder) if '.git' in subfolders]
615fcc3e947ac3f198638acb23b8a8118c3ec9cd
3,638,520
def isnotebook(): """ Utility function to detect if the code being run is within a jupyter notebook. Useful to change progress indicators for example. Returns ------- isnotebook : bool True if the function is being called inside a notebook, False otherwise. """ try: shel...
71e0a77c4bbf3afe16723b01ee5a8d08cf3b98a3
3,638,521
from typing import Optional from typing import Tuple from typing import List from typing import Dict def get_poagraph(dagmaf: DAGMaf.DAGMaf, fasta_provider: missings.FastaProvider, metadata: Optional[msa.MetadataCSV]) -> \ Tuple[List[graph.Node], Dict[msa.SequenceID, graph.Se...
cdc62d444cd22a8ff4c1b99382ffcc35a0ab33a6
3,638,522
def const_bool(value): """Create an expression representing the given boolean value. If value is not a boolean, it is converted to a boolean. So, for instance, const_bool(1) is equivalent to const_bool(True). """ return ['constant', 'bool', ['{0}'.format(1 if value else 0)]]
d11d01f94b8ad20d393a39a28dbfd18cc8fa217e
3,638,523
import struct def long_to_bytes(n, blocksize=0): """Convert an integer to a byte string. In Python 3.2+, use the native method instead:: >>> n.to_bytes(blocksize, 'big') For instance:: >>> n = 80 >>> n.to_bytes(2, 'big') b'\x00P' If the optional :data:`blocksize` i...
1157a466ce9754c12e01f7512e879cc28a2a4b23
3,638,524
def vector_matrix_mul(v, M): """ returns the product of vector v and matrix M Consider using brackets notation v[...] in your procedure to access entries of the input vector. This avoids some sparsity bugs. """ assert M.D[0] == v.D res = {k: 0 for k in M.D[1]} for i, j in M.f: ...
cd2751850f17b2a71aba906b9525cca91d0ddb82
3,638,525
def peek(library, session, address, width): """Read an 8, 16 or 32-bit value from the specified address. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :param address: Source address to read the value. :param width: Number of bits to read...
6203a516f5a67daa67ec0f37c0e3a8818515f2de
3,638,526
import pkg_resources import textwrap import os import io def create_text_image(text, image_export=False, **kwargs): """ Create a jpg with given text and return in bytes format """ text_canvas_w = 720 text_canvas_h = 744 text_canvas_bg = 'white' text_canvas_fg = 'black' text_canvas_font...
1cff45768f43c0c1737f599c38c377ae0366534b
3,638,527
def mtf_from_psf(psf, dx=None): """Compute the MTF from a given PSF. Parameters ---------- psf : `prysm.RichData` or `numpy.ndarray` object with data property having 2D data containing the psf, or the array itself dx : `float` sample spacing of the data Returns ----...
fb009d3068c67447d2f10c3448e91b258a0d7ca3
3,638,528
def check_intersection(vertical_line: Line, other_line: Line) -> bool: """ Check for intersection between two line segments. :param vertical_line: The first line segment. Guaranteed to be vertical. :param other_line: The second line segment. :return: Whether or not they intersect. """ intersection = get...
7e9279ea5976b99c9edb36ae5c59bcc69d22aa59
3,638,529
from krun.scheduler import ManifestManager from krun.platform import detect_platform def get_session_info(config): """Gets information about the session (for --info) Overwrites any existing manifest file. Separated from print_session_info for ease of testing""" platform = detect_platform(None, conf...
25729c3838fc7b600600dd74da44a3be9fd7b46d
3,638,530
def rotate(x, y, a): """Rotate vector (x, y) by an angle a.""" return x * np.cos(a) + y * np.sin(a), -x * np.sin(a) + y * np.cos(a)
2858539f3de5c15072657af5f39231f8e7867b6b
3,638,531
def filt_all(list_, func): """Like filter but reverse arguments and returns list""" return [i for i in list_ if func(i)]
72010b483cab3ae95d49b55ca6a70b0838b0a34d
3,638,532
def auth_user_logout(payload, override_authdb_path=None, raiseonfail=False, config=None): """Logs out a user. Deletes the session token from the session store. On the next request (redirect from POST /auth/logout to GET /), the frontend will is...
1f468a53f82a58f8c5c3f5397d6f026276a93f05
3,638,533
def rx_observer(on_next: NextHandler, on_error: ErrorHandler = default_error, on_completed: CompleteHandler = default_on_completed) -> Observer: """Return an observer. The underlying implementation use an named tuple. Args: on_next (NextHandler): on_next handler which process items on_erro...
2ebfd3c6b4e5ed854fdc89e76ac006fddd20ad0b
3,638,534
def _rav_setval_ ( self , value ) : """Assign the valeu for the variable >>> var = ... >>> var.value = 10 """ value = float ( value ) self.setVal ( value ) return self.getVal()
80ad7ddec68d5c97f72ed63dd6ba4a1101de99cb
3,638,535
import scipy def import_matrix_as_anndata(matrix_path, barcodes_path, genes_path): """Import a matrix as an Anndata object. :param matrix_path: path to the matrix ec file :type matrix_path: str :param barcodes_path: path to the barcodes txt file :type barcodes_path: str :param genes_path: pat...
83f5ccdaa945f26451ab2834c832e0e1ea58ce89
3,638,536
import torch import tqdm def get_representations(dataset, pretrained_model, alphabet, batch_size=128): """Returns: N x 1280 numpy array""" device = torch.device("cuda" if torch.cuda.is_available() else "cpu") pretrained_model = pretrained_model.to(device) dataloader = DataLoader( dataset, bat...
7a199156810b787ae7fb8ea059ebe69b6de70250
3,638,537
def rem_hap_cands(): """json endpoint to set a sample or set of sample's haplotype candidate designation to false""" form = flask.request.form samples = form['samples'] return mds.remove_hap_cands(samples)
ca22c2af4b6079f3b03accb3b414d553da75e1e3
3,638,538
from pathlib import Path def construct_subdirExample(str_dirname): """ Método auxiliar para utilizarmos nosso exemplo. Constrói um conjunto de Diretórios e arquivos para serem testados. DirOrigem/ | ├── dir01 │   ├── arq01.dat │   ├── arq02.dat ...
e06c900f16ab5e27df6cb269ad2ed8a6da17f62e
3,638,539
import json import pandas as pd from urllib.request import urlopen import os def geojson_to_df(in_geojson, encoding="utf-8", drop_geometry=True): """Converts a GeoJSON object to a pandas DataFrame. Args: in_geojson (str | dict): The input GeoJSON file or dict. encoding (str, optional): The en...
242230d241af9a6e87de52664dc60754eab10fae
3,638,540
def UndistortImage(image,image_size,\ image_rotation=None,image_center=None,\ out_xs=None,out_ys=None,\ direction='fwd',regenerate_grids=True,\ **kwargs): """Remember the recipe for fixin gwyddion image orientation: `image0=image0.T[:,:...
12cc1e1e428b8a860b0b29a6b81169cb6c1dc73d
3,638,541
def quartic_oscillator(grids, k=1.): """Potential of quantum quartic oscillator. Args: grids: numpy array of grid points for evaluating 1d potential. (num_grids,) k: strength constant for potential. Returns: vp: Potential on grid. (num_grid,) """ vp = 0.5 * k * gr...
c4a386816cd85e24080d62365d2bcd25b6735d5f
3,638,542
def compute_row_similarities(A): """ Compute pairwise similarities between the rows of a binary sparse matrix. Parameters ---------- A: scipy csr_matrix, shape (rows, cols) Binary matrix. Returns ------- sim: numpy array, shape (rows, rows) Pairwise column similarities....
96ab44ec15f94bf666da248100a98f282119caf1
3,638,543
def sha9(R, S): """Shape functions for a 4-noded quad element Parameters ---------- x : float x coordinate for a point within the element. y : float y coordinate for a point within the element. Returns ------- N : Numpy array Array of interpolation functions. Exa...
ba34cde6b5673853d34b9e074e2fbc05dc845aa5
3,638,544
def padding(seq, size, mode): """ Parameters ---------- seq: np.array The sequence to be padded. mode: str Select padding mode among {"zero", "repeat"}. Returns ------- seq: np.ndarray """ if mode == "zero": seq = np.array(trimmer(seq, size, fille...
3a0a070f784a355ead8439ff63f09918fa401014
3,638,545
def get_dense_span_ends_from_starts(dense_span_starts, dense_span_ends): """For every mention start positions finds the corresponding end position.""" seq_len = tf.shape(dense_span_starts)[0] start_pos = tf.cast(tf.where(tf.equal(dense_span_starts, 1)), tf.int32) end_pos = tf...
d825ed109b6055ca84adf46f6e5fd91cb5dd513a
3,638,546
def bb_to_plt_plot(x, y, w, h): """ Converts a bounding box to parameters for a plt.plot([..], [..]) for actual plotting with pyplot """ X = [x, x, x+w, x+w, x] Y = [y, y+h, y+h, y, y] return X, Y
10ea3d381969b7d30defdfdbbac0a8d58d06d4d4
3,638,547
def handler404(request, *args): """ Renders 404 page. :param request: the request object used :type request: HttpRequest """ return render(request, '404.html', status=404)
2ae6e036bb56b46ee16a4c0bec4182ba999f14ed
3,638,548
def merge_dimensions(z, axis, sizes): """Merge dimensions of a tensor into one dimension. This operation is the opposite of :func:`split_dimension`. Args: z (tensor): Tensor to merge. axis (int): Axis to merge into. sizes (iterable[int]): Sizes of dimensions to merge. Returns: ...
5ef62cd90ebf5bd9276f334a65a7a9075f5d3710
3,638,549
import collections import re def get_assignment_map_replaced(init_ckpt, name_replacement_dict={}, list_vars=None): """ name_replacement_dict = { old_name_str_chunk: new_name_str_chunk } """ if list_vars is None: list_vars = tf.global_...
fd7df6630f84bde9caf747540c05729b8898ffa0
3,638,550
def RULE110(): """RULE 110 celular automata node. .. code:: 000 : 0 001 : 1 010 : 1 011 : 1 100 : 0 101 : 1 110 : 1 111 : 0 """ return BooleanNode.from_output_list(outputs=[0,1,1,1,0,1,1,0], name="RULE 110")
3c79a7b6c25f031fdeac4a86f2afc770ad71ea23
3,638,551
def search_cut(sentence): """ HMM的切割方式 :param sentence: :return: """ return jieba.lcut_for_search(sentence)
7ee0f7eb1a16cd24920b98e38387b2c9b576990f
3,638,552
from typing import Counter def count_items(column_list:list): """ Contar os tipos (valores) e a quantidade de items de uma lista informada args: column_list (list): Lista de dados de diferentes tipos de valores return: Retorna dois valores, uma lista de tipos (list) e...
06cf25aed4d0de17fa8fb11303c9284355669cf5
3,638,553
import cloudpickle def py_call(obj, inputs=(), direct_args=()): """Create a task that calls Python code Example: >>> def hello(x): return b"Hello " + x.read() >>> a = tasks.const("Loom") >>> b = tasks.py_call((a,), hello) >>> client.submit(b) b'Hello Loom' """ task = ...
f89a5876fcf9b4c192f2b7c6d1362bf5a97e399c
3,638,554
def to_graph(grid): """ Build adjacency list representation of graph Land cells in grid are connected if they are vertically or horizontally adjacent """ adj_list = {} n_rows = len(grid) n_cols = len(grid[0]) land_val = "1" for i in range(n_rows): for j in range(n_cols): ...
ebdd0406b123a636a9d380391ef4c13220e2dabd
3,638,555
def validate_doc(doc): """ Check to see if the given document is a valid dictionary, that is, that it contains a single definition list. """ return len(doc.content) == 1 and \ isinstance(doc.content[0], pf.DefinitionList)
c60799ebbdaa7ec2e3a7e6607853ff021a40ed17
3,638,556
def is_renderable(obj, quiet=True): """ Checks if object is renderable Args: obj (unicode): Name of object to verify quiet (bool): If the function should keep quiet (default=True) Returns: (bool) if its renderable or not """ # unit test # make sure we are not working ...
7e0b402fc8634d96717209274dc5c69a32da395d
3,638,557
import traceback import traceback import traceback from datetime import datetime import requests import io import operator import csv import re def _refresh_database(bot, force=False, prune=True, callback=None, background=False, db=None): """ Actual implementation of refresh_database. Refreshes the datab...
ae88cbe622accfd6deb9056dd7fe33dbca19fa11
3,638,558
def V_bandpass(V, R_S, C, L, R_L, f): """ filter output voltage input voltage minus the current times the source impedance """ # current in circuit I = V/(R_S + Z_bandpass(C, L, R_L, f)) # voltage across circuit V_out = V - I*R_S return V_out
c21c54e7065a32531dca417eb7e50ea63db820d8
3,638,559
import os def get_server_url(): """ Return current server url, does not work in a task """ host = os.environ.get('HTTP_X_FORWARDED_HOST') or os.environ['HTTP_HOST'] return u'%s://%s' % (os.environ['wsgi.url_scheme'], host)
c71f2244b8dd023b11a6db0aee885d4d332f3a7c
3,638,560
from admiral.celery import celery def celery(): """Celery app test fixture.""" return celery
69f672e1c6a568e14a4ad9f5df723b454a346b03
3,638,561
def perm_cache(func): """ 根据用户+请求参数,把权限验证结果结果进行缓存 """ def _deco(self, request, view): # 只对查询(GET方法)进行权限缓存 if request.method != "GET": return func(self, request, view) user = request.user.username kwargs = "_".join("{}:{}".format(_k, _w) for _k, _w in list(vi...
4ca53057b12efb15dddb422b3aaaddd11898f4bd
3,638,562
def ast_walker(handler): """ A generic AST walker decorator. Decorates either a function or a class (if dispatching based on node type is required). ``handler`` will be wrapped in a :py:class:`~peval.Dispatcher` instance; see :py:class:`~peval.Dispatcher` for the details of the required class struct...
978e6718d81663914017af89cf41101ca68dd2bb
3,638,563
def html_escape(text): """Produce entities within text.""" L=[] for c in text: L.append(html_escape_table.get(c,c)) return "".join(L)
de73c127de8b6338c5db5c9ba7d1f5ebbd6d23a9
3,638,564
def qs_without_parameter(arg1, arg2): """ Removes an argument from the get URL. Use: {{ request|url_without_parameter:'page' }} Args: arg1: request arg2: parameter to remove """ parameters = {} for key, value in arg1.items(): if parameters.get(key, None) is ...
649931de5490621c92513877b21cb8cfce8d66ff
3,638,565
def find_power_graph(I, J, w_intersect=10, w_difference=1): """takes a graph with edges I,J, and returns a power graph with routing edges Ir,Jr and power edges Ip,Jp. Note that this treats the graph as undirected, and will internally convert edges to be undirected if not already.""" n = int(max(max(...
9e682eebd9664863d80689f0aa718f30e3ad611a
3,638,566
import string def getcomments(pyObject): """Get lines of comments immediately preceding an object's source code. Returns None when source can't be found. """ try: lines, lnum = findsource(pyObject) except (IOError, TypeError): return None if ismodule(pyObject): # Look...
f58421f176b42ecb2e1e883f48deb31025b13559
3,638,567
import time import requests import io def crack_captcha(headers): """ 破解验证码,完整的演示流程 :return: """ currentTime = str(int(time.time())*1000) # 向指定的url请求验证码图片 rand_captcha_url = 'http://59.49.77.231:81/getcode.asp?t=' + currentTime res = requests.get(rand_captcha_url, stream=True,headers=h...
538843289a64dde1229f7df0a260632fbbd557b6
3,638,568
from . import sill from clawpack.pyclaw.util import check_diff import numpy as np from clawpack.pyclaw.util import gen_variants from itertools import chain def test_2d_sill(): """test_2d_sill Tests against expected classic solution of shallow water equations over a sill.""" def verify_expected(expe...
5d37c3ad21d842c3f03d1b464609f94ee86e1496
3,638,569
def draw_box( canvas, layout, box_width=None, box_alpha=0, color_map=None, show_element_id=False, show_element_type=False, id_font_size=None, id_font_path=None, id_text_color=None, id_text_background_color=None, id_text_background_alpha=1, ): """Draw the layout region...
9d8ca19a35e91c6e8670aed05c2e61b2c89958c5
3,638,570
def login(request): """Home view, displays login mechanism""" return render(request, 'duck/login.html')
5d4474d4ce7bb8f7327e1a005fe9e485d8784ec7
3,638,571
def make_user_role_table(table_name='user', id_column_name='id'): """ Create the user-role association table so that it correctly references your own UserMixin subclass. """ return db.Table('fp_user_role', db.Column( 'user_id', db.Integer, ...
8e7570590686e78d2bf7f91ba3b16f14f4c42620
3,638,572
import re def _remove_comments_inline(text): """Removes the comments from the string 'text'.""" if 'auto-ignore' in text: return text if text.lstrip(' ').lstrip('\t').startswith('%'): return '' match = re.search(r'(?<!\\)%', text) if match: return text[:match.end()] + '\n' else: return tex...
463e29e1237a88e91c13a58ffea1b2ccdafd4a1d
3,638,573
def wide_to_tall(df: pd.DataFrame) -> pd.DataFrame: """Convert a wide table to a tall table Args: df (pd.DataFrame): wide table Returns: pd.DataFrame: tall table """ return df.unstack().dropna().reset_index()
50ab71d18f5fb1e4dba9207b71030c7f8ffdbcde
3,638,574
def is_pj_player_plus(value): """ :param value: The value to be checked :type value: Any :return: whether or not the value is a PJ Player+ :rtype: bool """ return isinstance(value, list) and len(value) == 4 or len(value) == 3
1c4e7a7513d746d25f6b3d7964455b0735c988fc
3,638,575
def pd_fuzz_partial_token_sort_ratio(col1, col2): """ Calculate "partial token sort" ratio (`fuzz.partial_token_sort_ratio`) between two text columns. Args: col1 (Spark Column): 1st text column col2 (Spark Column): 2nd text column Returns: Spark Column (IntegerType): result of `fuz...
d650d37d5936751f961260d98210e2d219200fe6
3,638,576
def looterCanReinforce(mine: Game) -> bool: """ Return True if, in the given game, the looter (the attack) can reinforce at this moment, regardless of whether its the first or the second time """ return getLooterReinforcementStatus(mine) != 0
e73fb193cc1c621766900c1f484db90e4e21decb
3,638,577
def _get_normed_sym_np(X_, _eps=DEFAULT_EPS): """ Compute the normalized and symmetrized probability matrix from relative probabilities X_, where X_ is a numpy array Parameters ---------- X_ : 2-d array_like (N, N) asymmetric probabilities. For instance, X_(i, j) = P(i|j) Returns ...
a6f5762a5bf41c83bd017d0661cc069f17bee618
3,638,578
def load_encoding_model(): """Model to encode image as vector of length 4096 using 2nd to last layer of VGG16""" base_model = VGG16(weights='imagenet', include_top=True) encoding_model = Model(inputs=base_model.input, outputs=base_model.get_layer('fc2').output) return enc...
b15f9d9b6d360a71db0fcb7fc0fa83c031f34047
3,638,579
import math def get_geohash_radius_approximation(latitude, longitude, radius, precision, georaptor_flag=False, minlevel=1, maxlevel=12): """ Get the list of geohashed that approximate a circle :param latitude: Float the longitude to get the radius approximation for :param longitude: Float the latitud...
cf8bbc4a8323b796c4f325f4f3ab9f8e3a169fa8
3,638,580
def manage_products(request, category_id, template_name="manage/category/products.html"): """ """ category = Category.objects.get(pk=category_id) inline = products_inline(request, category_id, True) # amount options amount_options = [] for value in (10, 25, 50, 100): amount_options....
4ece15c50e00198c422dbb452622dde938f2a9e6
3,638,581
def random_indices(X, size=None, p=None, sort_indices=True, **kwargs): """ Get indices for a random subset of the data. Parameters ---------- size: int * integer size to sample (required if p=None) p: float * threshold percentage to keep (required if size=None) Returns -...
680be93345ab5e3065a43fda5216a4ca8b986121
3,638,582
def get_facts(F5, uri): """ Issue a GET of the URI specified to the F5 appliance and return the result as facts. If the URI must have a slash as the first character, add it if missing In Ansible 2.2 found name clashing http://stackoverflow.com/questions/40281706/cant-read-custom-fa...
554cc7b9bf35d631c8742614142f5aa2ecaba9b4
3,638,583
from typing import Optional from typing import Sequence def parse_args(args: Optional[Sequence[str]] = None) -> Namespace: """ Parses args and validates the consistency of origin/target using the generator """ parser = ArgumentParser( prog="python -m luh3417.transfer", description...
475318fc9999b7b259a073e53b3b24d5ea46911a
3,638,584
def parse_papers_plus_json(data): """ Function which parses the papers_plus json and returns a pandas dataframe of the results. Solr Field definition shown below: <!-- Citing paper fields: papers, metadata, arxiv_metadata --> <!-- Papers --> <field name="sentencenum" type="pint" indexed="true" ...
44c7a27701e265a841e07f49741f03e4b49d4b95
3,638,585
from pathlib import Path from typing import Optional def get_credential(config_file: Path, credential_key: str = 'api_key') -> Optional[str]: """ Get a single credential from yaml file. Usual case is 'api_key' :param config_file: :param credential_key: :return: """ config = load_credential...
a3e5182c4b2e3fed777f6bd52e144a6d49e4f48f
3,638,586
import functools def authenticate_secondarily(endpoint): """Proper authentication for function views.""" @functools.wraps(endpoint) def wrapper(request: HttpRequest): if not request.user.is_authenticated: try: auth_result = PersonalAPIKeyAuthentication.authenticate(req...
ac7a5b63c2b556e1bb42986db8110a922485b96d
3,638,587
def gather_emails_GUIDs(mailbox, search, folder): """ Download GUID of messages passing search requirements """ mailbox.folder.set(folder) return (email for email in mailbox.uids(search))
d75ecdeaa4f95f9108276f2be236e33934d7de01
3,638,588
def pyrolite_meltsutil_datafolder(subfolder=None): """ Returns the path of the pyrolite-meltsutil data folder. Parameters ----------- subfolder : :class:`str` Subfolder within the pyrolite data folder. Returns ------- :class:`pathlib.Path` """ return get_module_datafold...
e1ae16fff0b2fcd247c57a40e4713eb0ee13f3e7
3,638,589
from typing import List def get_resource_record_set_cloud_formation_dict_list(hosted_zone: ResourceRecordSetList, with_soa: str, client: botocore.client.BaseClient, zone_id: str, ...
c7775a45763f733e2dc2392b5073f1bf18b7177c
3,638,590
import aiohttp async def make_async_request( url: str, method: str = 'GET', **kwargs) -> dict: """ Делает асинхронный запрос по указанному URL с параметрами и возвращает словарь из JSON-ответа Keyword Args: headers: Request HTTP Headers params: URI HTTP request params data...
a08fef6c9df201a9704791564c1ad75fb3f20d0d
3,638,591
def _prepare_line(edges, nodes): """prepare a plotly scatter3d line plot so that a set of disconnected edges can be drawn as a single line. `edges` are values associated with each edge (that get mapped to colors through a colorscale). `nodes` are pairs of (source, target) node indices for each edge...
be95f58a3938b628c89639d3311799eb359c19d2
3,638,592
import getpass def validate_password( password:str ) -> bool: """ Validates the password again a password policy. Args: password ( str, required ): password to verify. Returns: valid ( bool ): True if the password meets validity requirements....
eec09ad86d89184c4f87a8c0710e3af28f874429
3,638,593
from typing import Iterable from typing import List from typing import Dict from typing import Any def build_webhooks( handlers_: Iterable[handlers.WebhookHandler], *, resources: Iterable[references.Resource], name_suffix: str, client_config: reviews.WebhookClientConfig, ...
fc5ca5de1f09c40e08ea8918319b07186af2fe94
3,638,594
def ndo_real(data, n): """mimic of gmx_fio_ndo_real in gromacs""" return [data.unpack_real() for i in range(n)]
875edd4c78e591fcee1b3de30f0ed62a4d0b074d
3,638,595
from typing import Union from typing import Optional def get_field_type(field: Union[syntax.Field, syntax.Command], idl_file: syntax.IDLParsedSpec, idl_file_path: str) -> Optional[Union[syntax.Enum, syntax.Struct, syntax.Type]]: """Resolve and get field type of a field from the IDL file.""" ...
19445d7a142b940ff3cd0c445e716c070eeac489
3,638,596
import logging from datetime import datetime def query(context: models.Context, query_str: str) -> TimeSeriesCollection: """Do a monitoring query in the specified project. Note that the project can be either the project where the monitored resources are, or a workspace host project, in which case you will get ...
7d9f40ad59cb926ab5cec0013a08ea551290fc57
3,638,597
def get_status(): """get the node status and return data""" return data({})
0314331d249cebfeb63941961793fe9a72e0c329
3,638,598
import tokenize def read_orc(path, columns=None, storage_options=None, **kwargs): """Read cudf dataframe from ORC file(s). Note that this function is mostly borrowed from upstream Dask. Parameters ---------- path: str or list(str) Location of file(s), which can be a full URL with protoco...
2f26a088cd849fc21c171767a0db276844341b11
3,638,599