content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def upload():
"""
Implements the upload page form
"""
return render_template('upload.html') | 4dda3418621b3894234b049e22f810304050a398 | 6,800 |
def detect_changepoints(points, min_time, data_processor=acc_difference):
""" Detects changepoints on points that have at least a specific duration
Args:
points (:obj:`Point`)
min_time (float): Min time that a sub-segmented, bounded by two changepoints, must have
data_processor (functio... | 872c2e4d5d8cbb33de100495bc8d9ddb050400c8 | 6,801 |
from qalgebra.core.hilbert_space_algebra import LocalSpace
from qalgebra.core.scalar_algebra import ScalarValue
from qalgebra.library.spin_algebra import SpinSpace
def Sum(idx, *args, **kwargs):
"""Instantiator for an arbitrary indexed sum.
This returns a function that instantiates the appropriate
:class... | 8d1a1c97e28153b24a6e958b2694aac269b69f22 | 6,802 |
def quad1(P):
"""[summary]
Arguments:
P (type): [description]
Returns:
[type]: [description]
"""
x1, z1, x2, z2 = P
return (Fraction(x1, z1) - Fraction(x2, z2))**2 | f3e9c34740038242c29f4abbe168df573da12390 | 6,803 |
def update_position(position, velocity):
"""
:param position: position(previus/running) of a particle
:param velocity: the newest velocity that has been calculated during the specific iteration- new velocity is calculated
before the new position
:return: list - new position
"""
pos = []
... | 7734e4021d958f42d974401b78331bcd2911ac92 | 6,804 |
def respond_batch():
"""
responses with [{"batch": [{blacklist_1_name: true}, ]}]
"""
result = get_result(request)
return jsonify([{"batch": result}]) | 97b1ceaafa88aacba09fc0ba6c564e87bfb07b66 | 6,805 |
from typing import Union
import types
from typing import Iterable
def get_iterable_itemtype(obj):
"""Attempts to get an iterable's itemtype without iterating over it,
not even partly. Note that iterating over an iterable might modify
its inner state, e.g. if it is an iterator.
Note that obj is expecte... | 103a3928e4a161f119c8664e58ba7e6270a94a14 | 6,806 |
import re
def getTimerIPs():
"""
returns list of ip addr
"""
client = docker.from_env()
container_list = client.containers.list()
timer_ip_list = []
for container in container_list:
if re.search("^timer[1-9][0-9]*", container.name):
out = container.exec_run("awk 'END... | e4bc28407fb8b292df9a813809998bf6b323c938 | 6,807 |
def country_buttons():
"""Generates the country buttons for the layout
TODO(@andreasfo@gmail.com)
Fix to use this one instead of the dropdown menu
Returns:
dbcButtonGroup -- A button group of all countries
"""
countries = [{'label': '🇸🇪 Sweden',
'value': 'Swede... | 3a149d37ae2457c84cd2fd7ae774b5a7e4c7bbbf | 6,808 |
def BRepBlend_BlendTool_NbSamplesV(*args):
"""
:param S:
:type S: Handle_Adaptor3d_HSurface &
:param v1:
:type v1: float
:param v2:
:type v2: float
:rtype: int
"""
return _BRepBlend.BRepBlend_BlendTool_NbSamplesV(*args) | 99af0513463ce64d5369fde226e679e48a7e397a | 6,809 |
def patch_urllib(monkeypatch, requests_monitor):
"""
Patch urllib to provide the following features:
- Retry failed requests. Makes test runs more stable.
- Track statistics with RequestsMonitor.
Retries could have been implemented differently:
- In test.geocoders.util.GeocoderTestB... | 2e7dec88873351a0e95a3b6f963115d065b90a39 | 6,810 |
def get_response(session, viewstate, event_validation, event_target, outro=None, stream=False, hdfExport=''):
"""
Handles all the responses received from every request made to the website.
"""
url = "http://www.ssp.sp.gov.br/transparenciassp/"
data = [
('__EVENTTARGET', event_target),
... | 0bb31b29fb8fb8a0fe007f87d88b8d131fd4308c | 6,811 |
def matchVuln(vuln, element, criteria):
"""
================================================================================
Name:
matchVuln
Description:
Sets the finding details of a given VULN.
Parameter(s):
vuln: The VULN element to be searched.
element: ... | 7158b263fd70e921b0b131fd8f2537223521570f | 6,812 |
def require(*modules):
"""Check if the given modules are already available; if not add them to
the dependency list."""
deplist = []
for module in modules:
try:
__import__(module)
except ImportError:
deplist.append(module)
return deplist | 88df83cd33d8bddea63e4d2fbfb4d8351a3c23b1 | 6,813 |
def fixture_base_context(
env_name: str,
) -> dict:
"""Return a basic context"""
ctx = dict(
current_user="a_user",
current_host="a_host",
)
return ctx | fbfed439f784bdd64e93910bbb581955200af2bb | 6,814 |
import os
def parse_pharmvar(fn):
"""
Parse PharmVar gene data.
Parameters
----------
fn : str
Gene data directory.
"""
gene = os.path.basename(fn).split('-')[0]
rs_dict = {}
vfs = {'GRCh37': [], 'GRCh38': []}
alleles = {}
for i, assembly in enumerate(['GRCh37', ... | a62f1c57602f3093f9c2c1e5a70389baef6094bd | 6,815 |
from typing import Optional
from typing import List
import yaml
def definition(server: KedroLanguageServer, params: TextDocumentPositionParams) -> Optional[List[Location]]:
"""Support Goto Definition for a dataset or parameter.
Currently only support catalog defined in `conf/base`
"""
if not server.is... | 7713d92fafa2f0acf68ee34b4dc83f1d5100a9b3 | 6,816 |
def augmented_neighbors_list(q_id,
neighbors,
is_training,
processor,
train_eval=False):
"""Retrieve and convert the neighbors to a list.
Args:
q_id: a question id
neighbors: a table mapping ... | 3ae8756a60fdfa4ce3fc6de91d364c5edebcc0ff | 6,817 |
def estimate_tau_exp(chains, **kwargs):
"""
Estimate the exponential auto-correlation time for all parameters in a chain.
"""
# Calculate the normalised autocorrelation function in each parameter.
rho = np.nan * np.ones(chains.shape[1:])
for i in range(chains.shape[2]):
try:
... | 3de72cec6fa079913489c9c1b9b72ff572cedf60 | 6,818 |
def lda_model_onepass(dictionary, corpus, topics):
"""Create a single pass LDA model"""
start_time = time.time()
model = LdaMulticore(corpus, id2word = dictionary, num_topics = topics)
model.save(""./data/lda/all_topics_single.lda"")
print(model.print_topics(-1))
print("\nDone in {}".format(tim... | 3a88250af8c83fb23112b15cacaad39eeaebb27c | 6,819 |
import dataclasses
import pydantic
def paramclass(cls: type) -> type:
""" Parameter-Class Creation Decorator
Transforms a class-definition full of Params into a type-validated dataclass,
with methods for default value and description-dictionary retrieval.
Hdl21's `paramclass`es are immutable, str... | 5f5b4b6612d3afc7858a4b26419d9238aaf6ec92 | 6,820 |
import string
def text_process(mess):
"""
Takes in a string of text, then performs the following:
1. Remove all punctuation
2. Remove all stopwords
3. Returns a list of the cleaned text
"""
# Check characters to see if they are in punctuation
nopunc = [char for char in mess if char not... | 9069df05eb4d1b87c2091a64e7dd55754e362334 | 6,821 |
def IntCurveSurface_ThePolyhedronToolOfHInter_IsOnBound(*args):
"""
:param thePolyh:
:type thePolyh: IntCurveSurface_ThePolyhedronOfHInter &
:param Index1:
:type Index1: int
:param Index2:
:type Index2: int
:rtype: bool
"""
return _IntCurveSurface.IntCurveSurface_ThePolyhedronToolOf... | bd64cb058793730197a805d7660fe4c8dc4f7af5 | 6,822 |
def read_mrc_like_matlab(mrc_file):
""" Read MRC stack and make sure stack is 'Fortran indexed' before returning it. """
mrc_stack = mrcfile.open(mrc_file).data
fortran_indexed_stack = c_to_fortran(mrc_stack)
return fortran_indexed_stack | 245a7371e94ae6c05248d24e231ce56afc937dd1 | 6,823 |
from typing import List
def freeze_session(session: tf.Session,
keep_var_names: List[str] = None,
output_names: List[str] = None,
clear_devices: bool = True) -> tf.GraphDef:
"""
Freezes the state of a session into a pruned computation graph.
Creates... | 4754de754217031ac6151bc3360b6969a46a4e66 | 6,824 |
def linear_regression_noreg(X, y):
"""
Compute the weight parameter given X and y.
Inputs:
- X: A numpy array of shape (num_samples, D) containing feature.
- y: A numpy array of shape (num_samples, ) containing label
Returns:
- w: a numpy array of shape (D, )
"""
######################################... | e1a130dbf1c75db929779cc3d9d6b6097521c02e | 6,825 |
import os
def _update_core_rrds(data, core_metrics_dir, rrdclient, step, sys_maj_min):
"""Update core rrds"""
interval = int(step) * 2
total = 0
for cgrp in data:
rrd_basename = CORE_RRDS[cgrp]
rrdfile = os.path.join(core_metrics_dir, rrd_basename)
rrd.prepare(rrdclient, rrdf... | 21ce7c4002b7c07c7f072cfb802702262a8fdaeb | 6,826 |
def evaluation(evaluators, dataset, runners, execution_results, result_data):
"""Evaluate the model outputs.
Args:
evaluators: List of tuples of series and evaluation functions.
dataset: Dataset against which the evaluation is done.
runners: List of runners (contains series ids and loss... | ef3470edb8b2336bdc54507a5df8023f8095b995 | 6,827 |
def bestof(reps, func, *args, **kwargs):
"""Quickest func() among reps runs.
Returns (best time, last result)
"""
best = 2 ** 32
for i in range(reps):
start = timer()
ret = func(*args, **kwargs)
elapsed = timer() - start
if elapsed < best: best = elapsed
return (b... | 975d106a79b79cab3bc287d8b658585f45dd648d | 6,828 |
import tempfile
def gdal_aspect_analysis(dem, output=None, flat_values_are_zero=False):
"""Return the aspect of the terrain from the DEM.
The aspect is the compass direction of the steepest slope (0: North, 90: East, 180: South, 270: West).
Parameters
----------
dem : str
Path to file stor... | ec8aa51f799368508f78dcff81ae991087b56132 | 6,829 |
import requests
import json
def _handle_braze_response(response: requests.Response) -> int:
"""Handles server response from Braze API.
The amount of requests made is well
below the limits for the given API endpoint therefore Too Many Requests
API errors are not expected. In case they do, however, occ... | da8aca622f7a4812235797501a1afe56cc760ea4 | 6,830 |
def unpack_file(filepath, tmpdir):
"""
Attempt to unpack file.
filepath is the path to the file that should be attempted unpacked.
tmpdir is a path to a temporary directory unique to this thread where
the thread will attempt to unpack files to.
Returns a list of unpacked files or an empty list.
... | 79fb80fe61145e865b128587525bc743d19e2ad0 | 6,831 |
def xarray_image_as_png(img_data, loop_over=None, animate=False, frame_duration=1000):
"""
Render an Xarray image as a PNG.
:param img_data: An xarray dataset, containing 3 or 4 uint8 variables: red, greed, blue, and optionally alpha.
:param loop_over: Optional name of a dimension on img_data. If set,... | 201cb29144054417d7eb743690601ae37558dfbd | 6,832 |
def x_section_from_latlon(elevation_file,
x_section_lat0,
x_section_lon0,
x_section_lat1,
x_section_lon1,
as_polygon=False,
auto_clean=False):
"""
This wor... | 0773cf535ee18ff91db805d692687c67bf6b2ed4 | 6,833 |
import re
def convert_not_inline(line):
""" Convert the rest of part which are not inline code but might impact inline code
This part will dealing with following markdown syntax
- strong
- scratch
- italics
- image
- link
- checkbox
- highlight
:param line: str, the not inlin... | 871abca2977fc494036c6d5aa19de789cfbfd5b9 | 6,834 |
def uniform_square_aperture(side, skypos, frequency, skyunits='altaz',
east2ax1=None, pointing_center=None,
power=False):
"""
-----------------------------------------------------------------------------
Compute the electric field or power pattern p... | 275249164bba5fae8f8652f8af1f2c8dc13c9525 | 6,835 |
def sources_table(citator):
"""
Return the content for an HTML table listing every template that the
citator can link to.
"""
rows = []
for template in citator.templates.values():
# skip templates that can't make URLs
if not template.__dict__.get('URL_builder'):
con... | 460a06e03e7ec6d5cee465001d9b828976a4da1b | 6,836 |
def parse_bot_commands(data, starterbot_id):
"""
Parses a list of events coming from the Slack RTM API to find bot commands.
If a bot command is found, this function returns a tuple of command and channel.
If its not found, then this function returns None, None.
"""
user_id, message ... | 5d614cfdf55133180425a87aedac34896a54b552 | 6,837 |
from typing import Callable
def construct_obj_in_dict(d: dict, cls: Callable) -> dict:
"""
Args
d (dict):
d[name][charge][annotation]
"""
if not isinstance(d, dict):
return d
else:
new_d = deepcopy(d)
for key, value in d.items():
if value.get... | c069fb474a6a675f8d917483435856df506ff331 | 6,838 |
def signup_user(request):
"""
Function to sing up user that are not admins
:param request: This param contain all the information associated to the request
:param type request: Request
:return: The URL to render
:rtype: str
"""
try:
log = LoggerManager('info', 'singup_manager-in... | 3ea45a9b84cb8281f3afc6997230fdcbab75f045 | 6,839 |
def haar_rand_state(dim: int) -> np.ndarray:
"""
Given a Hilbert space dimension dim this function returns a vector
representing a random pure state operator drawn from the Haar measure.
:param dim: Hilbert space dimension.
:return: Returns a dim by 1 vector drawn from the Haar measure.
"""
... | 3d374fe32fee91667747df86d79f9feb08836c61 | 6,840 |
from pathlib import Path
def is_src_package(path: Path) -> bool:
"""Checks whether a package is of the form:
├─ src
│ └─ packagename
│ ├─ __init__.py
│ └─ ...
├─ tests
│ └─ ...
└─ setup.py
The check for the path will be if its a directory with only one subdirectory
... | 36bfd704a0a71a41e9943dc9a9d19cf5e46746f8 | 6,841 |
from re import T
from typing import Optional
from re import I
def value_element(units=(OneOrMore(T('NN')) | OneOrMore(T('NNP')) | OneOrMore(T('NNPS')) | OneOrMore(T('NNS')))('raw_units').add_action(merge)):
"""
Returns an Element for values with given units. By default, uses tags to guess that a unit exists.
... | 1b111fb30369d0d3b6c506d5f02e80b5c88044d5 | 6,842 |
def get_pattern(model_id, release_id) -> list:
"""
content demo:
[
'...',
{
0.1: [
['if', 'checker.check'],
3903,
['if', 'checker.check', '*', Variable(name="ip", value='10.0.0.1')],
['if checker.check():', 'if check... | 2307180d26e687fd7057c326e15e21b7aaf81471 | 6,843 |
def bit_remove(bin_name, byte_offset, byte_size, policy=None):
"""Creates a bit_remove_operation to be used with operate or operate_ordered.
Remove bytes from bitmap at byte_offset for byte_size.
Args:
bin_name (str): The name of the bin containing the map.
byte_offset (int): Position of b... | 356ff2f3421b67790f7e224ecc49c844335864f8 | 6,844 |
def has_session_keys_checksums(session_key_checksums):
"""Check if this session key is (likely) already used."""
assert session_key_checksums, 'Eh? No checksum for the session keys?'
LOG.debug('Check if session keys (hash) are already used: %s', session_key_checksums)
with connection.cursor() as cur:
... | 9f6240f5ba2640c43ed5ae75de46a7e04d0041e0 | 6,845 |
def four2five(data, format_, dst_dtype='float16', need_custom_tiling=True):
"""
Convert 4-dims "data" to 5-dims,the format of "data" is defined in "format_"
Args:
data (tvm.tensor.Tensor): 4-dims tensor of type float16, float32
format_ (str): a str defined the format of "data"
dst_d... | 71de138f15e5b407a244c1670c48eb806b3be765 | 6,846 |
def MT33_SDR(MT33):
"""Converts 3x3 matrix to strike dip and rake values (in radians)
Converts the 3x3 Moment Tensor to the strike, dip and rake.
Args
MT33: 3x3 numpy matrix
Returns
(float, float, float): tuple of strike, dip, rake angles in radians
(Note: Function from MTFIT.MTconv... | 0b80df0e43bc546aa36a06858f144f32d75cb478 | 6,847 |
from generate_changelog.utilities import pairs
from typing import Optional
from typing import List
import re
def get_commits_by_tags(repository: Repo, tag_filter_pattern: str, starting_tag: Optional[str] = None) -> List[dict]:
"""
Group commits by the tags they belong to.
Args:
repository: The gi... | 1e870d2169496e183c1df8d90ddceb4e63cb1689 | 6,848 |
def GetObject():
"""
Required module function.
@returns class object of the implemented adapter.
"""
return SpacePacketAdapter | 38ddac47a1ac7a58f203fc5552a00340a542518d | 6,849 |
import os
import copy
import io
import math
def filter_paths(ctx, raw_paths, path_type="repo", **kwds):
"""Filter ``paths``.
``path_type`` is ``repo`` or ``file``.
"""
cwd = os.getcwd()
filter_kwds = copy.deepcopy(kwds)
changed_in_commit_range = kwds.get("changed_in_commit_range", None)
... | b4eae04a1d836174793c02cf831116db69dfef31 | 6,850 |
def parse(args):
"""Parse the command-line arguments of the `inpaint` command.
Parameters
----------
args : list of str
List of arguments, without the command name.
Returns
-------
InPaint
Filled structure
"""
struct = InPaint()
struct.files = []
while cl... | 6b3eb929ce13559f9bd3d50ee2b15dd25e967d33 | 6,851 |
from unittest.mock import Mock
from datetime import datetime
def log_context(servicer_context: Mock) -> LogContext:
"""Mock LogContext."""
context = LogContext(
servicer_context,
"/abc.test/GetTest",
Mock(name="Request"),
Mock(name="Response", ByteSize=Mock(return_value=10)),
... | 1ea1b8d4e6dad80ac8d95925a70a7f79ec84a686 | 6,852 |
import os
def filename(name):
""" Get filename without extension"""
return os.path.splitext(name)[0] | 9899b6e187684ddb95ff9d1bd7974163a7e3e78b | 6,853 |
import base64
def base64_decode(string):
"""
Decodes data encoded with MIME base64
"""
return base64.b64decode(string) | 38870882fca9e6595e3f5b5f8943d0bf781f006c | 6,854 |
import re
def convert_operand_kind(operand_tuple):
"""Returns the corresponding operand type used in spirv-tools for the given
operand kind and quantifier used in the JSON grammar.
Arguments:
- operand_tuple: a tuple of two elements:
- operand kind: used in the JSON grammar
- qu... | 3d26a0b330ae64209655b24dfe86578cb4b8724c | 6,855 |
from datetime import datetime
def screen_missing_data(database,subject,begin=None,end=None):
""" Returns a DataFrame contanining the percentage (range [0,1]) of loss data
calculated based on the transitions of screen status. In general, if
screen_status(t) == screen_status(t+1), we declared we have at lea... | 70666ed7ddfea359c4c91afd8b52f9821580bda6 | 6,856 |
def check(text):
"""Check the text."""
error_code = "example.first"
msg = "First line always has an error."
reverse(text)
return [(1, 1, error_code, msg)] | 50d8406322225153c055b925609af702bb86d7b6 | 6,857 |
def figure(**kwargs):
"""
Create a new figure with the given settings.
Settings like the current colormap, title or axis limits as stored in the
current figure. This function creates a new figure, restores the default
settings and applies any settings passed to the function as keyword
arguments... | a7de48597ecc80872d8d4b108a642956200adcc2 | 6,858 |
from typing import List
from bs4 import BeautifulSoup
def parse(content: str, target: str = "all") -> List[Inline]:
"""Parses an HTML document and extracts."""
soup = BeautifulSoup(content, "html.parser")
if target == "all":
search_queries = chain(*_VALID_TARGETS.values())
elif target in _VAL... | 56238a4def01713220c7d59b266cfcc55f1daf7f | 6,859 |
def create_output(verified_specific_headers_list:list) -> str:
""" Design Output """
if args.verbose is True:
print("[!] INFO: Outputting Specific Header Information")
return_output = ""
for specific_header in verified_specific_headers_list:
split_header = specific_header.split(":")
... | e38fdf467d1f01167ff00040e7d0f7d8816e4915 | 6,860 |
def registered_response_data():
"""Body (bytes) of the registered response."""
return b"response data" | 1ee44d70592747947d76ff757901f44fde5c9946 | 6,861 |
def parse_log(log_file):
"""
Parses a log file into a list of lists containing the messages logged
:param log_file: path-like: Path to the log file
:return: list of lists containing messages in the log file
"""
parsed_logs = [[] for i in range(5)]
with open(log_file, 'r') as f:
for l... | 065618c66470a8c538cbe9346ba66949819672b9 | 6,862 |
def generate_experiment_fn(train_files,
eval_files,
num_epochs=None,
train_batch_size=40,
eval_batch_size=40,
embedding_size=8,
first_layer_size=100,
... | a7af08f955d1d93c1c9735b08b5e18b2fd9e405a | 6,863 |
def get_inclination_and_azimuth_from_locations(self, locations):
"""
self must to point to Main_InputWindow
"""
"""
Return "Inc" and "Azi" array objects in reference units.
"""
Inc = []
Azi = []
for MD in locations:
tangentVector = get_ASCT_from_MD(self, MD)
verticalVector = np.array([0.0,0.0,1.0,0.0])
i... | 2761137c670d3ad90c40d0689db062baf743d7a5 | 6,864 |
def _ensure_package(base, *parts):
"""Ensure that all the components of a module directory path exist, and
contain a file __init__.py."""
bits = []
for bit in parts[:-1]:
bits.append(bit)
base.ensure(*(bits + ['__init__.py']))
return base.ensure(*parts) | fc9bb95445cc1b0e8ec819dfafdaff7d5afbf372 | 6,865 |
def make_cat_matrix(n_rows: int, n_cats: int) -> tm.CategoricalMatrix:
"""Make categorical matrix for benchmarks."""
mat = tm.CategoricalMatrix(np.random.choice(np.arange(n_cats, dtype=int), n_rows))
return mat | 5c1f314a9582685d6c6da0f9ac0ee58fe9046952 | 6,866 |
def add_stabilizer_nodes(boundaries_raw, electrodes, nr_nodes_between):
"""
Segmentation of nodes:
we have the existing nodes
N.F is the ratio of required nodes and existing nodes
first, add N nodes to each segment
then, add one more node to the F first segments
* assume ord... | fe8ff9618ee34cb9caedd828a880af05a1c964f0 | 6,867 |
def read_data(creds):
"""Read court tracking data in and drop duplicate case numbers"""
# try:
df = gsheet.read_data(gsheet.open_sheet(gsheet.init_sheets(creds),"01_Community_lawyer_test_out_final","Frontend"))
# df.drop_duplicates("Case Number",inplace=True) #Do we want to drop duplicates???
retu... | 95bb588305c230c2f3aaa306e367da2602788f67 | 6,868 |
def _build_indie_lyrics(
root: str, num_workers: int = 8, max_size: int = 200000
) -> DocumentArray:
"""
Builds the indie lyrics dataset. Download the CSV files from:
https://www.kaggle.com/datasets/neisse/scrapped-lyrics-from-6-genres
:param root: the dataset root folder.
:param num_workers: th... | 9eaaf9742c587a649d036e5a7da30dc5ca37db79 | 6,869 |
def getHostname(request):
"""
Utility method for getting hostname of client.
"""
if request.getClientIP() in LOOPBACK_ADDRESSES and has_headers(request, X_FORWARDED_FOR):
# nginx typically returns ip addresses
addr = get_headers(request, X_FORWARDED_FOR)
if isIPAddress(addr):
... | 41ab9ed3a01d1e1bc53565115a8336a5eac741b3 | 6,870 |
def CollapseSolutionPosition(x,x0):
"""
Calculate a free-fall collapse solution
x - position to calculate time at in cm
x0 - initial position in cm
Sam Geen, March 2018
"""
X = x/x0
t = (np.arccos(np.sqrt(X)) + np.sqrt(X * (1.0-X))) * x0**1.5 / np.sqrt(2.0*units.G*gravity.centralmass)
... | 3d0aaeef997a688b72df38ea2188ea34d62c1d55 | 6,871 |
from scipy import signal
from nsdata import bfixpix
def scaleSpectralSky_cor(subframe, badpixelmask=None, maxshift=20, fitwidth=2, pord=1, nmed=3, dispaxis=0, spatial_index=None, refpix=None, tord=2):
"""
Use cross-correlation to subtract tilted sky backgrounds.
subframe : NumPy array
data subframe... | 50ee28ff81c4e981dca47e67ed525b7d9a421288 | 6,872 |
def login():
"""
Implements the login feature for the app.
Errors are shown if incorrect details are used. If the user tried
to access a page requiring login without being authenticated,
they are redirected there after sign in.
"""
if current_user.is_authenticated:
return redirect(u... | 43c60504648aa4e93e24150b1aceb98293a4064d | 6,873 |
def _get_plot_axes(grid):
"""Find which axes are being plotted.
Parameters
----------
grid : Grid
Returns
-------
tuple
"""
plot_axes = [0, 1, 2]
if np.unique(grid.nodes[:, 0]).size == 1:
plot_axes.remove(0)
if np.unique(grid.nodes[:, 1]).size == 1:
plot_ax... | 3112ba7d954c7b39bec035e31b5281919dc78244 | 6,874 |
import argparse
def make_parser(inheritable=False):
"""Make parser.
Parameters
----------
inheritable: bool
whether the parser can be inherited from (default False).
if True, sets ``add_help=False`` and ``conflict_hander='resolve'``
Returns
-------
parser: ArgumentParser
... | 444c242cb79dd28e7fba8c5d71a92af80e4b3178 | 6,875 |
def _read_uint(addr):
""" Read a uint """
value = gdb.parse_and_eval("*(unsigned int*)0x%x" % addr)
try:
if value is not None:
return _cast_uint(value)
except gdb.MemoryError:
pass
print("Can't read 0x%x to lookup KASLR uint value" % addr)
return None | abe969c2f8595fdf1efdc98157536131d7a8a5ca | 6,876 |
def line_at_infinity(n):
"""the line at infinity just contains the points at infinity"""
return points_at_infinity(n) | 8a787b4598e072c101f8babbe948c4996b121a9a | 6,877 |
def check_section(config:Namespace, name:str) -> Namespace:
"""Check that a section with the specified name is present."""
section = config._get(name)
if section is None:
raise ConfigurationError(f"Section {name} not found in configuration")
if not isinstance(section, Namespace):
raise ... | 09a315a77bd25a3a78b8e80592a32c8709aa511f | 6,878 |
import math
def ceil(a):
"""The ceil function.
Args:
a (Union[:class:`~taichi.lang.expr.Expr`, :class:`~taichi.lang.matrix.Matrix`]): A number or a matrix.
Returns:
The least integer greater than or equal to `a`.
"""
return _unary_operation(_ti_core.expr_ceil, math.ceil, a) | 456436d8d1104b4df16327665dd477139528f6fa | 6,879 |
from typing import Any
from typing import Optional
def Body(
default: Any = Undefined,
*,
default_factory: Optional[NoArgAnyCallable] = None,
alias: str = None,
title: str = None,
description: str = None,
const: bool = None,
gt: float = None,
ge: float = None,
lt: float = None,... | efc636d1b0e42736cecb04857afa67f636fd0bb6 | 6,880 |
def warp(img, pers_margin=425, margin_bottom=50, margin_top=450, margin_sides=150, reverse=False):
"""
This function warps an image. For the transformation a src polygon and a destination
polygon are used. The source polygon is calculated by the image shape and the margins
given. The destination polygon... | 06c4b08e43a3efcfaf3a44bd58727c6b0db833da | 6,881 |
def get_all_doorstations(hass):
"""Get all doorstations."""
return [
entry[DOOR_STATION]
for entry in hass.data[DOMAIN].values()
if DOOR_STATION in entry
] | a6e785e6c667b956ef41ad98681e38b142d99ef5 | 6,882 |
import requests
import json
def get_weather() -> dict:
"""Makes an api request for the weather api
country code queries the specific country
city name queries the specific city within that country
units determines the type of numerical data returned (centigrade or Fahrenheit)
:return: the respons... | 023253ec2466182515a345d2bca1f10adf7b67ab | 6,883 |
def _create_off_value():
"""create off value"""
return Tensor(0.0, mstype.float32) | 9cddddc27810fdfc4dbe3970aaa5c5a064f4345c | 6,884 |
from datetime import datetime
def is_datetime(value):
"""
Check if an object is a datetime
:param value:
:return:
"""
result = False
if isinstance(value, datetime.datetime):
result = True
# else:
# result = is_datetime_str(str(value))
return result | 95c2392c9a3da9e4fccb43bd50c54914ffe91b8e | 6,885 |
import math
def sigmoid(z):
"""Sigmoid function"""
if z > 100:
return 0
return 1.0 / (1.0 + math.exp(z)) | 097e1a85fc46264cb1c7cd74498d6cfab97e5b88 | 6,886 |
async def get_company_sumary(symbol: str, db: Session = Depends(get_db)):
"""
This method receibe a symbol, if does not exits in our database
go to extract data, save it on our database and retunr the
stored data
"""
company_solver = CompanySolver(company_symbol=symbol)
_ = company_solver.g... | 9cd4a5e6dfe4f308f564d956280cb6cd522c6296 | 6,887 |
def make_dataloaders(params: MinkLocParams, debug=False):
"""
Create training and validation dataloaders that return groups of k=2 similar elements
:param train_params:
:param model_params:
:return:
"""
datasets = make_datasets(params, debug=debug)
dataloders = {}
train_sampler = Ba... | 3868c414d77492814ba57c5872ea55dda7c3d108 | 6,888 |
def get_attn_pad_mask(seq_q, seq_k):
"""
由于各句子长度不一样,故需要通过PAD将所有句子填充到指定长度;
故用于填充的PAD在句子中无任何含义,无需注意力关注;
注意力掩码函数,可用于屏蔽单词位置为PAD的位置,将注意力放在其他单词上。
:param seq_q: [batch_size, seq_len]
:param seq_k: [batch_size, seq_len]
"""
batch_size, len_q = seq_q.size()
_, len_k = seq_k.size()
pad_... | 522fc244c02ec767b80da2f0c9b5cf6720e931c0 | 6,889 |
def convert_str_to_float(string):
"""Convert str to float
To handle the edge case
Args:
string (str): string
Returns:
f (float): float value
"""
try:
f = float(string)
except Exception:
f = np.nan
return f | f597d9d59c00f484d9b5183fc610fabf84529218 | 6,890 |
def node_tree(node: str):
"""Format printing for locate"""
str2list = list(node.replace(' ', ''))
count = 0
for i, e in enumerate(str2list):
if e == '(':
count += 1
str2list[i] = '(\n{}'.format('| ' * count)
elif e == ')':
count -= 1
str2... | 010805499cb6e886ec8811949a1d1d013db1d15f | 6,891 |
def process_data(data):
"""
:param datas:
:param args:
:return:
"""
# copy of the origin question_toks
for d in datas:
if 'origin_question_toks' not in d:
d['origin_question_toks'] = d['question_toks']
for entry in datas:
entry['question_toks'] = symbol_filt... | 3e2ab0daa83e48abc121b72cbf1970c8b5fabe87 | 6,892 |
from typing import Union
from typing import Collection
import typing
from typing import Literal
from typing import Callable
from typing import Optional
from typing import Any
from typing import Mapping
def concat(
adatas: Union[Collection[AnnData], "typing.Mapping[str, AnnData]"],
*,
axis: Literal[0, 1] =... | bf85455f3cebb61d4711c2022442d7bbcc75d6b2 | 6,893 |
import copy
def repeated_parity_data_binning(shots, nr_of_meas:int):
"""
Used for data binning of the repeated parity check experiment.
Assumes the data qubit is alternatively prepared in 0 and 1.
Args:
shots (1D array) : array containing all measured values of 1 qubit
nr_of_meas (int... | 3cd724579738f5ccf4bd664cf1b023d1c7c08f27 | 6,894 |
def get_user_activities(user_id, timestamp_start, timestamp_end):
""" Returns the activities for a user, between two times"""
activities = Activity.query \
.filter(Activity.user_id == user_id) \
.filter(Activity.timestamp_end >= timestamp_start) \
.filter(Activity.timestamp_start <= tim... | 0b58c1e6a430e0179d34b0ee6d8fdb70f6b102c1 | 6,895 |
def _find_matches(ref, pred):
""" find potential matches between objects in the reference and
predicted images. These need to have at least 1 pixel of overlap.
"""
matches = {}
for label in ref.labels:
mask = ref.labeled == label
matches[label] = [m for m in np.unique(pred.labeled[ma... | 82ea5c5a0c73996187d7f5409745b947b7e17960 | 6,896 |
def _process(config: ConfigType, should_make_dir: bool) -> ConfigType:
"""Process the config
Args:
config (ConfigType): Config object
should_make_dir (bool): Should make dir for saving logs, models etc
Returns:
[ConfigType]: Processed config
"""
config = _process_general_c... | 3bf2cc4eff379fcfe8f7d58332ae33658e7e5540 | 6,897 |
def calendar_heatmap_echarts(data_frame: pd.DataFrame, date_field: str = None, value_field: str = None,
title: str = "",
width: str = "100%", height: str = "300px") -> Echarts:
"""
日历热度图,显示日期热度
:param data_frame:
:param date_field: 日期列
:param... | e92a41dcb533f5fdb0fba91bb1f80b0199d1523e | 6,898 |
from typing import Union
import torch
def adj_to_edge_indices(adj: Union[torch.Tensor, np.ndarray]) -> Union[torch.Tensor, np.ndarray]:
"""
Args:
adj: a (N, N) adjacency matrix, where N is the number of nodes
Returns:
A (2, E) array, edge_idxs, where E is the number of edges,
... | b84d978e7ea6b24cf9b4e8aaa074581d4516435d | 6,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.