content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def snr2Ivar(flux, snr):
"""
Estimate the inverse variance given flux and S/N.
Parameters
----------
flux : scalar or array of float
Flux of the obejct.
snr : scalar or array of float
Signal to noise ratio
"""
return 1.0 / ((flux / snr) ** 2.0) | 5,331,500 |
def revision_to_cashflows(rev, end_date):
"""Converts a revision to a list of cashflows
end_date -- the date from which we want to stop computing
"""
if rev.end_date is not None:
end_date = next_month(rev.end_date)
result = []
for first_of_month in first_of_month_range(rev.start_date, en... | 5,331,501 |
def test_migrate_to_newest(external_archive, tmp_path, filename, nodes):
"""Test migrations from old archives to newest version."""
filepath_archive = get_archive_file(filename, **external_archive)
archive_format = ArchiveFormatSqlZip()
new_archive = tmp_path / 'out.aiida'
archive_format.migrate(f... | 5,331,502 |
def filter_verified_user(path, community_user_dataFrame,verified_user_file,sep = ',',header = None):
"""
根据已经认证的用户文件,过滤到保留社区中的认证用户。
:param path:认证用户文件的保存路径。
:param community_user_dataFrame:社区用户数据框,两列,列名(user_id, community_id)。
:param verified_user_file:认证用户的文件,为CSV文件,格式为(user_id, is_verified, name),... | 5,331,503 |
def calculate(series):
"""
:param series: a list of lists of [[(),()], [(),()]] for every swc tube in the pixel
:return:
"""
# gets every dates tuple in the list
dates = [t for t, v in series]
# define the dates as a set
ds = set(dates[0])
# get the intersection of every other set.
... | 5,331,504 |
def load_dataset(filename: str) -> Tuple[np.ndarray, np.ndarray]:
"""
Load dataset for comparing the Gaussian Naive Bayes and LDA classifiers. File is assumed to be an
ndarray of shape (n_samples, 3) where the first 2 columns represent features and the third column the class
Parameters
----------
... | 5,331,505 |
def intersections():
"""Intersects all surfaces in model. Uses python cmd line, not api."""
sc.doc.Views.Redraw()
layer('INTERSECTIONS')
objs = rs.AllObjects()
rs.SelectObjects(objs)
rs.Command('_Intersect', echo=False)
frac_isect_ids = rs.LastCreatedObjects()
rs.UnselectAllObjects()
... | 5,331,506 |
def readCSV(name,shape = [None], delimiter = ","):
""" Lectura de archivo csv name
Devuelve matriz con los datos y cabecera
"""
data = []
with open(name, 'r') as f:
reader = csv.reader(f,delimiter = delimiter)
for row in reader:
data.append(row[slice(*shape)])
ret... | 5,331,507 |
def build_category(category):
"""Build a single-item list of a YouTube category.
This refers to the Category of a video entry, such as "Film" or "Comedy",
not the atom/gdata element. This does not check if the category provided
is valid.
Keyword arguments:
category: String representing the category.
... | 5,331,508 |
def apply_and_save(base_file, out_filename, apply_function, save_function, *args):
""" apply_and_save does following process.
1. apply function to base_file
2. the 1's result will be saved as out_filename with base_file's directory
Arguments:
base_file {str} -- file name
... | 5,331,509 |
def all(event, context):
""" retrieves all experiment results from redis
params:
- namespace (optional)
- scope (optional, comma-separated list of experiments)
"""
r = _redis()
namespace = event.get('namespace', 'alephbet')
scope = event.get('scope')
if scope:
... | 5,331,510 |
def wait_for_save(filename, timeout=5):
"""Waits for FILENAME to update, waiting up to TIMEOUT seconds.
Returns True if a save was detected, and False otherwise.
"""
modification_time = os.path.getmtime(filename)
start_time = time.time()
while time.time() < start_time + timeout:
if (os.p... | 5,331,511 |
def check_submodule_update(job, position):
"""
Checks to see if certain submodules have been updated and post a comment to the PR if so.
"""
output = get_output_by_position(job, position)
modules = find_in_output(output, "CIVET_CLIENT_SUBMODULE_UPDATES")
if not modules:
return False
... | 5,331,512 |
def display_side_by_side(dfs: list, captions: list):
"""Display tables side by side to save vertical space
Input:
dfs: list of pandas.DataFrame
captions: list of table captions
"""
output = ""
combined = dict(zip(captions, dfs))
for caption, df in combined.items():
output... | 5,331,513 |
def _compute_subseq_errors_direct(series, weights):
"""
Subsequence errors (using one pass formulation)
:param Array{Float64,1} series
:param Array{Float64,1} weights
The subsequence errors is:
$$\begin{align}
E[i,j] &= Q[i,j] - \frac{S[i,j]^2}{W[i,j]}
\end{align}$$
Were W, S, ... | 5,331,514 |
def app_info():
"""
Show app infos (Version & License)
"""
print('\n\n ##### A Python script to read iMessage data #####')
print(' # Created by niftycode #')
print(f' # Version {VERSION} #')
print(' # MIT L... | 5,331,515 |
def concat(infilenames: List[str], outfilename: str) -> None:
"""Concatenates files along the time axis
If files are overlapping, the last one will be used.
Parameters
----------
infilenames: List[str]
filenames to concatenate
outfilename: str
filename
Notes
------
... | 5,331,516 |
def preprocess_dataframe(data):
"""Helper method to preprocess the dataframe.
Creates new columns for year,month,recalls and percentage change.
Limits the date range for the experiment (these data are trustworthy)."""
data['recalls'] = data['doc_count'] + 1
data.drop(columns=['product', 'Unnam... | 5,331,517 |
def is_solution(x:int, y:int) -> bool:
"""Returns try if (x, y) is a solution."""
# x and y are the values in a sequence of 15 terms of the following form:
# xxxxyxxxxxyxxxx
# x must be a positive integer
if x <= 0:
return False
# y must be a negative integer
if y >= 0:
re... | 5,331,518 |
def load_crl(file):
# type: (AnyStr) -> CRL
"""
Load CRL from file.
:param file: Name of file containing CRL in PEM format.
:return: M2Crypto.X509.CRL object.
"""
with BIO.openfile(file) as f:
cptr = m2.x509_crl_read_pem(f.bio_ptr())
return CRL(cptr, 1) | 5,331,519 |
def clean_and_lemmatize(text):
"""
Clean and lemmatize the text of a Tweet
Returns:
cleaned_text (string): The cleaned and lemmatized text.
"""
wnl = WordNetLemmatizer() # NLTK lemmatizer
converted_tweet = clean_and_tokenize(
text) # cleans the text and tokenize it
... | 5,331,520 |
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convolution with padding
Arguments:
in_planes {int} -- Number of channels in the input image
out_planes {int} -- Number of channels produced by the convolution
Keyword Arguments:
stride {int or tuple, option... | 5,331,521 |
def task_finish(request, pk):
"""タスクを完了するAPI
:param request:
:param pk:
:return:
"""
task = get_object_or_404(models.Task, pk=pk)
prev_task = task.get_prev_task()
if prev_task is None or prev_task.can_continue():
task.status = '99'
task.updated_user = request.user
... | 5,331,522 |
def add_runas_options(parser):
"""
Add options for commands which can run tasks as another user
Note that this includes the options from add_runas_prompt_options(). Only one of these
functions should be used.
"""
runas_group = optparse.OptionGroup(parser, "Privilege Escalation Options", "contr... | 5,331,523 |
def test_active_flag_is_working_for_file_lock(filename_for_test):
"""
Проверяем, что атрибут .active проставляется правильно.
"""
assert FileLock(filename_for_test).active == True
assert FileLock(None).active == False | 5,331,524 |
def add_parser(subparsers):
"""Add reduction parser"""
parser = subparsers.add_parser(
'reduce', aliases=['red'], help="""Reduce games""",
description="""Create reduced game files from input game files.""")
parser.add_argument(
'--input', '-i', metavar='<input-file>', default=sys.std... | 5,331,525 |
def write_password_db(filename, password, xml, compress=True):
"""Write a password database file."""
# Encode the data if needed.
if isinstance(xml, bytes):
encoded_data = xml
else:
encoded_data = xml.encode('utf-8')
# Compress the data if requested.
if compress:
compres... | 5,331,526 |
def config(program):
"""
Print the disco master configuration.
"""
for config in program.disco.config:
print("\t".join(config)) | 5,331,527 |
def test_log_missing_file():
""" Tail a single file on a single task """
returncode, stdout, stderr = exec_command(
['dcos', 'task', 'log', 'test-app', 'bogus'])
assert returncode == 1
assert stdout == b''
assert stderr == b'No files exist. Exiting.\n' | 5,331,528 |
def test_status_no_db_access(create_engine_mock):
"""
Tests that status does not try to access the database
"""
try:
from kolibri.utils import cli
cli.status.callback()
except SystemExit:
pass
create_engine_mock.assert_not_called() | 5,331,529 |
async def test_update_failed(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
) -> None:
"""Test data is not destroyed on update failure."""
entry = await init_integration(hass, aioclient_mock)
await async_setup_component(hass, HA_DOMAIN, {})
assert hass.states.get(CLIMATE_ID).state ==... | 5,331,530 |
def init_logging(verbose=False):
"""Set logging format to something more readable."""
level = logging.DEBUG if verbose else logging.WARNING
logging.basicConfig(level=level, format="[%(levelname)s] %(message)s") | 5,331,531 |
def fine_tune():
"""recreates top model architecture/weights and fine tunes with image augmentation and optimizations"""
# reconstruct vgg16 model
model = Sequential()
model.add(ZeroPadding2D((1, 1), input_shape=(3, img_width, img_height)))
model.add(Convolution2D(64, 3, 3, activation='relu', ... | 5,331,532 |
def normalize(a, seqlength=None, rv=None):
"""
Normalize the VSA vector
:param a: input VSA vector
:param seqlength: Optional, for BSC vectors must be set to a valid.
:param rv: Optional random vector, used for splitting ties on binary and ternary VSA vectors.
:return: new VSA vector
"""
... | 5,331,533 |
def load_pickled_coverage(in_fp):
"""
Replace (overwrite) coverage information from the given file handle.
"""
global _t
_t = load(in_fp) | 5,331,534 |
def MACD(df, n_fast, n_slow):
"""Calculate MACD, MACD Signal and MACD difference
:param df: pandas.DataFrame
:param n_fast:
:param n_slow:
:return: pandas.DataFrame
"""
EMAfast = pd.Series(df['Close'].ewm(span=n_fast, min_periods=n_slow).mean())
EMAslow = pd.Series(df['Close'].ewm... | 5,331,535 |
def find_x_chain(board: Board):
"""apply the x-chain logic
- an x-chain has an even number of chained cells
- odd links must be strong links, even links may be weak links (but can also be strong links)
- either the starting or the ending cell has the candidate as its candidate. therefore, all cells whic... | 5,331,536 |
def enable_cors_after_request_hook():
"""This executes after every route. We use it to attach CORS headers when applicable."""
headers = dict(
Origin="*", Methods="GET, POST, PUT, DELETE, OPTIONS",
Headers="Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token, Cache-Control, Last-Event-I... | 5,331,537 |
def ecef2map(xyz, spatialRef):
""" transform 3D cartesian Earth Centered Earth fixed coordinates, to
map coordinates (that is 2D) in a projection frame
Parameters
----------
xyz : np.array, size=(m,3), float
np.array with 3D coordinates, in WGS84. In the following form:
[[x, y, z], ... | 5,331,538 |
def dis2speed(t, dis):
"""
Return speed in distance travelled per hour.
Args:
t (datetime64[ms]): 1D array with time.
dis (float ): 1D array with distance travelled.
Returns:
float: 1D array with speed data.
"""
# divide by one hour (=3600 x 1... | 5,331,539 |
def default_context(plugin, context):
"""
Return the default context for plugins rendered with a template, which
simply is a single variable named ``plugin`` containing the plugin
instance.
"""
return {"plugin": plugin} | 5,331,540 |
def compare_times(G_lst: list, n: int = 100):
"""
Takes graph and sampling time n, and compute dijkstra for all nodes to all nodes n times
returns avg time per iter
"""
def compare_times_(func):
print(" Running {} ".format(func.__name__).center(100, "-"))
start_time = time.time()
... | 5,331,541 |
def get_model_from_key(model_name):
"""
Gets the model from a given key.
param:
model_name: name of model
return:
object
"""
_known_models = {}
#populate
for klass in Model.__subclasses__():
_known_models[klass.__name__] = klass
for sub in klass._... | 5,331,542 |
def main():
"""
The main function which gets called when this module is ran as a script.
This main function will set some example values and then it will run the model on the example.
Subsequently the results are plotted in a figure.
:return:
"""
forward = 0.01100343969
displacem... | 5,331,543 |
def default_fields(
coll_id=None, type_id=None, entity_id=None,
width=12, **kwargs):
"""
Returns a function that accepts a field width and returns a dictionary of entity values
for testing. The goal is to isolate default entity value settings from the test cases.
"""
def_label = kwar... | 5,331,544 |
def test(edm, runtime, toolkit, environment):
""" Run the test suite in a given environment with the specified toolkit.
"""
parameters = get_parameters(edm, runtime, toolkit, environment)
environ = environment_vars.get(toolkit, {}).copy()
environ["PYTHONUNBUFFERED"] = "1"
commands = [
(... | 5,331,545 |
def test_invalid_logout_not_logged_in(test_client):
"""
GIVEN a Flask application configured for testing
WHEN the '/users/logout' page is requested (GET) when the user is not logged in
THEN check that the user is redirected to the login page
"""
test_client.get('/users/logout', follow_redirects=... | 5,331,546 |
def predict_using_broadcasts(feature1, feature2, feature3, feature4):
"""
Scale the feature values and use the model to predict
:return: 1 if normal, -1 if abnormal 0 if something went wrong
"""
prediction = 0
x_test = [[feature1, feature2, feature3, feature4]]
try:
x_test = SCL.val... | 5,331,547 |
def make_positions(tensor, padding_idx, left_pad):
"""Replace non-padding symbols with their position numbers.
Position numbers begin at padding_idx+1.
Padding symbols are ignored, but it is necessary to specify whether padding
is added on the left side (left_pad=True) or right side (left_pad=False).
... | 5,331,548 |
def teq(state, *column_values):
"""Tag-Equals filter. Expects, that a first row contains tags and/or metadata
Tag row is ignored in comparison, but prepended to the result (in order to maintain the first row in the results).
Accepts one or more column-value pairs. Keep only rows where value in the column eq... | 5,331,549 |
def set_glb(name: str, value: Union[List[Any], Callable]):
"""
Sets the value of the provided option to the provided value without any
further checks.
:param name: Name of the option.
:param value: Value for the option
"""
global_options[name] = value | 5,331,550 |
def music(amusic=None, load=True, play=True, stop=False, loop=1):
"""For loading and playing music.
::Example::
music('bla.ogg', load=True, play=True)
music(stop=True)
"""
# perhaps the mixer is not included or initialised.
if pygame.mixer and pygame.mixer.get_init():
if load an... | 5,331,551 |
def adjust_labels(data_y, dataset, pred_type='actions'):
"""
Transforms original labels into the range [0, nb_labels-1]
:param data_y: numpy integer array
Sensor labels
:param pred_type: string, ['gestures', 'locomotion', 'actions', 'tasks']
Type of activities to be recognized
:retu... | 5,331,552 |
def test_CollaborationRecords_read(collab_env):
""" Tests if single reading of collab records is self-consistent and
hierarchy-enforcing.
# C1: Check that specified record exists (inherited from create())
# C2: Check that specified record was dynamically created
# C3: Check that specified reco... | 5,331,553 |
def is_str_or_bytes(x):
""" True if x is str or bytes.
This doesn't use rpartial to avoid infinite recursion.
"""
return isinstance(x, (str, bytes, bytearray)) | 5,331,554 |
def test_task_9(base_settings):
"""No. 9 tests collection for Task.
Test File: task-example2.json
"""
filename = base_settings["unittest_data_dir"] / "task-example2.json"
inst = task.Task.parse_file(
filename, content_type="application/json", encoding="utf-8"
)
assert "Task" == inst.... | 5,331,555 |
def _type_convert(new_type, obj):
"""
Convert type of `obj` to `force`.
"""
return new_type(obj) | 5,331,556 |
def create_tokenizer(corpus_file, vocab_size):
"""Create a tokenizer from a corpus file
Args:
corpus_file (Pathlib path): File containng corpus i.e. all unique words for
vocab_size (int): Vocabulary size of the tokenizer
Returns:
hugging_face tokenizer: Byte pair tokenizer used to ... | 5,331,557 |
def test_dim_name_creation():
"""Asserts that creation of unique dimension names works"""
create_names = ParamSpace._unique_dim_names
def check_names(*name_check_pdim):
"""Create the necessary input data for the create_names function, then
perform it and assert equality to the expected valu... | 5,331,558 |
def test_fenced_code_blocks_090():
"""
Test case 090: Simple example with tildes
"""
# Arrange
source_markdown = """~~~
<
>
~~~"""
expected_tokens = [
"[fcode-block(1,1):~:3::::::]",
"[text(2,1):\a<\a<\a\n \a>\a>\a:]",
"[end-fcode-block::3:False]",
]
expe... | 5,331,559 |
def mock_retrocookie(monkeypatch: MonkeyPatch) -> None:
"""Replace retrocookie function by noop."""
monkeypatch.setattr(__main__, "retrocookie", lambda *args, **kwargs: None) | 5,331,560 |
def copy_files(file_list, out_dir, fix_ext=(('.pyc', '.py'),)):
"""
TODO:
:param file_list:
:param out_dir:
:param fix_ext:
:return:
"""
rep_list = replaceext(file_list=file_list, ext=fix_ext)
if not rep_list or not all([osp.exists(x) for x in rep_list]):
raise IOError(rep_l... | 5,331,561 |
def get_readings(tag):
"""Get sensor readings and collate them in a dictionary."""
try:
enable_sensors(tag)
readings = {}
# IR sensor
readings["ir_temp"], readings["ir"] = tag.IRtemperature.read()
# humidity sensor
readings["humidity_temp"], readings["humidity"] =... | 5,331,562 |
def test_find_statement(test_df: pd.DataFrame) -> None:
"""Find a correctly aligned statement amidst wronly aligned statements."""
start, end = labeler.find_statement(
test_df,
"this speaker says something but alignment is correct".split(),
"fi",
size=40,
step=30,
)
... | 5,331,563 |
def digita_gw(request):
"""
Digita GW endpoint implementation
"""
identifier = request.data['DevEUI_uplink']['DevEUI']
apsen = core.models.apartment_sensor_models.ApartmentSensor.objects.get_or_create(identifier=identifier)[0]
payload = binascii.unhexlify(request.data['DevEUI_uplink']['payload_h... | 5,331,564 |
def resize_img(_img, maxdims=(1000, 700)):
"""
Resize a given image. Image can be either a Pillow Image, or a NumPy array. Resizing is done automatically such
that the entire image fits inside the given maxdims box, keeping aspect ratio intact
:param _img:
:param maxdims:
:return:
"""
tr... | 5,331,565 |
def natural_key(s):
"""Converts string ``s`` into a tuple that will sort "naturally"
(i.e., ``name5`` will come before ``name10`` and ``1`` will come
before ``A``). This function is designed to be used as the ``key``
argument to sorting functions.
:param s: the str/unicode string to convert.
... | 5,331,566 |
def query_props(path):
"""
Extracts a QueryProps object from a file name.
:param path: Path to a query file
:return: QueryProps of the file
"""
basename = os.path.basename(path)
match = re.match(r'''
(?P<topic>[^-]+?)
(\s*-\s*)
(?P<contributor>[A-Z]+)
(\s*-\s... | 5,331,567 |
def SetDocTimestampFrequency(doc:NexDoc, freq:float):
"""Sets the document timestamp frequency"""
return NexRun("SetDocTimestampFrequency", locals()) | 5,331,568 |
def test_gibbs_energy_data_are_parsed():
"""Test that Gibbs energy data can be parsed"""
result = convert_pop_data(POP_GIBBS_ENERGY)
assert match_sets(result, POP_GIBBS_ENERGY_RESULTS) | 5,331,569 |
def rsqrt(x:np.ndarray):
"""Computes reciprocal of square root of x element-wise.
Args:
x: input tensor
Returns:
output tensor
Examples:
>>> x = np.array([2., 0., -2.])
>>> rsqrt(x)
<tf.Tensor: shape=(3,), dtype=float32,
numpy=array([0.707, inf, nan], dtyp... | 5,331,570 |
def test_split_pane_session(capsys):
"""
Test a session with a single window, with a split pane
"""
window_data = [
{
"identity": "window",
"number": 0,
"title": "window",
"postfix": "~-",
"dir": DEFAULT_DIRECTORY,
"layout"... | 5,331,571 |
def test_get_payoff_settings():
"""Test the setup of payoff distributions."""
payoff_settings = get_payoff_settings(0.1)
assert payoff_settings.ndim == 2
assert payoff_settings.shape[-1] == 8
assert payoff_settings.shape[0] >= 1
for probability in payoff_settings[0, [2, 3, 6, 7]]:
assert... | 5,331,572 |
def is_card(obj):
"""Return true if the object is a card."""
return obj in CARDS_SET | 5,331,573 |
def plot_lines(
y: tuple,
x: np.ndarray = None,
points: bool = True,
x_axis_label: str = 'Index',
y_axis_label: str = 'Value',
plot_width: int = 1000,
plot_height: int = 500,
color: tuple = None,
legend: tuple = None,
title: str = 'Graph li... | 5,331,574 |
def obtain_csrf(session):
"""
Obtain the CSRF token from the login page.
"""
resp = session.get(FLOW_LOGIN_GET_URL)
contents = str(resp.content)
match = re.search(r'csrfToken" value="([a-z0-9\-]+)"', contents)
return match.group(1) | 5,331,575 |
def get_distance_curve(
kernel,
lambda_values,
N,
M=None,
):
""" Given number of elements per class, full kernel (with first N rows corr.
to mixture and the last M rows corr. to component, and set of lambda values
compute $\hat d(\lambda)$ for those values of lambda"""
d... | 5,331,576 |
def _print_activations(module, activation_input, activation_output):
"""A forward hook to be called whenever a module finishes computing an
output. Apply to a module using
module.register_forward_hook(_print_activations)
Prints the size, mean and standard deviation of the output activ... | 5,331,577 |
def test_Image_dt_source_constant(dt_source, xy, expected, tol=0.001):
"""Test getting constant dT values for a single date at a real point"""
m = default_image_obj(dt_source=dt_source)
output = utils.point_image_value(ee.Image(m.dt), xy)
assert abs(output['dt'] - expected) <= tol | 5,331,578 |
def wait_for_interrupts(threaded=False, epoll_timeout=1):
"""
This is the main blocking loop which, while active, will listen for interrupts and start your custom callbacks.
At some point in your script you need to start this to receive interrupt callbacks.
This blocking method is perfectly suited as “t... | 5,331,579 |
def _process_labels(labels, label_smoothing):
"""Pre-process a binary label tensor, maybe applying smoothing.
Parameters
----------
labels : tensor-like
Tensor of 0's and 1's.
label_smoothing : float or None
Float in [0, 1]. When 0, no smoothing occurs. When positive, the binary
... | 5,331,580 |
def guess_digit(image, avgs):
"""Return the digit whose average darkness in the training data is
closest to the darkness of ``image``. Note that ``avgs`` is
assumed to be a defaultdict whose keys are 0...9, and whose values
are the corresponding average darknesses across the training data.... | 5,331,581 |
def multiple_writes(self,
Y_splits,
Z_splits,
X_splits,
out_dir,
mem,
filename_prefix="bigbrain",
extension="nii",
nThreads=1,
... | 5,331,582 |
def new_parameter_value(data, parameter_key: str):
"""Return the new parameter value and if necessary, remove any obsolete multiple choice values."""
new_value = dict(bottle.request.json)[parameter_key]
source_parameter = data.datamodel["sources"][data.source["type"]]["parameters"][parameter_key]
if sou... | 5,331,583 |
def rotate_to_base_frame(
pybullet_client: bullet_client.BulletClient,
urdf_id: int,
vector: Sequence[float],
init_orientation_inv_quat: Optional[Sequence[float]] = (0, 0, 0, 1)
) -> np.ndarray:
"""Rotates the input vector to the base coordinate systems.
Note: This is different from world frame to ... | 5,331,584 |
def show_page_map(label):
"""Renders the base page map code."""
return render('page_map.html', {
'map_label': label.replace('_', ' '),
}) | 5,331,585 |
def create_clf_unicycle_position_controller(linear_velocity_gain=0.8, angular_velocity_gain=3):
"""Creates a unicycle model pose controller. Drives the unicycle model to a given position
and orientation. (($u: \mathbf{R}^{3 \times N} \times \mathbf{R}^{2 \times N} \to \mathbf{R}^{2 \times N}$)
linear_velo... | 5,331,586 |
def cluster_pipeline(gff3_file, strand, verbose):
"""
here clusters of sequences from the same locus are prepared
"""
cat = CAT % gff3_file
btsort1 = BEDTOOLS_SORT
if strand:
btmerge1 = BEDTOOLS_MERGE_ST
sys.stdout.write("###CLUSTERING IN\033[32m STRANDED MODE\033[0m###\n")
... | 5,331,587 |
def stft_reassign_from_sig(sig_wf: np.ndarray,
frequency_sample_rate_hz: float,
band_order_Nth: float) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray,
np.ndarray]:
"""
Librosa ST... | 5,331,588 |
def download(*urls, zip: str=None, unzip: bool=False, **kwargs) -> List[File]:
"""
Download multiple zippyshare urls
Parameters
-----------
*urls
Zippyshare urls.
zip: :class:`str`
Zip all downloaded files once finished.
Zip filename will be taken from ``zip`` parameter,... | 5,331,589 |
def pop_arg(args_list, expected_size_after=0, msg="Missing argument"):
"""helper function to get and check command line arguments"""
try:
value = args_list.pop(0)
except IndexError:
raise BadCommandUsage(msg)
if expected_size_after is not None and len(args_list) > expected_size_after:
... | 5,331,590 |
def main():
"""Make a jazz noise here"""
args = get_args()
cdhit_file = args.cdhit
protein_file = args.proteins
outfile = args.outfile
#print('boo')
# if cdhit_file == '' or protein_file == '':
# die('usage: find_unclustered.py [-h] -c str -p str [-o str]\nfind_unclustered.py: erro... | 5,331,591 |
def d4s(data):
"""
Beam parameter calculation according to the ISO standard D4sigma integrals
input: 2D array of intensity values (pixels)
output:
xx, yy: x and y centres
dx, dy: 4 sigma widths for x and y
angle: inferred rotation angle, radians
"""
gg = data
dimy, dimx = np.sha... | 5,331,592 |
def write_files_human_readable(json_object, input_path, path_to_save, use_time):
"""Save the list of directories that match the old_rollup criteria to a human readable file."""
todays_date_formatted = todays_date.strftime("%Y-%m-%d-%H-%M-%S")
if os.path.exists(path_to_save):
dir_path = os.path.join... | 5,331,593 |
def checkWarnings(func, func_args=[], func_kwargs={},
category=UserWarning,
nwarnings=1, message=None, known_warning=None):
"""Function to check expected warnings."""
if (not isinstance(category, list) or len(category) == 1) and nwarnings > 1:
if isinstance(category,... | 5,331,594 |
def test_title(title, expected_title):
"""Test that title is properly parsed.
1. Create a field parser for dictionary with specific title.
2. Parse a title.
3. Check the parsed title.
"""
actual_title = FieldParser(data={"title": title}).parse_title()
assert actual_title == expected_title, ... | 5,331,595 |
def add_name_slug(apps, schema_editor):
"""Correctly name_slug for every Interface with slash in the name."""
Interface = apps.get_model("nsot", "Interface")
for i in Interface.objects.iterator():
name_slug = slugify_interface(device_hostname=i.device_hostname, name=i.name)
i.name_slug = nam... | 5,331,596 |
def extract_times(imas_version=omas_rcparams['default_imas_version']):
"""
return list of strings with .time across all structures
:param imas_version: imas version
:return: list with times
"""
from omas.omas_utils import list_structures
from omas.omas_utils import load_structure
time... | 5,331,597 |
async def sl_setup(hass):
"""Set up the shopping list."""
assert await async_setup_component(hass, "shopping_list", {})
await sl_intent.async_setup_intents(hass) | 5,331,598 |
def test_eval_schedule_cron(schedule):
"""
Tests eval if the schedule is defined with cron expression
"""
schedule.opts.update({"pillar": {"schedule": {}}})
schedule.opts.update(
{"schedule": {"testjob": {"function": "test.true", "cron": "* * * * *"}}}
)
now = datetime.datetime.now()... | 5,331,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.