content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_data_table_metas(data_table_name, data_table_namespace):
"""
Gets metas from meta table associated with table named `data_table_name` and namespaced `data_table_namespace`.
Parameters
---------
data_table_name : string
table name of this data table
data_table_namespace : string
... | 26,800 |
def get_at_content(sequence):
"""Return content of AT in sequence, as float between 0 and 1, inclusive. """
sequence = sequence.upper()
a_content = sequence.count('A')
t_content = sequence.count('T')
return round((a_content+t_content)/len(sequence), 2) | 26,801 |
def page_not_found(e):
"""Handle nonexistin pages."""
_next = get_next_url()
if _next:
flash("Page Not Found", "danger")
return redirect(_next)
return render_template("404.html"), 404 | 26,802 |
def test_query(p: int = 1) -> int:
"""
Example 2 for a unit test
:param p: example of description
:return: return data
"""
return p | 26,803 |
def mirror_1d(d, xmin=None, xmax=None):
"""If necessary apply reflecting boundary conditions."""
if xmin is not None and xmax is not None:
xmed = (xmin+xmax)/2
return np.concatenate((2*xmin-d[d < xmed], d, 2*xmax-d[d >= xmed]))
elif xmin is not None:
return np.concatenate((2*xmin-d, ... | 26,804 |
def setup(bot):
"""
:param bot: a discord.client
:return: None
"""
bot.add_cog(AutoCensor(bot)) | 26,805 |
def incr_ratelimit(user, domain='all'):
"""Increases the rate-limit for the specified user"""
list_key, set_key, _ = redis_key(user, domain)
now = time.time()
# If we have no rules, we don't store anything
if len(rules) == 0:
return
# Start redis transaction
with client.pipeline() ... | 26,806 |
def TestCleanUp(user_profile_dir):
"""Cleans up test machine so as not to impact other tests.
Args:
user_profile_dir: the user-profile folder used by Chromoting tests.
"""
# Stop the host service.
RunCommandInSubProcess(CHROMOTING_HOST_PATH + ' --stop')
# Cleanup any host logs.
RunCommandInSubProce... | 26,807 |
def calc_vertical_avg(fld,msk):
"""Compute vertical average, ignoring continental or iceshelf points """
# Make mask of nans, assume input msk is 3D of same size as fld 3 spatial dims
nanmsk = np.where(msk==1,1,np.NAN)
v_avg = fld.copy()
v_avg.values = v_avg.values*msk.values
if 'Z' in... | 26,808 |
def get_logger(log_file, log_level="info"):
"""
create logger and output to file and stdout
"""
assert log_level in ["info", "debug"]
log_formatter = LogFormatter()
logger = logging.getLogger()
log_level = {"info": logging.INFO, "debug": logging.DEBUG}[log_level]
logger.setLevel(log_leve... | 26,809 |
def replace(data, match, repl):
"""Replace values for all key in match on repl value.
Recursively apply a function to values in a dict or list until the input
data is neither a dict nor a list.
"""
if isinstance(data, dict):
return {
key: repl if key in match else replace(value,... | 26,810 |
def get_current_date() ->str:
"""Forms a string to represent the current date using the time module"""
if len(str(time.gmtime()[2])) == 1:
current_date = str(time.gmtime()[0]) + '-' + str(time.gmtime()[1]) + '-0' + str(time.gmtime()[2])
else:
current_date = str(time.gmtime()[0]) + '-' +... | 26,811 |
def to_jsobj(obj):
"""Convert a Jsonable object to a JSON object, and return it."""
if isinstance(obj, LIST_TYPES):
return [to_jsobj(o) for o in obj]
if obj.__class__.__module__ == "builtins":
return obj
return obj.to_jsobj() | 26,812 |
def start(
context: Context,
on_startup: Callable[[web.Application], Awaitable[Any]],
on_cleanup: Callable[[web.Application], Awaitable[Any]],
):
"""
Start the web app.
"""
app = web.Application()
app['context'] = context
app.on_startup.append(on_startup)
app.on_cleanup.append(on... | 26,813 |
def EVAL_find_counter_exemplars(latent_representation_original, Z, idxs, counter_exemplar_idxs):
"""
Compute the values of the goal function.
"""
# prepare the data to apply the diversity optimization
data = np.zeros((len(idxs), np.shape(Z)[1]))
for i in range(len(idxs)):
data[i] = Z[i... | 26,814 |
def test_traversal_from_multiple_letters():
"""Test if traversal of multiple letters works correctly."""
test_tree = trie.TrieTree()
test_list = ['fae', 'fir', 'faerie', 'fox', 'forest']
for i in test_list:
test_tree.insert(i)
traversal_list = [i for i in test_tree.traversal('fae')]
test... | 26,815 |
def test_add():
"""Test add function."""
from src.kata import Add
assert Add(1)(2)(3) == 6 | 26,816 |
def min_energy(bond):
"""Calculate minimum energy.
Args:
bond: an instance of Bond or array[L1*L2][3].
"""
N_unit = L1*L2
coupling = bond.bond if isinstance(bond, Bond) else bond
# Create matrix A
a = np.zeros((N_unit, N_unit), dtype=float)
for i in range(N_unit):
a[i][... | 26,817 |
def find_result_node(flat_graph: dict) -> Tuple[str, dict]:
"""
Find result node in flat graph
:return: tuple with node id (str) and node dictionary of the result node.
"""
result_nodes = [(key, node) for (key, node) in flat_graph.items() if node.get("result")]
if len(result_nodes) == 1:
... | 26,818 |
def password_generator(size=25, chars=string.ascii_uppercase + string.ascii_lowercase + string.digits):
"""Returns a random 25 character password"""
return ''.join(random.choice(chars) for _ in range(size)) | 26,819 |
def create_cleaned_df(df, class_label_str):
"""Transform the wide-from Dataframe (df) from main.xlsx into one with
unique row names, values 0-1001 as the column names and a label column
containing the class label as an int.
Parameters
----------
df : pandas DataFrame
A DataFrame read in... | 26,820 |
def uni_to_int(dxu, x, lambda_val):
"""
Translates from single integrator to unicycle dynamics.
Parameters
----------
dxu :
Single integrator control input.
x :
Unicycle states (3 x N)
lambda_val :
Returns
-------
dx :
"""
n = dxu.shape[1]
dx = np... | 26,821 |
def pack_binary_command(cmd_type, cmd_args, is_response=False):
"""Packs the given command using the parameter ordering specified in GEARMAN_PARAMS_FOR_COMMAND.
*NOTE* Expects that all arguments in cmd_args are already str's.
"""
expected_cmd_params = GEARMAN_PARAMS_FOR_COMMAND.get(cmd_type, None)
i... | 26,822 |
def get_adjacency_spectrum(graph, k=np.inf, eigvals_only=False, which='LA', use_gpu=False):
"""
Gets the top k eigenpairs of the adjacency matrix
:param graph: undirected NetworkX graph
:param k: number of top k eigenpairs to obtain
:param eigvals_only: get only the eigenvalues i.e., no eigenvector... | 26,823 |
def make_system(*args, **kwargs):
"""
Factory function for contact systems. Checks the compatibility between the
substrate, interaction method and surface and returns an object of the
appropriate type to handle it. The returned object is always of a subtype
of SystemBase.
Parameters:
------... | 26,824 |
def _batch_normalization(x, norm, scale=None, norm_epsilon=1e-16, name=None):
"""
Normalizes a tensor by norm, and applies (optionally) a 'scale' \\(\gamma\\) to it, as well as
an 'offset' \\(\beta\\):
\\(\frac{\gamma(x)}{norm} + \beta\\)
'norm', 'scale' are all expected to be of shape:
... | 26,825 |
def place_owner_list(user_id):
"""
It retrieves the list of places for which the user is the owner.
Parameters:
- user_id: id of the user, which is owner and wants to get its own places.
Returns a tuple:
- list of Places owned by the user (empty if the user is not an owner)
- status messag... | 26,826 |
def job_met_heu(prob_label, tr, te, r, ni, n):
"""MeanEmbeddingTest with test_locs randomized.
tr unused."""
# MeanEmbeddingTest random locations
with util.ContextTimer() as t:
met_heu = tst.MeanEmbeddingTest.create_fit_gauss_heuristic(te, J, alpha, seed=180)
met_heu_test = met_heu.perf... | 26,827 |
def download():
"""Unchanged from web2py.
```
allows downloading of uploaded files
http://..../[app]/default/download/[filename]
```
"""
return response.download(request, db) | 26,828 |
def train_revenue_model_q2(df_listings: pd.DataFrame, df_daily_revenue: pd.DataFrame):
"""Trains the revenue estimator to be used on question 2.
Parameters
----------
df_listings : pd.DataFrame
Pandas dataframe with information about listings.
df_daily_revenue : pd.DataFrame
... | 26,829 |
def test_all(model_name):
"""
Test a given model on the whole MNIST training set
* Used for debugging
:return: None
"""
model = models.load_model(model_name)
test_loss, test_acc = model.evaluate(image_data_testing, label_data_testing)
print("Test Loss: {0} - Test Acc: {1}".format... | 26,830 |
def setupCLI():
"""
Handles the command line arguments for running the code, making optional date arguments easier and
cleaner to handle
Returns
-------
List of formatted Command Line arguments
"""
parser = argparse.ArgumentParser()
parser.add_argument('databaseName', type=str)
... | 26,831 |
def reopen(service, **kwargs):
"""Reopen an existing closed issue."""
issue = service.issue(kwargs.pop('number'))
if issue.state != 'closed':
raise GitIssueError('issue %s is not closed' % issue.number)
issue = issue.reopen()
_finish_('Reopened', issue.number, issue.url()) | 26,832 |
def set_transform_rotation(transform, rotation):
"""
Change the initial rotation of a transform matrix to the specified angle, ignoring previous angles
:param transform: The transform to change
:param rotation: The angle in degrees for the transform rotation to be
:retur... | 26,833 |
def named_cache(path):
"""
Return dictionary of cache with `(package name, package version)` mapped to cache entry.
This is a simple convenience wrapper around :py:func:`packages`.
"""
return {os.path.split(x.path)[1]: x for x in packages(path)} | 26,834 |
def action_id2arr(ids):
""" Converts action from id to array format (as understood by the environment) """
return actions[ids] | 26,835 |
def get_args():
"""Get command-line arguments."""
parser = argparse.ArgumentParser(
description='Emulate the tac program: print file(s) last line first.',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('file',
type=argparse.FileType('rt'... | 26,836 |
def cif_from_ase(ase,full_occupancies=False,add_fake_biso=False):
"""
Construct a CIF datablock from the ASE structure. The code is taken
from
https://wiki.fysik.dtu.dk/ase/epydoc/ase.io.cif-pysrc.html#write_cif,
as the original ASE code contains a bug in printing the
Hermann-Mauguin symmetry sp... | 26,837 |
def breadcrumb(instance=None, label=None):
"""
Create HTML Breadcrumb from instance
Starting with the instance, walk up the tree building a bootstrap3
compatiable breadcrumb
"""
from promgen import models
def site(obj):
yield reverse("site-detail"), obj.domain
def shard(obj):
... | 26,838 |
def parse_body_at(path_to_hdf5, num_frame, all=False):
"""
:param path_to_hdf5: path to annotations 'hdf5' file
:param num_frame: frame to extract annotations from
:param all: if True, all original landmarks are returned. Otherwise, only those used for evaluation are returned.
:return: confidence, ... | 26,839 |
def get_loader(data_args,
transform_args,
split,
task_sequence,
su_frac,
nih_frac,
cxr_frac,
tcga_frac,
batch_size,
is_training=False,
shuffle=False,
study... | 26,840 |
def get_domain(arn: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetDomainResult:
"""
The resource schema to create a CodeArtifact domain.
:param str arn: The ARN of the domain.
"""
__args__ = dict()
__args__['arn'] = arn
if opts is None:
... | 26,841 |
def collect_properties(service_instance, view_ref, obj_type, path_set=None, include_mors=False):
"""
Collect properties for managed objects from a view ref
Check the vSphere API documentation for example on retrieving
object properties:
- http://goo.gl/erbFDz
Original Source: https://git... | 26,842 |
async def test_find_in_range_defaults_inverted(hass, mqtt_mock):
"""Test find in range with default range but inverted."""
mqtt_cover = MqttCover(
{
"name": "cover.test",
"state_topic": "state-topic",
"get_position_topic": None,
"command_topic": "command-t... | 26,843 |
def _timeout(seconds):
"""Decorator for preventing a function from running for too long.
Inputs:
seconds (int): The number of seconds allowed.
Notes:
This decorator uses signal.SIGALRM, which is only available on Unix.
"""
assert isinstance(seconds, int), "@timeout(sec) requires an... | 26,844 |
def marginal_entropy(problem: dict, train_ixs: np.ndarray, obs_labels: np.ndarray, unlabeled_ixs: np.ndarray,
batch_size: int, **kwargs) -> np.ndarray:
"""
Score is -p(x)log[p(x)] i.e. marginal entropy of the point.
:param problem: dictionary that defines the problem, containing keys:
... | 26,845 |
def notify_owner(plugin, vc_room):
"""Notifies about the deletion of a Vidyo room from the Vidyo server."""
user = vc_room.vidyo_extension.owned_by_user
tpl = get_plugin_template_module('emails/remote_deleted.html', plugin=plugin, vc_room=vc_room, event=None,
vc_room_eve... | 26,846 |
def roc_plot_from_thresholds(roc_thresholds_by_model, save=False, debug=False):
"""
From a given dictionary of thresholds by model, create a ROC curve for each model.
Args:
roc_thresholds_by_model (dict): A dictionary of ROC thresholds by model name.
save (bool): False to display the ... | 26,847 |
def prepareNNImages(bact_img, ftsz_img, model, bacteria=False):
"""Preprocess raw iSIM images before running them throught the neural network.
Returns a 3D numpy array that contains the data for the neural network and the
positions dict generated by getTilePositions for tiling.
"""
# Set iSIM speci... | 26,848 |
def com_google_fonts_check_metadata_undeclared_fonts(family_metadata, family_directory):
"""Ensure METADATA.pb lists all font binaries."""
pb_binaries = []
for font_metadata in family_metadata.fonts:
pb_binaries.append(font_metadata.filename)
passed = True
binaries = []
for entry in os... | 26,849 |
def get_key(val):
"""
Get dict key by value
:param val:
:return:
"""
for key, value in HANDSHAKE.items():
if val == value:
return key | 26,850 |
def switch_to_frame_with_id(self, frame):
"""Swap Selenium's context to the given frame or iframe."""
elem = world.browser.find_element_by_id(frame)
world.browser.switch_to.frame(elem) | 26,851 |
def valid_text(val, rule):
"""Return True if regex fully matches non-empty string of value."""
if callable(rule):
match = rule(val)
else:
match = re.findall(rule, val)
return (False if not match or not val else
True if match is True else
match[0] == val) | 26,852 |
def settings():
"""Render the settings page."""
c = mongo.db[app.config['USERS_COLLECTION']]
user = c.find_one({'username': current_user.get_id()})
if not user:
return render_template()
user['id'] = str(user['_id'])
user.pop('_id', None)
return render_template('settings.html', user=u... | 26,853 |
def exportAllScansS3(folder_id):
""" Exports all Tenable scans found in a folder to S3. """
scan_list = []
scans = client.scan_helper.scans(folder_id=folder_id)
for scan in scans:
if scan.status() != 'completed':
continue
scan.download("./%s.html" % scan.details().info.name, format='html')
s... | 26,854 |
def pytest_runtest_teardown():
"""
Removing log handler which was created in func:`pytest_runtest_setup`
"""
fh = logging.getLogger().handlers[1]
fh.close()
logging.getLogger().removeHandler(fh) | 26,855 |
def check_ontology_graph(ontology_key, survol_agent=None):
"""This checks that a full ontology contains a minimal subset of classes and attributes.
This is for testing purpose only."""
url_script = {
"survol": "ontologies/Survol_RDFS.py",
"wmi": "ontologies/WMI_RDFS.py",
... | 26,856 |
def Retry(retry_value=Exception,
max_retries=None,
initial_delay_sec=1.0,
delay_growth_factor=1.5,
delay_growth_fuzz=0.1,
max_delay_sec=60):
"""Returns a retry decorator."""
if max_retries is None:
max_retries = 2**30 # Effectively forever.
if delay_growth_f... | 26,857 |
def download_handler(resource, _, filename=None, inline=False, activity_id=None):
"""Get the download URL from LFS server and redirect the user there
"""
if resource.get('url_type') != 'upload' or not resource.get('lfs_prefix'):
return None
context = get_context()
data_dict = {'resource': re... | 26,858 |
def _add_subtitle(fig, case_date: date, site_name: str):
"""Adds subtitle into figure."""
text = _get_subtitle_text(case_date, site_name)
fig.suptitle(text, fontsize=13, y=0.885, x=0.07, horizontalalignment='left',
verticalalignment='bottom') | 26,859 |
def body_open():
"""open the main logic"""
return " @coroutine\n def __query(__connection):" | 26,860 |
def db_add_entry(user_auth,\
name:str, user_id:str, user_pw:str, url:str=''):
"""
Add an entry into the credentials database, and returns the inserted row.
If insertion fails, return None.
"""
# SQL Query
sql = f'INSERT INTO {DB_TABLE}'
sql += '(name, user_id, user_pw, url, date_created... | 26,861 |
def First():
"""(read-only) Sets the first sensor active. Returns 0 if none."""
return lib.Sensors_Get_First() | 26,862 |
def rch_from_model_ds(model_ds, gwf):
"""get recharge package from model dataset.
Parameters
----------
model_ds : xarray.Dataset
dataset with model data.
gwf : flopy ModflowGwf
groundwaterflow object.
Returns
-------
rch : flopy ModflowGwfrch
rch package
""... | 26,863 |
def _drawdots_on_origin_image(mats, usage, img, notation_type, color=['yellow', 'green', 'blue', 'red']):
"""
For visualizatoin purpose, draw different color on original image.
:param mats:
:param usage: Detection or Classfifcation
:param img: original image
:param color: color list for each cat... | 26,864 |
def scale(*args, x = 1, y = 1):
"""
Returns a transformation which scales a path around the origin by the specified amount.
`scale(s)`: Scale uniformly by `s`.
`scale(sx, sy)`: Scale by `sx` along the x axis and by `sy` along the y axis.
`scale(x = sx)`: Scale along the x axis only.
`scale(y = sy)`: Scale along... | 26,865 |
def load_tweet_users_posted_rumours():
"""
load user history (whether a user posted any rumour in the past)
:return: dict {timestamp at which the user posted a rumour: user_id}
"""
with open(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'tweet_users_posted_rumours'), 'rb') as outf... | 26,866 |
def create_power_anomaly_pipeline(hparams):
"""
Generate anomalies of types 1 to 4 for a given power time series
"""
pipeline = Pipeline(path=os.path.join('run'))
seed = hparams.seed
# Type 1: Negative power spike potentially followed by zero values and finally a positive power spike
anomal... | 26,867 |
async def async_setup_entry(hass, config_entry):
"""Set up Tile as config entry."""
websession = aiohttp_client.async_get_clientsession(hass)
client = await async_login(
config_entry.data[CONF_USERNAME],
config_entry.data[CONF_PASSWORD],
session=websession,
)
async def asyn... | 26,868 |
def read_csv_by_chunks_createindices_and_partitionPQbygroup(input_csv_path,
parquet_dataset_output_path,
indices_csv_output_path,
chunksize,... | 26,869 |
def _generate_presigned_url(context, bucket, key, callback):
"""
Generates presigned URL
:param Context context: Thumbor's context
:param string bucket: Bucket name
:param string key: Path to get URL for
:param callable callback: Callback method once done
"""
Bucket(bucket, context.confi... | 26,870 |
def get_selection_uri_template():
"""
Utility function, to build Selection endpoint's Falcon uri_template string
>>> get_selection_uri_template()
'/v1/source/{source_id}/selection.{type}'
"""
str_source_uri = get_uri_template(source.str_route)
path_selection = selection.str_route
param... | 26,871 |
def client_thread_runner(port, nums=[]):
"""Client.
"""
tid = threading.current_thread().ident
sockobj = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sockobj.settimeout(1.0 * len(nums))
sockobj.connect(('localhost', port))
logging.info('Client {0} connected to server'.format(tid))
... | 26,872 |
def conv_single_step(a_slice_prev, W, b):
"""
Apply one filter defined by parameters W on a single slice (a_slice_prev) of the output activation
of the previous layer.
Arguments:
a_slice_prev -- slice of input data of shape (f, f, n_C_prev)
W -- Weight parameters contained in a window - ma... | 26,873 |
def _is_pyqt_obj(obj):
"""Checks if ``obj`` wraps an underlying C/C++ object."""
if isinstance(obj, QtCore.QObject):
try:
obj.parent()
return True
except RuntimeError:
return False
else:
return False | 26,874 |
def get_optimizer(
optim_type: str,
optimizer_grouped_parameters,
lr: float,
weight_decay: float,
eps: Optional[float] = 1e-6,
betas: Optional[Tuple[float, float]] = (0.9, 0.999),
momentum: Optional[float] = 0.9,
):
"""
Choose a Pytorch optimizer based on ... | 26,875 |
def point_maze():
"""IRL config for PointMaze environment."""
env_name = "imitation/PointMazeLeftVel-v0"
rollout_path = os.path.join(
serialize.get_output_dir(),
"train_experts/ground_truth/20201203_105631_297835/imitation_PointMazeLeftVel-v0",
"evaluating_rewards_PointMazeGroundTrut... | 26,876 |
def forward(observations, transitions, sequence_len, batch=False):
"""Implementation of the forward algorithm in Keras.
Returns the log probability of the given observations and transitions
by recursively summing over the probabilities of all paths through
the state space. All probabilities are in loga... | 26,877 |
def fib(n):
"""Return the n'th Fibonacci number.
"""
if n < 0:
raise ValueError("Fibonacci numbers are only defined for n >= 0.")
return _fib(n) | 26,878 |
def check_column(board):
"""
list -> bool
This function checks if every column has different numbers and returns
True is yes, and False if not.
>>> check_column(["**** ****", "***1 ****", "** 3****", \
"* 4 1****", " 9 5 ", " 6 83 *", "3 1 **", " 8 2***", " 2 ****"])
False
>>> ... | 26,879 |
def lines_len_in_circle(r, font_size=12, letter_width=7.2):
"""Return the amount of chars that fits each line in a circle according to
its radius *r*
Doctest:
.. doctest::
>>> lines_len_in_circle(20)
[2, 5, 2]
"""
lines = 2 * r // font_size
positions = [
x + (font_... | 26,880 |
def exec_psql(conn_str, query, **args): # type: (str, str, dict) -> str
"""
Executes SQL queries by forking and exec-ing '/usr/bin/psql'.
:param conn_str: A "connection string" that defines the postgresql resource in the format
{schema}://{user}:{password}@{host or IP}:{port}/{database}
:param query: The query to... | 26,881 |
def wait_for_dialog(bus, dialogs, context=None, timeout=None):
"""Wait for one of the dialogs given as argument.
Args:
bus (InterceptAllBusClient): Bus instance to listen on
dialogs (list): list of acceptable dialogs
context (behave Context): optional context providing scenario timeout
... | 26,882 |
def test_filtered_data_shape():
"""Test that filtering data returns same shape."""
data = rs.randn(100)
data_filt = glm.fsl_highpass_filter(data, 30)
nt.assert_equal(data.shape, data_filt.shape)
data = rs.randn(100, 3)
data_filt = glm.fsl_highpass_filter(data, 30)
nt.assert_equal(data.shape... | 26,883 |
def capacitorCorrection(m_cap):
"""Apply a correction to the measured capacitance value
to get a value closer to the real value.
One reason this may differ is measurement varies based on frequency.
The measurements are performed at 30Hz but capacitance values
are normally quoted for 1kH... | 26,884 |
def test_mat_vec_math():
"""test_mat_vec_math
Verifies that the Mat and Vec objects from
proteus.LinearAlgebraTools behave as expected together when
computing basic linear algebra for one trial.
"""
from proteus.LinearAlgebraTools import Vec
from proteus.LinearAlgebraTools import Mat
... | 26,885 |
def set_log_level(level):
"""Sets log level."""
global _log_level
_log_level = level | 26,886 |
def code128_quebrar_partes(partes):
"""
Obtém as partes em que o Code128 deverá ser quebrado.
Os códigos de barras Code128 requerem que os dados possuam um
comprimento par, para que os dados possam ser codificados nessa
simbologia.
Embora a chave do CF-e-SAT possua 44 digitos, nem todas as míd... | 26,887 |
def vortexforce(uu, vv, duu, dvv, idx2=1.0, idy2=1.0):
""" Add the omega_z component of the vortex force to the momentum
du/dt += omega_z * V
dv/dt -= omega_z * U
where omega_z = ddx(v) - ddy(u)
and (U,V) are the contravariant components of (u,v).
If the grid is orthogonal, they read
U = ... | 26,888 |
def prepare_connection(conn, database, datasette):
"""Modify SQLite connection in some way e.g. register custom SQL functions""" | 26,889 |
def saveCountLists(theoryCountList, realCountList):
"""
Saves the countList to a file for analysis
"""
wFile = open("count.txt", "w")
wFile.write('Predicted:\n')
for c in theoryCountList:
wFile.write(str(c))
wFile.write('\n')
wFile.write('\nActual:\n')
for c i... | 26,890 |
def wrist_mounted_calibration(calibration_data_folder, debug=False):
"""
Parse our config file and run handical.
"""
extrinsics_out_file = os.path.join(calibration_data_folder,
'extrinsics.txt')
config_filename = os.path.join(calibration_data_folder, 'robot_d... | 26,891 |
def debug(func):
"""Only for debugging purposes: prints a tree
It will print a nice execution tree with arguments and results
of all decorated functions.
"""
if not SYMPY_DEBUG:
#normal mode - do nothing
return func
#debug mode
def decorated(*args, **kwargs):
#r = f... | 26,892 |
def get_s3_keys(bucket):
"""Get a list of keys in an S3 bucket."""
keys = []
resp = s3.list_objects(Bucket=bucket)
for obj in resp['Contents']:
keys.append(obj['Key'])
return keys | 26,893 |
def plot_maxmin_points(lon, lat, data, extrema, nsize, symbol, color='k',
plotValue=True, transform=None):
"""
This function will find and plot relative maximum and minimum for a 2D grid. The function
can be used to plot an H for maximum values (e.g., High pressure) and an L for minim... | 26,894 |
def _get_results(model):
"""
Helper function to get the results from the solved model instances
"""
_invest = {}
results = solph.processing.convert_keys_to_strings(model.results())
for i in ["wind", "gas", "storage"]:
_invest[i] = results[(i, "electricity")]["scalars"]["invest"]
retu... | 26,895 |
def _get_vlan_list():
""" Aggregate vlan data.
Args:
Returns:
Tree of switches and vlan information by port
"""
log = logger.getlogger()
vlan_list = Tree()
for ntmpl_ind in CFG.yield_ntmpl_ind():
ntmpl_ifcs = CFG.get_ntmpl_ifcs_all(ntmpl_ind)
for ifc in ntmpl_ifcs:
... | 26,896 |
def subtract_overscan(ccd, overscan=None, overscan_axis=1, fits_section=None,
median=False, model=None):
"""
Subtract the overscan region from an image.
Parameters
----------
ccd : `~astropy.nddata.CCDData`
Data to have overscan frame corrected.
overscan : `~astro... | 26,897 |
def read_raw(omega):
"""Read the raw temperature, humidity and dewpoint values from an OMEGA iServer.
Parameters
----------
omega : :class:`msl.equipment.record_types.EquipmentRecord`
The Equipment Record of an OMEGA iServer.
Returns
-------
:class:`str`
The serial number o... | 26,898 |
def test_login_logout(client):
"""Make sure logging in and logging out works"""
rv = register_and_login(client, 'user1', 'default')
assert b'You were logged in' in rv.data
rv = logout(client)
assert b'You were logged out' in rv.data
rv = login(client, 'user1', 'wrongpassword')
assert b'Inval... | 26,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.