content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def all(*args, span=None):
"""Create a new expression of the intersection of all conditions in the
arguments
Parameters
----------
args : list
List of symbolic boolean expressions
span : Optional[Span]
The location of this operator in the source code.
Returns
-------... | 70,800 |
def test_full_measurement_2():
"""
Tests measurements of all qubits (2)
"""
qc = QuantumCircuit(3)
simulator = Simulator(seed=111)
qc.h(0)
qc.cx(0,1)
qc.cx(0,2)
qc.measure(range(3))
counts = simulator.simulate(qc, shots=10000)
assert list(counts.keys())==['000', '111'] an... | 70,801 |
def download_url(url, root, filename=None, md5=None):
"""Download a file from a url and place it in root.
Args:
url (str): URL to download file from
root (str): Directory to place downloaded file in
filename (str, optional): Name to save the file. If None, use base of the URL.
m... | 70,802 |
def test_incomplete_loggedin_domain_missing(incomplete_loggedin_app):
"""Test what happens when the profile response is incomplete.
Ensure we deny access if the profile endpoint doesn't return all the
information we need in order to decide if we should let someone in or
not.
"""
responses.add(r... | 70,803 |
def main(args=None):
"""Main function called by the `HENcalibrate` command line script."""
import argparse
from multiprocessing import Pool
description = ('Calibrate clean event files by associating the correct '
'energy to each PI channel. Uses either a specified rmf '
... | 70,804 |
def test_atomic_qname_enumeration_3_nistxml_sv_iv_atomic_qname_enumeration_4_3(mode, save_output, output_format):
"""
Type atomic/QName is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/atomic/QName/Schema+Instance/NISTSchema-SV-IV-atomic-QName-enumeration-4.xsd",
... | 70,805 |
def test_fetch_and_save_resources(monkeypatch):
"""Verify that the correct calls are being made to the storage backend."""
monkeypatch.setattr(atf_resources, 'storage', Mock())
monkeypatch.setattr(atf_resources, 'fetch_resource_data', Mock())
monkeypatch.setattr(atf_resources, 'create_layer', Mock())
... | 70,806 |
def plot_all_answer_traces(inputtrace: np.ndarray, colors: list) -> list:
"""
This function plots the answer traces of all tests; one plot per test.
:param inputtrace: Dataframe with the answer trace. Attributes of the dataframe: test, approach, answer, time.
:param colors: List of colors to use for th... | 70,807 |
def initialise_library(members, items, item_copies, library):
"""Takes in items that needs to be populated into the library,
and conduct a series of pre-defined events by members (loan, renewal, return)
The Library object after conducting the events is used to initialise the LibraryApplication
obje... | 70,808 |
def tester():
""" Tests by printing out the prime numbers between [1 and 20)."""
for number in range(1, 21):
print(number, is_prime_v3(number)) | 70,809 |
def send_deep_laser_device_response(request_dict):
""" Sends an http response to the deep laser client to ack a device request. """
assert type(request_dict) == dict
logger.debug(
"Posting device response to DL \n%s\n",
json.dumps(request_dict, sort_keys=True, indent=2),
)
deep_lase... | 70,810 |
def update_cache_bykey(cache_list, new_list, key='id'):
"""
Given a cache list of dicts, update the cache with a 2nd list of dicts by a specific key in the dict.
:param cache_list: List of dicts
:param new_list: New list of dicts to update by
:param key: Optional, key to use as the identifier to upd... | 70,811 |
def calc_theor_avg_mass(dictionary, cfg, prec=6, reducing_end=None) -> float:
"""Returns theoretical average mass for glycan in dictionary form"""
reducing_end_tag_mass = 0.0
if reducing_end is not None:
if reducing_end in cfg["reducing_end_tag_avg"].keys():
reducing_end_tag_mass = cfg["... | 70,812 |
async def test_create_raceplan(
client: _TestClient,
mocker: MockFixture,
token: MockFixture,
new_raceplan_interval_start: dict,
raceplan_interval_start: dict,
) -> None:
"""Should return 405 Method Not Allowed."""
RACEPLAN_ID = raceplan_interval_start["id"]
mocker.patch(
"race_s... | 70,813 |
def is_builtin(key):
"""Test builtin using inspect (some modules not seen
as builtin in sys.builtin_module_names may look builtin
anyway to inspect and in this case we want to filter them
out."""
try:
inspect.getfile(sys.modules[key])
except TypeError:
return True
return Fals... | 70,814 |
def get_node_info(session, node_id):
"""Wrapper for HAPI_GetNodeInfo
Fill an NodeInfo struct.
Args:
session (int): The session of Houdini you are interacting with.
node_id (int): The node to get.
Returns:
NodeInfo: NodeInfo of querying node
"""
node_info = HDATA.NodeInf... | 70,815 |
def Eliminar_Columnas(df, Dic):
""" Recibe el dataframe y el listado de las columnas que se quieren eliminar
"""
df = df.drop(columns=Dic)
return df | 70,816 |
def getCurrentUser():
"""
Get the current user associated with whatever email is stored in session
"""
if 'email' not in session:
return None
email = mailsane.normalize(session['email'])
if email.error:
return None
return getUser(str(email)) | 70,817 |
def wgs84_to_web_mercator(df, lon="LON", lat="LAT"):
"""convert mat long to web mercartor"""
k = 6378137
df.loc[:,"x"] = df[lon] * (k * np.pi/180.0)
df.loc[:,"y"] = np.log(np.tan((90 + df[lat]) * np.pi/360.0)) * k
return df | 70,818 |
def process_medusa(line):
"""
Process a medusa line and return a dictionary
:param line: A line from a medusa output file
:returns dict: A dictionary based upon the content
{ 'ip' : ip address
'port': port info - can be port # or module name
'user': username,
'pass': password,
... | 70,819 |
def parse_tpl_file(tpl_file):
""" parse a pest template file to get the parameter names
Parameters
----------
tpl_file : str
template file name
Returns
-------
par_names : list
list of parameter names
"""
par_names = []
with open(tpl_file,'r') as f:
try... | 70,820 |
def create_event(topic, color, service):
""" Creation of the event for the topic after the random session ended"""
day_colors = {"red": 1, "yellow": 3, "green": 7}
date = datetime.now().date() + timedelta(days=day_colors.get(color))
description = "This is an event created by CloudQuestions as "
desc... | 70,821 |
def ShowOSPlatform(OSs):
"""
List all the OS Platforms supported in Tetration Appliance
Agent Type | Platform | Architecture
"""
headers = ['Platform', 'Agent Type', 'Architecture']
ImportList = []
OSList = []
for key,value in OSs.items() :
ImportList.append(value)
... | 70,822 |
def find_factors(n):
"""
Finds a list of factors of a number
"""
factList = {1, n}
for i in range(2, int(n ** 0.5) + 1):
if (n % i == 0):
factList.add(i)
factList.add(n // i)
return sorted(factList) | 70,823 |
def unique(a):
""" Return the list with duplicate elements removed.
Args:
a (list): A list.
Returns (list):
The list with duplicate elements removed.
"""
# NOTES:
# 1. Built-in function 'set()' can convert a list (ordered) into a set (unordered).
# 2. B... | 70,824 |
def testmod_paths_from_testdir(testdir):
"""Generate test module paths in the given dir."""
for path in glob.glob(join(testdir, "test_*.py")):
yield path
for path in glob.glob(join(testdir, "test_*")):
if not isdir(path): continue
if not isfile(join(path, "__init__.py")): continue
... | 70,825 |
def test_validation_multiindex_unique(orca_session):
"""
Table validation should pass with a MultiIndex whose combinations are unique.
"""
d = {'id': [1,1,1], 'sub_id': [1,2,3], 'value': [4,4,4]}
orca.add_table('tab', pd.DataFrame(d).set_index(['id', 'sub_id']))
validate_table('tab') | 70,826 |
def configure_logging(flask_app):
"""Configure logging for this application."""
# Do not interfere if running in debug mode
if not flask_app.debug:
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter(
'[%(asctime)s] %(levelname)s in %(module)s: %(message)s'))... | 70,827 |
def test_get_json_object_attribute_error(spark_session):
"""test_get_json_object returns attribute error when column not found."""
with pytest.raises(ValueError) as column_not_found:
tr.get_json_object(
create_princess_df(spark_session), "columnNotPresent", "newCol", "path"
)
as... | 70,828 |
def sim_seird_decay(
s: float, e:float, i: float, r: float, d: float, beta: float, gamma: float, alpha: float, n_days: int,
decay1:float, decay2:float, decay3: float, decay4: float, step1_delta: int, fatal: float
) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
"""Simulate the... | 70,829 |
def do_quote_form(expressions, env):
"""Evaluate a quote form.
"""
check_form(expressions, 1, 1)
# BEGIN Question 6B
return expressions.first
# END Question 6B | 70,830 |
def setup_module(module):
"""Fixture for nose tests."""
from nose import SkipTest
try:
import numpy
except:
raise SkipTest("NumPy not available")
try:
import scipy
except:
raise SkipTest("SciPy not available") | 70,831 |
def test_can_update_volumes_from_xml():
"""
Tests 6 plate well is built correctly
"""
volumeSurvey = [{"well": "A1", "volume": 29.831}]
plate = Plate(size=6, well_volume=50)
updateVolumesFromEchoSurveyData(plate, volumeSurvey)
assert plate.contents == {
"A1": {
"id": "A1... | 70,832 |
def make_flatmap_image(braindata, height=1024, recache=False, **kwargs):
"""Generate flatmap image from volumetric brain data
This
Parameters
----------
braindata : one of: {cortex.Volume, cortex.Vertex, cortex.Dataview)
Object containing containing data to be plotted, subject (surface id... | 70,833 |
def compute_i_k_index(citations: List[int], k: int = 10):
"""Given a list of citations (integers) compute the i-k-index (default i10)."""
citations = np.asarray(citations)
i_k_index = (citations > k).sum()
return i_k_index | 70,834 |
def get_session_details_helper(client):
"""
Retrieve details regarding the current session within `client`
:param client: ICAT client containing an authenticated user
:type client: :class:`icat.client.Client`
:return: Details of the user's session, ready to be converted into a JSON response
... | 70,835 |
def _decompose_cz_into_syc(a: cirq.Qid, b: cirq.Qid):
"""Decomposes `cirq.CZ` into sycamore gates using precomputed coefficients.
This should only be called when exponent of `cirq.CZPowGate` is 1. Otherwise,
`_decompose_cphase_into_syc` should be called.
Args:
a: First qubit to operate on.
... | 70,836 |
def resnet18(use_rp=False, width=1, **kwargs):
"""Constructs a ResNet-18 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
if use_rp:
print('model using random projection')
model = ResNetRP(width, bb.BasicBlockRP, [2, 2, 2, 2], **kwargs)
els... | 70,837 |
def configure_ipv6_params():
"""3.3 IPv6"""
PropertyFile('/etc/sysctl.conf', ' = ').override({
'net.ipv6.conf.all.accept_ra': '0',
'net.ipv6.conf.default.accept_ra': '0',
'net.ipv6.conf.all.accept_redirects': '0',
'net.ipv6.conf.default.accept_redirects': '0'
}).write()
... | 70,838 |
def twist2velocity_cb(twist, args):
"""
Ros topic cmd_vel subscription callback.
@param twist: ROS topic twist
"""
# get process pipe connection
ros_write_conn = args[0]
# logging
log_txt = "%s received -> Linear: %s Angular: %s\r" % (rospy.get_caller_id(), twist.linear, twist.angular)
... | 70,839 |
def assign_seller(request, campaign_id):
"""
Shows a list of sellers to assign contacts to.
"""
campaign = Campaign.objects.get(pk=campaign_id)
campaign.count = ContactCampaignStatus.objects.filter(campaign=campaign, seller=None).count()
message = ""
if request.POST:
seller_list = [... | 70,840 |
def nmf_recommender():
"""Write your own code for NMF Here"""
pass | 70,841 |
def optimize(config: DictConfig):
"""
Run a multi-objectives hyperparameters optimization of the decision
thresholds, to maximize recall and precision directly while
also maximizing automation.
Args:
config (DictConfig): Hydra config passed from run.py
"""
commons.extras(config)
... | 70,842 |
def _swissroll_dataset():
"""Interwined spirals."""
sz = 100
Y = np.arange(sz) % 2
t = np.linspace(0, 4 * np.pi, sz)
X = t[:, None] * np.vstack([np.cos(t + Y * np.pi),
np.sin(t + Y * np.pi)]).T
X += 0.2 * np.random.randn(*X.shape)
return X, Y | 70,843 |
def load_mat_data(dataset_str):
""" dataset_str: protein, metabolic, conflict, powergrid """
dataset_path = 'data/' + dataset_str + '.mat'
mat = loadmat(dataset_path)
if dataset_str == 'powergrid':
adj = sp.lil_matrix(mat['G'], dtype=np.float32)
feats = None
return adj, feats
... | 70,844 |
async def repo_is_here(wannasee):
""" For .repo command, just returns the repo URL. """
await wannasee.edit("`Ironbot repo klik `[Disini!](https://github.com/tesbot07/ironbot).") | 70,845 |
def filter_row_by_data_type(col_name, data_type=None, get_type=False):
"""
A Pandas UDF function that returns bool if the value match with the data_type param passed to the function.
Also can return the data type
:param col_name: Column to be process
:param data_type: The data_type to be compared wi... | 70,846 |
def get_ajax_job_status_msg(jobid):
"""return the job status msg (as a string)"""
# user's browser requesting job status msg
global STAT_CODE_RUNNING
if not validate_jobid(jobid):
return Response("Invalid Job ID: %s" % jobid, mimetype='text/plain', headers = {'X-Dalton-Webapp':'OK'})
stat_co... | 70,847 |
def plot_composites(axs, regions, plotables, **kwargs):
"""
Draw plots of dry spell composites of some variables for a set of
regions on a set of existing figure axes.
Parameters
----------
axs : Array of <matplotlib.axes.Axes> instances.
Axes to which the data will be drawn.
regio... | 70,848 |
def run(args, config, prog_args):
"""Run an experiment."""
name = args.name
repo = pygit2.Repository('.')
with shelve.open('.em', writeback=True) as emdb:
exp_info = emdb.get(name)
if exp_info:
if exp_info['status'] == 'running':
return _die(E_IS_RUNNING.form... | 70,849 |
def setup_logger(verbosity, quiet):
# type: (int, bool) -> None
"""Sets up the logger.
:param int verbosity: Requested level of verbosity
:param bool quiet: Suppresses all logging when true
"""
local_logging_level, root_logging_level = _logging_levels(verbosity, quiet)
formatter = _KMSKeyR... | 70,850 |
def EarliestActiveTimestamp():
"""Calculates the earliest timestamp of an active channel.
Returns:
A DateTime representing the earliest possible timestamp of an active
channel.
"""
return datetime.now() - timedelta(hours=CHANNEL_LIFETIME_HOURS) | 70,851 |
def get_avg_male_ellipse(exp):
"""Gets the average major and minor axis lengths of the ellipse
fitted to the male for all males across all groups in an experiment.
Parameters
----------
exp : FixedCourtshipTrackingExperiment
Experiment to get average ellipses from.
Returns
... | 70,852 |
def on_request(f, name=None):
"""
An interceptor which updates the context value of `REQUEST` during the
enter stage.
:param f: Callable to update the request.
:param unicode name: Interceptor name.
:rtype: Interceptor
"""
return middleware(f, None, name=name) | 70,853 |
def build_model():
"""Build the model
Returns
-------
sklearn.pipeline.Pipeline
The model
"""
pipeline = Pipeline([
(const.FEATURES, FeatureUnion([
(const.TEXT_PIPELINE, Pipeline([
(const.VECT, CountVectorizer(tokenizer=tokenize)),
(c... | 70,854 |
def extend_and_specialize(items, loader):
# type: (List[Dict[Text, Any]], Loader) -> List[Dict[Text, Any]]
"""Apply 'extend' and 'specialize' to fully materialize derived record
types."""
items = deepcopy_strip(items)
types = {t["name"]: t for t in items} # type: Dict[Text, Any]
n = []
fo... | 70,855 |
def curl(url, tokens=None, headers=None, request_type="GET", data=None, parse=False,
validate=False, soft_validation=False):
"""
:rtype type
"""
_headers = {}
handler_chain = []
post_req = ["POST", "PUT"]
get_req = ["GET", "DELETE"]
print_url = Options.CURL_PRINT_ONLY is not None
write_only_... | 70,856 |
def main(model='../models/ticker', new_model_name="ticker", output_dir='../models/ticker', n_iter=40):
"""Set up the pipeline and entity recognizer, and train the new entity."""
random.seed(0)
if model is not None:
nlp = spacy.load(model) # load existing spaCy model
print("Loaded model '%s'... | 70,857 |
def prepare_colmap_inputs(
calibration_directory=None,
calibration_identifier=None,
image_info_path=None,
images_directory_path=None,
ref_images_data_path=None,
additional_images=None,
chunk_size=100,
client=None,
uri=None,
token_uri=None,
audience=None,
client_id=None,
... | 70,858 |
def tracebacks(enabled=True):
"""Context manager that enables or disables traceback collection."""
saved = Traceback.enabled
Traceback.enabled = enabled
try:
yield
finally:
Traceback.enabled = saved | 70,859 |
def reorder_atoms(mol):
"""change index of the atoms to ensure atoms are ordered by ascending residue number
"""
order = [(i.GetPDBResidueInfo().GetName().strip(), i.GetPDBResidueInfo().GetResidueNumber()) for i in mol.GetAtoms()] # currently the atom name is not used in sorting
order = [i[0] for i in s... | 70,860 |
def from_dict(
d,
mapping=None,
type_map=None,
ignore_fields=None,
infer_date=False,
convert_hyphens=False,
schema=None,
table=None,
partitions=None,
s3_key=None,
case_map=False,
case_insensitive=False,
ignore_malformed_json=True,
ignore_nested_arrarys=True,
n... | 70,861 |
def before_InsertingInto_needs_container(actor, x, y, ctxt) :
"""One can only insert things into a container."""
raise AbortAction(str_with_objs("{Bob|cap} can't put [the $x] into [the $y].", x=x, y=y), actor=actor) | 70,862 |
def stop_on_shutdown_event(f: Callable[[Agent, Event], None]):
"""
Decorator which can be used to wrap the handle_event method.
If a system_shutdown event is received, stop running without calling handle_event.
"""
@functools.wraps(f)
def wrapper(self, event, **kwargs):
if event["type"... | 70,863 |
def main():
"""
Trains the SVM on the training set and evaluates it on the test data.
"""
parser = argparse.ArgumentParser(description=".")
parser.add_argument('-p', '--pegasos', action='store_true')
parser.add_argument('-k', '--kernel', action='store_true')
parser.add_argument('-cv', '--c... | 70,864 |
def test_stretch_output_default(image_array_1band_stretch):
"""Test to ensure that an array provided is stretched between 0 and 255"""
arr = image_array_1band_stretch
# Stretch using the default value of 2%
arr_stretch = _stretch_im(arr.astype(np.uint8), str_clip=2)
assert arr_stretch.max() == 255... | 70,865 |
def testLog(capsys: Any) -> None:
"""Tests the log() function
"""
config.loglevel = 0
core.log("E: this shows")
core.log("W: this doesn't show")
core.log("I: this doesn't show")
core.log("DEBUG: this doesn't show")
core.log("this doesn't show")
capture = capsys.readouterr()
asser... | 70,866 |
def generate_full_uri(request=None, suffix=None):
"""
生成绝对链接
:param request:
:param suffix:
:return:
"""
url = suffix or ''
if request:
request_host = request.get_host()
host, *sub_path = request_host.split("/", 1)
base_uri = '{scheme}://{host}'.format(scheme=requ... | 70,867 |
def test_data3_important_metadata(dimap):
"""
Test important metadata parameters
"""
# Check extracted data is correct
expected = 'DIMAP'
assert dimap.metadata_format == expected, assert_error(expected, dimap.metadata_format)
expected = '2.12.1'
assert dimap.metadata_version == expected... | 70,868 |
def print_help_command():
"""Print command help information.
Print help information of command.
Args:
"""
print 'type in command: [q] [r]'
print ' q exit'
print ' r plot route result'
print ' r_map plot route result with ma... | 70,869 |
def bins_to_str(lbin):
"""
Return a list of unicode characters into a message
:lbin:list(bin), a list of characters
"""
sbin = ''.join(lbin)
lbin8 = wrap(sbin, 8)
message = chr(int(lbin8[0],2))
for c in lbin8[1:]:
message+=chr(int(c,2))
return message | 70,870 |
def _log_commit_progress(table_size, no_chunks):
"""Shim to avoid sgr spamming output with commit progress for small images"""
return table_size > 500000 or no_chunks > 100 | 70,871 |
def loss_function(outputs, targets, num_labels): # TODO: Add typing
"""
Loss function used to re-train the BERT model.
Using binary cross entropy logistic loss function as it's better suited for multi-label learning
"""
return nn.BCEWithLogitsLoss()(outputs, targets.view(
-1, num_labels)) | 70,872 |
def save_all_perfs_aurocs_auprcs(path="./",filename="perfs_aurocs_auprcs.txt",classes_unique=None,num_runs=1,perfs=None,aurocs=None,auprcs=None):
"""
Save the perfs, auROCs, and auPRCs from all runs.
classes_unique: list of strings, the unique class names.
num_runs: integer, number of runs.
perfs: n... | 70,873 |
def display_string_dump(elf_file, section_spec):
""" Display a strings dump of a section. section_spec is either a
section number or a name.
"""
section = _section_from_spec(elf_file, section_spec)
if section is None:
print("Section '%s' does not exist in the file!" % section_spec)
... | 70,874 |
def test_ccr_binomial_02():
"""
* utils: test_ccr_binomial_02 -- test CCR for binomial inference 02
"""
ccr = list(central_credible_region(beta(1, 10)))
pre_comp = [0.0025285785444617869, 0.30849710781876077]
assert ccr == pre_comp | 70,875 |
def get_backend() -> Optional[str]:
"""
Returns the current pandas plotting backend,
or ``None`` if pandas is not available.
Typically the result will be ``"matplotlib"``.
:return: str or None
"""
try:
import pandas
except ImportError: # pragma: no cover
return None
... | 70,876 |
def cmd_convert(args: argparse.Namespace) -> int:
"""Convert all raw samples to the specified output format."""
try:
files = find_files(args.path, '.raw')
except Exception as e:
print(f'Error - {e}.')
return 1
if not files:
print('Error - The given path does not contain ... | 70,877 |
def version():
""" Show the current version """
click.echo(constants.VOITHOS_VERSION) | 70,878 |
def p_enumerator_list(p):
"""
enumerator_list : enumerator COMMA enumerator_list
| enumerator
"""
_comma_list_element_processing(p) | 70,879 |
def PolygonACD(array, value):
"""
used by libcvcaller.py
inputs:
array
value
outputs:
array?
"""
try:
return libcv.PolygonACD(array, value)
except:
print "libcv failed in PolygonACD"
return [] | 70,880 |
def back_rm(img, edge_lim=20, dim=3):
""" Background extraction in TIFF series
For confocal Z-stacks only!
dem = 2 for one frame, 3 for z-stack
"""
if dim == 3:
mean_back = np.mean(img[:,:edge_lim,:edge_lim])
logging.debug('Mean background, {} px region: {:.3f}'.format(edge_lim, ... | 70,881 |
def formatcommand(input, style, indent, skip_keys, sort_keys, ensure_ascii, check_circular, allow_nan,
item_separator, dict_separator, **kwargs):
"""
(Re)formats the JSON input. Requires valid input.
Supports several predefined, named format 'styles' (e.g. -p, -c, -f, -l),
as well as ... | 70,882 |
def root(request):
"""
Tutorial > Root
"""
return HttpResponsePermanentRedirect(reverse('explore.views.tutorials')) | 70,883 |
def fill_noise(x, noise_type):
"""Fills tensor `x` with noise of type `noise_type`."""
if noise_type == 'u':
x.uniform_()
elif noise_type == 'n':
x.normal_()
else:
assert False | 70,884 |
def report1(cut):
"""Print a report about the current solution in the cutting
optimization problem given by the cut argument.
"""
print()
print("Using " + str(cut.solution.get_objective_value()) + " rolls")
print()
for v in range(cut.variables.get_num()):
print(" Cut" + str(v) + " ... | 70,885 |
def extract_spectral_data_from_df(df):
"""
takes a dataframe where each columns is a spectral sensor. Expands each columns into a dataframe and returns a
dictionary of dataframes
:param df: dataframe of binary format spectral data
:return: dictionary of dataframes of expanded spectral data
"""
... | 70,886 |
def gsfLoadScaleFactor(
p_sf, subrecord_id: c_int, c_flag: c_char, precision: c_double, offset: c_int
) -> int:
"""
:param p_sf: POINTER(gsfpy3_09.gsfRecords.c_gsfScaleFactors)
:param subrecord_id: c_int
:param c_flag: c_char
:param precision: c_double
:param offset: c_int
:return: 0 if ... | 70,887 |
def test_search_intersects_and_bbox(app_client):
"""Test POST search intersects and bbox are mutually exclusive (core)"""
bbox = [-118, 34, -117, 35]
geoj = Polygon.from_bounds(*bbox).__geo_interface__
params = {"bbox": bbox, "intersects": geoj}
resp = app_client.post("/search", json=params)
ass... | 70,888 |
def get_ip(request, real_ip_only=False, right_most_proxy=False):
"""
Returns client's best-matched ip-address, or None
@deprecated - Do not edit
"""
best_matched_ip = None
for key in defs.IPWARE_META_PRECEDENCE_ORDER:
value = request.META.get(key, request.META.get(key.replace('_', '-'), ... | 70,889 |
def ratbagcli_list(ctx):
"""
List all connected devices
If a device name is given, only devices with that name are
listed. The name may be a part of the name, e.g. G303 matches the
"Logitech G303" device.
"""
try:
mainloop = GLib.MainLoop()
ratbagd = ratbag.Ratbag.create(bla... | 70,890 |
def parse_textfile(input_text):
"""This funtion converts text into a list of available emission maps, a dict of emission data and a dict of
metadata. The expected input is:
input_text: str
"""
list_available_maps = ''
dict_data = {}
dict_meta = {}
start_data_row = -1
end_data_row = ... | 70,891 |
def test_list_procedures_converts_procedures_present_response():
"""
A list of ProcedureSummaries object should be returned when procedures
are present.
"""
expected = ProcedureSummary.from_json(
LIST_PROCEDURES_POSITIVE_RESPONSE["procedures"][0]
)
with requests_mock.Mocker() as moc... | 70,892 |
def auto_annotate(img_paths):
"""
Auto annotates a list of images using DETR.
Args:
"""
detr = torch.hub.load('facebookresearch/detr', 'detr_resnet50', pretrained=True)
detr.eval()
annotations = []
for img_path in img_paths:
res = predict(detr, img_path)
annotations += ... | 70,893 |
def get_sample_info(fin):
"""
Read in information from phenotype file
Create a dictionary to store each column
"""
f = open(fin,'r')
f = f.read().split('\n')
f = map(lambda x: x.rstrip(), f)
if '' in f:
f.remove('')
header = f[0].split('\t') # list
c = f[1:]
# Check... | 70,894 |
def parseVarMap(text):
"""Parse a string of the form [ namelist, slicelist ]"""
n = 0
m = _ListStart.match(text)
if m is None:
raise CDMSError("Parsing cdms_filemap near " + text[0:_NPRINT])
result = []
n += m.end()
s, nconsume = parselist(text[n:], parseName)
result.append(s)
... | 70,895 |
def plot_ssp(env, **kwargs):
"""Plots the sound speed profile.
:param env: environment description
Other keyword arguments applicable for `arlpy.plot.plot()` are also supported.
If the sound speed profile is range-dependent, this function only plots the first profile.
>>> import arlpy.uwapm as p... | 70,896 |
def pins_to_sessions(
tsm: SMContext,
pins: typing.List[str],
sites: typing.List[int] = [],
fill_pin_site_info=True,
):
"""
get the sessions for the selected pins
Args:
tsm (SMContext): tsm context for nidcpower
pins (typing.List[str]): desired pins for which the TSMDCPower ... | 70,897 |
def get_V_hs_min(V_vent_g_i):
"""(39)
Args:
V_vent_g_i: 暖冷房区画iの全般換気量(m3/h)
Returns:
熱源機の最低風量(m3/h)
"""
return np.sum(V_vent_g_i[:5], axis=0) | 70,898 |
def rearm_windows():
"""Rearm Windows License"""
rearm_cmd = r'cscript c:\Windows\System32\slmgr.vbs -rearm //nologo'
return subprocess.check_call(rearm_cmd) == 0 | 70,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.