content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _text2ids_conversion(source_filename, target_filename, users, subreddits, vocab):
"""Converts a text file with format user\t subreddit\t text to the same format with ids. Also splits into sentences.
The new format is 'user_id\t subreddit_id\t sentence1\t sentence2\t.... \n
sentence: is in format word_i... | 38,300 |
def test_mapr_standalone_streams(sdc_builder, sdc_executor, cluster):
"""This test will start MapR Streams producer and consumer pipelines which check for integrity of data
from a MapR Streams producer to MapR Streams consumer. Both the pipelines run as standalone. Specifically, this
would look like:
M... | 38,301 |
def subprocess_run(*args, silent=None, dry_run=False, **kwargs):
"""Same in functionality, but better than subprocess.run
Args:
silent (bool): do not log subprocess commands.
check (bool): will capture stderr, and print them on fail.
abort_on_fail (bool): call ctx.exit on fail, but does... | 38,302 |
def test_attempt_setting_tags_when_some_tags_have_been_restricted():
"""
Verify that tags are excluded from being added to a submission's tags if the tag is restricted
"""
userid_owner = db_utils.create_user()
userid_tag_adder = db_utils.create_user()
journalid = db_utils.create_journal(userid_o... | 38,303 |
def is_url(url):
"""
Check if given URL is a valid URL.
:param str url: The url to validate
:returns: if the url is valid or not
:rtype: bool
"""
return urlparse(url).scheme != "" | 38,304 |
def star(locid, tmass_id):
"""Return data on an individual star.
"""
apstar_id = 'apogee.apo25m.s.stars.{0:d}.{1}'.format(locid, tmass_id)
data = stars[apstar_id]
flagtxt = ", ".join(starflag.flagname(stars[apstar_id].ORstarflag))
return render_template('star.html',
ti... | 38,305 |
def dot_product_attention(q,
k,
v,
bias,
dropout_rate=0.0,
image_shapes=None,
name=None,
save_weigths_to=None,
d... | 38,306 |
def OneTrainLogDir(config: CfgNode, root_dir: str = ".") -> List[str]:
"""
1回の訓練と検証時のデータを保存する`model`,`record`,`result` ディレクトリを作成するための関数.
Args:
config (CfgNode): 訓練の条件設定が保存された辞書.
root_dir (str): 親ディレクトリのパス.
"""
model_dir = DirCheckAndMake(os.path.join(root_dir, config.model_dir))
... | 38,307 |
def extract_words(text):
"""Return the words in a tweet, not including punctuation.
>>> extract_words('anything else.....not my job')
['anything', 'else', 'not', 'my', 'job']
>>> extract_words('i love my job. #winning')
['i', 'love', 'my', 'job', 'winning']
>>> extract_words('make justin # 1 by... | 38,308 |
async def async_setup_platform( # pylint: disable=too-many-locals
hass: HomeAssistant,
config: ConfigType, # pylint: disable=unused-argument
async_add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the Calibration sensor."""
if discovery_in... | 38,309 |
def calculate_subgraph_edge_overlap(
graph: BELGraph,
annotation: str = 'Subgraph',
) -> Tuple[
Mapping[str, EdgeSet],
Mapping[str, Mapping[str, EdgeSet]],
Mapping[str, Mapping[str, EdgeSet]],
Mapping[str, Mapping[str, float]],
]:
"""Build a Dataframe to show the overlap between different su... | 38,310 |
def d2logistic_offset_p(x, p):
"""
Wrapper function for :func:`d2logistic_offset`: `d2logistic_offset(x, *p)`
"""
return d2logistic_offset(x, *p) | 38,311 |
def extract_coeffs_knots_from_splines(attitude_splines, k):
"""
Extract spline characteristics (coeffs, knots, splines). The spline being
defined as
.. math:: S(t) = \sum_{n=0}^{N-1} a_n B_n(t)
where :math:`c_n` are the spline coefficients and :math:`B_n(t)` is the
spline basis evaluated at ti... | 38,312 |
def migrate_iceberg(rt_info, start_shipper_task=True, create_table=True):
"""
切换rt的hdfs存储格式为iceberg,可以重复执行
:param rt_info: rt的详细信息
:param start_shipper_task: 启动任务
:param create_table: 是否尝试创建iceberg表,默认为true
:return rt的hdfs存储信息
"""
rt_id = rt_info[RESULT_TABLE_ID]
# 数据按照id倒序排列,第一个即为最新... | 38,313 |
async def test_labware_data_gets_standard_definition() -> None:
"""It should be able to get a "standard" labware's definition."""
expected = get_labware_definition(
load_name="opentrons_96_tiprack_300ul",
namespace="opentrons",
version=1
)
result = await LabwareDataProvider().get... | 38,314 |
def get_token(username: str = AUTH[0], password: str = AUTH[1]):
"""
Gets an access token from Cisco DNA Center always-on sandbox. Returns the token
string if successful; False (None) otherwise
"""
# Declare Useful local variabales to simplify request process
api_path = "https://sandboxdnac.cis... | 38,315 |
def disk_info(hard_disk):
"""Return a dictionary with information regarding a virtul hard disk.
The dictionary with information regarding hard disk image
contains:
:VHD_UUID:
:VHD_PARENT_UUID:
:VHD_STATE:
:VHD_TYPE:
:VHD_PATH: the path for virtual hard driv... | 38,316 |
def get_corporation(corporation_id):
"""
Get corporation details for a corporation id from ESI
:param corporation_id: ID for the required corporation
:return: Dictionary containing corporation details
"""
op = esiapp.op['get_corporations_corporation_id'](corporation_id=corporation_id)
retur... | 38,317 |
def _is_list(v):
"""
Returns True if the given value is a @list.
:param v: the value to check.
:return: True if the value is a @list, False if not.
"""
# Note: A value is a @list if all of these hold True:
# 1. It is an Object.
# 2. It has the @list property.
return _is_object(v) a... | 38,318 |
def test_build_feedstock_nonexist_config_file(mocker):
"""
Tests that execution fails and the correct error message is shown if the default config file doesn't exist.
"""
mocker.patch(
'os.getcwd',
return_value="/test/test_recipe"
)
mocker.patch(
'os.path.exists',
... | 38,319 |
def _find_onehot_actual(x):
"""Map one-hot value to one-hot name"""
try:
value = list(x).index(1)
except:
value = np.nan
return value | 38,320 |
def trajectories_from_file(filepath: str, device_ids: Optional[Set[str]] = None) -> kapture.Trajectories:
"""
Reads trajectories from CSV file.
:param filepath: input file path
:param device_ids: input set of valid device ids (rig or sensor).
If the trajectories contains unknown... | 38,321 |
def test_find_file_mhs():
"""
Tests finding an MHS file for a given date.
"""
l1c_path = DATA_PATH / "mhs" / "l1c"
date = np.datetime64("2019-01-01T01:33:00")
l1c_file = L1CFile.find_file(date, l1c_path, sensor=sensors.MHS)
data = l1c_file.to_xarray_dataset()
assert date > data.scan_tim... | 38,322 |
def test_eval_pp_main_no_converge():
"""
raises NoCutoffConvergence if there is no gcut convergence
"""
test_inputs_dir = os.path.join(main_test_inputs_dir, 'eval_pp_main_test')
with pytest.raises(eval_pp.NoCutoffConvergence):
with tools_for_tests.TemporaryDirectory() as tmp_dir:
... | 38,323 |
def test_random_rotation_expand():
"""
Test RandomRotation op
"""
logger.info("test_random_rotation_op")
# First dataset
data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
decode_op = c_vision.Decode()
# expand is set to be True to match output size
... | 38,324 |
def test_get_keg_sum():
"""Проверка общего количества боченков.
"""
keg = Kegs()
CountGen = 0
while True:
try:
next(keg.keg_gen)
CountGen += 1
except StopIteration:
assert CountGen == 90
break | 38,325 |
def mth_to_last(data):
"""Check if index number is valid, then process.
The index number is the last item in the list. If the list is
shorter than the index number, return. Otherwise print the item
in the list that corresponds to the index number, going backwards.
We need to add a -1 because the in... | 38,326 |
def run_split(self):
"""Splitter mass and energy balance function based on one input stream."""
top, bot = self.outs
feed = self.ins[0]
top_mol = top.mol
feed_mol = feed.mol
top_mol[:] = feed_mol * self.split
bot.mol[:] = feed_mol - top_mol
bot.T = top.T = feed.T
bot.P = top.P = feed... | 38,327 |
def process_expression_data():
"""Process expression data and augment with provided metadata"""
expression_path = DATA_DIR + "/expression"
create_directories(expression_path)
# Load sampleplatform.xslx
logger.info("Load sampleplatform.xslx data in Pandas")
df_sampleplatform_origin = pd.read_ex... | 38,328 |
def lower_text(text: str) -> str:
"""Transform all the text to lowercase.
Args:
text : Input text
Returns:
Output text
"""
return text.lower() | 38,329 |
def pca(X,keep=2):
"""Perfrom PCA on data X. Assumes that data points correspond to columns.
"""
# Z = (X.T - mean(X,1)).T # subtract mean
C = dot(X,X.T)
V,D = eig(C)
B = D[:,0:keep]
return dot(B.T,X) | 38,330 |
def stock_span(prices: array) -> list:
"""
Time Complexity: O(n*n)
"""
span_values: list = []
for i, price in enumerate(prices):
count: int = 1
for j in range(i - 1, -1, -1):
if prices[j] > price:
break
count += 1
span_values.append(... | 38,331 |
async def module_on_config_reloaded(ctx, name):
"""Handle `Core` config reload event."""
if name == 'modules':
_resize_part_deques() | 38,332 |
def get_replication_tasks(replication_instance_arn):
"""Returns the ist of replication tasks"""
existing_tasks = []
dms_client = boto3.client('dms')
replication_tasks = dms_client.describe_replication_tasks()
for task in replication_tasks['ReplicationTasks']:
if task['ReplicationInstanceArn'... | 38,333 |
def getProgramFields():
"""
Get the data element names and return them as a list.
"""
_, progFields = callAPI("GET", "program-fields", quiet='True')
return progFields | 38,334 |
async def on_startup():
"""Initialize the database with the tables"""
initialization() | 38,335 |
def to_hbase(df, table, row_key="row_key"):
"""
Column names must be as "family:column", must contain row_key
:param table: table name
:param row_key: default row key column
:return:
"""
hbase_host = Context().config.get_config["hbase.host"]
conf = {"hbase.zookeeper.quorum": hbase_host,
... | 38,336 |
def base64url_decode(msg):
"""
Decode a base64 message based on JWT spec, Appendix B.
"Notes on implementing base64url encoding without padding"
"""
rem = len(msg) % 4
if rem:
msg += b'=' * (4 - rem)
return base64.urlsafe_b64decode(msg) | 38,337 |
def status(request):
"""
Status page for the Product Database
"""
app_config = AppSettings()
is_cisco_api_enabled = app_config.is_cisco_api_enabled()
context = {
"is_cisco_api_enabled": is_cisco_api_enabled
}
if is_cisco_api_enabled:
# test access (once every 30 minutes... | 38,338 |
def _evaluate_batch(
batch: torch.LongTensor, # statements
model: QualifierModel,
column: int,
evaluator: RankBasedEvaluator,
all_pos_triples: Optional[torch.LongTensor], # statements?
relation_filter: Optional[torch.BoolTensor],
filtering_necessary: bool,
data_geometric: Optional[Data... | 38,339 |
def readFile(f):
"""
This helper method returns an appropriate file handle given a path f.
This handles UTF-8, which is itself an ASCII extension, so also ASCII.
"""
return codecs.open(f, 'r', encoding='UTF-8') | 38,340 |
def print_list(languages):
"""Print the list of available languages."""
pat = '{:<7}{:<26}{:<8}{:<5}'
print(pat.format('Code', 'Name', 'Version', 'Installed'))
for lang in languages:
remote_version = version_str(lang.remote_version)
local_version = '-'
if lang.local_version is no... | 38,341 |
def _RegistryGetValue(key, value):
"""Use _winreg or reg.exe to obtain the value of a registry key.
Using _winreg is preferable because it solves an issue on some corporate
environments where access to reg.exe is locked down. However, we still need
to fallback to reg.exe for the case where the _winreg module i... | 38,342 |
def mock_cloud_login_fixture(hass, setup_api):
"""Mock cloud is logged in."""
hass.data[DOMAIN].id_token = jwt.encode(
{
"email": "hello@home-assistant.io",
"custom:sub-exp": "2018-01-03",
"cognito:username": "abcdefghjkl",
},
"test",
) | 38,343 |
def reverse_complement_sequence(sequence, complementary_base_dict):
"""
Finds the reverse complement of a sequence.
Parameters
----------
sequence : str
The sequence to reverse complement.
complementary_base_dict: dict
A dict that maps bases (`str`) to their complementary bases
... | 38,344 |
def mergeWithFixes(pullRequest: PullRequest.PullRequest, commit_title: str,
commit_message: str, merge_method: str, sha: str):
"""Fixed version of PyGithub merge with commit_title, merge_method, and sha."""
post_parameters = dict()
post_parameters["commit_title"] = commit_title
post_parameters["... | 38,345 |
def top2daz(north, east, up):
"""Compute azimouth, zenith and distance from a topocentric vector.
Given a topocentric vector (aka north, east and up components), compute
the azimouth, zenith angle and distance between the two points.
Args:
north (float): the north component (in... | 38,346 |
def watch_status(old_attr={}, new_attr={}, instance=None, sender=None, **kw):
"""Set nomination date when app is pending review."""
new_status = new_attr.get('status')
if not new_status:
return
addon = instance
if new_status == amo.STATUS_PENDING and old_attr['status'] != new_status:
... | 38,347 |
def run_wsgi_app(application):
"""Runs your WSGI-compliant application object in a CGI environment.
Compared to wsgiref.handlers.CGIHandler().run(application), this
function takes some shortcuts. Those are possible because the
app server makes stronger promises than the CGI standard.
"""
env = dict(os.env... | 38,348 |
def get_ground_truth_vector(classes : torch.Tensor, n_domains : int,
n_classes : int) -> torch.Tensor:
"""
Get the ground truth vector for the phase where the feature extractor
tries that discriminator cannot distinguish the domain that the sample
comes from.
Args:
... | 38,349 |
def main():
"""Main entry point"""
parser = argparse.ArgumentParser(prog="librivox_align.py")
parser.add_argument("book_yml", help="YAML file with book details")
args = parser.parse_args()
logging.basicConfig(level=logging.DEBUG)
_LOGGER.debug(args)
args.book_yml = Path(args.book_yml)
... | 38,350 |
def get_midpoints(ar, mode='linear'):
"""
Returns the midpoints of an array; i.e. if you have the left edge of a set
of bins and want the middle, this will do that for you.
:param ar:
The array or list of length L to find the midpoints of
:param mode:
Whether to find the midpoint in... | 38,351 |
def tokenize(text):
"""
INPUT:
text (str): message strings which need to be cleaned
OUTPUT:
clean_tokens: tokens of the messages which are cleaned
"""
# remove punctuations
tokenizer = RegexpTokenizer(r'\w+')
tokens = tokenizer.tokenize(text)
tokens = [w for w in tokens if ... | 38,352 |
def quit(code, input):
""" quit - Quit from the server. Owner only. """
code.quit() | 38,353 |
def test_parse_unknown_type():
"""Check that ResponseParseError is raised on attempt to parse response of unknown type.
1. Create response factory.
2. Register new response type.
3. Try to parse a response with unregistered type.
4. Check that ResponseParseError is raised.
5. Check the message ... | 38,354 |
def time(is_train):
"""Questions for calculating start, end, or time differences."""
context = composition.Context()
start_minutes = random.randint(1, 24*60 - 1)
while True:
duration_minutes = random.randint(1, 12*60 - 1)
if train_test_split.is_train(duration_minutes) == is_train:
break
end_minu... | 38,355 |
def tree_uia(obj, indent="", output_list=None):
""" Dump the structure of the subtree of a UIA control to a string suitable for debug output """
top = output_list is None
if output_list is None:
output_list = []
output_list.append(indent + str(obj))
subindent = indent + " "
for child i... | 38,356 |
def countpaths(pseq, distinct=True, trim=True):
"""
This function returns the number of paths in a path dictionary or list.
The distinct parameter excludes paths that are reverses of other paths
in the count.
The trim parameter excludes loops.
"""
if isinstance(pseq, list):
... | 38,357 |
def clear_loggers():
"""
Remove handlers from all loggers
"""
import logging
loggers = [logging.getLogger()] + list(logging.Logger.manager.loggerDict.values())
for logger in loggers:
handlers = getattr(logger, "handlers", [])
for handler in handlers:
logger.removeHan... | 38,358 |
def test_rbcs_special_simplification(rbcs: ReducedBCSDrudge):
"""Test the special simplification facilities for pairing algebra."""
dr = rbcs
p = dr.names
n_, pdag_, p_ = rbcs.cartan, rbcs.raise_, rbcs.lower
a = p.a
b = p.b
# Test the simplification based on Cartan with or without index.
... | 38,359 |
def get_all_active_alerts(strategy):
"""
Generate and return an array of all the actives alerts :
symbol: str market identifier
id: int alert identifier
"""
results = []
with strategy._mutex:
try:
for k, strategy_trader in strategy._strategy_traders.items():
... | 38,360 |
def one_hot_vector(val, lst):
"""
Converts a value to a one-hot vector based on options in lst
"""
if val not in lst:
val = lst[-1]
return map(lambda x: x == val, lst) | 38,361 |
def to_rgb(array):
"""Add a channel dimension with 3 entries"""
return np.tile(array[:, :, np.newaxis], (1, 1, 3)) | 38,362 |
def clear_logical_volume(path):
"""Obfuscate the logical volume.
:param path: logical volume path
"""
volume_clear = CONF.libvirt.volume_clear
if volume_clear not in ('none', 'shred', 'zero'):
LOG.error(_LE("ignoring unrecognized volume_clear='%s' value"),
volume_clear)
... | 38,363 |
def is_valid_identifier(string):
"""
Check if string is a valid package name
:param string: package name as string
:return: boolean
"""
if not re.match("[_A-Za-z][_a-zA-Z0-9]*$", string):
return False
if keyword.iskeyword(string):
return False
return True | 38,364 |
def _wait_for_indexer(func: Callable) -> Callable:
"""A decorator function to automatically wait for indexer timeout
when running `func`.
"""
# To preserve the original type signature of `func` in the sphinx docs
@wraps(func)
def wrapped(*args: Any, **kwargs: Any) -> Any:
# First wait fo... | 38,365 |
def test10(args):
"""
CIFAR-10 test set creator.
It returns a reader creator, each sample in the reader is image pixels in
[0, 1] and label in [0, 9].
:return: Test reader creator.
:rtype: callable
"""
return reader_creator_filepath(args.data, 'test_batch', False, args) | 38,366 |
def prettytable_print(results, failed=False):
"""Print a list of query results in prettytable"""
column_names = ['Query', 'Start Time', 'Time Taken (s)', 'Client ID']
if failed: column_names.append('Error')
table = prettytable.PrettyTable(column_names)
table.align = 'l'
table.float_format = '.2'
# Group t... | 38,367 |
def test_atomic_duration_min_exclusive_nistxml_sv_iv_atomic_duration_min_exclusive_1_1(mode, save_output, output_format):
"""
Type atomic/duration is restricted by facet minExclusive with value
P1970Y01M01DT00H00M00S.
"""
assert_bindings(
schema="nistData/atomic/duration/Schema+Instance/NIST... | 38,368 |
def get_saver(moving_average_decay, nontrainable_restore_names=None):
"""
Gets the saver that restores the variavles for testing
by default, restores to moving exponential average versions of
trainable variables
if nontrainable_restore_names is set, then restores
nontrainable variables that ma... | 38,369 |
def test_skip_delay_on_empty_batch(sdc_builder, sdc_executor, stage_attributes):
"""
Tests if there is no delay when a batch contains no records and skip_delay_on_empty_batch is true.
There should be a delay as specified if skip_delay_on_empty_batch is false even if the record batch is empty.
The pipel... | 38,370 |
def mark_time(times, msg=None):
"""
Time measurement utility.
Measures times of execution between subsequent calls using
time.clock(). The time is printed if the msg argument is not None.
Examples
--------
>>> times = []
>>> mark_time(times)
... do something
>>> mark_time(time... | 38,371 |
def goto(vehicle, dNorth, dEast, gotoFunction=None):
"""
Moves the vehicle to a position dNorth metres North and dEast metres East of the current position.
The method takes a function pointer argument with a single `dronekit.lib.LocationGlobal` parameter for
the target position. This allows it to be ca... | 38,372 |
def lines_from_string(string, as_interned=False):
"""
Create a list of file lines from a given string.
Args:
string (str): File string
as_interned (bool): List of "interned" strings (default False)
Returns:
strings (list): File line list
"""
if as_interned:
retu... | 38,373 |
def run_server():
"""Run server with command line arguments."""
parser = argparse.ArgumentParser(description='Set port.')
parser.add_argument('-p', '--port', help='Port', required=False)
args = vars(parser.parse_args())
app = make_app()
port = args.get('port') or 9001
app.listen(port)
pr... | 38,374 |
def _get_data(preload=False):
"""Get data."""
raw = read_raw_fif(raw_fname, preload=preload, verbose='warning')
events = read_events(event_name)
picks = pick_types(raw.info, meg=True, eeg=True, stim=True,
ecg=True, eog=True, include=['STI 014'],
exclude='bad... | 38,375 |
def make_full_filter_set(filts, signal_length=None):
"""Create the full set of filters by extending the filterbank to negative FFT
frequencies.
Args:
filts (array_like): Array containing the cochlear filterbank in frequency space,
i.e., the output of make_erb_cos_filters_nx. Each row of ``filts`` is a
... | 38,376 |
def _rearrangeTmt10plexMatrix(matrix):
"""Rearranges a TMT 10plex isotope impurity matrix, so that the impurities
are positioned appropriately.
#TODO: explain why
impurityMatrix = [
[0.00, 0.00, 100.00, 5.00, 0.00], #126(C) -> affects C series only
[0.00, 0.20, 100.00, 5.00, 0.00], #127... | 38,377 |
def from_autonetkit(topology):
"""Convert an AutoNetKit graph into an FNSS Topology object.
The current implementation of this function only renames the weight
attribute from *weight* to *ospf_cost*
Parameters
----------
topology : NetworkX graph
An AutoNetKit NetworkX graph
Retur... | 38,378 |
def create_default_fake_filter():
"""Return the default temporal, spatial, and spatiotemporal filters."""
nx, ny, nt = get_default_filter_size()
time = np.arange(nt)
return create_spatiotemporal_filter(nx, ny, nt) | 38,379 |
def ClementsBekkers(data, sign='+', samplerate=0.1, rise=2.0, decay=10.0, threshold=3.5,
dispFlag=True, subtractMode=False, direction=1,
lpfilter=2000, template_type=2, ntau=5,
markercolor=(1, 0, 0, 1)):
"""Use Clementes-Bekkers algorithm to find events in... | 38,380 |
def extract_words(path_to_file):
"""
Takes a path to a file and returns the non-stop
words, after properly removing nonalphanumeric chars
and normalizing for lower case
"""
words = re.findall('[a-z]{2,}', open(path_to_file).read().lower())
stopwords = set(open('../stop_words.txt').read().spl... | 38,381 |
def umass_coherence(T, corpus):
"""
Find the UMass coherence of a topic
input:
T (list of strings): topic to find coherence of
"""
sum = 0
# Go through all distinct pairs in the topic
for i, item_i in enumerate(T):
w_i, weight_i = item_i
for j, item_j in ... | 38,382 |
def get_train_test_sents(corpus, split=0.8, shuffle=True):
"""Get train and test sentences.
Args:
corpus: nltk.corpus that supports sents() function
split (double): fraction to use as training set
shuffle (int or bool): seed for shuffle of input data, or False to just
take the trai... | 38,383 |
def load_cifar10(filename):
"""
Load the Preprocessed data
"""
features, labels = pckl.load(open(filename, mode="rb"))
return features, labels | 38,384 |
def _uninstrument_client(
client: typing.Union[httpx.Client, httpx.AsyncClient]
) -> None:
"""Disables instrumentation for the given Client or AsyncClient"""
# pylint: disable=protected-access
unwrap(client, "send") | 38,385 |
def suite():
"""Gather all the tests from this package in a test suite."""
test_suite = unittest.TestSuite()
test_suite.addTest(unittest.makeSuite(TestBodyEval, "test"))
return test_suite | 38,386 |
def fetch_quality(data: dict, classification: ClassificationResult, attenuations: dict) -> dict:
"""Returns Cloudnet quality bits.
Args:
data: Containing :class:`Radar` and :class:`Lidar` instances.
classification: A :class:`ClassificationResult` instance.
attenuations: Dictionary conta... | 38,387 |
def _batch_set_multiple(batch: Any, key: Any, value: Any) -> Any:
"""Sets multiple key value pairs in a non-tuple batch."""
# Numpy arrays and Torch tensors can take tuples and lists as keys, so try to do a normal
# __getitem__ call before resulting to list comprehension.
try:
# Check if one can... | 38,388 |
def in_docker():
""" Returns: True if running in a docker container, else False """
if not os.path.exists('/proc/1/cgroup'):
return False
with open('/proc/1/cgroup', 'rt') as ifh:
return 'docker' in ifh.read() | 38,389 |
def filehasher_main():
"""
Parse arguments from argparse/questionnaire.
Invoke :func:`bbarchivist.hashutils.verifier` with those arguments.
"""
hashdict = hashutils.verifier_config_loader()
hashutils.verifier_config_writer(hashdict)
if len(sys.argv) > 1:
parser = argutils.default_pa... | 38,390 |
def set_up_(devices):
"""
Calling set-up functions on a weird data device.
:in: devices [Device]
"""
for device in devices:
device.set_up()
# for device_class in connected_devices.keys():
# for device_type in connected_devices[device_class]:
# say(' '.join([
# ... | 38,391 |
def add_subscription_channel(username, profile_name, device_id, channel):
"""
:param username: Username of a user requesting the data
:param profile_name:
:param device_id:
:param channel:
:return:
"""
def append_channel(subscriptions):
subscriptions.append(channel)
... | 38,392 |
def fft2erb(fft, fs, nfft):
"""
Convert Bark frequencies to Hz.
Args:
fft (np.array) : fft bin numbers.
Returns:
(np.array): frequencies in Bark [Bark].
"""
return hz2erb((fft * fs) / (nfft + 1)) | 38,393 |
def get_activity_id(activity_name):
"""Get activity enum from it's name."""
activity_id = None
if activity_name == 'STAND':
activity_id = 0
elif activity_name == 'SIT':
activity_id = 1
elif activity_name == 'WALK':
activity_id = 2
elif activity_name == 'RUN':
acti... | 38,394 |
def process_tasks(dag, dag_spec, root_path=None):
"""
Initialize Task objects from TaskSpec, extract product and dependencies
if needed and set the dag dependencies structure
"""
root_path = root_path or '.'
# options
extract_up = dag_spec['meta']['extract_upstream']
extract_prod = dag_... | 38,395 |
def is_ipv4(v):
"""
Check value is valid IPv4 address
>>> is_ipv4("192.168.0.1")
True
>>> is_ipv4("192.168.0")
False
>>> is_ipv4("192.168.0.1.1")
False
>>> is_ipv4("192.168.1.256")
False
>>> is_ipv4("192.168.a.250")
False
>>> is_ipv4("11.24.0.09")
False
"""
... | 38,396 |
def deprecated(help_message: Optional[str] = None):
"""Decorator to mark a function as deprecated.
Args:
help_message (`Optional[str]`): An optional message to guide the user on how to
switch to non-deprecated usage of the library.
"""
def decorator(deprecated_function: Callable):
... | 38,397 |
def test_get_centerline_optic(params):
"""Test centerline extraction with optic"""
# TODO: add assert on the output .csv files for more precision
im = Image(params['fname_image'])
# Add non-numerical values at the top corner of the image for testing purpose
im.change_type('float32')
im.data[0, 0... | 38,398 |
def permitted_info_attributes(info_layer_name, permissions):
"""Get permitted attributes for a feature info result layer.
:param str info_layer_name: Layer name from feature info result
:param obj permissions: OGC service permissions
"""
# get WMS layer name for info result layer
wms_layer_name... | 38,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.