content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def interface_details():
"""Get interface details, CLI view"""
if success_login_form is None:
return redirect(url_for('base_blueprint.login'))
else:
return render_template('more_int_detials.html',
details=GetDetails.more_int_details(device, username, password,... | f5643644583babb92a188d04c77a59582db69b52 | 29,951 |
def complement_sequence(sequence: str, reverse: bool = False) -> str:
"""Complement the given sequence, with optional reversing.
Args:
sequence: Input sequence
reverse: Whether or not to perform reverse complementation
Returns:
Complemented (and optionally reversed) string
"""
... | 74c85857f3abf669cfaa43d05d1f0190a448bb54 | 29,952 |
def calc_llr(tree_dict: StrDict) -> int:
"""
Calculate the longest linear route for a synthetic route
:param tree_dict: the route
"""
return calc_depth(tree_dict) // 2 | 18c4cf62e434ee1e7c5902871feb323c1b72a96d | 29,953 |
def _GetArmVersion(arch):
"""Returns arm_version for the GN build with the given architecture."""
if arch == 'armeabi':
return 6
elif arch == 'armeabi-v7a':
return 7
elif arch in ['arm64-v8a', 'x86', 'x86_64']:
return None
else:
raise Exception('Unknown arch: ' + arch... | fbad0d1066fe4a7e81d2341291b436f5dd98fff0 | 29,954 |
def package_copy(r, id, type, revision_number=None, version_name=None):
"""
Copy package - create a duplicate of the Package, set author as current user
"""
revision = get_package_revision(id, type, revision_number, version_name)
""" it may be useful to copy your own package ...
if r.user.pk == revision.author.pk... | 8f244a6e8b1309b8b129f316698047b6c78f0186 | 29,955 |
def contract(equation, *operands, **kwargs):
"""
Wrapper around :func:`opt_einsum.contract` that caches contraction paths.
:param bool cache_path: whether to cache the contraction path.
Defaults to True.
"""
backend = kwargs.pop('backend', 'numpy')
cache_path = kwargs.pop('cache_path', ... | c7ac17fcee8eef036181e0ee2a96d0b0d4a38593 | 29,956 |
import array
def _compute_jn_pcoa_avg_ranges(jn_flipped_matrices, method):
"""Computes PCoA average and ranges for jackknife plotting
returns 1) an array of jn_averages
2) an array of upper values of the ranges
3) an array of lower values for the ranges
method: the method by whi... | bba0003df771b60a55b11b67a7df7cb36039d69f | 29,957 |
from typing import List
def get_readmission_label_keys(time_windows: List[int]) -> List[str]:
"""Get label keys for readmission.
Args:
time_windows: list<int> of the considered time windows (in days) for
readmission.
Returns:
list<str> of labels for readmission within X days
"""
... | 1ba53ef818aadb719832d23afb250fb817b1e087 | 29,958 |
def multiplication(image1, image2):
""" Multiply (pixel-wise) the two input images and return the result.
<gui>
<item name="image1" type="Image" label="Image 1"/>
<item name="image2" type="Image" label="Image 2"/>
<item name="result" type="Image" role="return"
... | 2813758eba743155960d617eb03aafa937a4cfc0 | 29,960 |
def ioat_scan_accel_engine(client, pci_whitelist):
"""Scan and enable IOAT accel engine.
Args:
pci_whitelist: Python list of PCI addresses in
domain:bus:device.function format or
domain.bus.device.function format
"""
params = {}
if pci_whitelist... | 714e40288b2ba141d113c0951bf2c171ebcc76d3 | 29,961 |
import zipfile
import csv
def load_test(tstfile):
"""Load a test from file.
This reads a test from a csv file.
Parameters
----------
tstfile : :class:`str`
Path to the file
"""
# default version string
version_string = "1.0.0"
try:
with zipfile.ZipFile(tstfile, "r... | c8b4e7f2dfc7e627afd1ae58a64723a4deed8248 | 29,962 |
def reorder_instruments(curr_instruments):
"""
Dialog to remove and add instruments at certain indexes.
:param curr_instruments: initial list of instruments
:return: The list of instruments in the new order
"""
while True:
instruments_with_indexes(curr_instruments)
tmp_instrument... | 03c042e086d99c9e5ab52c37a2272af82411c777 | 29,963 |
def compute_propeller_with_normal_position(arg_class, cabin_arr):
"""
compute propeller array and connected arm array
:param cabin_arr: numpy array of cabin
:param arg_class: argument class
:return: propeller_arr, arm_arr
"""
l1 = arg_class.l1
l2 = arg_class.l2
l3 = arg_class.l3
... | c58aa5939f1b4fef05c9bfa09781310a9b64ab52 | 29,964 |
def get_dims_linear(weight_mat_layers, weight_dict):
"""
Returns a list of dimensions of layers of an mlp in decreasing order.
"""
dims = []
for ix, layer in enumerate(weight_mat_layers):
dim_out, dim_in = weight_dict[layer].shape
if ix == 0:
dims.extend([dim_in, dim_out... | eba82695a5c3bd1f850703b172e1f0a7b84fa010 | 29,965 |
def yices_distinct(n, arg):
"""Returns (distinct arg[0] ... arg[n-1])."""
return libyices.yices_distinct(n, arg) | 7d37cf6a2193cb4bb0d1d46f4f9986afbe35ad50 | 29,966 |
def is_cog_contributor():
"""Check if whoever used the command is in the bots contributors."""
async def predicate(ctx):
if str(ctx.author.id) in ctx.bot.contributors:
return True
else:
raise NotAContributorError(f"Command {ctx.command.name} raised an error: {str(ctx.aut... | d0a7d8096f03ce1bbeed2e6c6265c46d0ae1022a | 29,967 |
def tuplify2d(x):
"""Convert ``x`` to a tuple of length two.
It performs the following conversion:
.. code-block:: python
x => x if isinstance(x, tuple) and len(x) == 2
x => (x, x) if not isinstance(x, tuple)
Args:
x (any): the object to be converted
Returns:
tupl... | 64170b14dbe7eb8885d21f45acff6b43979f1219 | 29,968 |
def init_mako(app, **kw):
"""
Initializes the Mako TemplateLookup based on the application configuration
and updates the _request_ctx_stack before each request
"""
def get_first(dicts, keys, default=None):
# look in one or more dictionaries returning the first found value
for d ... | 60713b06cde3be9eca72207aea69a30d9061cffc | 29,970 |
import time
def erase_devices():
"""Erase all the drives on this server.
This method performs sanitize erase on all the supported physical drives
in this server. This erase cannot be performed on logical drives.
:returns: a dictionary of controllers with drives and the erase status.
:raises exce... | 5f9a7a2328b24cb0fb45ea560f570b596c0326d7 | 29,971 |
def earlyon(time,duration,*args):
"""
Some lights have a slight delay before they turn on (capacitors that need
to be charged up?). This takes the current time and subtracts that delay
so the code looks like they turn on at the right time, but we really send
the command a little bit early to give th... | 5671d46ffe42bd456689cffc3ce3e1f6731101c8 | 29,972 |
def downsample_seg_to_mip(seg, mip_start, mip_end):
"""
Downsample a segmentation to the desired mip level.
Args:
seg (3darray): A volume segmentation.
mip_start (int): The MIP level of seg.
mip_end (int): The desired MIP level.
Returns:
3darray: seg downsampled to :par... | 9245c6f1b0602f284a7d565758e322af083e6242 | 29,973 |
def example(name):
"""Renders a sample page with the name specified in the URL."""
return template('<b>Hello {{name}}</b>!', name=name) | df52c3ed0708698d7049223b5ea1b7d98f8c3eb7 | 29,974 |
def tri(N, M=None, k=0, dtype=float):
"""Creates an array with ones at and below the given diagonal.
Args:
N (int): Number of rows.
M (int): Number of columns. ``M == N`` by default.
k (int): The sub-diagonal at and below which the array is filled. Zero
is the main diagonal,... | e7de7d0bc41563450d7e98071a14ca3b85f250c5 | 29,975 |
def UpdateGClientBranch(webkit_rev, magic_gclient_branch):
"""Update the magic gclient branch to point at |webkit_rev|.
Returns: true if the branch didn't need changes."""
target = FindSVNRev(webkit_rev)
if not target:
print "r%s not available; fetching." % webkit_rev
subprocess.check_call(['git', 'fet... | 52de6ec5139052de914d29d44b926938227894db | 29,976 |
def calculate_trajectories(particles, daughters, alpha=1.):
"""Calculates the trajectories of the particles.
Args:
particles: a dataframe with the particle information.
daughters: a dataframe where each line represents a daughter for the particles.
alpha: for how long should stable trac... | fb9422ac315dc1c2b6e6781cfef93e8235dd7f2d | 29,978 |
def site_title(request, registry, settings):
"""Expose website name from ``tm.site_title`` config variable to templates.
This is the default ``<title>`` tag.
Example:
.. code-block:: html+jinja
<meta>
<title>My page - {{ site_title }}</title>
</meta>
"""
# Use .g... | fcc61acecabb163ef6e55ed2fde7d4d025a8082a | 29,979 |
import typing
from pathlib import Path
import importlib
import inspect
import ast
def linkcode_resolve(repo_link: str, domain: str, info: dict[str, str]) -> typing.Optional[str]:
"""
Function called by linkcode to get the URL for a given resource.
See for more details:
https://www.sphinx-doc.org/en/m... | 1fd4571b81f98c82c57dae43a2be957380dca91f | 29,980 |
def deterministic_hash(items):
"""
Intermediary hashing function that allows deterministic hashing of a list of items.
:param items: List of items to hash
:return: Numeric, deterministic hash, returns 0 if item is none
"""
h = 0
for item in items:
if not item:
pass
... | da3950039762e2b499f522cbd891a87d98633bd9 | 29,982 |
def fetch_known_transcripts_with_gene_label(cursor, datasets):
""" Fetch known transcripts along with the gene they belong to """
datasets = format_for_IN(datasets)
query = """SELECT DISTINCT gene_ID,transcript_ID FROM observed
LEFT JOIN transcript_annotations AS ta ON ta.ID = observed.t... | 92dbd97ee79672ff0986c2caecf90ab95f05fa70 | 29,985 |
def change_data():
"""Редактирование профиля пользователя."""
form = ChangeDataForm()
if form.validate_on_submit():
current_user.age = form.age.data
current_user.country = form.country.data
current_user.city = form.city.data
current_user.telegram = form.telegram.data
... | 6dc8299a07733fe7291d1c8b646848f6e1b60c60 | 29,986 |
from io import StringIO
def run_checks(root, parent, cmds, scmds, paths='', opts={}):
"""Run the checks given in 'cmds', expected to have well-known signatures,
and report results for any which fail.
Return failure if any of them did.
NB: the function name of the commands passed in is used to name t... | bde53f0f0fca0b6d12f6cf58b631cc841a0d567f | 29,988 |
def numpy_to_rdkit(adj, nf, ef, sanitize=False):
"""
Converts a molecule from numpy to RDKit format.
:param adj: binary numpy array of shape (N, N)
:param nf: numpy array of shape (N, F)
:param ef: numpy array of shape (N, N, S)
:param sanitize: whether to sanitize the molecule after conversion... | 93295c556037ffa3e84373b73ca1308a9a1d53b7 | 29,989 |
from typing import Dict
from typing import Any
from pathlib import Path
def get_path(key: str, **kwargs: Dict[str, Any]) -> Path:
"""Get a file path string system variable as a pathlib.Path instance.
See signature of get() for parameter details."""
return Path(get(key, **kwargs)) | 9fe34573ced90c266ef7b73a430cc95ba4d09bc5 | 29,990 |
def get_reduced_tree(tree, reduce_by):
"""
Given a tree decomposition in tree and a required
size of reduction, produces a new tree decomposition
with treewidth reduced by the requested size and a list
of eliminated nodes.
We use a greedy algorithm to find nodes to eliminate.
This algorithm ... | a644ae326ef86e9b53bb3c3c510e46740038c8d3 | 29,992 |
from pathlib import Path
def temp_path(suffix=""):
"""Return the path of a temporary directory."""
directory = mkdtemp(suffix=suffix)
return Path(directory) | 2cd196a2a1974816d49d75fd10a0d43b03c12612 | 29,993 |
def maybe_utf8(value):
"""Encode to utf-8, only if the value is Unicode."""
if isinstance(value, unicode):
return value.encode("utf-8")
return value | 82e15ef35527e064a2b5bf3934c135985d60e1fe | 29,994 |
def parse_id_as_interval(id_string, regex):
""" The fasta ids contain the locus information. """
match = regex.match(id_string)
genome = match.group("genome")
seqid = match.group("seqid")
start_tmp = int(match.group("start"))
end_tmp = int(match.group("end"))
start = min([start_tmp, end_tm... | 7d35bdd7b4418d1edcd433cd39b9defc9050c6f6 | 29,995 |
def map_sentences_to_indices_of_vectors(sentences, word_to_index_glove, unknown_token):
""" map senteces to integers that represent the index of each word in the glove vocabulary """
# the list to be returned
mapped_sentences = []
# get the index of the unknown token
unknown_token_index = word_to_... | 04a27bd4ccd5ac9d0366218107ee36b61d4a7655 | 29,996 |
import numpy
def jordan_wigner_dual_basis_jellium(grid, spinless=False,
include_constant=False):
"""Return the jellium Hamiltonian as QubitOperator in the dual basis.
Args:
grid (Grid): The discretization to use.
spinless (bool): Whether to use the spinles... | d52a5a102297213de830f58c8190337589d0d9ca | 29,998 |
def boxcar_decay(tbins, t0, area_box, height_box, area_decay):
"""
Compute the lightcurve from one or more boxcar-decay functions.
Parameters
----------
tbins : array
edges of the time bins used for the lightcurve
t0 : float or array
start times of the boxcar-decays
area_box... | 31beb8d6cab940bd75a814121833535819c17e69 | 29,999 |
def updateShaderState(self):
"""Updates all shader program variables. """
if not self.ready():
return
opts = self.opts
self.shader.load()
voxValXform = self.imageTexture.voxValXform
voxValXform = [voxValXform[0, 0], voxValXform[0, 3], 0, 0]
invNumLabels = 1.0 / (opts.lut.max() ... | 611b093ce51e99e5c7c1e3da5dcc7cd1a8c07b01 | 30,000 |
import _winreg
from cake.registry import queryString
def _getMinGWInstallDir():
"""Returns the MinGW install directory.
Typically: 'C:\MinGW'.
@return: The path to the MinGW install directory.
@rtype: string
@raise WindowsError: If MinGW is not installed.
"""
possibleSubKeys = [
r"SOFTW... | 262f65aaf413fe718b753ffa706c97c80b73f349 | 30,001 |
import urllib
def nextbus(a, r, c="vehicleLocations", e=0):
"""Returns the most recent latitude and
longitude of the selected bus line using
the NextBus API (nbapi)
Arguments: a=agency, r=route, c=command,
e=epoch timestamp for start date of track,
0 = the last 15 minutes
"""
nbapi = "... | 08ce12f3a1d96572014dc528de255f89e5b0ee46 | 30,002 |
def latest_blog_posts(context, num):
"""
Displays the most recent blog posts. It takes an argument, num
and displays so many posts depending on the value.
"""
latest_blog_posts = Post.objects.all()[:num].select_related()
return {
'latest_blog_posts': latest_blog_posts
} | 74ee23753e674e1dd1f8fa8af92002c739a28ee3 | 30,003 |
from typing import List
from typing import Dict
import copy
def _expand_array_paths_to_preserve(paths: List[DetailedPath]) -> Dict[str, List[int]]:
"""
Used by "filter_element_match" - Returns a dictionary of string paths mapped to array indices that we want
to preserve.
:param paths: A list of lists... | 7f44a717285bc30c3162d39dcf18a1cdc3920bed | 30,004 |
def get_request_fixture_names(request):
"""Get list of fixture names for the given FixtureRequest.
Get the internal and mutable list of fixture names in the enclosing scope of
the given request object.
Compatibility with pytest 3.0.
"""
return request._pyfuncitem._fixtureinfo.names_closure | 665fff4538f3817b6eb882f9a873683d69003bfd | 30,005 |
def _unique(values, *, return_inverse=False):
"""Helper function to find unique values with support for python objects.
Uses pure python method for object dtype, and numpy method for
all other dtypes.
Parameters
----------
values : ndarray
Values to check for unknowns.
return_inve... | 4768b0e055cfd9a42b5332f7a47aa608aa7b90c0 | 30,006 |
def _create_range_tool(
data,
min_time,
max_time,
plot_range,
width,
height,
time_column: str = None,
y: str = "y_index",
):
"""Create plot bar to act as as range selector."""
ext_min = min_time - ((max_time - min_time) * 0.15)
ext_max = max_time + ((max_time - min_time) * 0.... | 42cf2d4f5986dd454a9aa968ce4db4136b5acd1f | 30,007 |
def pivot(df, index, column, value):
"""
Pivot a dataframe. Reverse operation of melting. Useful for configuring evolution
See pandas' pivot_table documentation for more details
Args:
- index (list): indexes argument of pd.pivot_table
- column (str): column name to pivot on
- val... | b9a8c63d5ce320f4a156c8f42b92173dd1d86ca0 | 30,008 |
def split_pdf_image_into_row_image_block(pdf_image):
"""
split the whole pdf image into row image block
:param pdf_image: the whole color pdf image
:return:
"""
gray_image = cv2.cvtColor(pdf_image, cv2.COLOR_BGR2GRAY)
binarized_image = cv2.adaptiveThreshold(
src=gray_image,
m... | 9a304f54167c4fbb7739c7022b12c5b574240861 | 30,009 |
def get_tokens():
""" Get all the active tokens in the datbase."""
return query_db('select token from token') | 960c613147d3d55a3e56dcef06fc974a4c553929 | 30,010 |
def get_stats(beta0, n, sigma, lam, pen, ntrials=100, maxiter=100):
"""
run ntrials regression problems
return mean of the mse, and 95% confidence interval
"""
if pen is None:
mses = run_trials_ols(beta0, n, sigma, ntrials=ntrials)
else:
mses = run_trials(beta0, n, sigma, lam, p... | e6357f64b40eb424e295088920f5f8dcba558896 | 30,012 |
def squeeze_output_dim_0(initial_ndims, point_types):
"""Determine if the output needs to squeeze a singular dimension 0.
The dimension 0 is squeezed iff all input parameters:
- contain one sample,
- have the corresponding dimension 0 squeezed,
i.e. if all input parameters have ndim strictly less t... | 448291f75d758867e65c1693de6c40ab80a7b642 | 30,013 |
import math
def quaternion_from_matrix(matrix, isprecise=False):
"""Return quaternion from rotation matrix.
If isprecise is True, the input matrix is assumed to be a precise rotation
matrix and a faster algorithm is used.
"""
M = np.array(matrix, dtype=np.float64, copy=False)[:4, :4]
if ispre... | dcc4ee7e6b2493a96a78b7da45b6f6edb12be550 | 30,014 |
def check_version(stdout):
"""Check version of Ensembl-VEP.
Example of the first part of an output from the command `vep --help`:
#----------------------------------#
# ENSEMBL VARIANT EFFECT PREDICTOR #
#----------------------------------#
Versions:
ensembl : 104.1af1dce
... | 5c3b716db7016f1b612f764fb54e3b25d970b0f2 | 30,015 |
def tf_config():
""" Default tensorflow config. """
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
return config | fdc28c9968457af92afb18f8315e07c04890ff50 | 30,016 |
def customize_response_cros(data):
"""定制跨域响应体"""
response = make_response(jsonify(data))
# 设置响应请求头
response.headers["Access-Control-Allow-Origin"] = '*' # 允许使用响应数据的域。也可以利用请求header中的host字段做一个过滤器。
response.headers["Access-Control-Allow-Methods"] = 'POST' # 允许的请求方法
response.headers["Access-Contro... | c702644bc9faae45057263a207e42e110d125165 | 30,019 |
def shortdateformat(value, default_value=None):
"""
Example value: datetime.strptime("2018-07-25 10:15:00", "%Y-%m-%d %H:%M:%S")
Example output: '25 July'
"shortdateformat" was designed for use in summary tables where space is tight and dates are shown on their own line.
The original intended use w... | 31ce7fa824df3d746d5e81e960864fabb1329307 | 30,020 |
def build_suffix_array(text):
"""
Build suffix array of the string text and
return a list result of the same length as the text
such that the value result[i] is the index (0-based)
in text where the i-th lexicographically smallest
suffix of text starts.
"""
order = sort_characters(text)
... | 05eb036cb749e030d84bb2d494a447faa7f93e6c | 30,021 |
from mne.utils import _time_mask
def compute_auc(dip, tmin=-np.inf, tmax=np.inf):
"""Compute the AUC values for a DipoleFixed object."""
if not isinstance(dip, DipoleFixed):
raise TypeError('dip must be a DipoleFixed, got "%s"' % (type(dip),))
pick = pick_types(dip.info, meg=False, dipole=True)
... | cedfeb7934ee86e6c1ae702ba0cbecceb83c90db | 30,023 |
def left_join(ht1, ht2):
"""
:param ht1: left hash table
:param ht2: right hash table
:return: list of joined values from both hash tables
"""
results = []
for item in ht1.table:
while item is not None:
key = item.val[0]
joined = [key, ht1.get(key), ht2.get(k... | 8f34e03d055a32ea337b27cd800eeb393d136dfa | 30,024 |
from typing import Tuple
import torch
import re
def load_pretrained_cifar10_model(
path: str, resnet_size: int = 32,
) -> Tuple[nn.Module, DifferentiableNormalize]:
"""
Loads a pretrained CIFAR-10 ResNet from the given path along with its
associated normalizer.
"""
model: nn.Module = getattr(ci... | 2d1a907b2d90459661bdd0e578828ac0949d68e3 | 30,025 |
import logging
def create_project(**kwargs): # noqa: E501
"""Creates a project with an original network file.
Creates a project with an original network file. # noqa: E501
:param designation:
:type designation: str
:param description:
:type description: str
:param network_designation:
... | c57951358383b18f35fdf9c6ca899f09979565ae | 30,027 |
def _get_boto_client(cluster, access_key, secret_key):
"""
Returns a boto client object that can be used to communicate with the Object
Storage cluster.
"""
client = boto.connect_s3(aws_access_key_id=access_key,
aws_secret_access_key=secret_key,
... | 4351e74610948c17c8c35ae86a5fa1ca15f4158f | 30,028 |
def triangleArea(a: Vec3, b: Vec3, c: Vec3) -> float:
"""
Calculate area of triangle
:return: area
"""
return cross3(b - a, c - a).length() / 2.0 | ad5c73e07421c01f3db3a9d4592ec218307c8a80 | 30,029 |
async def read_object_name(app, device_id, addr):
"""
Execute a single request using `ReadPropertyRequest`.
This will read the `objectName` property of a remote device.
:param app: An app instance
:param device_id: BACnet device id (integer number)
:param addr: The network address of the remote ... | 3e9e023be615911ca0f43ff2a0aec62cec695d25 | 30,030 |
import requests
from bs4 import BeautifulSoup
def jws_omex_dict():
""" Returns dictionary of available JWS combine archives.
:return: { id: download_url } dict
"""
jws_omex = {}
num_omex = 0
for page_iter in range(NUM_PAGES):
url = URL.format(page_iter+1) # 1 based counting
p... | 21e378038bbce07a166d315a183a08ce69f9a544 | 30,031 |
def ztrsv(A,
x,
Uplo=CblasLower,
TransA=CblasNoTrans,
Diag=CblasNonUnit):
"""
returns x'
This function computes inv(op(A)) x for x, where op(A) = A, A^T, A^H
for TransA = CblasNoTrans, CblasTrans, CblasConjTrans. When Uplo is
CblasUpper then the upper triangl... | 11b3420e09718fabc907b484142b67ce4f828c4f | 30,032 |
def get_trainable_vars(name=None):
"""Return the trainable variables.
Parameters
----------
name : str
the scope
Returns
-------
list of tf.Variable
trainable variables
"""
return tf.compat.v1.get_collection(
tf.compat.v1.GraphKeys.TRAINABLE_VARIABLES, scope... | 3c5b005613a7a6f0cd0420e60337ed7bf88bf92f | 30,033 |
def player_to_string(game: reversi.ReversiGame, player_colour: str, player: ai_players.Player) \
-> str:
""" Returns the string representation of the type of the player.
Preconditions:
- player_colour in {'white', 'black'}
"""
if game.get_human_player() == 1 and player_colour == 'black'... | a1e6dfe184d471616fac7a1ab1bbb2d959c5457c | 30,034 |
from typing import Any
def encode_pd_timestamp(v: pd.Timestamp) -> Any:
"""
Specializes :func:`encode` for invocations where ``v`` is an instance of
the :class:`~pandas.Timestamp` class.
"""
return {
"__kind__": kind_inst,
"class": "pandas.Timestamp",
"args": encode([str(v)... | fec08229d2a9b8f7115986e4c97677b401200adf | 30,035 |
async def getWebUserAmount(cls:"WebIndex", where:str="1=1", values:tuple=()) -> int:
""" simply gives a number of all matched user """
res:list = cls.Web.BASE.PhaazeDB.selectQuery(f"SELECT COUNT(*) AS `I` FROM `user` WHERE {where}", values)
return res[0]['I'] | a019a8de0644a7295cfafdce80a544ae31bcb225 | 30,036 |
def randomise_spikes(spiketrain, n_surrogates=1, decimals=None):
"""
Generates surrogates of a spike train by spike time randomization.
The surrogates are obtained by keeping the spike count of the original
`spiketrain`, but placing the spikes randomly in the interval
`[spiketrain.t_start, spiketra... | cf8d911f73a3a62b9586ea41c4683ba84a91b8a1 | 30,037 |
def interface_PSO(theta, args):
"""
Function to interface the PSO with the ANFIS. Each particle has its own
ANFIS instance.
theta (nPop, n_var)
learners (nPop, )
J (nPop, )
"""
args_PSO = (args[0], args[1])
learners = args[2]
nPop = theta.shape[0]
... | a725db597ccf4a5928c305ad1493bcd0c99b94a5 | 30,038 |
def corr2d(X, K):
"""计算二维互相关运算。"""
h, w = K.shape
Y = mnp.zeros((X.shape[0] - h + 1, X.shape[1] - w + 1))
for i in range(Y.shape[0]):
for j in range(Y.shape[1]):
Y[i, j] = (X[i:i + h, j:j + w] * K).sum()
return Y | dcbd523879df0f2529a0e68b6c65d829addbc786 | 30,039 |
from src.praxxis.sqlite import sqlite_scene
from src.praxxis.sqlite import sqlite_notebook
from src.praxxis.display import display_scene
def history(history_db, library_db, current_scene_db):
"""displays the notebook history of the sceen"""
curr_scene = sqlite_scene.get_current_scene(history_db)
not... | c6ac411488f69b61678fb298639a8dfa0a103901 | 30,040 |
def get_optimal_parameters_from_dict(selected_dict, num_features):
""" Find optimal parameters from dictionary of selected features
Arguments
---------
selected_dict: dictionary
keys = parameters
values = dictionary
keys = task index
values = list of list of sel... | d473f963c482bcdd8a2eebd65f2e9ae50fe46a32 | 30,041 |
async def _get_input_dialog(self: 'TelegramClient', dialog):
"""
Returns a :tl:`InputDialogPeer`. This is a bit tricky because
it may or not need access to the client to convert what's given
into an input entity.
"""
try:
if dialog.SUBCLASS_OF_ID == 0xa21c9795: # crc32(b'InputDialogPeer... | a58570d5192713e3813cd3cfc6d1295916684a96 | 30,042 |
from datetime import datetime
def kep_to_sat(kep,epoch,bstar=0.21109E-4,whichconst=wgs72,afspc_mode=False):
"""kep_to_sat(kep,epoch,bstar=0.21109E-4,whichconst=wgs72,afspc_mode=False)
Converts a set of keplerian elements into a Satellite object.
Args:
kep(1x6 numpy array): the osculatin... | 9f5a9f3d487d9ea924ea1c8858c8b0796e543bf2 | 30,043 |
def enumerate ():
""" Returns an iterator to the features map.
"""
return __all_features.iteritems () | fda0a96102add04c4282a61f99d9a664e76f2bd6 | 30,044 |
def _create_forward(out_node):
"""Create a user-friendly forward function.
Ensures that a single value instead of a tuple is returned if the user asked
for the gradient with respect to only one input.
Args:
out_node: The function definition AST.
Returns:
The function definition with potentially cha... | 80cdd1814d62b282c1cde37c783d97a067264e51 | 30,045 |
def _get_trip_from_id(trip_obj_list, trip_id):
""" Get a trip from a list, based on a trip id """
found_trip_obj = None
for trip_obj in trip_obj_list:
if trip_obj.id == trip_id:
found_trip_obj = trip_obj
break
return found_trip_obj | f2bbacfccda1e4ff778ba793ad238f744400f020 | 30,047 |
def density_plot(df, y_column, models, model_names=(), columns_to_exclude=()):
"""This function creates the density plot of predicted positive class probability on actual positive and negative
data by each model in models in the same plot. It also computes the difference between the distributions on
p... | e3120e3b5fc0b07e12e5fa41fe0f288a9d98495c | 30,048 |
def clip_chk(x, lb, ub, allow_nan=False):
"""Clip all element of `x` to be between `lb` and `ub` like :func:`numpy:numpy.clip`, but also check
:func:`numpy:numpy.isclose`.
Shapes of all input variables must be broadcast compatible.
Parameters
----------
x : :class:`numpy:numpy.ndarray`
... | e799e00adb4152a7d2ca2faf95eb82744149e59d | 30,049 |
def grid_arc_seconds_1d_to_grid_pixel_indexes_1d(grid_arc_seconds_1d, shape, pixel_scales, origin=(0.0, 0.0)):
""" Convert a grid of (y,x) arc second coordinates to a grid of (y,x) pixel 1D indexes. Pixel coordinates are \
returned as integers such that they are the pixel from the top-left of the 2D grid going ... | 966133fe0a979c913b704a448d02124005a9946d | 30,050 |
import fnmatch
def make_test_run_filter(
complete: bool = False, failed: bool = False, incomplete: bool = False,
name: str = None,
newer_than: dt.datetime = None, older_than: dt.datetime = None,
passed: bool = False, result_error: bool = False,
show_skipped: bool = False, sys_n... | 57f20287ac957b394b8ac25946da3da42deec8ec | 30,051 |
def get_runnable_tasks(graph):
"""Parse a graph and return all runnable tasks."""
tasks = []
to_remove = []
# tasks that follow task that raises an error
following_err = dict()
for tsk in graph.sorted_nodes:
if tsk not in graph.sorted_nodes:
continue
# since the list ... | 155206f67986e65b74148e173d6641d994dd08bd | 30,052 |
def get_defaults(lang):
"""Get the language-specific defaults, if available in spaCy. This allows
using lexical attribute getters that depend on static language data, e.g.
Token.like_num, Token.is_stop, Doc.noun_chunks etc.
lang (unicode): ISO 639-1 language code.
RETURNS (Language.Defaults): The l... | 3ef08b4bd410407ad8519d1c4f84c6c279aa8257 | 30,053 |
def h2(*text, **kwargs):
"""Return a header 2"""
return tydoc().h2(*text, **kwargs) | 7b5b465282222c31d84121e6f890da964cb63fd5 | 30,054 |
def update_comment(comment_id, data):
"""
update comment using its id.
"""
comment = Comment.query.get(comment_id)
for attribute in data:
setattr(comment, attribute, data[attribute])
db.session.commit()
return comment_schema.dump(comment).data | aaeb88479bf82ea3ac09a56d17e09c4ba05eda47 | 30,055 |
def RMSE(A, A_tilde):
"""
Root mean square error. Gives the standard deviation of the residuals
(prediction errors).
Parameters
----------
A : ndarray
Forecast.
A_tilde : ndarray
Observation.
Returns
-------
float
Root mean square error.
"""
ret... | 58a5b833725497be224804a71855819afa9fc33f | 30,057 |
def remove_punct(tokens):
"""
Remove punctuation marks from lists of tokens
Parameters
----------
tokens: list
a nested list containing lists of tokens or a list of spacy docs
Returns
-------
filtered_comments: list
nested lists of tokens
"""
filtered_comments... | c6d7b70a6bf3efe7be3dd144f10ac0f8f5b11e72 | 30,058 |
def to_camel_case(string: str) -> str:
"""
Converts a ``snake_case`` string to ``camelCase``.
:param string: A ``snake_case`` string.
:return: A ``camelCase`` version of the input.
"""
components = string.split("_")
return components[0] + "".join(x.capitalize() for x in components[1:]) | ae0d82efd9a5a65ef16cc401a0fe302b4f04d524 | 30,059 |
import requests
def reconnect(user_data):
"""
Attempt to perform a login to the Unistudium website, saving the cookies in user_data.
Returns:
"OK" if the login was performed correctly, else a description with the error that can be used to inform the users.
"""
# Check if user's session ex... | e05096d69605300680b29bc12784faa3734f40b2 | 30,060 |
from typing import Optional
from typing import Collection
from typing import List
from typing import Tuple
from typing import Set
from typing import Dict
import operator
def yake(
doc: Doc,
*,
normalize: Optional[str] = "lemma",
ngrams: int | Collection[int] = (1, 2, 3),
include_pos: Optional[str ... | b467f0598c70dbf1cec70dafec12ac4259720f91 | 30,061 |
def parse_qsub_defaults(parsed):
"""Unpack QSUB_DEFAULTS."""
d = parsed.split() if type(parsed) == str else parsed
options={}
for arg in d:
if "=" in arg:
k,v = arg.split("=")
options[k.strip("-")] = v.strip()
else:
options[arg.strip("-")] = ""
... | a5c50aef405d88bcb018af48904a384b090d22a2 | 30,062 |
import torch
def load_embeddings(word_map=None, binary=True):
"""
Creates an embedding tensor for the specified word map, for loading into the model.
:param word_emb_file: file containing embeddings (stored in GloVe format)
:param word_map: word map. If None, it will be comprised from the embeddings v... | 9c43d00411dd6036297c21569a232d52bd71acac | 30,063 |
from typing import Dict
import json
import requests
def update_business_profile(business: Business, profile_info: Dict) -> Dict:
"""Set the legal type of the business."""
if not business or not profile_info:
return {'error': babel('Business and profile_info required.')}
# contact phone is optiona... | 68c0ce0d9d205d34b02f7933ca3bc0e7179c7a12 | 30,064 |
def nextpow2(i):
""" Find the next power of 2 for number i """
n = 1
while n < i:
n *= 2
return n | 5dbe396b222ccf79d3cd2017b32174f9e894a5f2 | 30,065 |
from typing import Sequence
from typing import Dict
from typing import List
from typing import Set
from typing import Tuple
def _extra_topo_sort(bad_ordering: Sequence[DiscoveredExtension]) -> Sequence[DiscoveredExtension]:
"""
Simple depth-first search version of a topological sort, but without
recursion... | cdaf0229dda2460e68ee24afb987ca9f7e029d4d | 30,066 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.