content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def pull_csvs(glob_mask: str = '*.csv'):
"""
This convenience function loads the maternity csvs. I've made it add the file name as some of the files have
columns that are all over the place. It combines the csvs into a dataframe end on end.
:param glob_mask: str
this should be a glob expression ... | 78,800 |
def gaussian(x, a, x0, sigma,c):
"""
gaussian function for fitting
"""
return a * np.exp(-(x-x0)**2/(2*sigma**2)) + c | 78,801 |
def multitrainer(trainers, keep_on_gpu=False):
"""Train multiple models in parallel.
Parameters
----------
trainers : sequence[ModelTrainer]
keep_on_gpu : bool, default=False
Keep all models on GPU (risk of out-of-memory)
"""
initial_epoch = max(min(trainer.initial_epoch for train... | 78,802 |
def spectrum_selection(pth, oms_list, requested_m, requested_n=None):
""" collects spectrum availability and call the select_candidate function
# step 1 collects pth spectrum availability
# step 2 if n is not None try to assign the spectrum
# if the spectrum is not available then sends back a... | 78,803 |
def trigram_bow_generator(filepath, dictionary):
"""
generator function to read reviews from a file
and yield a bag-of-words representation
"""
for review in LineSentence(filepath):
yield dictionary.doc2bow(review) | 78,804 |
def create_local_pbs_profile(
profile="pbs", local_controller=False, custom_template=None
):
"""Creata a PBS profile for ipyparallel.
Parameters
----------
profile : str
Profile name.
local_controller : bool
Create a ipcontroller on a seperate node if True and locally if False.
... | 78,805 |
def graph_BFS(graph, start):
"""
My Python implementation of BFS for a graph
Traverses a graph from a starting vertex and returns an array of the vertices in traversal order
Time complexity: O(V + E), V = Number of vertices, E = Number of edges
Space complexity: O(V)
"""
# Track BFS... | 78,806 |
def main() -> None:
"""Constructs and prints a graph for a hospital."""
# LOCAL VARIABLES
tps_args = parse_arguments() # Arguments parsed from sys.argv
# Separate Rooms?
sep_rooms = separate_rooms(tps_args)
# Directory to store the graph files in
graph_dir = graph_directory(tps_args)
#... | 78,807 |
def test_generate_spi_driving_strength_value_checks():
"""
Generates ft4222_test cases verifying the values of the SPI_DrivingStrength Enum.
"""
values = [('DS_4MA', 0),
('DS_8MA', 1),
('DS_12MA', 2),
('DS_16MA', 3)]
for name, value in values:
yield ... | 78,808 |
def to_sparse_tensor(edge_index: Tensor, edge_weight: Optional[Tensor] = None,
num_nodes: Optional[int] = None, is_sorted: bool = False) -> SparseTensor:
"""Convert edge index to a torch_sparse sparse tensor
Parameters
----------
edge_index : Tensor
edge index with shape [2... | 78,809 |
def clear(n, p, steps):
"""Assumes n & steps positive ints, p a float
n: the initial number of molecules
p: the probability of a molecule being cleared
steps: the length of the simulation"""
numRemaining = [n]
for t in range(steps):
numRemaining.append(n*((1-p)**t))
pylab.plo... | 78,810 |
def get_metadata(data):
"""Gets metadata from the input cloutformation file content."""
return data['Metadata'] | 78,811 |
def cross_count_helper(df, i):
"""
tools for multy thread bi_count
"""
name = "count_"+ '_'.join(i)
df[name] = df.groupby(i)[i[0]].transform('count')
return df[[name]].fillna(-99999).astype(np.int32) | 78,812 |
def while_f():
"""printing small 'f' using while loop"""
i=0
while i<7:
j=0
while j<4:
if j==1 and i!=0 or i==0 and j in(2,3)or i==3 and j!=3 :
print("*",end=" ")
else:
print(" ",end=" ")
j+=1
... | 78,813 |
def _convert_path(element):
"""
Convert an OSM way element into the format for a networkx path.
Parameters
----------
element : dict
an OSM way element
Returns
-------
path : dict
"""
path = {"osmid": element["id"]}
# remove any consecutive duplicate elements in th... | 78,814 |
def spike(time, flux):
"""
Function to calculate the metric called "spike" for K2 objects.
When spike > 1.0, the object is said to have bad arc drift.
args
time : time reference for light curve (seconds)
flux : flux of light curve
returns
spike : spike metric
"""
... | 78,815 |
def prv_axis(dcm):
"""compute the principle rotation vector from a dcm
:param dcm: direction cosine matrix to extract rotation vector
from
:return evec: principle rotation vector (eigvec corres. to the
eigval of +1)
:return phi: magnitude of the angle of rotation (radi... | 78,816 |
def knuth_plass_breaks(paragraph:List[Spec],
line_lengths:Union[List[Num], Num, \
Generator[Num, None, None]], # l1, l2,... in the paper
looseness:int=0, # q in the paper
tolerance:int=1, # rho in the paper
fitness_demerit:Num=100, ... | 78,817 |
def test_create_download_path(dataset, downloader_options_factory, tmpdir, caplog, mock_get_metadata):
"""
:GIVEN: A dataset name.
:WHEN: Creating the destination directory for downloads.
:THEN: Verify the directory is created.
"""
with tmpdir.as_cwd():
expected_path = os.path.join(os.... | 78,818 |
def most_repeatable_cycles(data: np.ndarray, /) -> List[int]:
"""
Get the indexes of the most repeatable cycles in TimeSeries or array.
This function returns an ordered list of the most repeatable to the least
repeatable cycles.
It works by recursively discarding the cycle than maximizes the
r... | 78,819 |
async def guild_create(client: "Client", gateway: "Gateway", event: "GatewayDispatch") -> typing.List[typing.Awaitable]:
"""
|coro|
This event is called when a guild is created.
It does see whether the guild is cached and if not, it caches it.
Parameters
----------
c... | 78,820 |
def topographic_similarity(utts: torch.Tensor, labels: torch.Tensor, max_samples=10000):
"""
(quoting Angeliki 2018)
"The intuition behind this measure is that semantically similar objects should have similar messages."
a and b should be discrete; 2-dimensional. with item index along first dimension, a... | 78,821 |
def _split_file(header, path, dialect=None, list_columns=None, list_separator=None,
encoding='utf-8'):
"""Split a CSV file into columns, one column per file.
:arg str header: The names for each column of the file.
:arg str path: The full path to the file.
:arg Dialect dialect: The CSV d... | 78,822 |
def copy_file(name, src, is_executable = False, allow_symlink = False, **kwargs):
"""Copies a file to another location.
This is a wrapper around copy_file within bazel-skylib.
Args:
name: Name of the rule.
src: A Label. The file to make a copy of. (Can also be the label of a rule
tha... | 78,823 |
def run_evaluation_with_invocab(query_mat, query_words, corpus_mat, corpus_words, train_vocab, drop_first=False):
"""
Same as run_evaluation, but also saving separate statistics for in vocabulary queries.
"""
num_queries = len(query_mat)
log.d("Running {} queries...".format(num_queries))
recall ... | 78,824 |
def driver_not_found(): # pragma: no cover
"""
Helper function to raise CudaSupportError driver not found error
"""
_raise_driver_not_found() | 78,825 |
def test_get_gpubsub_publisher_topic_exists(
config, auth_client, mock_pubsub_client, emulator, metrics):
"""Do not raise if topic already exists."""
changes_chnl = asyncio.Queue()
exp = google_exceptions.AlreadyExists('foo')
mock_pubsub_client.return_value.create_topic.side_effect = [exp]
... | 78,826 |
def handle_client(client): # Takes client socket as argument.
"""Handles a single client connection."""
try:
name = None
name = client.recv(BUFSIZ).decode("utf8")
if name == "{quit}":
print("<unkown> has disconnected")
fc = open("connections_log", "a+")
... | 78,827 |
def raise_if_not_all_objets_fresh(
objects: typing.List[str],
engine=sqlalchemy.engine.base.Engine,
same_day: bool = False,
max_hours: typing.Union[int, None] = None,
) -> None:
"""Raise ValueError unless all Snowflake objects in objects were last modified today and/or less than max_hours ago."""
... | 78,828 |
def dicttonx(
treedict,
h5file,
h5path="/",
mode="w",
overwrite_data=False,
create_dataset_args=None,
):
"""
Write a nested dictionary to a HDF5 file, using string keys as member names.
The NeXus convention is used to identify attributes with ``"@"`` character,
therefor the datas... | 78,829 |
def init_actions_(service, args):
"""
This needs to return an array of actions representing the depencies between actions.
Looks at ACTION_DEPS in this module for an example of what is expected
"""
# some default logic for simple actions
return {
'test': ['install']
} | 78,830 |
def eff_pol(suc, disch):
"""Polytropic efficiency.
Parameters
----------
suc : ccp.State
Suction state.
disch : ccp.State
Discharge state.
Returns
-------
eff_pol : pint.Quantity
Polytropic efficiency (dimensionless).
"""
wp = head_pol(suc, disch)
... | 78,831 |
def get_l16_config():
"""Returns the ViT-L/16 configuration."""
config = ml_collections.ConfigDict()
config.name = 'ViT-L_16'
config.patches = ml_collections.ConfigDict({'size': (16, 16)})
config.hidden_size = 1024
config.transformer = ml_collections.ConfigDict()
config.transformer.mlp_dim = 4096
config... | 78,832 |
def get_featurizer(name, **kwargs):
"""Put new featurizers here!
"""
if name == "tabular":
return TabularFeaturizer(**kwargs)
if name == "propositional":
return PropositionalFeaturizer(**kwargs)
if name == 'SARState':
return SARStateFeaturizer(**kwargs)
if name == 'SAR... | 78,833 |
def get_ip_and_port():
"""The network information function.
"""
s = socket.socket(
family=socket.AF_INET,
type=socket.SOCK_DGRAM,
proto=0,
fileno=None)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 0)
s.connect(('<broadcast>', 0))
ip, port = s.getsockname(... | 78,834 |
def prepare_input(imagePaths, img_size):
"""
Prepare input
IA: not for production
"""
import os
import cv2
import random
GRAY_SCALE_VEC = False
if GRAY_SCALE_VEC:
print(">ia> Converting to grayscale ...")
# initialize the data and labels
print(">ia> Lo... | 78,835 |
def test10():
"""This test checks if the refactor auxiliary function returns an unchanged init
file if the maximum number of iterations is set to zero.
"""
for _ in range(10):
constr = dict()
constr["DETERMINISTIC"], constr["AGENTS"] = False, 1000
constr["MAXITER"], constr["STAR... | 78,836 |
def get_dict(db,name):
"""
Retrieve python dictionary stored in redis database as json string.
"""
data_json = db.get(name)
data_dict = json.loads(data_json,object_hook=json_tools.decode_dict)
return data_dict | 78,837 |
def close_program():
"""7-second timer, then program closes."""
countdown = 7
while countdown:
clear_screen()
print("I hope you enjoyed using this program!")
print("Contact Michael Tiday with issues or suggestions.\n")
print(f"Program exits in {countdown} seconds.")
... | 78,838 |
def sentinel2_get_info(bucket, scene_path, request_pays=False):
"""Get sentinel-2 metadata."""
data = json.loads(
aws.get_object(bucket, f"{scene_path}/tileInfo.json", request_pays=request_pays)
)
return {
"sat": data["productName"][0:3],
"coverage": data.get("dataCoveragePercent... | 78,839 |
def svn_wc_prop_set(*args):
"""
svn_wc_prop_set(char const * name, svn_string_t const * value, char const * path, svn_wc_adm_access_t * adm_access,
apr_pool_t pool) -> svn_error_t
"""
return _wc.svn_wc_prop_set(*args) | 78,840 |
def to_naive_utc(dtime):
"""convert a datetime object to UTC and than remove the tzinfo, if
datetime is naive already, return it
"""
if not hasattr(dtime, 'tzinfo') or dtime.tzinfo is None:
return dtime
dtime_utc = dtime.astimezone(pytz.UTC)
dtime_naive = dtime_utc.replace(tzinfo=None)
... | 78,841 |
def revise_item(ebay_id, site_id=HOME_SITE_ID, item_dict=None):
"""Perform a ReviseItem call."""
revise_dict = {'Item': item_dict or {}}
revise_dict['Item']['ItemID'] = ebay_id
try:
# Initialize TradingAPI
api = get_trading_api(site_id=site_id, api_call='ReviseItem',
... | 78,842 |
def write_dataframe(data_frame, file):
""" Writes a DataFrame as a CSV file"""
data_frame.to_csv(file) | 78,843 |
def closing(managed):
"""
If the managed object already provides its own context management
via the __enter__ and __exit__ methods, it is returned
unchanged. However, if the instance does not, a ClosingContext
will be created to wrap it. When the ClosingContext exits, it will
call managed.close(... | 78,844 |
def __plot_confusion_matrix(cm, classes, path, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
plt.figure(figsize=(10, 10))
if normalize:
cm = cm.astype('... | 78,845 |
def petal(t, r, angle):
"""Use the Turtle (t) to draw a petal using two arcs
with the radius (r) and angle.
"""
for i in range(2):
t.circle(r,angle)
t.left(180-angle) | 78,846 |
def compute_spearman_distance(election_1: OrdinalElection, election_2: OrdinalElection) -> int:
""" Compute Spearman distance between elections """
votes_1 = election_1.votes
votes_2 = election_2.votes
params = {'voters': election_1.num_voters, 'candidates': election_1.num_candidates}
file_name = ... | 78,847 |
def dfSegsNodesNDataDpkt(
VersionsDir=r"C:\3s\Projekte\Projekt\04 - Versionen\Version82.3"
,Model=r"MDBDOC\FBG.mdb" # a Access Model
,am=None # a Access Model already processed
,SEGsDefPattern='(?P<SEG_Ki>\S+)~(?P<SEG_Kk>\S+)$' # RSLW-Beschreibung: liefert die Knotennamen der Segmentdefinition ()... | 78,848 |
def conv2d_direct(*args, **kwargs):
"""Schedule function for directly-scheduled conv2d."""
assert not kwargs, "Do not support kwargs in template function call"
args = deserialize_args(args)
data, kernel = args[:2]
layout = args[-2]
cfg = autotvm.get_config()
args = [cfg] + args
conv = co... | 78,849 |
def Image_Cmc(gallery_features, gallery_ids, gallery_cams, query_features, query_ids, query_cams, rank_size):
"""
features: numpy array of shape (n, d)
label`s: numpy array of shape (n)
"""
# Sample query
data = {'feature':gallery_features, 'id':gallery_ids, 'cam':gallery_cams}
g_idx = np.ar... | 78,850 |
def create_dummy_class(klass, dependency):
"""
When a dependency of a class is not available, create a dummy class which throws ImportError when used.
Args:
klass (str): name of the class.
dependency (str): name of the dependency.
Returns:
class: a class object
"""
clas... | 78,851 |
def persistent_ios_simulator(simctl_path, minimum_os, sim_device,
sim_os_version):
"""Finds or creates a persistent compatible iOS simulator.
Boots the simulator if needed. Does not shut down or delete the simulator when
done.
Args:
simctl_path: The path to the `simctl` binary... | 78,852 |
def test_ROIsPlot(tmp_path):
""" the BET report capable test """
import nibabel as nb
import numpy as np
im = nb.load(
str(
get_template(
"OASIS30ANTs",
resolution=1,
desc="4",
suffix="dseg",
extension=[... | 78,853 |
def register():
"""Register classes to Blender."""
# Unregister native operators for custom behavior
unregister_class(stax.ops.ops_sequencer.SEQUENCER_OT_toggle_meta)
# Set Custom UI and operators
for cls in classes:
register_class(cls)
# Custom Properties
bpy.types.Scene.project_n... | 78,854 |
def loads_function(s):
"""Restores a function serialized with :func:`dumps_function`."""
name, code, globals_, defaults, closure, func_dict, doc, qualname, kwdefaults, annotations = loads(s)
code = marshal.loads(code)
for k, v in globals_.items():
if isinstance(v, Module):
globals_[k... | 78,855 |
def convert_single_example(ex_index, example, max_seq_length,
tokenizer):
"""Converts a single `InputExample` into a single `InputFeatures`."""
tokens = tokenizer.tokenize(example.text)
# Account for [CLS] and [SEP] with "- 2"
if len(tokens) > max_seq_length - 2:
tokens = tokens[... | 78,856 |
def load(repo_dir: str, repo_url: str) -> t.Optional[RepoUtil]:
"""
Load git repository from local directory into Python object.
:param repo_dir: (str) directory where .git file is located
:param repo_url: (str) url to Github repository
"""
repo = RepoUtil(repo_url)
try:
repo.... | 78,857 |
def session_transaction():
"""Provide a transactional scope around a series of operations."""
try:
yield db_session
db_session.commit()
except IrmaDatabaseError:
db_session.rollback()
raise
finally:
db_session.close() | 78,858 |
def loads(s, bqm):
"""Load a COOrdinate formatted binary quadratic model from a string."""
pattern = re.compile(_LINE_REGEX)
for line in s.split('\n'):
match = pattern.search(line)
if match is not None:
u, v, bias = int(match.group(1)), int(match.group(2)), float(match.group(3)... | 78,859 |
def remove_duplicate_joints(seq):
"""
:param seq: [n_frames x 96]
"""
n_frames = len(seq)
if len(seq.shape) == 2:
assert seq.shape[1] == 96, str(seq.shape)
seq = seq.reshape((n_frames, 32, 3))
assert len(seq.shape) == 3, str(seq.shape)
valid_jids = [
0, 1, 2, 3, 4, 5,... | 78,860 |
def use_arrays(*funcs):
"""Switch the listed functions or names of functions to use the "array"
version by default. This affects all versions of any given cspyce function.
If the list is empty, apply this operation to all cspyce functions.
"""
if funcs:
cspyce.GLOBAL_STATUS.add('ARRAYS')
... | 78,861 |
def set_optimizer_momentum(optimizer: Optimizer, value: float, index: int = 0):
"""
Set momentum of ``index`` 'th param group of optimizer to ``value``
Args:
optimizer: PyTorch optimizer
value (float): new value of momentum
index (int, optional): integer index of optimizer's param g... | 78,862 |
def strip_non_printing(text):
"""Removes non-printing (including control) characters from text.
(same as moses script).
"""
return ''.join([c for c in text if c.isprintable()]) | 78,863 |
def ntp_bottle_to_cast(
sB,
tB,
pB,
S,
T,
P,
tol_p=1e-4,
interp="linear",
eos="gsw",
grav=None,
rho_c=None,
):
"""Find the neutral tangent plane from a bottle to a cast
Finds a point on the cast salinity, temperature, and pressure `(S, T, P)`
where the salinity, ... | 78,864 |
def polyline(*points):
"""Converts a list of points to a Path composed of lines connecting those
points (i.e. a linear spline or polyline). See also `polygon()`."""
return Path(*[Line(points[i], points[i+1])
for i in range(len(points) - 1)]) | 78,865 |
def transfer(alias, sub_nas, args):
"""
:param alias:
:param sub_nas:
\n:param args [new_owner, type]:
\n:returns True if success or False if failed:
\nif sub_nas defined passes call to sub_nas otherwise
we try to transfer alias
"""
# handle sub_nas first
nargs = len(args)
if... | 78,866 |
def get_true_positives(data, classifier):
"""Find the total positives that also are selected by our classifier."""
return data[data["foundSegment"] & classifier(data)].size | 78,867 |
def africa(container, images):
"""Creates the Africa tab container within a parent container"""
multipane = ttk.Notebook(container)
f11 = ttk.Frame(multipane)
f12 = ttk.Frame(multipane)
multipane.add(f11, text='South Africa')
multipane.add(f12, text='Northwest Africa')
multipane.grid(row=... | 78,868 |
def make_app(file="./random-mac-classifier.pickled"):
"""
This is the app factory.
Parameters
----------
file : str
The name of the file containing the
saved (pickled) classifier.
Returns
-------
flask app
An instance of the app.
"""
# Restore (unpickle) the classifier.
classifier ... | 78,869 |
def prt(i):
"""
这是一个打印方法,输出输入参数
:return:
"""
print("start...")
x = 0
for j in range(i):
x += j
print(x)
print('end...') | 78,870 |
def test_apply_patch(mock_repo):
"""
GIVEN GitRepo initialized with a path and repo
WHEN apply_patch is called with a valid branch_name and valid path
THEN git.am is called
"""
repo = GitRepo('./', mock_repo)
with patch('git.repo.fun.name_to_object'):
repo.branch.apply_patch('test_b... | 78,871 |
def cc_forbidden_error_response(account_id):
"""Build a crown charge registration class access forbidden error response."""
message = CROWN_CHARGE_FORBIDDEN.format(account_id=account_id)
current_app.logger.info(str(HTTPStatus.FORBIDDEN.value) + ': ' + message)
return jsonify({'message': message}), HTTPS... | 78,872 |
def fit_func_invexp(x, a, b, c):
"""Fits an inverse exponential function to the semivariogram."""
if a < 0:
return -9999
if b < 0:
return -9999
if c < 0:
return -9999
# Here a is sigma2_o, b is sigma2_b, and c is L_b
return a + b*(1. - np.exp(-1*x/c)) | 78,873 |
def validate_configuration():
"""
Method to validate the configuration file.
"""
for var in [value for key, value in \
Config.__dict__.items() if not key.startswith('__')]:
if not isinstance(var, (int, float, str, tuple, list, set, dict)):
log.error('Configurtion error! Pl... | 78,874 |
def test_parse_run_results_failures(
unique_id: str,
failures: int,
dbt_run_results: dict,
) -> None:
"""Validate the failures of the nth result."""
parsed_run_results = soda_dbt.parse_run_results(dbt_run_results)
run_result = [
run_result
for run_result in parsed_run_results
... | 78,875 |
def omniglot_tasksets(
train_ways,
train_samples,
test_ways,
test_samples,
root,
**kwargs
):
"""
Benchmark definition for Omniglot.
"""
data_transforms = transforms.Compose([
transforms.Resize(28, interpolation=LANCZOS),
transforms.ToTensor(),
lambda x: 1.... | 78,876 |
def if_gte_python37() -> Tuple[int, int]: # pragma: py-gte-37
"""Test function for pragma ``py-gte-37``."""
return (3, 7) | 78,877 |
def tsv_to_list(stream: TextIO) -> List[List[yattag.doc.Doc]]:
"""Turns a tab-separated table into a list of lists."""
table = []
first = True
type_index = 0
for line in stream.readlines():
if not line.strip():
continue
if first:
first = False
for... | 78,878 |
def test_greedy():
"""
>>> food = ["Burger", "Pizza", "Coca Cola", "Rice",
... "Sambhar", "Chicken", "Fries", "Milk"]
>>> value = [80, 100, 60, 70, 50, 110, 90, 60]
>>> weight = [40, 60, 40, 70, 100, 85, 55, 70]
>>> foods = build_menu(food, value, weight)
>>> foods # doctest: +NORMA... | 78,879 |
def flatten(
container: RequiresContext[
_EnvType, RequiresContext[_EnvType, _ValueType],
],
) -> RequiresContext[_EnvType, _ValueType]:
"""Case for ``RequiresContext`` container.""" | 78,880 |
def CustomShortestPath(p1, p2, m, n):
"""This should be a faster way to find the shorest path, as we only have a
cartesian grid. So Dijkstra might be overkill
This function takes p1 and p2 in cartesian coords, and returns a simple
path between them by correcting x pos. then y pos.
this will not na... | 78,881 |
def _resolve(o):
"""
Make sure that this object becomes a Query object.
In case of a tuple/list, create a QueryTuple/List,
otherwise, return a Static
"""
if isinstance(o, Query):
return o
elif isinstance(o, tuple):
return Tuple(o)
elif isinstance(o, list):
retur... | 78,882 |
def add_fields_to_cr(cr_id, patient_fields):
"""Use the Omicia API to fill in custom patient fields for a clinical report
e.g. patient_fields: '{"Patient Name": "Eric", "Gender": "Male", "Accession Number": "1234"}'
"""
#Construct request
url = "{}/reports/{}/patient_fields"
url = url.format(FAB... | 78,883 |
def checkin_command(gbxtag_as_str):
"""
This command will navigate to the edit asset page on lansweeper
,change the contact and location to "5TH FLOOR IT STORAGE ROOM
and remove any associated user relations
"""
gbxtag = gbxtag_as_str
theteachingsofbuddha = 1
# This s... | 78,884 |
def add_commands(add_command):
"""Adds the websocket commands"""
add_command(GetDashboardsCommand) | 78,885 |
def test_list_nmtokens_max_length_2_nistxml_sv_iv_list_nmtokens_max_length_3_5(mode, save_output, output_format):
"""
Type list/NMTOKENS is restricted by facet maxLength with value 7.
"""
assert_bindings(
schema="nistData/list/NMTOKENS/Schema+Instance/NISTSchema-SV-IV-list-NMTOKENS-maxLength-3.x... | 78,886 |
def test_investment_project_interaction_changed_sync_to_es(es_with_signals):
"""
Test projects get synced to Elasticsearch when an interaction's project is changed.
When an interaction's project is switched to another project, both the old
and new project should be updated in Elasticsearch.
"""
... | 78,887 |
def test_client_list_jobs(client):
"""List jobs for a project."""
# [START bigquery_list_jobs]
# TODO(developer): Uncomment the lines below and replace with your values.
# from google.cloud import bigquery
# project = 'my_project' # replace with your project ID
# client = bigquery.Client(proje... | 78,888 |
def update_daily_status():
"""update the daily user stats."""
today = datetime.datetime.today()
date = today.date()
# if it is run on mid night, we should count previous day's data
if today.hour == 0:
date -= datetime.timedelta(days=1)
count = Profile.objects.filter(last_visit_date=date... | 78,889 |
def handle_klio(*args, max_thread_count=None, thread_limiter=None, **kwargs):
"""Serialize & deserialize incoming PCollections as a KlioMessage.
Behind the scenes, this generates :class:`KlioContext
<klio.transforms.core.KlioContext>`, handles de/serialize the
incoming PCollection as a Klio Message, as... | 78,890 |
def specgram_func(i, gtime, duration, padding, node_id, channel, NFFT, noverlap, freq_range, filter=None):
"""Worker process to compute specgrams"""
session = globals()['mppool'].g_session # Worker process namespace is a bit odd
# actually read the audio data
data = session.ReadDataAtGTime(node_id, gti... | 78,891 |
def par_ACS_ERS(CEOS_SAR_leader, SLC_par, logpath=None):
"""
| ISP parameter file generation for ERS SLC data from the ACS processor
| Copyright 2005, Gamma Remote Sensing, v1.3 17-Oct-2005 clw/uw
Parameters
----------
CEOS_SAR_leader:
(input) ERS CEOS SAR leader file
SLC_par:
... | 78,892 |
def generate_exclusions(proteins):
"""
Generate a series of exclusion spheres for some cavities
:param proteins: a list of protein cavities
:return: the combined exclusion spheres
"""
pass | 78,893 |
def preparehost(host="", keyname="",pushkey=False):
"""
prepare ssh host to do docker on
e.g.
python3 do.py preparehost --host '192.168.0.250:22'
"""
c=j.tools.cuisine.get(host)
print ("install jumpscale, this will take a while")
#be carefull this will remove history, will be installed... | 78,894 |
def background_thread(session):
"""Send server generated events to client."""
print("BG THREAD FIRED!")
# Save timer to db on stop.
# db.session.remove() <-- clear sessions like this?
# https://github.com/miguelgrinberg/Flask-SocketIO/issues/410
thread_live = True
timer = None
while thr... | 78,895 |
def getBleu(bleus):
"""
"""
return sum(bleus, BleuStats()).bleu() | 78,896 |
def normalize_val(val, min_v, max_v):
"""
print 'nomalized depth value'
nomalize values to 0-255 & close distance value has low value.
"""
return (((val - min_v) / (max_v - min_v)) * 255).astype(np.uint8) | 78,897 |
def make_sasl_acl(perm, krb_realm):
"""Create SASL ACL"""
scheme = 'sasl'
principal = '{}/{}@{}'
host_principal = principal.format(CURRENT_USER, HOSTNAME, krb_realm)
acls = [kazoo.security.make_acl(scheme, host_principal,
read='r' in perm,
... | 78,898 |
def fill_coords(datafr):
"""
Interpoleert op cellen met NaN waarden
:return DataFrame
"""
# df_dropped_na = datafr.dropna()
# nonNA = list(df_dropped_na.index.values)
#
# for i in range(len(nonNA) - 1):
# prev_lat = datafr.at[nonNA[i], 'latitude']
# diff_lat = abs(datafr... | 78,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.