content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def banner():
"""
Function prints banner with its version
"""
_ = BANNER
if not getattr(LOGGER_HANDLER, "is_tty", False):
_ = re.sub("\033.+?m", "", _)
dataToStdout(_) | 5,305,000 |
def create_read_supported_services_cmd() -> list:
"""Create TaiSEIA device services request protocol data."""
return SAInfoRequestPacket.create(
sa_info_type=SARegisterServiceIDEnum.READ_SUPPORTED_SERVICES
).to_pdu() | 5,305,001 |
def normalize_name(name: str) -> str:
"""Replace hyphen (-) and slash (/) with underscore (_) to generate valid
C++ and Python symbols.
"""
name = name.replace('+', '_PLUS_')
return re.sub('[^a-zA-Z0-9_]', '_', name) | 5,305,002 |
def cross_validation(*, task,
pipeline,
X,
y,
cv_method,
metrics,
inverse=None):
"""
Performs cross validation.
-------------------------
Parameters
... | 5,305,003 |
def _update_or_add_directives(directives, insert_at_top, block):
"""Adds or replaces directives in a config block."""
for directive in directives:
_update_or_add_directive(block, directive, insert_at_top)
if block and '\n' not in block[-1]: # could be " \n " or ["\n"] !
block.append(ngin... | 5,305,004 |
def generate_host_key(args):
"""Generate SSH host keys with ssh-keygen."""
key_paths = [
args.output_dir / ssh_host_key_filename(algorithm)
for algorithm, _ in HOST_KEYS
]
okay = True
for key_path in key_paths:
if key_path.exists():
LOG.error('attempt to overwrit... | 5,305,005 |
def get_replication_configuration(registry_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetReplicationConfigurationResult:
"""
The AWS::ECR::ReplicationConfiguration resource configures the replication destinations for an Amazon Elastic Con... | 5,305,006 |
def _GetTokenScopes(access_token):
"""Return the list of valid scopes for the given token as a list."""
url = _OAUTH2_TOKENINFO_TEMPLATE.format(access_token=access_token)
response = apitools_base.MakeRequest(
apitools_base.GetHttp(), apitools_base.Request(url))
if response.status_code not in [ht... | 5,305,007 |
def sample(f1, f2, f3, f4):
"""
@see: field 1
@note : is it a field? has space before colon
@param f1: field 3 with an arg
@type f1: integer
@param f2 : is it a field? has space before colon
@return: some value
@param f3: another one
"""
return 1 | 5,305,008 |
def read_tree(attributes, data):
"""
Read the attibutes and create the pickle and tree files
"""
att_trees = []
index = 0
for attribute in attributes:
if attributes[attribute].get('qi', False):
if attributes[attribute].get('category', False):
categories = get_... | 5,305,009 |
def _split_material_groups(src, dst):
"""Splits .obj material groups.
This functions adds matgroup tags so we can split the geometry per material
group.
Args:
src(str): path to source .obj file.
dst(str): path to target .obj file.
"""
matre = re.compile(r'^usemtl\s*(?P<mat>.*)\... | 5,305,010 |
async def server(request, response, args):
""" Function define the web page to configure the start of servers """
config = ServerConfig()
disabled, action, submit = manage_default_button(request, config)
page = main_frame(request, response, args,lang.servers_configuration,
Switch(text=lang.ftp , name=b"ftp" ,... | 5,305,011 |
def cexpr_operands(self):
"""
return a dictionary with the operands of a cexpr_t.
"""
if self.op >= cot_comma and self.op <= cot_asgumod or \
self.op >= cot_lor and self.op <= cot_fdiv or \
self.op == cot_idx:
return {'x': self.x, 'y': self.y}
elif self.op == cot_tern:
... | 5,305,012 |
def live_ticket(db, live_taxpayer):
"""Return an authentication ticket usable with AFIP's test servers.
AFIP doesn't allow requesting tickets too often, so we after a few runs
of the test suite, we can't generate tickets any more and have to wait.
This helper generates a ticket, and saves it to disk i... | 5,305,013 |
def define_model():
"""
This model is a little less accurate than the best one I found.
But it also has onlya quarter the paramenters so its a lot smaller.
"""
model = k.Sequential()
model.add(k.layers.Conv2D(filters=15, kernel_size=(3,3), strides=(1, 1), padding="valid", input_shape=(40, 24, 1)... | 5,305,014 |
def volume_opt(src, dest, require=True):
"""Return a volume's argument for docker run
Don't use volume_opt with hard-coded linux paths, it will make Windows try and mkdir in
C:\\WINDOWS\\system32 and fail. volume_opt can handle C:\\... syntax correctly. Instead,
just use '-v /linux/path:/mount/point an... | 5,305,015 |
def _project_rf(input, output, offset_x=0, offset_y=0, return_pos=False):
"""Project one-hot output gradient, using back-propagation, and return its bounding box at the input."""
# create one-hot output gradient tensor, with 1 in the center (spatially)
pos = [0] * len(output.shape) # index 0th batch/channel/etc... | 5,305,016 |
def _test_remove_comments():
"""
Unit test for L{_remove_comments}.
"""
s = '/*d s kjlsdf */*//*/*//**/**/*//**/a' * 50
assert len(_remove_comments(s)) == len(s)
s = '/**/' * 50 + '/*5845*/*/*//*/**/dfd' + '/*//**//'
assert len(_remove_comments(s)) == len(s)
s = 'a/**/' * 50 + '/**//**//... | 5,305,017 |
def fill_ts_missing_entries(start, end, timeseries, interpolation_method, timestep):
"""
:param start: "YYYY-MM-DD HH:MM:SS" the starting timestamp of the timeseries index
:param end: "YYYY-MM-DD HH:MM:SS" the last timestamp of the timeseries index
:param timeseries: list of [time, value] lists
:pa... | 5,305,018 |
def play_game(iterations, initialize_game):
"""
Simulate gameplay and record number of rounds and trains used each time
"""
winners = []
records = {}
for i in range(iterations):
record = {}
game, players = initialize_game()
record["deck"] = game.cards
record["des... | 5,305,019 |
def check_tf_min_version(min_required_version, message=""):
""" Skip if tf_version < min_required_version """
config = get_test_config()
reason = _append_message("conversion requires tf >= {}".format(min_required_version), message)
return unittest.skipIf(config.tf_version < LooseVersion(min_required_ver... | 5,305,020 |
def filt2(
kernel: np.ndarray,
im1: np.ndarray,
reflect_style: Union[str, int, float] = "odd",
) -> np.ndarray:
"""
Improved version of filter2 in MATLAB, which includes reflection.
Default style is 'odd'. Also can be 'even', or 'wrap'.
Args:
kernel: Kernel
im1: Input ndarra... | 5,305,021 |
def getAccountASABalance(account: Addr, assetId: Int) -> TealType.uint64:
"""
This subroutine returns the amount of ASA held by a certain
account. Note that the asset id must also be passed in the ``foreignAssets``
field in the outer transaction (otherwise you will get a reference error)
:param Add... | 5,305,022 |
def get_package_version():
"""get version from top-level package init"""
version_file = read('pywcmp/__init__.py')
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeE... | 5,305,023 |
def copyFilesToEOS(directory, destination, filenames):
""" Copy the given filenames to EOS.
Files which failed are returned so that these files can be saved and the admin can be alerted to take
additional actions.
Args:
directory (str): Path to the directory where the files are stored locally.... | 5,305,024 |
def random_date_strf() -> str:
"""Generate a random date."""
year = random_year()
day_of_year = random_day_of_year(year=year)
return datetime.strptime(f"{year}-{day_of_year}", "%Y-%j").strftime("%Y-%m-%d") | 5,305,025 |
def __sample(data, labels, sampling_rate):
"""subsample data"""
indices = []
for i in set(labels):
idxs = [x for x in range(len(labels)) if labels[x] == i]
n = len(idxs)
s = int(np.ceil(len(idxs) * sampling_rate))
aux = np.random.permutation(n)[0:s]
indices += [idxs[x... | 5,305,026 |
def main():
"""
Finds all the metadata .json files and builds a list of the URLs. Will
then try and copy them using the filename of the URL rather than the hash
"""
c = ConfigParser.ConfigParser()
c.read(ffs.Path('~/.dc.ini').abspath)
bucket_name = c.get('ckan', 'aws_bucket')
conn = s3c... | 5,305,027 |
def format_span_json(span):
"""Helper to format a Span in JSON format.
:type span: :class:`~opencensus.trace.span.Span`
:param span: A Span to be transferred to JSON format.
:rtype: dict
:returns: Formatted Span.
"""
span_json = {
'displayName': _get_truncatable_str(span.name),
... | 5,305,028 |
async def main(req: func.HttpRequest, starter: str) -> func.HttpResponse:
"""This function starts up the orchestrator from an HTTP endpoint. It retrieves
the user requested entity state and returns it back as a HTTP response.
Args:
req (func.HttpRequest): An HTTP Request object, it can be used... | 5,305,029 |
def slide_to_img(slide, new_mpp=0.5, return_np=True, return_sizes=False):
"""
Scale slide image based on desired microns per pixel
"""
old_mpp_x = np.float(slide.properties['openslide.mpp-x'])
old_mpp_y = np.float(slide.properties['openslide.mpp-y'])
new_mpp = np.float(new_mpp)
SCA... | 5,305,030 |
def get_table2(res):
"""
Puts columns for table 2 together in a Dataframe and adds labels
Args:
res(list): list of arrays containing the subject
specific paramater estimates
Returns:
table2(Pd.DataFrame): Dataframe containing table 2
"""
rownames = [
"mean... | 5,305,031 |
def decode_dist_anchor(det_residual, det_angle_cls, det_angle_res, batch_anchors_3d, is_training):
"""
Decode bin loss anchors:
Args:
det_residual: [bs, points_num, 6]
det_angle_cls: [bs, points_num, -1]
det_angle_res: [bs, points_num, -1]
batch_anchors_3d: [bs, points_num, 7... | 5,305,032 |
def test_atomic_integer_max_inclusive_3_nistxml_sv_iv_atomic_integer_max_inclusive_4_1(mode, save_output, output_format):
"""
Type atomic/integer is restricted by facet maxInclusive with value
-2761698266856349.
"""
assert_bindings(
schema="nistData/atomic/integer/Schema+Instance/NISTSchema-... | 5,305,033 |
def refund_query():
"""
swagger-doc: 'do refund query'
required: []
req:
page_limit:
description: 'records in one page 分页中每页条数'
type: 'integer'
page_no:
description: 'page no, start from 1 分页中页序号'
type: 'integer'
order_id:
description: '订单编号'
... | 5,305,034 |
def display_graph_frame(graph_panel):
"""Remove currently displayed graph if necessary, and display given graph in main panel."""
if graph_panel is not None:
_main_panel.DestroyChildren()
_main_panel.AddChild(graph_panel) | 5,305,035 |
def _save(conn: sqlite3.Connection, tablename: str,
keys: Mapping[str, Any], values: Mapping[str, Any]) -> None:
"""Write cached result into the table, creating it if it does not already exist."""
_create_table(conn, tablename, keys, values)
# Combine all fields
entries = dict(keys)
entrie... | 5,305,036 |
def init_logging(log_level):
"""
Init logging settings with default set to INFO.
"""
level = log_level_to_string_map[log_level]
if level in os.environ:
msg = "%(levelname)s - %(name)s:%(lineno)s - %(message)s"
else:
msg = "%(levelname)s - %(message)s"
logging_conf = {
... | 5,305,037 |
def qt_551_plus():
""" Return True if Qt version is 5.5.1+ """
from distutils.version import LooseVersion
from PyQt5.QtCore import QT_VERSION_STR
return LooseVersion(QT_VERSION_STR) >= LooseVersion("5.5.1") | 5,305,038 |
def dist_to_pixel(val_dist, mode,
d_max=D_MAX, d_min=D_MIN):
""" Returns pixel value from distance measurment
Args:
val_dist: distance value (m)
mode: 'inverse' vs 'standard'
d_max: maximum distance to consider
d_min: minimum distance to consider
Returns:
... | 5,305,039 |
def parse_args():
"""Parse command line arguements.
Parameters:
Nothing
Returns:
arguments: argparse.Namespace object
An object containing all of the added arguments.
Outputs:
Nothing
"""
input_help = 'Images to tweak back to flts. Default is f*dr?.fits'
... | 5,305,040 |
def test_tutorial(nb_path, cell_values, tmp_path, tmp_env):
"""Test tutorial in the IPython notebook at *fname*.
If *cell_values* are given, values in the specified cells are tested.
"""
# The notebook can be run without errors
nb, errors = run_notebook(nb_path, tmp_path, tmp_env)
assert errors... | 5,305,041 |
def test_gnupg_gen_key_conf(gnupg_gen_key_conf: Path):
"""Test that a GnuPG script to generate a keypair can be provided."""
assert gnupg_gen_key_conf.exists()
content = gnupg_gen_key_conf.read_text("utf-8")
assert "commit" in content | 5,305,042 |
def normal_probability_plot(data):
"""Plot the distribution of normal probabilities of errors."""
norm = distributions.normal_distribution()
n = len(data["delta_hl"])
if n <= 10:
a = 3 / 8
else:
a = 0.5
y = flex.sorted(flex.double(data["delta_hl"]))
x = [norm.quantile((i + ... | 5,305,043 |
def save_data_with_time_stamp(signal):
"""
Save signal in time-stamped file.
Creates a filename using the current time.
Args:
signal: array of ellipsometer readings
Returns:
filename of the file created
"""
t = time.localtime()
time_stamp_name = time.strftime('lab3-%Y-%... | 5,305,044 |
def calc_vega(
asset_price, asset_volatility, strike_price, time_to_expiration, risk_free_rate
):
"""The first-order partial-derivative with respect to the underlying asset volatility of
the Black-Scholes equation is known as vega. Vega refers to how the option value
changes when there is a change in th... | 5,305,045 |
def bmi(weight, height):
""" (number, number) -> number
Returns the body mass index from the provided weight (pounds) and height (inches).
important information:
bmi: weight * 703 / height**2
"""
raise NotImplementedError("Delete this line and put your code here") | 5,305,046 |
def create_and_upload_marketplace_pack(upload_config: Any, pack: Any, storage_bucket: Any, index_folder_path: str,
packs_dependencies_mapping: dict, private_bucket_name: str,
private_storage_bucket: bool = None,
... | 5,305,047 |
def IM_jump_if_false(self):
""" Set ip to value in 2nd_param if 1st_param is zero. """
IM_jump_if(self, lambda s: s == 0) | 5,305,048 |
def get_short_doi(doi, cache={}, verbose=False):
"""
Get the shortDOI for a DOI. Providing a cache dictionary will prevent
multiple API requests for the same DOI.
"""
if doi in cache:
return cache[doi]
quoted_doi = urllib.request.quote(doi)
url = 'http://shortdoi.org/{}?format=json'.... | 5,305,049 |
def calculate_payments(yearly_payments_percentage, cost_reductions,
days_with_payments, days_for_discount_rate):
""" Calculates payments for a participant/investor """
return [period_payment(yearly_payments_percentage, ccr,
days_with_payments[i], days_for_disco... | 5,305,050 |
def draw_random(G, **kwargs):
"""Draw networkx graph with random layout.
Parameters
----------
G : graph
A networkx graph
kwargs : optional keywords
See hvplot.networkx.draw() for a description of optional
keywords, with the exception of the pos parameter which is not
us... | 5,305,051 |
def test_preprocessor_visit_one_children(patch, magic, preprocessor):
"""
Check that a single inline_expression is found
"""
tree = magic()
c1 = magic()
replace = magic()
c1.children = [magic()]
tree.children = [c1]
def is_inline(n):
return n == c1
preprocessor.visit(tre... | 5,305,052 |
def connect_to_contract(address):
"""Helper function for connecting to a contract at an address"""
url = "https://mainnet.infura.io/v3/1a09c4705f114af2997548dd901d655b"
endpt = RPCEndpoint(network=network, provider=provider, url=url)
endpt.connect()
c = Contract(node=endpt, address=address, abi=tel... | 5,305,053 |
def get_user():
"""Retreives a single user from a Database, and render it using a HTML template"""
try:
data = json.loads(request.data)
except ValueError:
return '', 400
else:
email = data['customer']['email']
# For more complex queries, consider moving queries to a separate... | 5,305,054 |
def allclose_nparray(data_expected, data_actual, rtol, atol=1e-08):
"""Compare whether arrays are element-wise equal within tolerances."""
if not np.allclose(data_expected, data_actual, rtol, atol):
count_unequal_element(data_expected, data_actual, rtol, atol) | 5,305,055 |
def phys_tokens(toks):
"""Return all physical tokens, even line continuations.
tokenize.generate_tokens() doesn't return a token for the backslash that
continues lines. This wrapper provides those tokens so that we can
re-create a faithful representation of the original source.
Returns the same v... | 5,305,056 |
def sniff(
resource: bytes,
mime_type_string: str = "unknown/unknown",
no_sniff: bool = False,
check_for_apache_bug: bool = False) -> str:
"""
Implementation of algorithm in:
https://mimesniff.spec.whatwg.org/#determining-the-computed-mime-type-of-a-resource
The main met... | 5,305,057 |
def decrypt(key, enc, use_base64=True):
"""Optionally base64-decode and decrypt."""
decoded = enc
if use_base64:
decoded = base64.b64decode(enc)
raw = _cipher(key).decrypt(decoded)
return _unpad(raw).decode("utf-8") | 5,305,058 |
def create_rng(random_state):
"""
Creates a random state object
Parameters
----------
random_state : int or NoneType or np.random.RandomState
Input to create RNG
Returns
-------
rng : np.random.RandomState
Pseudo-random number generator
"""
if random_state is N... | 5,305,059 |
def read_header(file_handle):
"""Reads a CPHD header from a file.
Parameters
----------
file_handle
Readable File object, i.e., ``file_handle = open(filename, 'rb')``.
Handle of the CPHD file that is to be read
Returns
-------
Dict
Dictionary containing CPHD header val... | 5,305,060 |
async def validate_input(hass: core.HomeAssistant, conf):
"""Validate the user input allows us to connect."""
try:
info = await async_get_discovery_info(
hass,
conf[CONF_HOST],
conf[CONF_PORT],
conf.get(CONF_SECURE, False),
conf[CONF_ACCESS_TOK... | 5,305,061 |
def read():
"""Return the contents of the Windows Common Setup as a string"""
setup_in = open(PATH)
try:
return setup_in.read()
finally:
setup_in.close() | 5,305,062 |
def longest_subarray(numbers: List[int], limit: int) -> int:
"""https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/"""
# monotone increasing queue with indices that could become the sliding window minimum
min_queue = deque()
# monotone decreasing q... | 5,305,063 |
def consume_items(events, limit=20):
"""Consume a whole array and yield a limited amount of events from it."""
start_prefix, start_event, start_value = next(events)
end_prefix = start_prefix
end_event = start_event.replace('start', 'end')
reverse = limit < 0
limit = abs(limit)
rows = colle... | 5,305,064 |
def ris_defaultValue_get(fieldsTuple):
"""
params: fieldsTuple, ()
return: fieldVaule_dict, {}
"""
#
ris_element = fieldsTuple[0]
if len(fieldsTuple[1]) != 0:
default_value = fieldsTuple[1][0]
else:
default_value = []
fieldValue_dict = {}
fieldValue_dict[ris_eleme... | 5,305,065 |
def _write_prototxt(train_net, param_list, file_name, depth, blob):
"""
Given a list of parameters with length (depth + 1), insert noise with given
parameters to the prototext given and write to redeye directory with given
file name.
"""
if os.path.isfile(file_name):
return
extra_layers = []
new_train_net ... | 5,305,066 |
def project_to_2d(X, camera_params):
"""
Project 3D points to 2D using the Human3.6M camera projection function.
This is a differentiable and batched reimplementation of the original MATLAB script.
Arguments:
X -- 3D points in *camera space* to transform (N, *, 3)
camera_params -- intrinsic... | 5,305,067 |
def batch(args):
"""
%prog batch splits output
The arguments are two folders.
Input FASTA sequences are in splits/.
Output csv files are in output/.
Must have folders swissprot/, tair/, trembl/ that contains the respective
BLAST output. Once finished, you can run, for example:
$ paral... | 5,305,068 |
def disp_var_globals(*varnames, head_=True, align_=True, scope_=globals()):
"""
def func():
a = "hoge"
b = 123
c = [1,"1"]
disp_var_globals("a","b","c",scope=locals())
func()
>>> a: hoge
>>> b: 123
>>> c: [1, '1']
"""
if head_: print(f"#=== VARIABLE INFO ... | 5,305,069 |
def read_header_keywords_table(filepath):
""" Read a table of .fits keywords from a .csv file into a
HeaderKeywordList of HeaderKeyword objects.
:param filepath: The location of the .csv file containing the header
keyword table.
:type filepath: str
"""
# Open the file a... | 5,305,070 |
def compara(chave, lst):
"""Compara usuários da lista lst através da chave
A comparacão ocorre montando um dicionário de listas de usuário
temporáriamente em dic. Uma vez que todo o dicionário está montado
os índices do dicionário que contém mais do que um elemento são
copiados para o dicionário de... | 5,305,071 |
def exists(bucket: str, key: str) -> bool:
"""Checks if there is an object in the object store with the given key
Args:
bucket (dict): Bucket containing data
key (str): Prefix for key in object store
Returns:
bool: True if exists in store
"""
# Get the object and use the key... | 5,305,072 |
def apply_module_to_android_project(module_path, project_path, app_config, skip_jar=False, include_tests=False, local_build_steps=None):
"""Take the module in a specific folder and apply it to an eclipse android project in another folder"""
if not os.path.exists(os.path.join(module_path, 'manifest.json')):
... | 5,305,073 |
def format_element_to_matlab_confusion_matrix(row, col, confusion_matrix):
"""
Return a string for the element on row, col location for
confusion_matrix to either
number of observation\npercentage of observations or
percentage_correct_classifications\npercentage_incorrect_classifications
per cla... | 5,305,074 |
def add_lazy_nh4_pm25(d, dict_sum):
"""Calculates sum of particulate NH4.
Parameters
----------
d : xarray.Dataset
RRFS-CMAQ model data
Returns
-------
xarray.Dataset
RRFS-CMAQ model data including new NH4 calculation
"""
keys = _get_keys(d)
allvars = Series(di... | 5,305,075 |
def test_radio_button(qtbot):
"""Make sure the QtModeRadioButton works to change layer modes"""
layer = Points()
assert layer.mode != Mode.ADD
btn = QtModeRadioButton(layer, 'test_button', Mode.ADD, tooltip='tooltip')
assert btn.property('mode') == 'test_button'
assert btn.toolTip() == 'tooltip... | 5,305,076 |
def test_read():
"""Test reading a whole agp file with a comment on the first line"""
agp_path = os.path.join(os.path.dirname(__file__), "data", "test.agp")
for row_number, row in enumerate(agp.open_agp(agp_path)):
if row_number == 0:
assert agp.is_string(row)
else:
a... | 5,305,077 |
def record(episode,
episode_reward,
worker_idx,
global_ep_reward,
total_loss,
num_steps):
"""Helper function to store score and print statistics.
Arguments:
episode: Current episode
episode_reward: Reward accumulated over the current episode
... | 5,305,078 |
def transform_cav2im3d_entropy(cavity_coords, grid_min, grid_shape, pharmaco):
"""
Takes coordinates of grid points and outputs an im3d for skimage
Uses entropy at 3A of pharmacophores as values to set the "greyscale"
"""
# First we simply the pharmacophores
names = np.array([0, 1, 1, 3, 3, 3, 4, 5, 0, 0, 0]) # ... | 5,305,079 |
def _normalize_title(key: str) -> str:
"""MediaWiki treats the first character of article names as upper-case."""
if not key: # Empty string
return ""
key = _normalize_spaces(key)
return key[0].upper() + key[1:] | 5,305,080 |
def n_coeffs_to_degree(n_coeffs):
"""what is degree if 2d polynomial has n_coeffs coefficients"""
delta_sqrt = int((8 * n_coeffs + 1.)**.5 + 0.5)
if delta_sqrt**2 != (8*n_coeffs+1.):
raise ValueError('Wrong input in n_coeffs_to_degree(): {:}'.format(n_coeffs))
return int((delta_sqrt - 3.) / 2. +... | 5,305,081 |
def test_query_vizier():
"""Test for the query_vizier function"""
# 2MASS catalog
catalog = '2MASS'
sky_coords = SkyCoord(ra=1.23, dec=2.34, unit=(q.degree, q.degree), frame='icrs')
# Query target
results = query.query_vizier(catalog, target='Vega', search_radius=20 * q.arcsec, verbose=True)
... | 5,305,082 |
def import_precip_file_df(fname, conn: sqlite3.Connection):
"""
Import a single raw precipitation data file.
New style using pandas.
This was slower for me, perhaps because method='multi' was failing for me with sqlite3.
:param fname: Filename
:param conn: DB connection
:return: None
"""... | 5,305,083 |
def _write_worker(audit_key, audit_version, plugin_key, plugin_config,
input_queue, worker_type):
"""Worker function for store and alert plugins.
Arguments:
audit_key (str): Audit key name in configuration
audit_version (str): Audit version string.
plugin_key (str): Pl... | 5,305,084 |
def admin_access(app):
"""Grant admin-access with this fixture"""
with mock.patch.dict(app.tornado_settings, {'admin_access': True}):
yield | 5,305,085 |
def add_port_groups(port_groups):
""" add each port_group in list of port_groups using the function add_port_group """
for port_group in port_groups:
add_port_group(port_group) | 5,305,086 |
def load():
"""Loads settings static configuration.
As the configuration is static and immutable, it is loaded only once from the disk.
Returns an instance of the `Settings` class.
"""
global _SETTINGS
if _SETTINGS is not None:
return _SETTINGS
s = _load_yaml(SUBSTRA_TESTS_CONFIG_... | 5,305,087 |
def modinv(a, b):
""" Returns x such that (x * a) (mod b) == 1
reference: https://stackoverflow.com/questions/4798654/modular-multiplicative-inverse-function-in-python
"""
g, x, _ = egcd(a, b)
if g != 1:
raise Exception('modular inverse does not exist')
else:
return x % b | 5,305,088 |
def keygen():
"""
Generate private and public keys for the "greased", bootstrappable encryption scheme.
The main idea here is that we want to minimize computation during decryption because it originally contains
an expensive modulus operation (c % p) that is too much for our somewhat homomorphic en... | 5,305,089 |
def process_image(image_path):
"""
Given a path to a file, pre-process that image in preparation for making a prediction.
:param image_path: the path to the image file
:return: the image represented by a flattened numpy array
"""
im_transforms = TRANSFORM_TEST_VALIDATION
# Open image
im = Image.open(image_path... | 5,305,090 |
def checksum_md5(filename, blocksize=8192):
"""Calculate md5sum.
Parameters
----------
filename : str or pathlib.Path
input filename.
blocksize : int
MD5 has 128-byte digest blocks (default: 8192 is 128x64).
Returns
-------
md5 : str
calculated md5sum.
"""
... | 5,305,091 |
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Unifi Controller."""
from pyunifi.controller import Controller, APIError
host = config.get(CONF_HOST)
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
site_id = config.get(CONF_SITE_ID)
... | 5,305,092 |
def proxyobj(bus, path, interface):
""" commodity to apply an interface to a proxy object """
obj = bus.get_object('org.bluez', path)
return dbus.Interface(obj, interface) | 5,305,093 |
def get_create_idea():
"""
Renvoie la vue pour créer une nouvelle Idée
:return:
"""
user = User.query.filter_by(id=session['uid']).first()
return render_template(
'create_idea.html',
title='Proposez une nouvelle idée de projet',
data={'user': user}
) | 5,305,094 |
def scale_size(range=None, name=None, breaks=None, labels=None, limits=None, na_value=None, guide=None, trans=None,
format=None):
"""
Scale for size.
Parameters
----------
range : list
The range of the mapped aesthetics result.
name : str
The name of the scale - u... | 5,305,095 |
async def test_options_flow_import(hass, pyscript_bypass_setup):
"""Test options flow aborts because configuration needs to be managed via configuration.yaml."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data=PYSCRIPT_SCHEMA({CONF_ALLO... | 5,305,096 |
def conv2d(input,
num_filters,
filter_size,
stride=1,
padding=0,
dilation=1,
groups=None,
param_attr=None,
bias_attr=None,
use_cudnn=True,
act=None,
name=None,
data_format="NCHW"):
"""... | 5,305,097 |
def test_help(_, capsys):
"""Expect help from `smif` or `smif -h`
"""
msg = "Command line tools for smif"
main([])
output = capsys.readouterr()
assert msg in output.out
main(['-h'])
output = capsys.readouterr()
assert msg in output.out | 5,305,098 |
def modifies(repo, subset, x):
"""``modifies(pattern)``
Changesets modifying files matched by pattern.
The pattern without explicit kind like ``glob:`` is expected to be
relative to the current directory and match against a file or a
directory.
"""
# i18n: "modifies" is a keyword
pat = ... | 5,305,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.