content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import time
def getDateRange(dt):
""" 获取时间戳范围
参数
--------------
dt: str
url请求中传递过来的date参数
返回值
--------------
turple
返回一对 (起始时间戳,终止时间戳)
"""
if dt == 'weekend':
startDT = "2017-03-25 00:00:00"
endDT = "2017-03-27 00:00:00"
elif dt == 'weekday':
... | 1265df8cb736a8ac13515220b68296c7517771ad | 47,700 |
import random
def generate_random_color():
"""
Generate random color.
"""
r = random.random()
g = random.random()
b = random.random()
return (r, g, b) | 11416e6714a08bfbea8c6939774d1f0e54664ac4 | 47,701 |
def get_highest_in_hierarchy(nodes):
"""Return highest nodes in the hierarchy that are in the `nodes` list.
The "highest in hierarchy" are the nodes closest to world: top-most level.
Args:
nodes (list): The nodes in which find the highest in hierarchies.
Returns:
list: The highest nod... | ddd3f061fd381989a8a2f5cd8f9525371400ed1a | 47,702 |
def get_host_finding_detail_command(client, args):
"""
Retrieve information about particular host finding based on host finding id.
:param client: object of client
:param args: Demisto arguments provided by the user
:return: command output
"""
client_detail = get_client_detail_from_context(... | 9254d00c7dae7a136061a7f78c239998bb8bed31 | 47,703 |
def MPC_GetRxGainExternalRx() -> int:
"""Gets current reception gain
Returns
-------
int
Reception gain (raw value)
"""
gain = c_uint32()
CTS3Exception._check_error(_MPuLib.MPC_GetRxGainExternalRx(
c_uint8(0),
byref(gain)))
return gain.value | 2fdfc6b89458ce9d758eb9493d2d280d86036f32 | 47,704 |
import copy
def tiwary_mmvt_model(tmpdir_factory, tiwary_mmvt_model_persistent):
"""
Create a copy of the model that is not persistent. But this at least
doesn't require us to generate an entirely new model
"""
tiwary_mmvt_model = copy.deepcopy(tiwary_mmvt_model_persistent)
return tiwary_mmvt_... | 381dd449c8cbcfbdf43ed9a3e8b71fff09f9a2c9 | 47,705 |
def _get_disposable_app_filename(clientInfo):
"""
Get name of file used to store creds.
"""
return clientInfo.get('file', clientInfo['name'] + '.client_data.json') | 7d6a67443cd8815ddfde3f69aae450d59f59a437 | 47,706 |
from typing import Optional
from typing import Dict
import os
import glob
def voc_to_df(img_dir:str, ann_dir:str, save_path:Optional[str]=None, class_map:Optional[Dict[str,str]]=None, **kwargs) -> pd.DataFrame:
""" finished, checked,
pascal voc annotations (in xml format) to one DataFrame (csv file)
Par... | 9bee1ef1d40514ebc9f685b2d735462dd3c6b76e | 47,707 |
def _timestamp_from_record_tuple(record):
"""Extract timestamp from HBase tuple record
"""
return record[0]['timestamp'] | de0ff6f12e14093a236cab651d4baae2299d2124 | 47,708 |
def concretize_backward_bound(backward_linexp: LinearExpression,
act_bound: Bound) -> Bound:
"""Compute the value of a backward bound.
Args:
backward_linexp: Coefficients of linear functions defined over a layer.
act_bound: Bound on the activations of that layer.
Returns:
... | d95d9c01acebf126490f706ce4c6d29fd509e923 | 47,709 |
def order_sell_stop_loss(symbol,quantity,stopPrice,timeInForce='gtc'):
"""Submits a stop order to be turned into a market order once a certain stop price is reached.
:param symbol: The stock ticker of the stock to sell.
:type symbol: str
:param quantity: The number of stocks to sell.
:type quantity... | 08273662492940766dc22494c724cc40a92f9278 | 47,710 |
import functools
def downloadable(orderby=None, limitby=None):
"""Return list of downloadable books.
Args:
orderby: orderby expression, see select()
limitby: limitby expression, see seelct()
Returns:
Records instance representing list of Creator instances.
"""
db = curren... | abb316f1ddcc40969de57dbc8784ede6cddf0997 | 47,711 |
def kube_upgrade_download_images(token):
"""
Ask System Inventory to kube upgrade download images
"""
return _patch_kube_upgrade_state(token, "downloading-images") | 67c94ddb2acb250bc4003fb08bbe822bd172b3a4 | 47,712 |
import cmath
def builtin_precision(n):
"""
Count the digits in an integer.
Count the significant figures of a floating point number.
"""
if isinstance(n, BInt):
ds = str(n).lstrip('-')
return BInt(len(ds))
elif isinstance(n, BFloat):
if cmath.isinf(n.value) or cmath.isnan(n.value):
return BInt(0)
ds ... | fa2397e984c29f7305322d4ad081ef91f150f653 | 47,713 |
import random
from datetime import datetime
import logging
def main():
""" Handler for the main (index) page """
if _SINGLE_PAGE_UI:
# Redirect to the single page UI
return redirect(url_for("page"))
user = current_user()
# Initial tab to show, if any
tab = request.args.get("tab"... | 7ea4e33eeacd5cef0604433ec7d394184b248795 | 47,714 |
def integrate(n=1.0):
"""
integrate the Lane Emden equations, and return the solution as a dictionary
"""
if n > 4.99:
raise SystemExit('Error: integrate: choose n < 4.99.')
list_xi = []
list_theta = []
list_d_theta = []
# Initial Conditions
xi = 1e-6
theta = 1.0
d... | 1fd8349ccc3a758dd2d107e939207dfb2d9ea424 | 47,715 |
def purge_all_unused():
"""Remove all unused data blocks."""
counter = 0
# keep this order.
# as the lower things are contained in the higher ones..
counter += purge_block(bpy.data.objects)
counter += purge_block(bpy.data.meshes)
counter += purge_block(bpy.data.materials)
counter += purg... | 8f77142f5d89a3a934dec3d01423ac942b62c914 | 47,716 |
from openmmtools.multistate import MultiStateReporter, MultiStateSamplerAnalyzer
from perses.analysis.utils import open_netcdf
def analyze_repex(nc_file_path):
""" Analyze RepEx simulation and return the free energy over time and the final free energy. """
reporter = MultiStateReporter(nc_file_path)
nc_f... | 28ada066c51498297d1d48cdf6b3ff649ecec7f5 | 47,717 |
import urllib
def get_url_params(url, encoding="utf-8"):
"""
get the main_part and query_part from a url
"""
frags = urllib.parse.urlparse(url, allow_fragments=True)
components = (frags.scheme, frags.netloc, frags.path, frags.params, "", "")
return urllib.parse.urlunparse(components), urllib.p... | 0a4bf8848e7ec2588070477c81e8a1b8c7ad695e | 47,718 |
def get_direction_values() -> []:
""" Returns all payment directions as enum """
return [DIRECTION_IN, DIRECTION_OUT, DIRECTION_TRANSFER] | 89be5df7089b32936442c19062923b318c9e956d | 47,719 |
from typing import Tuple
import torch
import multiprocessing
def run_simulations_on_all_cores(
agent: agent_base.Agent, env_name: str, batch_size: int
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""
Run multiple simulations using the same agent on multiple cores to obtaine actions,
observati... | 7ae6e587843b2fe707c28967a0531638dfaf2b61 | 47,720 |
def expected_svg(image: str) -> str:
"""Calculate expected SVG."""
return Scour().scour_string(image) | bf8355a8e65c8dbc60279c745135d2156ac15f40 | 47,721 |
import subprocess
def make_lint_report(nb_fpath):
"""Run the tutorial linter on a notebook and capture the output."""
cmdline = ["python", "ci/lint_tutorial.py", nb_fpath]
res = subprocess.run(cmdline, capture_output=True)
return res.stdout.decode() | efa21f6ed52affee862300ae18ed4b639ac9e29a | 47,722 |
def get_valid_ip_address(ls):
"""
Question 7.10: Compute all valid IP addresses
from decimal string, given that
"""
ips = []
# loop over first ip packet
first_idx = 1
while first_idx < 4 and first_idx < len(ls):
second_idx = 1
while second_idx < 4 and \
fi... | eb8b8fc574f489ab260c1a854c4fb1302ca170f8 | 47,723 |
def lemma_details_internal(request):
"""
Render word-detail.html for a lemma. `index` view function renders a whole page that contains word-detail.html too.
This function, however, is used by javascript to dynamically replace the paradigm with the ones of different sizes.
`lemma-id` and `paradigm-size`... | 72b925e3814c69573d83cf597c634b27ab3f4309 | 47,724 |
from typing import Dict
from typing import Tuple
from typing import Any
def _pack_single_bin(
rect_dict: Dict[int, Tuple[Number, Number]],
aspect_ratio: Tuple[Number, Number],
max_size: Tuple[float, float],
sort_by_area: bool,
density: float,
precision: float,
) -> Tuple[Dict[int, Tuple[Number... | 024709ebebc4e5d13ce6d26c8a80dbc6e96d0d59 | 47,725 |
def device_list():
"""Return a list of devices."""
return IMPL.device_list() | f6f461ee4c8897bad46099903ec0aa7973fc3996 | 47,726 |
import os
def getAvailableLanguages():
"""generates a list of locale names, plus their full localized language and country names.
@rtype: list of tuples
"""
#Make a list of all the locales found in NVDA's locale dir
l=[x for x in os.listdir('locale') if not x.startswith('.')]
l=[x for x in l if os.path.isfile('... | 1fb33de6aedcb0edd7429eae3665e02f113f6419 | 47,727 |
from io import StringIO
def analyze(source_code):
""" Trace the source code for display in the browser.
:param source_code: Source code to trace.
:return: (tracing_report, output)
"""
tracer = TraceRunner()
tracer.standard_files.old_files['stderr'] = StringIO()
tracer.max_width = 200000
... | c2d0e61bf5403d9fefccedd05a5c4e505375404b | 47,728 |
def _padding_for_dimension(data, axis, pad_value):
"""Tile `pad_value` so it can be used to pad `data` at the given axis.
Returns a tensor `result` that has the same shape as `data` up to dimension
`axis`, but where each value `data[i0...iaxis]` is replaced by `pad_value`.
I.e., returns `result[i0...iaxis, j0.... | d99c7afb4218bf7e78bef9d3adc2b62dfb5d6790 | 47,729 |
def is_error_status(status):
"""Function that determines whether the RPC status is an error.
Args:
status: Initialized RpcStatus message to check for errors.
"""
status.check_initialized()
return RpcError.from_state(status.state) is not None | 4b2f427eaea201e5abe4239d246b16632b932a12 | 47,730 |
import typing
def getOption(key: str) -> typing.Union[str, bool, None]:
"""Get the value of a CLI solution option. If not defined, will return `None`."""
return _solutionOptions.get(key, None) | 3debc54bb57f11d465cfbedf0df711724ef25f48 | 47,731 |
def primes(upto):
"""
Prime sieve below an <upto> value.
Copied from http://rebrained.com/?p=458
Parameters
----------
upto : int
Find all primes leq this limit.
"""
primes = np.arange(3, upto+1, 2)
isprime = np.ones((upto-1)/2, dtype=bool)
for factor in primes[:int(np... | bf20e031af9d087614391a4de101bea466d4fb0d | 47,732 |
import copy
def _filter_heads(heads, heads_height, radius, polygon):
"""Filter the head candidates following Kienholz et al. (2014), Ch. 4.1.2
Parameters
----------
heads : list of shapely.geometry.Point instances
The heads to filter out (in raster coordinates).
heads_height : list
... | 41b310f521b08d6b882d8906dc75a3460f266946 | 47,733 |
def getTestSuite(select="unit"):
"""
Get test suite
select is one of the following:
"unit" return suite of unit tests only
"component" return suite of unit and component tests
"all" return suite of unit, component and integration tests
"pending" ... | ee8757a69d7240316265475f98a3137eea872ec2 | 47,734 |
def program_name(output_str):
""" Reads the program name from the output file string.
:param output_str: string of the program's output file
:type output_str: str
:rtype: str
"""
prog_string = _get_prog_string(output_str)
prog_name = prog_string.split(':')[1].strip()
prog_n... | 281714b432f2579697b22dd0116f75bbc59cc457 | 47,735 |
def delistify(a, b=None):
"""
If a single element list, extract the element as an object, otherwise
leave as it is.
Examples
--------
>>> delistify('string')
'string'
>>> delistify(['string'])
'string'
>>> delistify(['string', 'other'])
['string', 'other']
>>> delisti... | 61053bd9b37aff70d0e1892a6051c68a53f67d97 | 47,736 |
def upload_parts(
mcg_obj, awscli_pod, bucketname, object_key, body_path, upload_id, uploaded_parts
):
"""
Uploads individual parts to a bucket
Args:
mcg_obj (obj): An MCG object containing the MCG S3 connection credentials
awscli_pod (pod): A pod running the AWSCLI tools
bucket... | 5b3bc840fea74506afe5849bdf2d1a081adcbdc4 | 47,737 |
from typing import List
def get_available_datasets(m1: str, m2: str) -> List[str]:
"""Calculate what datasets are available between m1 and m2
Args:
m1 (str): Name (or path) to pretrained HF model 1
m2 (str): Name (or path) to pretrained HF model 2
Returns:
List[str]: List of all ... | f52df0aeffaf3c7691b9e0ed62ae604347ced3aa | 47,738 |
import dill
import os
def load(x, dtype=None, **kwargs):
"""
Load local or remote files in a wide range of formats
Parameters
----------
:param x: a string containing a URL or file path
:param dtype: Optional argument for specifying how the data should be loaded; can be one of:
- 'pickl... | 20bcf1a6267964d5c971ac2627471002e1ebe801 | 47,739 |
import torch
def histc_cast(input: Tensor, bins: int, min: int, max: int) -> Tensor:
"""Helper function to make torch.histc work with other than fp32/64.
The function torch.histc is only implemented for fp32/64 which makes
impossible to be used by fp16 or others. What this function does, is cast
inpu... | 086081405a9a60322d09cb737d9827c3eb720de0 | 47,740 |
def getkwpars(camera,parname):
"""Extract the correct row of the parameter file based on the
value of CAMERA. Parameters are returned as a keyword:value
dictionary."""
d={}
f=pyfits.open(parname)
t=f[1].data
cols=f[1].columns
# Pick out the matching row of the "camera" column.
cams ... | 994e992e1afaf178cd8aa80cf6d5e9a2e01bb21c | 47,741 |
def get_routes():
"""
Get a list of routes for this agency.
NOT USED. RESERVE.
:return:
"""
# First get the list of routes
route_list_xml = get_nextbus_request(command='routeList', a=NEXTBUS_AGENCY)
route_list_dom = parseString(route_list_xml)
routes = [] # Collect here the routes
... | bf4cf8eb50011b8ae452f86017261d6e04d7b54e | 47,742 |
import requests
from bs4 import BeautifulSoup
def get_new_drugs(month=7,year=2017):
"""Returns a list of all new drug ids or urls."""
drugs = []
query_url=FDA_URL+FDA_QRY_URL+FDA_MONTH+str(month)+FDA_YEAR+str(year)
req = requests.get(query_url)
print( req.status_code)
soup = BeautifulSoup(req.... | 775690adadfaa5ffc5141f6e29e506e632743805 | 47,743 |
import subprocess
def pipe_through(clip, command_and_args):
"""
*pipe_through* pipes *clip* through *command_and_args*, which can be a
string that is passed to the shell. If it is a list, any arguments after
the first one are arguments to the shell, not to the command.
"""
if isinstance(comman... | 56e0907758271dff5849cbb071761f424f90e719 | 47,744 |
from re import T
import re
def jwt_token(value: str) -> T.Union[T.Match[str], None]:
"""
JWT Token Validator
Detail: https://en.wikipedia.org/wiki/JSON_Web_Token
"""
_jwt_pat = r'^[\w\d\-\_\=]+\.[\w\d\-\_\=]+\.?[\w\d\-\_\.\+\/\=]*$'
return re.fullmatch(_jwt_pat, value) | 60158b572cedf8c3dcf4da4f3cac27b156a89015 | 47,745 |
def paginate(parser, token, paginator_class=None):
"""Paginate objects.
Usage:
.. code-block:: html+django
{% paginate entries %}
After this call, the *entries* variable in the template context is replaced
by only the entries of the current page.
You can also keep your *entries* ori... | f511dc445a41146425fa49ef4495162167466a4a | 47,746 |
def autocorrelation(x, lag):
"""Credit goes to https://github.com/blue-yonder/tsfresh"""
if type(x) is pd.Series:
x = x.values
if len(x) < lag:
return np.nan
# Slice the relevant subseries based on the lag
y1 = x[:(len(x) - lag)]
y2 = x[lag:]
# Subtract the mean of the wh... | f69ab3685d57e105313054e33ed8c5c67560c3fc | 47,747 |
from fsleyes.views.lightboxpanel import LightBoxPanel
def run_with_lightboxpanel(func, *args, **kwargs):
"""Create a ``FSLeyesFrame`` with a ``LightBoxPanel`` and run the given
function.
"""
return run_with_viewpanel(func, LightBoxPanel, *args, **kwargs) | 704b94f3a61237eb356e39ca858e47cabc07b907 | 47,748 |
import requests
def auth_callback():
"""
Callback route for after authorization.
parameters:
- name: code
in: args
type: string
required: true
description: Authorization code sent by OAuth Server
- name: state
in: args
type: string
r... | 9748f6a87fa0522a781c551cb5d39f0c356938ae | 47,749 |
def convert_specification_to_graph(formula):
"""Converts a specification formula to a specification graph."""
given_clause, when_clause, then_clause = get_fundamental_clauses(formula)
when_property = convert_clause_to_graph(when_clause)
then_property = convert_clause_to_graph(then_clause)
final_pr... | 5b3f5ba4a8dc7cf90e7438213223ea888820b4c1 | 47,750 |
def get_sens_spec(y_true, y_pred):
"""
Args:
y_true: list of binary ground-truth labels
y_pred: list of binary predictions
Returns:
sensitivity: True Positive Rate = Sensitivity
specificity: True Negative Rate = Specificity (TNR = 1-FPR)
"""
stat_table = sensitivity_s... | 3279caecfeb2a795719b0fabd0f465d2efe16967 | 47,751 |
def shape(context):
"""Returns a new, independent geometry with coordinates *copied* from the
context.
"""
if hasattr(context, "__geo_interface__"):
ob = context.__geo_interface__
else:
ob = context
geom_type = ob.get("type").lower()
if 'coordinates' in ob and _is_coordinates... | d120ca2455ab19cbd426407255da7182dd420d43 | 47,752 |
import csv
def process_csv(csv_path, image='image_id_', stage='image_stage_', fake='image_fake_', answer='image_answer_'):
"""
Process a csv file to a list of Result objects
:param csv_path:
:param image:
:param stage:
:param fake:
:param answer:
:return:
"""
results = []
w... | f363521cac13e80d92b9398e284ed6c9b7cf3e54 | 47,753 |
from typing import OrderedDict
import itertools
def extract_colorpalette(palette_name: str, n: int=None, mode: str='hex'):
"""
Convert color palette to color ramp list.
palette_name {str} name of color palette
n {int} size of color ramp. If None, automatically return the maximum number of colors in t... | c0365ee4f20cdd7c0498317b9d54469f5c655248 | 47,754 |
def max_wave_speed(u):
"""Returns the maximum wave speed for the Euler system"""
# Primitive variables
rho = u[0, 0::3]
v = u[0, 1::3] / rho
E = u[0, 2::3]
p = (constants.gamma - 1) * (E - 0.5 * rho * v * v)
# Get the wave speed
wave_speed = np.fabs(v) + np.sqrt(constants.gamma * p / r... | 4026af0bf620941cffd51e16773656f6469674b2 | 47,755 |
def detect_face(frame):
"""
detect human faces in image using haar-cascade
Args:
frame:
Returns:
coordinates of detected faces
"""
faces = face_cascade.detectMultiScale(frame, 1.1, 2, 0, (20, 20))
return faces | 3b4162491580013d94d826583d138175cbfb14dc | 47,756 |
def read_aq(filename, UTC=False):
"""read in a corrected record that has been exported from Aquarius springboard"""
#filename = r'NO3+NO2,water,insitu_as_N.mg_l.(purged,_ex_situ_SUNA2)@364200119420001.EntireRecord (1).csv'
#skiprows=15
#UTC=False
meta_data = read_aq_metadata(filename)
skipro... | 8fe6acdc2d83c8adb2c569e29fa7a0831b5f018d | 47,757 |
def create_plan(
self,
plan_name: str,
plan_trial_days: int,
plan_length: int,
plan_type: str,
main_currency_code: str = 'USD',
initial_price_usd: float = None,
initial_price_gbp: float = None,
initial_price_eur: float = None,
recurring_price_usd: float = None,
recurring_pric... | 555a1e2e6d0cd4baa61d4b97aa66c814e2df6d2a | 47,758 |
from typing import Optional
def make(target: str = "all", rules: dict = rules) -> Optional[File]:
"""
Make a target (file) using a series of rules.
"""
rule = rules.get(target)
if not rule:
# No rule. See if target already exists.
file = File(target)
if not file.exists():
... | e6bd9927c469d1717a331daebf0d2103309b8509 | 47,759 |
def _make_datasets(tfds_datasetname: str,
vocab: seqio.vocabularies.Vocabulary,
batch_size: int,
sequence_length: int,
has_test: bool = True) -> base.Datasets:
"""Make Datasets object from tokenized tfds dataset."""
if has_test:
splits ... | 500276122c913d98daf7483f1d5c2255bc050b95 | 47,760 |
def fftconvolve2d(inData, inKernel):
"""
Parameters
----------
inData: array_like
Image to be convolved.
inKernel: array_like
Convolution kernel. Odd size preferred.
Returns
-------
outData: array_like
Convolved image.
"""
# Input sizes
y1, x1 = inD... | 84b2c4320fb99783bbbf309626ab1a5bed6747d4 | 47,761 |
import random
def middle_of_bracket_teams():
"""
Finds teams whose only rounds have been one of the following results:
1 - win by forfeit
2 - lenient_late rounds
3 - byes
These teams have speaks of zero but _should_ have average speaks, so they
should be paired into the middle of their b... | 1b2f2adeec3f69d0dcfb4e9fcd6aea3966f0c84b | 47,762 |
def unsorted_segment_sum(tensor, segment_ids, num_segments):
"""Custom PyTorch op to replicate TensorFlow's `unsorted_segment_sum`."""
result_shape = (num_segments, tensor.size(1))
result = tensor.new_full(result_shape, 0) # Init empty result tensor.
segment_ids = segment_ids.unsqueeze(-1).expand(-1, t... | 44740eeb5cc202646c28c39cd65ce727f10bb2da | 47,763 |
def predict_dataframe(df, model_class, hyperspectral_pool, site_label_dict, domain_label_dict, HSI_size=20, k_neighbors=5):
"""Iterate through a geopandas dataframe and get neighbors for each tree.
Args:
df: a geopandas dataframe
model_class: A deeptreeattention model class to extract layer features
... | eb9bf4dbc841c3263b9c509eee71391aebd61257 | 47,764 |
def extract_trades_of_period(dataframe: pd.DataFrame, trades: pd.DataFrame,
date_index=False) -> pd.DataFrame:
"""
Compare trades and backtested pair DataFrames to get trades performed on backtested period
:return: the DataFrame of a trades of period
"""
if date_index:
... | 63726301b2f53a46167976c8656ecd6024ad61e7 | 47,765 |
import io
import PIL
def chunks(png):
"""Yield ``(chunk_type, chunk_raw_data)`` from ``png``.
.. note::
``chunk_raw_data`` includes chunk length, type, and CRC.
:arg png: If ``png`` is a :any:`path-like object` or :any:`file-like object`
object, read the content into bytes.
:type png: path-like, file-li... | cb79306217663a1908d6dce0bc3591b38676c071 | 47,766 |
def get_device_tracking_counters_vlan_message_type(device, vlanid, message_type="received"):
""" Get device_tracking vlan count message type
Args:
device ('obj'): device object
vlanid ('str'): vlan
message_type ('str', optional): message type. Defaults to "received"
... | 3de23dbb76cefd84cdb71f9e62934a3dcc452d9c | 47,767 |
import fnmatch
def match(name: str, expression: str) -> bool:
"""Test whether NAME matches EXPRESSION.
Patterns are Unix shell style:
* matches everything
? matches any single character
[seq] matches any character in seq
[!seq] matches any char ... | 62a56bbb33f73519c80b9319211f8f55543aef85 | 47,768 |
from typing import Dict
from pathlib import Path
import shutil
import re
def fixup_attachment_references(tree: Node, attachments: Dict[Path, AttachmentInfo], source_root_dir: Path,
target_root_dir: Path):
"""
The export from Confluence results in attachments identified by page_... | 2c208edef86d5a301bfa20aa7889107dd97c5e3a | 47,769 |
def before_request():
""" CORS preflight, required for off-server access """
def _build_cors_prelight_response():
response = make_response()
response.headers.add("Access-Control-Allow-Origin", "*")
response.headers.add("Access-Control-Allow-Headers", "*")
response.headers.add("A... | 4a08fba97383b800d0ec303fb4abd97d21e1e2ed | 47,770 |
import scipy
def waa_leijnse_2008_from_A_obs(
A_obs,
f_Hz,
L_km,
T_K=293.0,
gamma=2.06e-5,
delta=0.24,
n_antenna=np.complex(1.73, 0.014),
l_antenna=0.001,
):
"""Calculate wet antenna attenuation according to Leijnse et al. 2008
Calculate the wet antenna attenuation from observ... | 23f4c902a424c309ffc3fd41365a20cdaadffce2 | 47,771 |
def find_brackets(text: str) -> tuple:
"""
Find position of angled brackets in a string and return as a tuple (start, end)
ISSUES:
- Will return a value for "<adjective noun>" which isn't what we want
(Maybe can resolve this by checking returned str matches certain
values - done... | 8f61563118fb5f205d0e77ffb38f11e2703be6bf | 47,772 |
import torch
import datasets
def fake():
""" Fake Dataset by torchvision
Returns:
ImageDataset
"""
target_transform = transforms.Compose([
transforms.Lambda(lambda x: torch.LongTensor([x])),
transforms.Lambda(lambda x: F.one_hot(x, num_classes=10).float()),
])
tr... | 53525a2e2155671ec4fd3d5ff82817cd785b449e | 47,773 |
def find_e0(energy, mu=None, group=None, _larch=None):
"""calculate E0 given mu(energy)
This finds the point with maximum derivative with some
checks to avoid spurious glitches.
Arguments
----------
energy: array of x-ray energies, in eV or group
mu: array of mu(E)
group: outpu... | c905a4f3da8f697d09c21f7934b23ae7179a94e7 | 47,774 |
def move_odict_item(odict, key, newpos):
"""
References:
http://stackoverflow.com/questions/22663966/changing-order-of-ordered-dictionary-in-python
CommandLine:
python -m utool.util_dict --exec-move_odict_item
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict impor... | 2bf86d8a5da8b474b8d487a0247424cb360c0d35 | 47,775 |
def document_search_keys():
"""A list of Regulations.gov document search keys."""
return ['documents', 'totalNumRecords'] | c0969bde192a249c087590332d5deeff19ee06eb | 47,776 |
from datetime import datetime
def sleep_timer(enable=None, period=1800, **kwargs):
"""
Setup sleep timer to schedule power off upon inactivity.
NOTE: Do not access pillar data in this function as they will not be available when called from engines (separate processes).
Optional arguments:
- en... | 48f366b7217e156a222770702e38a23b2058de46 | 47,777 |
from typing import Optional
def environment():
"""
Environment Setting
"""
form = EnvironmentForm()
# TODO: find a way to apply dynamic validation
if gluu_settings.db.get("DEPLOYMENT_ARCH") == "gke":
form.gmail_account.validators.append(InputRequired())
else:
form.gmail_acc... | 33d648a62258587fda1a8230168d6206e26c2e9a | 47,778 |
def eqn23_rule(model,g,tm):
""" Ensures that once you begin to use H2, you cannot transition backwards to old technologies. """
if tm > 1:
return model.hydrogen_use[g,tm] >= model.hydrogen_use[g,tm-1]
else:
return Constraint.NoConstraint | da4b9ecd3afced23ea3c29372d96d457d5881b5e | 47,779 |
import sys
from typing import Union
def _is_union_type(t) -> bool:
"""Check if the argument is a union type."""
if sys.version_info >= (3, 10):
# This checks for the `|` based syntax introduced in Python 3.10.
p310_check = t.__class__ is UnionType
else:
p310_check = False
retur... | 5c6a525fa873ef96e962f16912dbea566ff15219 | 47,780 |
def post_reasoner_predict(request_body):
"""Get predicted associations for a given ReasonerAPI query.
:param request_body: The ReasonerStdAPI query in JSON
:return: Predictions as a ReasonerStdAPI Message
"""
query_graph = request_body["message"]["query_graph"]
model_id = 'openpredict-basel... | 678afe8ab472d1cd0c8702221c405cdb3a37e7ee | 47,781 |
import re
def readjMRUItxt(filename):
"""
Read .txt format file
Parameters
----------
filename : string
Name of jmrui .txt file
Returns
-------
array-like
Complex data
dict
Header information
"""
signalRe = re.compile(r'Signal (\d{1,}) out of (\d{1... | 0c6fc4123d81b4116aa90e6f65f0c7d91454b2f9 | 47,782 |
def call_hooks(event, entry):
"""
Rerun pre or post hooks
"""
hook = event + "-command"
if entry.config["holland:backup"][hook] is not None:
cmd = entry.config["holland:backup"][hook]
try:
cmd = Template(cmd).safe_substitute(
hook=hook, backupset=entry.ba... | 095d5ab2f676d68e3ed7818ae2c54e5c9bae3c40 | 47,783 |
def make_envs(env_id, log_dir, gamma, max_train_ep_length, max_eval_ep_length, seed):
"""Make training and evaluation environments (vectorized envs)."""
# Training env
train_env = gym.make(env_id)
train_env.seed(seed) # Set random seed
train_env = TimeLimitW... | 7c0b7347ee64ec2712a0d72110190f2aab20a31b | 47,784 |
def list_or_caseless_string(value):
"""
Converts the value into a list of ``caseless_string``'s. If the value is
not iterable a one-element list with stringified value will be returned.
"""
if isinstance(value, basestring):
return [caseless_string(value)]
else:
try:
... | 2052e551a07aae23948ab1286a153d863fcdb9a5 | 47,785 |
import aiohttp
from typing import List
import time
import asyncio
async def fetch_all(
session: aiohttp.ClientSession,
urls: List[str],
output=False,
task_per_second: int = 1000,
forbidden_max: int = 10,
output_number: int = 100,
):
"""
Fetches multiple sites using a list of URLs given... | da7f145c1bcf7ffd41a5124197868d0d04c94997 | 47,786 |
from operator import xor
def keyinplaintext(ciphertext, keylen, keyindex, seed, seedindex, decfunc=xor, keyfunc=None):
"""Solves the case when the key used to encrypt is embedded in the plaintext itself.
This function assumes a polyalphabetic substition cipher is used.
Arguments:
ciphertext -- t... | 4a9aaac70c297fae4105106b379085c4cb49fd96 | 47,787 |
def LBGI_HBGI(df):
"""
Connecter function to calculate rh and rl, used for ADRR function
Args:
(pd.DataFrame): dataframe of data with DateTime, Time and Glucose columns
Returns:
LBGI (float): Low blood glucose index
HBGI (float): High blood glucose index
... | 361b9a33286c9beb1b72024ee459fdc01f007a4f | 47,788 |
import requests
import os
import filecmp
def metadata_edit(gvar):
"""
Edit the specified cloud metadata file.
"""
mandatory = ['-cn', '-mn']
required = ['-te']
optional = ['-g', '-H', '-h', '-s', '-v', '-x509', '-xA']
if gvar['retrieve_options']:
return mandatory + required + opt... | 73c8ab09619cffc2f1447ac0ca1aebba5a6577d7 | 47,789 |
import pandas as pd
def describe(col, data):
"""
return basic statistical descriptions
"""
d = {}
# number of observations
d['Nobs'] = [data[col].count()]
# mean
d['Mean'] = [data[col].mean()]
# std
d['Std.'] = [data[col].std()]
# mad
d['Mad'] = [data[col].mad()]
# ... | 300310365fe67a5b76747474c77d0a674299fe49 | 47,790 |
import nose
def nose_command(verbose=True, detailed=True, cover=None):
"""Returns the NoseTest TestCommand runner.
You can use this directly if you want, or pass any of these kwargs to
test_command instead, while also passing nose=True.
KWArgs:
verbose: print verbose test output
deta... | 1b3885b427d593217c12a83694fdff0221ffd104 | 47,791 |
def dealt_damage(
attacker: Pokemon,
defender: Pokemon,
attack_type: str,
attack_power: float,
attack_modifier: float = 1,
defense_modifier: float = 1,
global_modifier: float = 1,
) -> float:
"""
Calculates the damage dealt by a pokemon to another one.
Args:
attacker (Po... | dd91b9e1b1a7b1ba4b2f9e28785ab0b8fea24cdb | 47,792 |
def last_breakout_failed(mode,
historical_data,
num_days_entry=55,
num_days_exit=20):
"""
Returns a Boolean result indicating whether the last breakout cycle before the specified date,
if acted upon, would have led to a loss.
Ar... | 8075fb9457d63f33845973a38de249b326622d05 | 47,793 |
import yaml
def timing_report(file_path):
"""Check whether `file_path` is a valid YAML timing report file
@param file_path
@return ``True`` if valid, ``False`` otherwise
@throw IOError if `file_path` cannot be opened for reading
@throw YAMLError if `file_path` cannot be parsed as a YAML file
... | b0a4641581dc1f68ef5264bddd29ace167c39042 | 47,794 |
def _resample(resampling_way,
ts_list,
resampling_period,
adding_method=AddingMethod.LINEAR_INTERPOLATION,
timestamp_position=TimestampPosition.BEG,
aggregation_method=AggregationMethod.AVG,
nb_points_by_chunk=50000,
gener... | 5bbeb832401977e7310f94a7462fefdf700cff92 | 47,795 |
def send_roll(team, roll, args):
"""Post the roll to Slack."""
chat = Chat(team.get_bot_token())
try:
# Attempt to post message
chat.post_message(
args['channel_id'],
roll,
username='Roll Bot',
icon_emoji=':game_die:'
)
except Err... | 3d7b41eb9056d68f10b9bf342ea31634f71cea5d | 47,796 |
def get_intervals(x):
"""
From an unsorted and possibly sparse collection
of 1D coordinates, compute the number of bins and
the distance between bin centres.
Default is nearest-metre precision, which should be
fine for most seismic surveys.
"""
# Preliminaries.
x = np.asanyarray... | 5de65241c0a2a1d0e508927c3dc3cacceef243a9 | 47,797 |
def cmt_final_digest(parent_digest: str, spec_digest: str, refs_digest: str) -> str:
"""Determine digest of commit based on digests of its parent, specs, and refs.
Parameters
----------
parent_digest : str
digest of the parent value
spec_digest : str
digest of the user spec value
... | a77a3cfcc85d9798720af1cda79b06ca2185e1f2 | 47,798 |
def get_mouse_loc():
"""
Get the x,y location of the mouse
"""
pos = pygame.mouse.get_pos()
return pos[0], pos[1] | c427ba118a31461b3b70a628698837505d899359 | 47,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.