content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def align_coefs(coefs, lag, verbose=False):
"""
coefs: n* lag x n. the i * lagth row of col k is the auto-coefficient of k on k
# align the coefs:
# split into same lag
return: lag x n x n. the
"""
assert len(coefs.shape) == 2
assert coefs.shape[0] / lag == coefs.shape[1]
n = coef... | b5b10a736b1cca25d692ce5763cd77195727d6fb | 3,624,649 |
def calc_zq(qz, zp, zm, En, aa):
"""
function used in computing polar geodesic coordinates
Parameters:
qz (float)
zp (float): polar root
zm (float): polar root
En (float): energy
aa (float): spin
Returns:
zq (float)
"""
ktheta = (aa ** 2 * (1 - E... | 4cd285a74ba1d86b438ec8ef379aed898e6613f5 | 3,624,650 |
def equation_dw18(dbconn, speccode, biomassassign, dbh, ht):
""" Equation form: ((a + b * dbh + c * (dbh ^ d))-(e + f * dbh + g * (dbh ^ h))) """
qstr = "SELECT a, b, c, d, e, f, g, h FROM VolBioCoeffs WHERE SpecCode = '%s'" % (biomassassign)
c = dbconn.cursor()
c.execute(qstr)
coeffs = c.fetchone()... | de2cc9702bdfcce3686fe5fa50d346571803ce55 | 3,624,651 |
def denormalize(images, min_, max_):
"""scales image back to min_, max_ range"""
return [((i + 1) / 2 * (max_ - min_)) + min_ for i in images] | 3071e3c76754bda8ea2ce9607003cfd1b4f97e48 | 3,624,652 |
def update_config(config, args):
"""Update config by ArgumentParser
Args:
args: ArgumentParser contains options
Return:
config: updated config
"""
if args.cfg:
_update_config_from_file(config, args.cfg)
config.defrost()
if args.dataset:
config.DATA.DATASET = a... | f0c7dbb0ea32b8682ad2b2c7fe60ce0caa0e6b1f | 3,624,653 |
def update_or_create_variable(site, slug, date, value):
"""Update or create variable
"""
variable = None
try:
variable = Variable.objects.get(site=site, slug=slug)
variable.update_value(date, value)
variable.save()
except Variable.DoesNotExist:
LOGGER.info("Variable c... | 75feb3716199354e9b3137dd14f15fd96743bdb2 | 3,624,654 |
def version_is_locked(version):
"""
Determine if a version is locked
"""
return getattr(version, "versionlock", None) | b2f76d89c2d0082ad13d5d896e5360d394c83ee1 | 3,624,655 |
from datetime import datetime
import platform
def generate(request, recipient):
"""
Generate a test email.
:param request: the current request
:type request: pyramid.request.Request
:param recipient: the recipient of the test email
:type recipient: str
:returns: a 4-element tuple contain... | 6b4926e5fb1e1791cc6ef20b6ad53a76a0451b16 | 3,624,656 |
def pssm_scan(pwm, seqs, background_probs=[0.27, 0.23, 0.23, 0.27], pad_mode='median', n_jobs=10, verbose=True):
"""
"""
def pwm2pssm(arr, background_probs):
"""Convert pwm array to pssm array
pwm means that rows sum to one
"""
arr = arr / arr.sum(1, keepdims=True)
ar... | 077ec517fde9d65d626a3473674c400b0199c40b | 3,624,657 |
def build_orientation_img(d, mask):
"""
Args:
d: [.., H, W, 8]
mask: [..., H, W]
"""
y = np.expand_dims(mask, -1)
cw = color_wheel
did = np.argmax(d, -1)
new_shape = []
for ss in xrange(len(y.shape) - 1):
new_shape.append(y.shape[ss])
new_shape.append(3)
c... | 3a67abb8e7a108c7eeb56e3c4717166f90c44869 | 3,624,658 |
def compute_projection_transforms(origins, transformer) -> np.ndarray:
"""
Convert vectors from one coordinate system to another. Unlike positions,
this cannot be done with a simple pyproj call. We first need to set up a
vector start and end point, convert those into the new coordinate system
and th... | 90f86b83c16a9190444c501c88c6bbc09a2388b7 | 3,624,659 |
def get_function_by_name(full_name):
"""
RETURN FUNCTION
"""
# IMPORT MODULE FOR HANDLER
path = full_name.split(".")
function_name = path[-1]
path = ".".join(path[:-1])
constructor = None
try:
temp = __import__(path, globals(), locals(), [function_name], -1)
output =... | 12131fe15f3614518469f217596192692b2e7a51 | 3,624,660 |
def get_app(endpoints):
"""
:param list(Endpoint) endpoints: Endpoints describing the mapper
:rtype: aiohttp.web.Application
:returns: an app configured as describes in endpoints
"""
app = web.Application(middlewares=[error_middleware])
async def on_startup(app):
app['rabbitmq_conne... | bc56aeabefe0ff057721c740d10d0073e51687cd | 3,624,661 |
import copy
def get_abbr_data():
"""
Get a deep copy of the abbreviation map.
Returns
-------
:class:`dict` (:class:`str`, :class:`str`)
A dictionary of the identifiers, the keys are the abbreviation.
"""
return copy.deepcopy(_glass_type_registry) | 98465fa72e64b95f51c7548e233b172be13bdec2 | 3,624,663 |
from typing import Union
def _load_data_input_from_file(path: str, **further_parse_args) -> Union[pd.DataFrame, list]:
"""Load and process the input data according the input file format."""
if path.endswith(CSV):
return from_dataframe_file(path, CSV)
elif path.endswith(XLS_FORMATS):
retur... | 67b3ebe052d78640340850fb7200c1672a550544 | 3,624,664 |
def generate_ceiling_json(conf: ConfigManager, polyline, room_id: str, multiplication_factor: float) -> dict:
"""
Generate a json describing a ceiling.
:param conf: ConfigManager
:param polyline: Outline of the room
:param room_id: id of the room
:param multiplication_factor: Scale factor to rea... | 56617b32543c9dea58ff9c15efe42b82eb7ea002 | 3,624,665 |
def _compute_edge_transforms(node_states,
depth,
num_transforms,
ignore_zero=True,
name="transform"):
"""Helper function that computes transformation for keys and values.
Let B be the number of batch... | 8c7c88014dd33e0b44df953407a0e64c9cabda15 | 3,624,666 |
def optimize(model, **kwargs):
"""Removes LogSoftmax and positive scaling (Mul) layers from the network because they do not change the prediction.
Args:
model (NeuralNet): The NeuralNet model.
Returns:
NeuralNet: The NeuralNet model with removed layers.
"""
while( (isinstance(model... | 6b7cd43377517c2ea301a629cbf8fb46c8f0e4fe | 3,624,667 |
import logging
def fetch_run(workspace: Workspace, run_recovery_id: str) -> Run:
"""
Finds an existing run in an experiment, based on a recovery ID that contains the experiment ID and the actual RunId.
The run can be specified either in the experiment_name:run_id format, or just the run_id.
:param wo... | ba9c3b8d2c5c50cc82ac50ad4485b4348e11f9d1 | 3,624,668 |
def mono_anal(y, fs, param=None):
"""Run pyin on an audio signal y.
Parameters
----------
y : np.array
audio signal
fs : float
audio sample rate
param : dict default=None
threshdistr : int, default=2
Yin threshold distribution identifier.
- 0 ... | 24b2607d97c2254ff5def47370e301cd60199e7e | 3,624,669 |
def format_dict(_dict, tidy=True):
"""
This function format a dict. If the main dict or a deep dict has only on element
{"col_name":{0.5: 200}} we get 200
:param _dict: dict to be formatted
:param tidy:
:return:
"""
if tidy is True:
levels = 2
while (levels>=0):
... | 8db7ca24e73202ad409c9ae7e5890dd68fcc64e3 | 3,624,672 |
def get_crc24(data: str) -> dict:
"""
Implementation of the CRC-24 algorithm from OpenPGP.
Returns the CRC-24 checksum value in decimal and hexadecimal format.
"""
data = bytearray(data.encode('utf-8'))
crc = 0x00b704ce
for byte in data:
crc = (CRC24_TABLE[((crc >> 16) ^ byte) & 0xff... | 368fb2565301e54809fa5841fcd504c3547c3c13 | 3,624,673 |
def pfirst(*args, **kwargs):
"""
For each occurrence of this function in source code, print only on the first call. e.g.
>>> for n in [1, 2]:
... _ = pfirst(n * 10)
... _ = pfirst(n * 100)
10
100
"""
stack = _getstack()
if not stack in pfirst.seen_stacktraces:
pf... | 1ca85da1112543c13f1113c1cf3eb7b1d2f03942 | 3,624,676 |
import gzip
import itertools
def read_obo(file):
""" read ontology from file
:param file: file path of file handle
"""
G = nx.DiGraph()
if isinstance(file, str):
if file.endswith('.gz'):
f = gzip.open(file, 'rt')
else:
f = open(file)
we_opened_file ... | e41e0201f349d1030e16b59bf78b3a3d6ac3c5eb | 3,624,677 |
def _GetColocationNames(op):
"""Returns names of the ops that `op` should be colocated with."""
colocation_names = []
try:
class_values = op.get_attr('_class')
except ValueError:
# No _class attr
return
for val in class_values:
val = compat.as_str(val)
if val.startswith('loc:@'):
col... | d68cb092f878e506b9b1999b4cbd9ff43f571b99 | 3,624,678 |
def _current_trace():
"""Returns the innermost Jax tracer."""
tracers = _masters()
if tracers:
return tracers[-1]
return None | f467c31b1082ae8eb002a4b66f988364876a130f | 3,624,679 |
def tailor_queries(query_item, query_target):
"""
This substitutes common parameters for values from the script.
Later, this will be a data driven exercise.
"""
replacements = dict()
replacements['{{deployment}}'] = query_target.split('_')[0]
replacements['{{org_id}}'] = query_target.split('... | 40a7b0890f9ccb5beffab28567da5f4898b0fd92 | 3,624,680 |
def enlarge(image, size, axis=1, efunc=energy_function, cfunc=compute_cost, dfunc=duplicate_seam, bfunc=backtrack_seam, rfunc=remove_seam):
"""Enlarges the size of the image by duplicating the low energy seams.
We start by getting the k seams to duplicate through function find_seams.
We iterate through the... | 0eca80d904663cc3ba3ab2e68debd4a2bb76ac7b | 3,624,682 |
import random
def get_answer(random_country_index):
""" Function that randomly decides the type of the answer (either LANGUAGES or CAPITALS).
It also accesses the dictionary using the randomly generated index and it fetches the
corresponding item from it."""
random_question = random.randint(1,10)
... | 99bff119dd63f6893fcb4693d832873400b6c3ae | 3,624,684 |
def Rx(r):
"""Construct a rotation matrix around X-axis."""
return _Rx(np.cos(r), np.sin(r)) | f225d98c9df560ab32e0834a710e79c5fdb25f41 | 3,624,685 |
from datetime import datetime
def dtime(dstr):
"""Convert datetime strings to datetime instances."""
if isinstance(dstr, bytes):
dstr = dstr.decode()
return datetime.datetime.strptime(dstr, fs_fmt) | fc2c1ec626b9cb11aee9b694a75f0010febfba45 | 3,624,686 |
def _create_split(last_key, next_key, query):
"""Create a new {@link Query} given the query and range..
Args:
last_key: the previous key. If null then assumed to be the beginning.
next_key: the next key. If null then assumed to be the end.
query: the desired query.
Returns:
A split query with fe... | 10f62ce1b5cf36bd04083fac3c601eb6a19ca16d | 3,624,687 |
import struct
def compute_checksum(message):
"""Calculates the 16-bit one's complement of the one's complement sum
of a given message."""
# If the message length isn't a multiple of 2 bytes, we pad with
# zeros
if len(message) % 2:
message += struct.pack('x')
# We build our blocks to... | 30b9665d8fce75d0b55b43f025b9c7c755507522 | 3,624,688 |
def mockup_return(*args, **kwargs):
"""Mockup to replace regular functions for error injection."""
return False | 92172e58a11e48a09c8f181ac55aa717b5fbb94d | 3,624,690 |
def publish_shelter(shelter_id=None):
"""
Publish/Unpublish a shelter.
"""
shelter = Shelter.query.filter(Shelter.id == shelter_id).first()
if shelter:
shelter.is_published = request.args.get('publish',
not shelter.is_published)
db.sess... | d435229b6e9b78773f25ea058b5a3ad890c817a3 | 3,624,691 |
from datetime import datetime
def convert_utc_to_pdt(time_of_interest: datetime) -> datetime:
""" Get the datetime in Pacific Daylight Timezone (PDT) : UTC-7 given a
datetime in UTC timezone """
return time_of_interest.astimezone(timezone(offset=timedelta(hours=PDT_UTC_OFFSET))) | 72620398f9d6bc5a952fa1a47e062bf70b5477bd | 3,624,692 |
def format_input(param):
"""Return a string with all the inputs property formatted. """
tmp1 = ' {type} {var}{ctor}; XC_LI_.load({var});\n'
tmp2 = ' {type} {var}{ctor}; XC_LI_.load({var}, {sample});\n'
inputs = ''
for par in param:
if 'sample' in par:
inputs += tmp2.format(... | 41b4c26369e3be43b5466c9c375609571d5a04a4 | 3,624,693 |
def example(method):
"""Performs a short example run of the retrievals using local
machine.
Parameters
----------
method : str
The method to use to perform the atmopsheric retrieval; can
either be ``multinest`` or ``emcee``
"""
# Ensure that the method parameter is valid
... | d31cee875522ed9a69e82a70288e3a551b317226 | 3,624,694 |
def patient_sur(N, t, survival, show=False):
""" generate N patient survival time from survival function """
y_n = np.random.uniform(0, 1.0, N)
x_n = np.interp(1 - y_n, 1 - survival, t)
if show:
plt.plot(x_n, y_n, '.')
plt.plot(t, survival)
plt.xlabel('Time')
plt.ylabel... | 40a4388927c3aed7782b8bc94a3fed98109f6a71 | 3,624,695 |
def get_git_project_files():
"""Retrieve a list of all non-ignored files, including untracked files,
excluding deleted files.
:return: sorted list of git project files
:rtype: :class:`list`
"""
cached_and_untracked_files = git_ls_files(
'--cached', # All files cached in the index
... | e856d693a9de3643740e4311ffef310b29b4f490 | 3,624,697 |
def add_codes(err_cls):
"""Add error codes to string messages via class attribute names."""
class ErrorsWithCodes(object):
def __getattribute__(self, code):
msg = getattr(err_cls, code)
return "[{code}] {msg}".format(code=code, msg=msg)
return ErrorsWithCodes() | 24ec122c290628c218a01867824fda681c4e7e88 | 3,624,699 |
from typing import Dict
import torch
def get_token_ids_from_text_field_tensors(
text_field_tensors: Dict[str, Dict[str, torch.Tensor]],
) -> torch.Tensor:
"""
Our `TextFieldTensors` are complex output structures, because they try to handle a lot of
potential variation. Sometimes, you just want to grab... | 4898da3be21bac6011fe3d559d772da31c31f730 | 3,624,700 |
def ping():
"""Determine if the container is working and healthy. In this sample container, we declare
it healthy if we can load the model successfully."""
global clf
if clf is None:
clf = ScoringService.get_model()
status = 200
return flask.Response(response='\n', status=status, mimetyp... | 350454d3771963bde5bfea94d3cb73d17629331d | 3,624,701 |
import math
def s_linear(y, a):
"""Transformation function."""
assert y >= 0.0
assert y <= 1.0
assert a > 0.0
assert a < 1.0
return correct_to_01(abs(y - a) / abs(math.floor(a - y) + a)) | 42dc5246d09d2d5924772acd1f481e63fd9d64f5 | 3,624,702 |
def posts_from_rest_files(fnames):
"""
Read posts from ReST files
"""
ret = []
for parts, docinfo in _parse_rest_files(fnames):
page = posts.Post(title=parts['title'],
contents=parts['body'],
slug=docinfo['slug'],
... | 30a3f04683536b4de31fd586ca52eb2f53f82f4b | 3,624,703 |
async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool:
"""Set up configured Weatherbit."""
# We allow setup only through config flow type of config
return True | 9c5b9abb131d9828904f51aee39243ff4136b8e2 | 3,624,704 |
def _validate_licence(data: dict) -> dict:
"""Validates that a Licence exists and that the Goods exist on that Licence"""
serializer = HMRCIntegrationUsageUpdateLicenceSerializer(data=data)
if not serializer.is_valid():
data["errors"] = serializer.errors
return data
try:
licen... | b4ab5daf915ec605ef135b07ed8da93c627b679d | 3,624,705 |
def extend_bed(bed, bp, direction='both'):
"""Extend each interval in bed file with specified basepairs.
If bp is a list, each interval will be extended bp[0] toward upstream, and
bp[1] toward downstream.
Note: Be careful! This method does not deal with strandedness of the interval.
:param (pybedt... | 94ae8f33353edceaf45511b5525ca3e2e72d3588 | 3,624,706 |
def chem_potential_water_t_exact(SA, t, p):
"""
Calculates the chemical potential of water in seawater.
Parameters
----------
SA : array-like
Absolute Salinity, g/kg
t : array-like
In-situ temperature (ITS-90), degrees C
p : array-like
Sea pressure (absolute pressure... | 153b6a9a235250fc21139a96da107dc3bfb0c7eb | 3,624,707 |
import random
def generate_neg_edges(G, num_neg_edges):
"""
Given a graph, sample negative edges from the complement graph.
:param G: graph
:param num_neg_edges: number of edges to sample
:returns neg_edges: the sampled edges
"""
G_comp = nx.complement(G)
neg_edges = random.sample(G_co... | fcbb577d8101cf54f227e82b279cbd8c8c24e85b | 3,624,708 |
def bolster_missing_time_periods(filter_time_periods, queryset, date_range_type, columns):
""" Given the following, generate a list of dict results split by fiscal years/quarters/months
Args:
filter_time_periods: list of time_period objects usually provided by filters
- {'start_... | c54361ab493c8590dac8c7a621831d2c9e9f1c25 | 3,624,709 |
import concurrent.futures
import datetime
def screenStocks_Multiproccesed(ticker_list, strategy, last_days):
"""
Screens stock list with strategy. Returns list of [tickers, last buy dates, stock performance stats] if last buy date of stock is within last_days
This particular function is multiproccesed wit... | 09f059885ff7aae27ea1a489de278894f5a6434b | 3,624,710 |
def get_cached_locale(locale):
"""
Gets the given locale from cache if present.
Parameters
----------
locale : `str`
The local to get from cache.
Returns
-------
locale : `str`
"""
return LOCALES.setdefault(locale, locale) | beb47af067b498b713352be0fd1e05e04145ad79 | 3,624,711 |
def _IsTpuTraining(p):
"""Whether we should create embedding tables and run lookup on tpu."""
return not p.is_inference and py_utils.use_tpu() | fdfe5e646125c0458da825be184c92609cb86ee2 | 3,624,712 |
def get_first_index_where(array, criterion, value):
"""get the first index where array fulfills a criterion w.r.t. value,
where criterion may be "geq" (greater equal), "gt" (greater than),
"leq" (less equal) or "lt" (less than). If criterion is met nowhere,
function returns len(array)
Args:
... | ed4bc09e107bddac20480610988768fea8e45a95 | 3,624,713 |
from typing import Tuple
def score_per_player(df: pd.DataFrame,
selected_player: str) -> Tuple[pd.DataFrame, pd.DataFrame]:
"""Plot score per player
Parameters:
-----------
selected_game_df : pandas.core.frame.DataFrame
Data for the selected game
selected_player : s... | a95b4c5c77e866212e2b5e1d33b648977fcec07b | 3,624,714 |
def GetXcodeDeveloperDirectory():
"""Returns the active developer directory as reported by 'xcode-select -p'.
Returns None if none is set."""
if not MacOS():
return None
return GetCommandOutput("xcode-select -p") | 4fea53abe054beaaa9599df5f745126e208e98c0 | 3,624,715 |
def norm(a, b):
""" Return a unit normal to a and b. """
k = np.cross(a, b)
return k / np.linalg.norm(k) | 4fb52fea0e61a9611ebfca26bff22c8cbd71fd52 | 3,624,716 |
def logical_factor_rules() -> FrozenDict:
"""Logical factor rules for Mixture of Experts."""
rules = flax_core.unfreeze(adafactor.standard_logical_factor_rules())
rules.update({
'expert': FactorDim.BATCH,
'expert_mlp': FactorDim.COLUMN,
'unmodeled': FactorDim.NONE
})
return flax_core.freeze(... | f79aee3825c53f09cd8b0a719c78522d908617bf | 3,624,717 |
from typing import Sequence
from typing import Optional
from typing import Union
def row_rounder(row: Sequence[str], line: Optional[int], has_total_col: bool = False) -> Sequence[Union[str, float]]:
"""
To convert the data in a CSV row to percentages and then smartly round the
percentages to no decimal wi... | 89d0f76469c6125c81871ba3bff045e529fcce35 | 3,624,718 |
def three_blocks_avgpooling(img_width, img_height, img_channels, output_dim):
"""
Define model architecture.
# Arguments
img_width: Target image widht.
img_height: Target image height.
img_channels: Target image channels.
output_dim: Dimension of model output.
# ... | ed5ca6122d03877fd02d0d6f63d98dab04169a09 | 3,624,719 |
import re
def parse_life_105(file):
"""Parse a Life 1.05 file, returning a tuple:
positions: list of (x,y) co-ordinates
comments: all comments in file, as a list of strings, one per line.
"""
lines = file.split("\n")
comments = []
positions = []
ox, oy = 0, 0
x, y = ox, oy... | 3faf204bb52f5c1dd5b350401afdaa2a021f80d4 | 3,624,720 |
def save_vertex_attributes(mesh):
"""
Saves the boundary and cut attributes that are on the mesh on a dictionary.
"""
v_attributes_dict = {'boundary_1': [], 'boundary_2': [], 'cut': {}}
cut_indices = []
for vkey, data in mesh.vertices(data=True):
cut_index = data['cut']
if cut_i... | 91a46dd1060849e4581ee1fe037ce0ff7fadecd0 | 3,624,722 |
import traceback
def server_error_to_message(e, error_statement, error_detail, rows = None):
"""サーバーエラーレスポンス(メッセージ付き) server error response with message
Args:
e (Exception): 例外 exception
error_statement (str): エラー情報(処理内容)error info. process contents
error_detail (str): エラー情報詳細 error d... | ad34548aaf84c7f9c574fd017df78ebe01f340a7 | 3,624,723 |
def eliminate_nonvalid_coords(coords, mapshape):
""" Eliminate nonvalid indices
Args:
coords(set of tuples): input set of positions
h(int): height
w(int): width
Returns:
set of valid coordinates
"""
h, w = mapshape
valid = []
for j, i in coords:
if j < 0 or j >= h:... | a872f551c072f0e36e10d7aac02d68a370cdfdf1 | 3,624,724 |
from typing import Sequence
from typing import Optional
def construct_1d_ndarray_preserving_na(
values: Sequence, dtype: Optional[DtypeObj] = None, copy: bool = False
) -> np.ndarray:
"""
Construct a new ndarray, coercing `values` to `dtype`, preserving NA.
Parameters
----------
values : Sequ... | 8d4f6b77a89c848985d1b8a2fe21ba952da51fff | 3,624,726 |
def getPosUntilRoot(object):
"""
Go through the hierarchy of the object until reaching the top level,
increment the position to get the transformation due to parents.
@type object: hostObject
@param object: the object
@rtype: list
@return: the cumulative translation along the ... | 00ed1bbb3cce4c8f1309d2ee4b24025e767f7df9 | 3,624,727 |
import tqdm
def build_embedding_matrix(
embedding_model: gensim.models.keyedvectors.KeyedVectors,
embedding_dim,
vocab) -> np.ndarray:
"""
Builds the embedding matrix.
Parameters
----------
embedding_model : gensim.models.keyedvectors.KeyedVectors
Embedding model.
... | 31fbbd91dd7f835cf0b4123ddf42cce6c78063bd | 3,624,728 |
def calls_fixture(hass):
"""Track calls to a mock service."""
return async_mock_service(hass, "test", "automation") | 5a75d6de7e260b0845e38b6540a3fc3ee367f0ad | 3,624,729 |
def load_yaml(yaml_file, template_params=None, return_config_str=False):
"""
load_yaml_str will take in a string that has the correct yaml formatting
and generate classes or types according to the configuration in the yaml.
Example:
params = {'SOURCE_PATH': '/tmp/source', 'AGE': 30}
obj... | 9be438692be2ba54bcd345f29ed6c1f469df3586 | 3,624,730 |
def bprp_to_bv(bprp):
"""
Calculate a B-V color from a G_BP - G_RP color.
Poor fit at large and small bp-rp. (Especially bad for low-mass stars).
"""
p = [-0.0334115504231673, 0.3754200727545447, -1.4691791496336342,
2.209433533403669, -0.39641699367657274, 0.14752490961352926]
retur... | dbd75562649d7f1b093aa37efbb15fa95fd16541 | 3,624,731 |
def have_flirt():
""" Return True if we can call flirt without error
Relies on the fact that flirt produces text on stdout when called with no
arguments
"""
p = Popen('flirt', stdout=PIPE, stderr=PIPE, shell=True)
stdout, stderr = p.communicate()
return stdout != '' | 34aef0b7bde4ca7dd087f4048084e0bb06beeb13 | 3,624,732 |
def effective_request_host(request):
"""Return the effective request-host, as defined by RFC 2965."""
return eff_request_host(request)[1] | 2443630193f5c1a02538347d71077f6ac69cc2e5 | 3,624,733 |
import ast
import requests
def get_nginx_generation_value(host) -> int:
"""
Send request to /api/api_version/nginx and parse the response.
:param host:
:return: 'generation' value
"""
resp = ast.literal_eval(requests.get(f"{host}/api/{NGINX_API_VERSION}/nginx").text)
return resp['generati... | c2ff155c711c7e668b86edf6523fecab5a0d508a | 3,624,734 |
def get_job_by_id(job_id): # noqa: E501
"""Find my job by Id
For valid response try integer Ids with value >= 1 and <= 1000.\\ \\ Other values will generated exceptions # noqa: E501
:param job_id: Id of job to be fetched
:type job_id: str
:rtype: Job
"""
job = q.fetch_job... | 87fbc03012527c1eb60c946024fef5e00e7ef49f | 3,624,736 |
def delete_client(client_id):
"""
Delete a client
---
tags:
- clients
parameters:
- name: client_id
in: path
type: integer
example: 1
operationId: deleteClient
produces:
- application/json
schemes: ['http', 'https']
responses:
200:
... | 3c2cd9c19bbbb9082a7b7247253f0414d3b09f88 | 3,624,737 |
def get_textregion_avg_line_distance(text_region: PageXMLTextRegion,
avg_type: str = "macro") -> np.float:
"""Returns the median distance between subsequent lines in a
textregion object. If the textregion contains smaller textregions, it only
considers line distances bet... | f0311add31985b7fb87a740cd3f02846f7e3183f | 3,624,738 |
import time
def dns_lookup(qname, **kwargs):
"""Function to perform DNS lookup queries.
Args:
qname (str) : The Domain name that you would like perform a DNS lookup for.
**ns (str/list): The nameserver to use when querying the provided domain.
... | ff4516aa5f85fb74b37174fcd8d4ac1d11b5f678 | 3,624,739 |
def get_aperture_fluxes(data, ap_radius):
"""
Make an aperture for every pixel, and do aperture photometry at all of them.
:param data: A 2D numpy array with the data to do photometry on
:ap_radius: The radius of the aperture to use.
"""
# Get all coordinates
nx, ny = data.shape
xx, yy... | 14fba44448771182431c1f3546122ce991c16b45 | 3,624,743 |
def _trash_ratio(text):
"""
Return ratio of non-common symbols.
"""
trash_count = 0
for char in text:
if char in list(u'.\'"+-!?()[]{}*+@#$%^&_=|/\\'):
trash_count += 1
return trash_count / float(len(text)) | 135bcabaa36a565b2e998932c70aaf4caf943af9 | 3,624,744 |
def compute_graph_nn_2(xyz, k_nn1, k_nn2):
"""compute simulteneoulsy 2 knn structures
only saves target for knn2
assumption : knn1 <= knn2"""
assert k_nn1 <= k_nn2, "knn1 must be smaller than knn2"
num_ver = xyz.shape[0]
#compute nearest neighbors
graph = dict([("is_nn", True)])
nn = Nea... | c4fd0e417243ca4726d21fb0f4837a2c139954e9 | 3,624,745 |
def index_of_spaces(text):
"""
Given text, return all space indices
@param text is the string to analyze
@returns a list of integers representing the indices
"""
res = []
for i in range(0, len(text)):
if text[i] == ' ':
res.append(i)
return res | 97b3618ffa54ee6d1b50c5bca3e196d3a6ae7f2a | 3,624,746 |
def decrypt_story():
"""Load the file store.txt, and decript it"""
return CiphertextMessage(get_story_string()).decrypt_message() | 13ba9c6fba8fd358639606663f2928ead3bf8825 | 3,624,748 |
def aaa_get_kvm_launch_url(in_cookie, in_ipv4):
""" Auto-generated UCS XML API Method. """
method = ExternalMethod("AaaGetKVMLaunchUrl")
method.in_cookie = in_cookie
method.in_ipv4 = in_ipv4
xml_request = method.to_xml(option=WriteXmlOption.DIRTY)
return xml_request | 2bf389507028fc4b8ca5f0069295a5869f60ef67 | 3,624,749 |
def get_default_hparams():
""" Return default hyper-parameters """
params_dict = {
# Experiment Params:
'is_training': True, # train mode (relevant only for accelerated LSTM mode)
'data_set': 'cat', # datasets to train on
'epochs': 50, # how many times to go over the full trai... | 803cc08fc9de77b7c2608d10f6eca457ac175ab8 | 3,624,750 |
def _get_mf_picks(info, int_order, ext_order, ignore_ref=False, verbose=None):
"""Pick types for Maxwell filtering."""
# Check for T1/T2 mag types
mag_inds_T1T2 = _get_T1T2_mag_inds(info)
if len(mag_inds_T1T2) > 0:
warn('%d T1/T2 magnetometer channel types found. If using SSS, it is '
... | 83e3609ec7fd0916d8d76f1750ca918b45313b81 | 3,624,751 |
def bbcMicro_partPhonemeCount(pronunc):
"""Returns the number of 'part phonemes' (at least that's what I'm calling them) for the BBC Micro phonemes in pronunc. The *SPEAK command cannot take more than 117 part-phonemes at a time before saying "Line too long", and in some cases it takes less than that (I'm not sure... | bd1337214f8c0d39c79a7cd94e5720717335aad8 | 3,624,752 |
def build_MLP(X, y, layers=(50, 25, 15), dropout=0.1, activation='relu',
out_act='softmax'):
"""Utility function for building a Multi-layer perceptron.
Args:
- X: numpy array, input to the model.
- y: numpy array, target of the model.
- layers: tuple of ints, number of hid... | 8af98f627b67fdffccf8c340915bffa768a5c497 | 3,624,753 |
def idc(funcname):
"""获取所属机房逻辑"""
try:
custom_args = handle(custom_param_file,"custom_args")
return custom_args[funcname]
except Exception as e:
print "[error]:",e
return None | 3a5ee6c5a1cfd66c6f2c9a6988d2668355cc9e9a | 3,624,754 |
import yaml
def format_bundle(bundle):
"""
Converts a bundle object into a push-ready bundle by
changing list values of 'customResourceDefinitions',
'clusterServiceVersions', and 'packages' into stringified yaml literals.
This format is required by the Marketplace backend.
:param bundle: A b... | 472e7d4ad915ef1a57eef3e5ac4ae4085a67138f | 3,624,755 |
from typing import Optional
from typing import Tuple
def es_client(
host: Text,
port: int = 9200,
url_prefix: Optional[Text] = None,
username: Optional[Text] = None,
password: Optional[Text] = None,
timeout: int = 180) -> elasticsearch.client.Elasticsearch:
""" Elas... | 87d73e4cdbe629bc2e0cb325df6703e3b2d62de3 | 3,624,756 |
def insert_at_midpoint(item, iterable):
"""
Inserts an item at the index of the midpoint of a list
Returns that list with the item inserted
"""
midpoint = int(len(iterable) / 2)
iterable.insert(midpoint, item)
return iterable | 9801e2f4cd1011914f15634898ed4d502edfee34 | 3,624,758 |
def upgrade(sql_connection, version=None):
"""
Upgrade the database's current migration level
:param sql_connection: sqlalchemy connection string
:param version: version to upgrade (defaults to latest)
:retval version number
"""
db_version(sql_connection) # Ensure db is under migration con... | 6bcfe5b79d8d7f955cfd47e2cbaa407b191eaa94 | 3,624,759 |
def unwrap_if_necessary(graph_node: PerceptionGraphNode) -> UnwrappedPerceptionGraphNode:
"""
Some nodes might be wrapped in tuples together with IDs to prevent them
from being compared equal and collapsed in perception graphs.
This method removes that wrapping.
"""
if isinstance(graph_node, tup... | 26aa90de70b06c498c71d8181d631e0c496718e8 | 3,624,760 |
def func(p, data):
"""
Calculate z = (x/maj)**2 + (y/min)**2
Note that z = 1 is an ellipse
"""
x0, y0, major, minor, pa = p
x, y = data
pa = radians(pa)
sinP = sin(-pa)
cosP = cos(-pa)
xt = x - x0
yt = y - y0
xr = xt * cosP - yt * sinP
yr = xt * sinP + yt * cosP
re... | dbef77e2fd5d61ef78bcce278023f6abfa86c609 | 3,624,761 |
import string
def urlEncode(s):
"""
Returns the encoded version of the given string, safe for using as a URL.
"""
return string.join(map(lambda c: _urlEncode[c], list(s)), '') | ac5467b6fdb8e9e1a4f4a300dba7b3372bad01ee | 3,624,762 |
def euclideanDistance(data_points, query_instance):
"""
Calculate euclidean distance
:param data_points: data points of a given dataset
:param query_instance: instance of a dataset for which the distance matrix will be computed for
:return: distance value
"""
return np.sqrt(((data_points -... | fbab617733535dd1b3af47c3d2c972fa29009fbc | 3,624,763 |
from typing import Tuple
def _move_jackknife_sample_id_to_value(
slice_key: slicer.SliceKeyType, sample: metric_types.MetricsDict
) -> Tuple[slicer.SliceKeyType, metric_types.MetricsDict]:
"""Moves the jackknife sample ID from the key to value.
Args:
slice_key: The slice key which contains the sample_id.... | 0711418b4974639123c0a92ffb4122d8b5c6bcad | 3,624,764 |
def dfanet(classes=19, **kwargs):
"""
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
return xceptionAx3(classes, **kwargs) | 0004186558fe467bc1bf01b8e070d446231d870f | 3,624,765 |
def experiment_fn(run_config: RunConfig, params: HParams):
"""The experiment function, provided to learn_runner.
:param run_config:
:param params:
:return:
"""
run_config = run_config.replace(save_checkpoints_steps=params.min_eval_frequency)
estimator = tf.estimator.Estimator(
mod... | 7a0e411af98ca344ee321fc88435556d80fd783f | 3,624,766 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.