content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_wint_exceptions():
"""Test wint function exceptions."""
dep_vector = np.array([0.99, 1 + 3j, 0.5])
wobj = std_wobj(dep_name="wobj_a", dep_vector=dep_vector)
AE(peng.wint, TypeError, "Cannot convert complex to integer", wobj) | 35,300 |
def set_task_state(success: bool, task_id: str):
"""Update the state of the Airflow task.
:param success: whether the task was successful or not.
:param task_id: the task id.
:return: None.
"""
if success:
logging.info(f"{task_id} success")
else:
msg_failed = f"{task_id} fai... | 35,301 |
def has_columns(df, columns):
"""Check if DataFrame has necessary columns.
Args:
df (pd.DataFrame): DataFrame.
columns (list(str): columns to check for.
Returns:
bool: True if DataFrame has specified columns.
"""
result = True
for column in columns:
if column no... | 35,302 |
def render(template, **kwargs):
"""Render template with default values set"""
return JINJA_ENV.get_template(template).render(
autograde=autograde,
css=CSS,
favicon=FAVICON,
timestamp=timestamp_utc_iso(),
**kwargs
) | 35,303 |
def _cytof_analysis_derivation(context: DeriveFilesContext) -> DeriveFilesResult:
"""Generate a combined CSV for CyTOF analysis data"""
cell_counts_analysis_csvs = pd.json_normalize(
data=context.trial_metadata,
record_path=["assays", "cytof", "records"],
meta=[prism.PROTOCOL_ID_FIELD_NA... | 35,304 |
def get_field(name, data):
"""
Return a valid Field by given data
"""
if isinstance(data, AbstractField):
return data
data = keys_to_string(data)
type = data.get('type', 'object')
if type == "string":
return StringField(name=name, **data)
elif type == "boolean":
r... | 35,305 |
def data_context_connectivity_context_connectivity_serviceuuid_namevalue_name_get(uuid, value_name): # noqa: E501
"""data_context_connectivity_context_connectivity_serviceuuid_namevalue_name_get
returns tapi.common.NameAndValue # noqa: E501
:param uuid: Id of connectivity-service
:type uuid: str
... | 35,306 |
def update_google_analytics(context, request, ga_config, filename, file_size_downloaded,
file_at_id, lab, user_uuid, user_groups, file_experiment_type, file_type='other'):
""" Helper for @@download that updates GA in response to a download.
"""
ga_cid = request.cookies.get("clien... | 35,307 |
def open_alleles_file(N0, n, U, Es, mmax, mwt, mutmax, rep):
"""
This function opens the output files and returns file
handles to each.
"""
sim_id = 'N%d_n%d_U%.6f_Es%.5f_mmax%.2f_mwt%.2f_mutmax%d_rep%d' %(N0, n, U, Es, mmax, mwt, mutmax, rep)
data_dir = '../SIM_DATA'
outfile = open("%s/alleles_%s.csv" %(data_di... | 35,308 |
def approximateWcs(wcs, camera_wrapper=None, detector_name=None,
obs_metadata=None,
order=3, nx=20, ny=20, iterations=3,
skyTolerance=0.001*LsstGeom.arcseconds, pixelTolerance=0.02):
"""
Approximate an existing WCS as a TAN-SIP WCS
The fit is perform... | 35,309 |
def parse_table_column_names(table_definition_text):
"""
Parse the table and column names from the given SQL table
definition. Return (table-name, (col1-name, col2-name, ...)).
Naïvely assumes that ","s separate column definitions regardless of
quoting, escaping, and context.
"""
match = _... | 35,310 |
def temporary_macro(tag, macro, app, app_version, nevents):
"""Create temporary macro."""
app_map = {'BACCARAT': 'Bacc'}
if app_version.startswith('3'):
## mdc2 no longer requires these
macro_extras = Template("") # dedent("""
# /$app/beamOn $nevents
# exit
# """))
... | 35,311 |
def patch_debugtoolbar(settings):
"""
Patches the pyramid_debugtoolbar (if installed) to display a link to the related rollbar item.
"""
try:
from pyramid_debugtoolbar import tbtools
except ImportError:
return
rollbar_web_base = settings.get('rollbar.web_base', DEFAULT_WEB_BASE)... | 35,312 |
def show_all_positions():
"""
This leads user to the position page when user clicks on the positions
button on the top right and it is supposed to show user all the positions
in the database
"""
db=main()
conn = create_connection(db)
mycur = conn.cursor()
post=mycur.execute("SELECT *... | 35,313 |
def get_subtree_tips(terms: list, name: str, tree):
"""
get lists of subsubtrees from subtree
"""
# get the duplicate sequences
dups = [e for e in terms if e.startswith(name)]
subtree_tips = []
# for individual sequence among duplicate sequences
for dup in dups:
# create a copy o... | 35,314 |
def save_text(datadir, split):
"""
Loads the captions json, extracts the image ids and captions and
stores them so they can be used by TextImageDataset format.
"""
path = f'{datadir}/annotations/captions_{split}.json'
with open(path, 'r') as f:
captions = json.load(f)
x = captions['a... | 35,315 |
def pressure_to_cm_h2o(press_in):
"""Convert pressure in [pa] to [cm H2O]
Returns a rounded integer"""
conversion_factor = 98.0665
return int(round(press_in / conversion_factor)) | 35,316 |
def write_triggers(trigger_file, function_file, model, is_direct, has_gid, **generator_args):
"""
:param str file trigger_file: File where triggers will be written.
:param str file function_file: File where functions will be written.
:param model: A :ref:`declarative <sqla:declarative_toplevel>` class.
... | 35,317 |
def truncate_seq_pair(tokens_a, tokens_b, max_num_tokens):
"""Truncates a pair of sequences to a maximum sequence length."""
while True:
total_length = len(tokens_a) + len(tokens_b)
if total_length <= max_num_tokens:
break
trunc_tokens = tokens_a if len(tokens_a) > len(... | 35,318 |
def generate_config_file():
"""
Generate configuration file by copying the default configuration.
"""
dest_path = os.path.join(CWD, "calendar.yml")
if not os.path.exists(dest_path):
shutil.copyfile(DEFAULT_CONFIG_PATH, dest_path)
sys.exit(0)
else:
raise ex.ExcalFileExists... | 35,319 |
def parse_deceased_field(deceased_field):
"""
Parse the deceased field.
At this point the deceased field, if it exists, is garbage as it contains First Name, Last Name, Ethnicity,
Gender, D.O.B. and Notes. We need to explode this data into the appropriate fields.
:param list deceased_field: a list... | 35,320 |
def rate(epoch, rate_init, epochs_per_order):
""" Computes learning rate as a function of epoch index.
Inputs:
epoch - Index of current epoch.
rate_init - Initial rate.
epochs_per_order - Number of epochs to drop an order of magnitude.
"""
return rate_init * 10.0 ** (-epoch /... | 35,321 |
def has_loop(net):
"""
Check if the network is a loop
"""
try:
networkx.algorithms.cycles.find_cycle(net)
return True
except networkx.exception.NetworkXNoCycle:
return False | 35,322 |
def get_query_name(hmma):
"""
get the panther family name from the query target
"""
hmma_list = hmma.split ('.')
if len(hmma_list) > 2:
hmm_fam = hmma_list[0]
hmm_sf = hmma_list[1]
something_else = hmma_list[2]
elif len(hmma_list) == 2:
hmm_fam = hmma_list[0]
... | 35,323 |
def staff_member_required(view_func, redirect_field_name=REDIRECT_FIELD_NAME, login_url='admin:login'):
"""
Decorator for views that checks that the user is logged in and is a staff
member, displaying the login page if necessary.
"""
return user_passes_test(
lambda u: u.is_active and u... | 35,324 |
def get_event_listeners(ctx: Configuration) -> Dict:
"""List of events that is being listened for."""
try:
req = restapi(ctx, METH_GET, hass.URL_API_EVENTS)
return req.json() if req.status_code == 200 else {} # type: ignore
except (HomeAssistantCliError, ValueError):
# ValueError ... | 35,325 |
def process_tce(tce):
"""Processes the light curve for a Kepler TCE and returns processed data
Args:
tce: Row of the input TCE table.
Returns:
Processed TCE data at each stage (flattening, folding, binning).
Raises:
IOError: If the light curve files for this Kepler ID cannot be found.
"""
# R... | 35,326 |
def validate_config_yaml(config):
"""Validates a Project config YAML against the schema.
Args:
config (dict): The parsed contents of the project config YAML file.
Raises:
jsonschema.exceptions.ValidationError: if the YAML contents do not match the
schema.
"""
schema = read_yaml_file(_PROJECT_C... | 35,327 |
def _build_kwic(docs, search_tokens, context_size, match_type, ignore_case, glob_method, inverse,
highlight_keyword=None, with_metadata=False, with_window_indices=False,
only_token_masks=False):
"""
Helper function to build keywords-in-context (KWIC) results from documents `docs`... | 35,328 |
def get_sqnet(model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create SQNet model with specific parameters.
Parameters:
----------
model_name : str or None, default None
Model name for loading pretrained ... | 35,329 |
def filter_records(records,
arns_to_filter_for=None,
from_date=datetime.datetime(1970, 1, 1, tzinfo=pytz.utc),
to_date=datetime.datetime.now(tz=pytz.utc)):
"""Filter records so they match the given condition"""
result = list(pipe(records, filterz(_by_time... | 35,330 |
def _check_dataframe(dataframe, dtypes):
"""Assert dataframe columns are of the correct type."""
expected = dataframe.dtypes.apply(lambda x: x.name)
expected.name = "pandas_type"
expected.index.name = "column_name"
expected = expected.reset_index()
expected = expected.sort_values(by="column_name... | 35,331 |
def generate_prob_matrix(A: int, D: int)\
-> Tuple[Dict[Tuple[int, int], int], Dict[Tuple[int, int], int], np.ndarray]:
"""Generate the probability outcome matrix"""
transient_state, absorbing_state = generate_states(A, D)
transient_state_lookup = {s: i for i, s in enumerate(transient_state)}
ab... | 35,332 |
def test_common():
"""Test that all the attributions method works as explainer"""
input_shape, nb_labels, samples = ((16, 16, 3), 10, 20)
x, y = generate_data(input_shape, nb_labels, samples)
model = generate_model(input_shape, nb_labels)
explainers = _default_methods(model)
metrics = [
... | 35,333 |
def FileTemplateGetNext():
"""
Get the preset template file name that will be used in the next Save/Load action, if it has been preset
Output: Template file name that will be used in the next Save/Load action. Returned Variable will be empty if no next template file name is preset.
"""
pass | 35,334 |
def _prepare_func(app_id, run_id, train_fn, args_dict, local_logdir):
"""
Args:
app_id:
run_id:
train_fn:
args_dict:
local_logdir:
Returns:
"""
def _wrapper_fun(iter):
"""
Args:
iter:
Returns:
"""
for ... | 35,335 |
def convert_camel_to_snake(string, remove_non_alphanumeric=True):
"""
converts CamelCase to snake_case
:type string: str
:rtype: str
"""
if remove_non_alphanumeric:
string = remove_non_alpha(string, replace_with='_', keep_underscore=True)
s1 = _first_cap_re.sub(r'\1_\2', string)
result = _all_cap_re.sub(r'\1... | 35,336 |
def log_to_syslog(message: Message) -> None:
"""
Writes logs to syslog.
Parameters:
message (Message): Message that contains log information.
Returns:
None
"""
syslog.syslog(message.status.value, message.detail) | 35,337 |
async def configure_hacs(hass, configuration, hass_config_dir):
"""Configure HACS."""
from .aiogithub import AIOGitHub
from .hacsbase import HacsBase as hacs
from .hacsbase.configuration import HacsConfiguration
from .hacsbase.data import HacsData
from . import const as const
from .ha... | 35,338 |
def attrdict(d: dict) -> AttrDict:
"""Add attribute access to a dict.
This function takes a dict with nested dicts as input and convert into an AttrDict
object which allows attribute access to keys.
Returns:
A dict-like object with attribute access to keys.
"""
def addattrs(d):
... | 35,339 |
def form(cik, year):
"""Returns form 13F for specified CIK number. From https://fmpcloud.io/documentation#thirteenForm
Input:
cik : CIK number for which you'd like the 13F form
year = year for which you'd like the 13F form.
Returns:
Form 13F for specified company
""" ... | 35,340 |
def check_bel_script_line_by_line(bel_script_path, error_report_file_path, bel_version):
"""Check statements in file or string for correct.
result['trees'][line_number] = {'statement': statement, 'tree': tree}
result['errors'][line_number] = {'statement': statement, 'error': ex}
# can be used as comme... | 35,341 |
def create(cls, **data):
"""Create a single instance of a Resource.
Arguments:
cls (Resource class): The resource to create.
All other keyword arguments will be provided to the request
when POSTing. For example::
create(Foo, name="bar", email="baz@foo.com")
...would try to create... | 35,342 |
def mixup_batch(holder):
"""
Mixup samples in an array
Inputs:
holder: list of datapoint preprocessed with format ['images', 'weights', 'labels']
Outputs:
mixup_samples: Samples have been mixed up from list of sample
"""
gamma = np.random.beta(0.4, 0.4)
mixup_samples = []
... | 35,343 |
def load_test_data(intop_order=1):
"""
Load testing data from TEST_PATH.
"""
print('Loading testing data')
img_name = TEST_PATH + '/image_test' + str(IMG_HEIGHT) + '_' \
+ str(IMG_WIDTH) + '_' + str(intop_order) + '.npy'
reload_flag = os.path.exists(img_name) and \
... | 35,344 |
def get_cluster_role_template_binding(cluster_id=None,name=None,role_template_id=None,opts=None):
"""
Use this data source to retrieve information about a Rancher v2 cluster role template binding.
> This content is derived from https://github.com/terraform-providers/terraform-provider-rancher2/blob/master/... | 35,345 |
def np_where(cond, x, y):
"""
Wrap np.where() to allow for keyword arguments
"""
return np.where(cond, x, y) | 35,346 |
def score_feedback_comp_micro_shujun(pred_df, gt_df, discourse_type):
"""
A function that scores for the kaggle
Student Writing Competition
Uses the steps in the evaluation page here:
https://www.kaggle.com/c/feedback-prize-2021/overview/evaluation
"""
gt_df = gt_df.loc[gt_df['disco... | 35,347 |
def _url_for_language_resolve_view(url, new_language):
"""
Figure out the new URL by resolving the old URL and re-reversing it using
the new language.
"""
view = urlresolvers.resolve(url)
with language_context(new_language):
new_url = urlresolvers.reverse(view.url_name, args=view.args, k... | 35,348 |
def rsp_matrix(m,k):
"""
Description: This function creates the matrix used for finding the parameters of reals signal perceptron using a system of linear equations
is_Implemented:
True
Args:
(m:int): The domain size , the amount of possible variables that each variable can take
... | 35,349 |
def pretty_format_dict(dct):
"""
Parameters
----------
dct: dict[Any, Any]
Returns
-------
str
"""
return "{}".format(json.dumps(dct, indent=4)) | 35,350 |
def report_account_status(context):
"""报告账户持仓状态"""
logger = context.logger
latest_dt = context.now.strftime(r"%Y-%m-%d %H:%M:%S")
logger.info("=" * 30 + f" 账户状态【{latest_dt}】 " + "=" * 30)
account = context.account()
cash = account.cash
positions = account.positions(symbol="", side="")
... | 35,351 |
def extract_encodings(
args, text_file, tok_file, embed_file, lang="en", max_seq_length=None
):
"""Get final encodings (not all layers, as extract_embeddings does)."""
embed_file_path = f"{embed_file}.npy"
if os.path.exists(embed_file_path):
logger.info("loading file from {}".format(embed_file_p... | 35,352 |
def get_default_release():
# type: () -> Optional[str]
"""Try to guess a default release."""
release = os.environ.get("SENTRY_RELEASE")
if release:
return release
with open(os.path.devnull, "w+") as null:
try:
release = (
subprocess.Popen(
... | 35,353 |
def session_try_readonly(dbtype, dbfile, echo=False):
"""Creates a read-only session to an SQLite database.
If read-only sessions are not supported by the underlying sqlite3 python DB
driver, then a normal session is returned. A warning is emitted in case the
underlying filesystem does not support locking prop... | 35,354 |
def generate_lab_saliva(directory, file_date, records):
"""
Generate lab saliva file.
"""
lab_saliva_description = (
lambda: {
'ORDPATNAME': _('random.custom_code', mask='SIS########', digit='#'),
'SAMPLEID': _('random.custom_code', mask='H#########', digit='#'),
... | 35,355 |
def clear_screen(tty=""):
"""Clear the screen."""
global __gef_redirect_output_fd__
if not tty:
gdb.execute("shell clear -x")
return
# Since the tty can be closed at any time, a PermissionError exception can
# occur when `clear_screen` is called. We handle this scenario properly
... | 35,356 |
def run_identical_doubleint_2D(dx, du, statespace, x0, ltidyn, poltrack, apol,
assignment_epoch, nagents, ntargets, collisions, collision_tol, dt=0.01, maxtime=10):
""" Setup the engine and simulation scenario
Input:
- dx: agent statesize
- du: agent control input s... | 35,357 |
def rebuild_field_path(sort_field, resource):
"""
convert dot connected fields into a valid field reference
:param sort_field:
:return: path_to_field
"""
sorted = strip_sort_indicator(sort_field)
split_sorted = sorted.split()
sort_with_this = ""
for s in split_sorted:
if s... | 35,358 |
def load_data(pkl_paths, use_attr, no_img, batch_size, uncertain_label=False, n_class_attr=2, image_dir='images', resampling=False, resol=299):
"""
Note: Inception needs (299,299,3) images with inputs scaled between -1 and 1
Loads data with transformations applied, and upsample the minority class if there i... | 35,359 |
def scalar_function(x, y):
"""
Returns the f(x,y) defined in the problem statement.
"""
#Your code here
if x <= y:
out = x*y
else:
out = x/y
return out
raise NotImplementedError | 35,360 |
def getImageParticles(imagedata,stackid,noDie=True):
"""
Provided a Stack Id & imagedata, to find particles
"""
particleq = appiondata.ApParticleData(image=imagedata)
stackpdata = appiondata.ApStackParticleData()
stackpdata['particle'] = particleq
stackpdata['stack'] = appiondata.ApStackData.direct_query(stacki... | 35,361 |
def build_evaluation(
resource_id,
compliance_type,
event,
resource_type=DEFAULT_RESOURCE_TYPE,
annotation=None,
):
"""Form an evaluation as a dictionary. Usually suited to report on scheduled rules.
Keyword arguments:
resource_id -- the unique id of the resource to report
compliance... | 35,362 |
def match_countries(df_to_match, olympics):
"""Changes the names of the countries in the df_to_match df so that they match
the names of the countries in the olympics df.
Parameters
-----------
df_to_match : either of the two dataframes:
- gdp
- pop
olympics ... | 35,363 |
def main():
"""
Entry point
"""
results = [i for i in range(2, 1000000) if equals_sum_fifth_powers(i)]
print(f"Total: {sum(results)} (values: {results})")
return | 35,364 |
def get_reply(session, url, post=False, data=None, headers=None, quiet=False):
"""
Download an HTML page using the requests session. Low-level function
that allows for flexible request configuration.
@param session: Requests session.
@type session: requests.Session
@param url: URL pattern with... | 35,365 |
def get_stock_rack_size():
"""
Returns the number of available positions in a stock rack.
"""
return get_stock_rack_shape().size | 35,366 |
def is_valid_constant_type(x):
"""
@return: True if the name is a legal constant type. Only simple types are allowed.
@rtype: bool
"""
return x in PRIMITIVE_TYPES | 35,367 |
def logsumexp(tensor: torch.Tensor, dim: int = -1, keepdim: bool = False) -> torch.Tensor:
"""
A numerically stable computation of logsumexp.
This is mathematically equivalent to `tensor.exp().sum(dim, keep=keepdim).log()`.
This function is typically used for summing log probabilities.
Parameters
... | 35,368 |
def testmod(module=None, run=True, optionflags=None,):
"""
Tests a doctest modules with numba functions. When run in nosetests, only
populates module.__test__, when run as main, runs the doctests.
"""
if module is None:
mod_globals = sys._getframe(1).f_globals
modname = mod_globals['... | 35,369 |
def test_check_whitespace_glyphnames():
""" Font has **proper** whitespace glyph names? """
check = CheckTester(universal_profile,
"com.google.fonts/check/whitespace_glyphnames")
def deleteGlyphEncodings(font, cp):
""" This routine is used on to introduce errors
... | 35,370 |
def shrink_piecwise_linear(r,rvar,theta):
"""Implement the piecewise linear shrinkage function.
With minor modifications and variance normalization.
theta[...,0] : abscissa of first vertex, scaled by sqrt(rvar)
theta[...,1] : abscissa of second vertex, scaled by sqrt(rvar)
theta[...,... | 35,371 |
def LoadAuth(decoratee):
"""Decorator to check if the auth is valid and loads auth if not."""
@wraps(decoratee)
def _decorated(self, *args, **kwargs):
if self.auth is None: # Initialize auth if needed.
self.auth = GoogleAuth()
if self.auth.access_token_expired:
self.auth.LocalWebserverAuth()
... | 35,372 |
def cols_with_nulls(df):
""" Convert whitespace entries to NaN, Return columns with NaN
"""
# Note: Empty string will be converted to NaN automatically,
df.replace(r'^\s*$', np.nan, regex=True, inplace=True)
return list(df.isnull().any().index) | 35,373 |
def recursive_feature_selection_roc_auc(clf,
X,
y,
sample_weight=None,
n_features=10,
cv_steps=10,
... | 35,374 |
def mermin_klyshko_quantum_bound(n):
"""The quantum bound for the Mermin-Klyshko inequality is :math:`2^{3(n-1)/2}`.
:param n: The number of measurement nodes.
:type n: Int
:returns: The quantum bound.
:rtype: Float
"""
return 2 ** (3 * (n - 1) / 2) | 35,375 |
def get_serial_port_selected():
"""Get the selected serial port from the Settings.
:return: The currently selected serial port in the Settings.
"""
return ServerCompilerSettings().serial_port | 35,376 |
def main(args):
"""Produce library bundle"""
if platform.system() == "Darwin":
res = gen_archive_darwin(args.output, args.libs)
else:
ar_script = gen_archive_script(
args.output, [expand_path(lpath) for lpath in args.libs]
)
res = gen_archive(ar_script)
retu... | 35,377 |
async def set_version_response_headers(response: Response) -> None:
"""Set Opentrons-Version headers on the response, without checking the request.
This function should be used inside a `fastapi.Depends` as a router
or application dependency.
"""
response.headers[API_VERSION_HEADER] = f"{API_VERSIO... | 35,378 |
def test_result_error_failure():
"""Ensures that ResultE can be typecasted to failure."""
container: ResultE[int] = Failure(ValueError('1'))
assert str(container.failure()) == '1' | 35,379 |
def run_in_background(func: callable, *args, **kwargs) -> Future:
""" run func(*args, **kwargs) in background and return Future for its outputs """
return GLOBAL_EXECUTOR.submit(func, *args, **kwargs) | 35,380 |
def setup_env():
""" Sets required environment variables for GAE datastore library """
os.environ['AUTH_DOMAIN'] = "appscale.com"
os.environ['USER_EMAIL'] = ""
os.environ['USER_NICKNAME'] = ""
os.environ['APPLICATION_ID'] = "" | 35,381 |
def remove_injector():
"""Remove a thread-local injector."""
if getattr(_LOCAL, "injector", None):
del _LOCAL.injector | 35,382 |
def vlan_no_trunk_allowed(dut, hs1, hs2, step):
"""
This test verifies that even though we have sub-interfaces with
vlan id 2 on both interfaces, if the switch interfaces don't support
vlan trunk allowed for vlan id 2 on both the interfaces then packet
transfer is not possible.
"""
dut_port1... | 35,383 |
def get_eigenvectors(
q,
dm: Union[DynamicalMatrix, DynamicalMatrixNAC],
ddm: DerivativeOfDynamicalMatrix,
perturbation=None,
derivative_order=None,
nac_q_direction=None,
):
"""Return degenerated eigenvalues and rotated eigenvalues."""
if nac_q_direction is not None and (np.abs(q) < 1e-5... | 35,384 |
def _get_formatted_atom_types_names_for(connection):
"""Return formatted atom_type names for a connection."""
names = []
for member in connection.connection_members:
if not member.atom_type:
label = ""
else:
label = member.atom_type.name
names.append(label)
... | 35,385 |
def anti_commutator(H1,H2):
""" Calculates the anticommutator of two Hamiltonians :math:`H_1` and :math:`H_2`.
.. math::
\\{H_1,H_2\\}_+ = H_1 H_2 + H_2 H_1
Examples
--------
The following script shows how to compute the anticommutator of two `hamiltonian` objects.
.. literalinclude:: ../../doc_examples/ant... | 35,386 |
def test_endpoint_without_authentication():
"""
This test makes sure that we are able to have endpoints without any authentication.
"""
secret_key = 'example'
app = create_app()
app.add_middleware(AuthenticationMiddleware, backend=JWTAuthenticationBackend(secret_key=secret_key, algorithm='RS256'... | 35,387 |
def download(self, auth=False):
"""
needs source url (from webs ite) and destination save location
"""
source_url = 'http://www.spitzer.caltech.edu/uploaded_files/images/0006/3034/ssc2008-11a12_Huge.jpg'
hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) C... | 35,388 |
def windowed_dataset(dataset, size, shift=None, stride=1, drop_remainder=True):
"""Create a windowed `Dataset`.
Arguments:
dataset: A `Dataset` of output shape ((...), (...), ... (...)) or a `dict`
of the same.
size: A `tf.int64` scalar `tf.Tensor`, representing the n... | 35,389 |
def dnds(seq1, seq2):
"""Main function to calculate dN/dS between two DNA sequences per Nei &
Gojobori 1986. This includes the per site conversion adapted from Jukes &
Cantor 1967.
"""
# Strip any whitespace from both strings
seq1 = clean_sequence(seq1)
seq2 = clean_sequence(seq2)
# Chec... | 35,390 |
def send_t1_to_server_with_action(ptfhost, ptfadapter, tbinfo):
"""
Starts IO test from T1 router to server.
As part of IO test the background thread sends and sniffs packets.
As soon as sender and sniffer threads are in running state, a callback action is performed.
When action is finished, the sen... | 35,391 |
def create_LED_indicator_rect(**kwargs) -> QPushButton:
"""
False: dim red
True : green
"""
# fmt: off
SS = (
"QPushButton {"
"background-color: " + COLOR_INDIAN_RED_2 + ";"
"color: black;"
"border: 1px solid black;"
"border-radius: 0px;"
... | 35,392 |
def make_obstime_plot(data_file, period, ref_mjd=58369.30, save=False,
show=False, max_freq=2500, min_freq=200):
"""
Generates observation exposure plot
:param data_file: json file with data
:param period: period to use for phase calculation
:param ref_mjd: reference MJD to use
:param c... | 35,393 |
def handle_activity(bot, ievent):
""" no arguments - show running threads. """
try: import threading
except ImportError:
ievent.reply("threading is not enabled.")
return
result = {}
todo = threadloops
for thread in threadloops:
name = "%s_%s" % (getname(type(thread)), t... | 35,394 |
async def test_ingress_post(
fixture_name,
data_format,
request,
async_test_client,
mock_async_kafka_producer,
monkeypatch,
settings,
):
"""
Parameterized /ingress [POST] test with X12, FHIR, and HL7 inputs
:param fixture_name: The name of the pytest fixture used for parameterize... | 35,395 |
def check_data_struct():
"""
Check that all data is in place first
"""
if not os.path.exists(PROJECT_ROOT+'/data'):
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), PROJECT_ROOT+'/data')
if not os.path.exists(PROJECT_ROOT+'/data/CUB_200_2011'):
raise FileNotFoundErro... | 35,396 |
def bind(task):
"""Bind a task method for use in a pipeline
This decorator method adapts a task method to work
in a pipeline. Specifically, it routes successful
Result input to the task logic, and passes through
failure Result input without performing any
additional actions.
Args:
... | 35,397 |
def display_all_spellings(phone_num):
""" (str) ->
Displays all posible phone numbers with the last four digits
replaced with a corresponding letter from the phone keys
"""
translate = {'0':'0', '1':'1', '2': ('a','b','c'), '3': ('d','e','f'),
'4': ('g','h','i'), '5': ('j','k'... | 35,398 |
def test_fast_3():
"""Test for fast prediction time, using knn, series 3"""
model_3 = Pipeline(filename='./tests/test_series/Serie3.csv',
type='fast',
freq='15T',
targetcol='INSTALACIONES [kWh]',
datecol='MSJO_DATUM',
... | 35,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.