content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def greyscale(state):
"""
Preprocess state (210, 160, 3) image into
a (80, 80, 1) image in grey scale
"""
state = np.reshape(state, [210, 160, 3]).astype(np.float32)
# grey scale
state = state[:, :, 0] * 0.299 + state[:, :, 1] * 0.587 + state[:, :, 2] * 0.114
# karpathy
state = sta... | 5,352,500 |
def main(
cl,
re,
ma,
n_ca,
n_th,
gen=100,
tolx=1e-8,
tolf=1e-8,
fix_te=True,
t_te_min=0.0,
t_c_min=0.01,
r_le_min=0.05,
A_cs_min=None,
A_bins_min=None,
Cm_max=None,
strategy="rand-to-best/1/exp/random",
f=None,
cr=None,
adaptivity=2,
repr_... | 5,352,501 |
def test_generate_notification_payload(mocker, mocker2):
"""Test generate_notification_payload function."""
es.FINAL_DATA = {
"xyz/xyz": {
"notify": "true",
"direct_updates": [{
"ecosystem": "maven",
"name": "io.vertx:vertx-web",
"l... | 5,352,502 |
def get_mnist(data_folder='./', chunk_size=128):
"""Retreives images of mnist digits and corresponding labels
Saves data within a folder called mnist.
Required inputs:
data_folder - path to location where mnist is saved
Optional inputs:
chunk_size - ... | 5,352,503 |
def functional_common_information(dist, rvs=None, crvs=None, rv_mode=None):
"""
Compute the functional common information, F, of `dist`. It is the entropy
of the smallest random variable W such that all the variables in `rvs` are
rendered independent conditioned on W, and W is a function of `rvs`.
... | 5,352,504 |
def kubernetes_client() -> BatchV1Api:
"""
returns a kubernetes client
"""
config.load_config()
return BatchV1Api() | 5,352,505 |
def __test(priority_queue):
"""
Priority-Queue Test.
__test(priority_queue) -> None
@type priority_queue: basepriorityqueue
@param priority_queue: priority-queue instance.
"""
if not isinstance(priority_queue, basepriorityqueue):
raise TypeError("Expected type was P... | 5,352,506 |
def get_replication_set_output(arn: Optional[pulumi.Input[str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetReplicationSetResult]:
"""
Resource type definition for AWS::SSMIncidents::ReplicationSet
:param str arn: The ARN of the ReplicationSet.
... | 5,352,507 |
def adjust_wire_offset(wire):
"""
Adjusts the wire's offset so that the two labels have a
distinct last bit.
:param wire: the wire in question
"""
false_label = get_last_bit(wire.false_label.label)
true_label = get_last_bit(wire.true_label.label)
while false_label == true_l... | 5,352,508 |
def admin_only(func):
"""[TODO summary of func]
args:
[TODO insert arguments]
returns:
[TODO insert returns]
"""
def isadmin(invoker, chatadmins):
adminids = []
for admin in chatadmins:
adminids.append(admin.user.id)
return invoker.id in adminids
... | 5,352,509 |
def create_simple():
"""Create an instance of the `Simple` class."""
return Simple() | 5,352,510 |
def contains_rep_info(line):
"""
Checks does that line contains link to the github repo (pretty simple 'algorithm' at the moment)
:param line: string from aa readme file
:return: true if it has link to the github repository
:type line:string
:rtype: boolean
"""
return True if line.find(... | 5,352,511 |
def GetAtomPairFingerprintAsBitVect(mol):
""" Returns the Atom-pair fingerprint for a molecule as
a SparseBitVect. Note that this doesn't match the standard
definition of atom pairs, which uses counts of the
pairs, not just their presence.
**Arguments**:
- mol: a molecule
**Returns**: a SparseBitVect... | 5,352,512 |
def get_registrations_by_player_id(db_cursor: sqlite3.Cursor, player_id: int) -> list[registration.Registration]:
"""
Get a list of registrations by player id.
:param db_cursor: database object to interact with database
:param player_id: player id
:return: a list of registrations
"""
db_cur... | 5,352,513 |
def main(argv=None, from_checkout=False):
"""Top-level script function to create a new Zope instance."""
if argv is None:
argv = sys.argv
try:
options = parse_args(argv, from_checkout)
except SystemExit as e:
if e.code:
return 2
else:
return 0
... | 5,352,514 |
def process_twitter_outbox():
""" Send Pending Twitter Messages """
msg.process_outbox(contact_method = "TWITTER") | 5,352,515 |
def run_sim(alpha,db,m,DELTA,game,game_constants,i):
"""run a single simulation and save interaction data for each clone"""
rates = (DEATH_RATE,DEATH_RATE/db)
rand = np.random.RandomState()
data = [get_areas_and_fitnesses(tissue,DELTA,game,game_constants)
for tissue in lib.run_simulation... | 5,352,516 |
def IMDB(*args, **kwargs):
""" Defines IMDB datasets.
The labels includes:
- 0 : Negative
- 1 : Positive
Create sentiment analysis dataset: IMDB
Separately returns the training and test dataset
Arguments:
root: Directory where the datasets are saved. Default: "... | 5,352,517 |
def load_multiples(image_file_list: List, method: str='mean', stretch: bool=True, **kwargs) -> ImageLike:
"""Combine multiple image files into one superimposed image.
Parameters
----------
image_file_list : list
A list of the files to be superimposed.
method : {'mean', 'max', 'sum'}
... | 5,352,518 |
def select_seeds(
img: np.ndarray, clust_result: np.ndarray, FN: int = 500,
TN: int = 700, n_clust_object: int = 2
):
"""
Sample seeds from the fluid and retina regions acording to the procedure
described in Rashno et al. 2017
Args:
img (np.ndarray): Image from where to sample the seeds.... | 5,352,519 |
async def test_form(hass):
"""Test we get the form."""
await setup.async_setup_component(hass, "persistent_notification", {})
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == "form"
assert result["errors... | 5,352,520 |
def common(list1, list2):
"""
This function is passed two lists and returns a new list containing
those elements that appear in both of the lists passed in.
"""
common_list = []
temp_list = list1.copy()
temp_list.extend(list2)
temp_list = list(set(temp_list))
temp_list.sort()
for... | 5,352,521 |
def create_combobox(root, values, **kwargs):
"""Creates and Grids A Combobox"""
box = ttk.Combobox(root, values=values, **kwargs)
box.set(values[0])
return box | 5,352,522 |
def configure_logging_console(logger_type):
"""
Configure logger
:param logger_type: The type to write logger and setup on the modules of App
:return _imoporter_log:
"""
_date_name = datetime.now().strftime('%Y-%m-%dT%H%M')
_importer_logger = logging.getLogger(logger_type)
... | 5,352,523 |
def chi_x2(samples,df):
"""
Compute the central chi-squared statistics for set of chi-squared
distributed samples.
Parameters:
- - - - -
samples : chi-square random variables
df : degrees of freedom
"""
return chi2.pdf(samples,df) | 5,352,524 |
def integrate(
pc2i,
eos,
initial_frac=DEFAULT_INITIAL_FRAC,
rtol=DEFAULT_RTOL,
):
"""integrate the TOV equations with central pressure "pc2i" and equation of state described by energy density "eps/c2" and pressure "p/c2"
expects eos = (logenthalpy, pressurec2, energy_density... | 5,352,525 |
def add_ingress_port_to_security_lists(**kwargs):
"""Checks if the given ingress port already is a security list,
if not it gets added.
Args:
**kwargs: Optional parameters
Keyword Args:
security_lists (list): A list of security_lists.
port (int): The port to check
... | 5,352,526 |
def describe_cluster_instances(stack_name, node_type):
"""Return the cluster instances optionally filtered by tag."""
instances = _describe_cluster_instances(stack_name, filter_by_node_type=str(node_type))
if not instances:
# Support for cluster that do not have aws-parallelcluster-node-type tag
... | 5,352,527 |
def region_root(data_dir):
"""Returns the path of test regions."""
return os.path.join(data_dir, 'regions') | 5,352,528 |
def list_statistics_keys():
"""ListStatistics definition"""
return ["list", "counts"] | 5,352,529 |
def forecast_handler(req, req_body, res, res_body, zip):
"""Handles forecast requests"""
return True | 5,352,530 |
def _configure_output(args):
"""
Configures the output. Loads templates and applies the specified formatter if any.
If none of these configurations are specified, it will return the default output
which is to print each value to standard out.
"""
writer = _get_writer(args)
if args.template:... | 5,352,531 |
def refToMastoidsNP(data, M1, M2):
"""
"""
mastoidsMean = np.mean([M1, M2], axis=0)
mastoidsMean = mastoidsMean.reshape(mastoidsMean.shape[0], 1)
newData = data - mastoidsMean
return newData | 5,352,532 |
def override_kwargs(
kwargs: Dict[str, str],
func: Callable[..., Any],
filter: Callable[..., Any] = lambda _: True,
) -> Dict[str, str]:
"""Override the kwargs of a function given a function to apply and an optional filter.
Parameters
----------
kwargs : Tuple
The function kwargs in... | 5,352,533 |
def prepare_for_revival(bucket, obj_prefix):
"""
Makes a manifest for reviving any deleted objects in the bucket. A deleted
object is one that has a delete marker as its latest version.
:param bucket: The bucket that contains the stanzas.
:param obj_prefix: The prefix of the uploaded stanzas.
:... | 5,352,534 |
def map_to_orf(fastq, index_dir, ht_prefix, mapped_sam,
unmapped_fastq, log_file, run_config):
"""
Align remaining reads to ORF index files using ``hisat2``.
``hisat2 --version`` is also invoked as ``hisat2`` does not log
its own version when it is run.
:param fastq: FASTQ file (inp... | 5,352,535 |
def run_blend_images(
network_pkl1: str,
network_pkl2: str,
seeds: Optional[List[int]] = [700, 701, 702, 703, 704, 705, 706, 707],
outdir: str = "./out_blend",
truncation_psi: float = 0.7,
noise_mode: str = "const",
blending_layers: List[int] = [4, 8, 16, 32, 64, 128, 256],
network_size:... | 5,352,536 |
def make_drive_resource() -> Resource:
"""
Authenticates and returns a google drive resource.
"""
google_oauth_creds = ast.literal_eval(
credstash.getSecret("IA_PIPELINE_GLOBAL_GOOGLE_SHEETS_API_KEY")
)
with open("key.json", "w") as fp:
json.dump(google_oauth_creds, fp)
cre... | 5,352,537 |
def make_subparser(sub, command_name, help, command_func=None, details=None, **kwargs):
"""
Create the "sub-parser" for our command-line parser.
This facilitates having multiple "commands" for a single script,
for example "norm_yaml", "make_rest", etc.
"""
if command_func is None:
comma... | 5,352,538 |
def _get_static_settings():
"""Configuration required for Galaxy static middleware.
Returns dictionary of the settings necessary for a galaxy App
to be wrapped in the static middleware.
This mainly consists of the filesystem locations of url-mapped
static resources.
"""
static_dir = os.pat... | 5,352,539 |
def application():
""" Flask application fixture. """
def _view():
return 'OK', 200
application = Flask('test-application')
application.testing = True
application.add_url_rule('/', 'page', view_func=_view)
return application | 5,352,540 |
def test_emr_container_operator_execute_complete_fail(check_job_status):
"""Assert execute_complete throw AirflowException"""
check_job_status.return_value = JOB_ID
with pytest.raises(AirflowException):
_emr_emr_container_operator_init().execute_complete(
context=None, event={"status": "... | 5,352,541 |
def get_qe_specific_fp_run_inputs(
configure, code_pw, code_wannier90, code_pw2wannier90,
get_repeated_pw_input, get_metadata_singlecore
):
"""
Creates the InSb inputs for the QE fp_run workflow. For the
higher-level workflows (fp_tb, optimize_*), these are passed
in the 'fp_run' namespace.
... | 5,352,542 |
def _get_cohort_representation(cohort, course):
"""
Returns a JSON representation of a cohort.
"""
group_id, partition_id = cohorts.get_group_info_for_cohort(cohort)
assignment_type = cohorts.get_assignment_type(cohort)
return {
'name': cohort.name,
'id': cohort.id,
'user... | 5,352,543 |
def config_string(cfg_dict):
""" Pretty-print cfg_dict with one-line queries """
upper_level = ["queries", "show_attributes", "priority", "gtf", "bed", "prefix", "outdir", "threads", "output_by_query"]
query_level = ["feature", "feature_anchor", "distance", "strand", "relative_location", "filter_attribute", "attri... | 5,352,544 |
def area_km2_per_grid(infra_dataset, df_store):
"""Total area in km2 per assettype per grid, given in geographic coordinates
Arguments:
*infra_dataset* : a shapely object with WGS-84 coordinates
*df_store* : (empty) geopandas dataframe containing coordinates per grid for each grid
R... | 5,352,545 |
def cli_runner(script_info):
"""Create a CLI runner for testing a CLI command.
Scope: module
.. code-block:: python
def test_cmd(cli_runner):
result = cli_runner(mycmd)
assert result.exit_code == 0
"""
from click.testing import CliRunner
def cli_invoke(command... | 5,352,546 |
def sgf_to_gamestate(sgf_string):
"""
Creates a GameState object from the first game in the given collection
"""
# Don't Repeat Yourself; parsing handled by sgf_iter_states
for (gs, move, player) in sgf_iter_states(sgf_string, True):
pass
# gs has been updated in-place to the final s... | 5,352,547 |
def register_email(email: str) -> None:
""" Stores an email in the mailing list. """
emails = load_file("emails")
if email not in emails["emails"]:
emails["emails"].append(email)
dump_file(emails, "emails") | 5,352,548 |
def get_titlebar_text():
"""Return (style, text) tuples for startup."""
return [
("class:title", "Hello World!"),
("class:title", " (Press <Exit> to quit.)"),
] | 5,352,549 |
def main(config_file_name):
"""
:param config_file_name: str, name of the configuration json file
:return:
"""
global push_notifier, settings
# read config file
settings = Settings(config_file_name)
# tell scraper about the settings
scraper.settings_ref = settings
# create not... | 5,352,550 |
def on_message(client, userdata, msg):
"""
callback func
"""
print("got: "+msg.topic+" "+str(msg.payload)+"\n") | 5,352,551 |
def image_fnames_captions(captions_file, images_dir, partition):
"""
Loads annotations file and return lists with each image's path and caption
Arguments:
partition: string
either 'train' or 'val'
Returns:
all_captions: list of strings
list with each image capti... | 5,352,552 |
def build_menu(
buttons: list,
columns: int = 3,
header_button=None,
footer_button=None,
resize_keyboard: bool = True
):
"""Хелпер для удобного построения меню."""
menu = [buttons[i:i + columns] for i in range(0, len(buttons), columns)]
if header_button:
menu.... | 5,352,553 |
def pandas_dataframe_to_unit_arrays(df, column_units=None):
"""Attach units to data in pandas dataframes and return united arrays.
Parameters
----------
df : `pandas.DataFrame`
Data in pandas dataframe.
column_units : dict
Dictionary of units to attach to columns of the dataframe. ... | 5,352,554 |
def is_empty(value: Any) -> bool:
"""
empty means given value is one of none, zero length string, empty list, empty dict
"""
if value is None:
return True
elif isinstance(value, str):
return len(value) == 0
elif isinstance(value, list):
return len(value) == 0
elif isinstance(value, dict):
return len(valu... | 5,352,555 |
def get_worksheets (path, **kwargs):
"""
Gets all available worksheets within a xlsx-file and returns a list
:param path: Path to excel file
:type path: str
:return: Returns a list with all worksheets within the excel-file
:rtype: list
"""
if not os.path.isabs(path):
path =... | 5,352,556 |
def blankScreen(disp, pix):
# pylint: disable=unused-argument
"""A blank screen used to hide any serial console output."""
if disp is None:
return
disp.show(Group()) | 5,352,557 |
def read_caffe_mean(caffe_mean_file):
"""
Reads caffe formatted mean file
:param caffe_mean_file: path to caffe mean file, presumably with 'binaryproto' suffix
:return: mean image, converted from BGR to RGB format
"""
import caffe_parser
import numpy as np
mean_blob = caffe_parser.caffe... | 5,352,558 |
def test_chunked_las_reading_gives_expected_points(las_file_path):
"""
Test chunked LAS reading
"""
with laspy.open(las_file_path) as las_reader:
with laspy.open(las_file_path) as reader:
las = las_reader.read()
check_chunked_reading_is_gives_expected_points(las, reader, ... | 5,352,559 |
def estimate_pauli_sum(pauli_terms,
basis_transform_dict,
program,
variance_bound,
quantum_resource,
commutation_check=True,
symmetrize=True,
rand_samples=16):... | 5,352,560 |
def version(ctx, f):
"""Extract the assets of a local Minecraft version"""
extractor.pack(ctx.obj["v"], ctx.obj["o"], lambda s: print(s) if ctx.obj["d"] else '', f) | 5,352,561 |
def GetQuasiSequenceOrderp(ProteinSequence, maxlag=30, weight=0.1, distancematrix={}):
"""
###############################################################################
Computing quasi-sequence-order descriptors for a given protein.
[1]:Kuo-Chen Chou. Prediction of Protein Subcellar Locations by
... | 5,352,562 |
def check(lst: list, search_element: int) -> bool:
"""Check if the list contains the search_element."""
return any([True for i in lst if i == search_element]) | 5,352,563 |
def step_with_model(rhs, state, dt=.125, n=100):
"""Perform a number of time steps with a model"""
for t in range(n):
qt_dot = rhs(state)
new_qt = state['QT'] + dt * qt_dot['QT']
state = assoc(state, 'QT', new_qt)
yield state | 5,352,564 |
def halfcube(random_start=0,random_end=32,halfwidth0=1,pow=-1):
"""
Produce a halfcube with given dimension and decaying power
:param random_start: decay starting parameter
:param random_end: decay ending parameter
:param halfwidth0: base halfwidth
:param pow: decaying power
:return: A (rand... | 5,352,565 |
def db_connection():
"""Function for connecting, creating and
Returns
-------
"""
db_credentials = read_json('data/sql-connection.json')
conn = pyodbc.connect(
"Driver={};Server={};Database={};uid={};pwd={};".format(
db_credentials.get('driver'),
db_credentials... | 5,352,566 |
def valid_passphrase(module, **kwargs):
"""Tests whether the given passphrase is valid for the specified device.
Return: <boolean> <error>"""
for req in ["device", "passphrase"]:
if req not in kwargs or kwargs[req] is None:
errmsg = "valid_passphrase: {0} is a required parameter".format... | 5,352,567 |
def contract_address(deploy_hash_base16: str, fn_store_id: int) -> bytes:
"""
Should match what the EE does (new_function_address)
//32 bytes for deploy hash + 4 bytes ID
blake2b256( [0;32] ++ [0;4] )
deploy_hash ++ fn_store_id
"""
def hash(data: bytes) -> bytes:
h = blake2... | 5,352,568 |
def security_safety(session):
"""Check for security issues in dependencies."""
# Include all extras here to check all is safe for ci.
session.install(".[dev,lint,tests,security]")
session.run("python", "-m", "safety", "check") | 5,352,569 |
def dump_js_escaped_json(obj, cls=EdxJSONEncoder):
"""
JSON dumps and escapes objects that are safe to be embedded in JavaScript.
Use this for anything but strings (e.g. dicts, tuples, lists, bools, and
numbers). For strings, use js_escaped_string.
The output of this method is also usable as plai... | 5,352,570 |
def test_execution_failure(tmp_path):
"""Test script error."""
script = "ls non-existing-file"
error_msg = "execution failure, see the stdout and stderr files in /"
runner = ScriptRunner(EXE_RUNNER_NAME, script, tmp_path)
with pytest.raises(ScriptExecutionError, match=error_msg):
runner.run... | 5,352,571 |
def scan_repositories(read_repofile_func=_read_repofile):
"""
Scan the repository mapping file and produce RepositoriesMap msg.
See the description of the actor for more details.
"""
# TODO: add filter based on the current arch
# TODO: deprecate the product type and introduce the "channels" ?..... | 5,352,572 |
def RawTuple(num_fields, name_prefix='field'):
"""
Creates a tuple of `num_field` untyped scalars.
"""
assert isinstance(num_fields, int)
assert num_fields >= 0
return NamedTuple(name_prefix, *([np.void] * num_fields)) | 5,352,573 |
def uninitializePlugin(mobject):
""" Unitializes the plug-in. """
mplugin2 = om2.MFnPlugin(mobject, kAuthor, kVersion, kRequiredAPIVersion)
DEREGISTER_LOCATOR_NODE(n_DebugVector.DebugVector, mplugin2)
DEREGISTER_LOCATOR_NODE(n_DebugMatrix.DebugMatrix, mplugin2)
DEREGISTER_LOCATOR_NODE(n_MeshControl... | 5,352,574 |
def test_success_ignore_blank_program_activity_name(database):
""" Testing program activity name validation to ignore blanks if monetary sum is 0 """
op = ObjectClassProgramActivityFactory(row_number=1, beginning_period_of_availa=2016, agency_identifier='test',
main_ac... | 5,352,575 |
def pose2mat(R, p):
""" convert pose to transformation matrix """
p0 = p.ravel()
H = np.block([
[R, p0[:, np.newaxis]],
[np.zeros(3), 1]
])
return H | 5,352,576 |
def _fill_missing_values(df=None):
"""replace missing values with NaN"""
# fills in rows where lake refroze in same season
df['WINTER'].replace(to_replace='"', method='ffill', inplace=True)
# use nan as the missing value
for headr in ['DAYS', 'OPENED', 'CLOSED']:
df[headr].replace(to_replac... | 5,352,577 |
def stop_tracking(
unsafe_password: str = None,
save_to_json: Union[str, Path] = None,
firestore_key_file: str = None,
firestore_collection_name: str = "counts",
verbose: bool = False,
):
"""
Stop tracking user inputs to a streamlit app.
Should be called after `streamlit-analytics.start... | 5,352,578 |
def csi_prelu(data, alpha, axis, out_dtype, q_params, layer_name=""):
"""Quantized activation relu.
Parameters
----------
data : relay.Expr
The quantized input data.
alpha : relay.Expr
The quantized alpha.
out_dtype : str
Specifies the output data type for mixed precisi... | 5,352,579 |
def scale_image(in_fname, out_fname, max_width, max_height):
"""Scales an image with the same aspect ratio centered in an
image box with the given max_width and max_height
if in_fname == out_fname the image can only be scaled down
"""
# local import to avoid testing dependency on PIL:
try:... | 5,352,580 |
def test_crps_ensemble_dim(o, f_prob, dim):
"""Check that crps_ensemble reduces only dim."""
actual = crps_ensemble(o, f_prob, dim=dim)
assert_only_dim_reduced(dim, actual, o) | 5,352,581 |
def json(filename):
"""Returns the parsed contents of the given JSON fixture file."""
content = contents(filename)
return json_.loads(content) | 5,352,582 |
def _parse_assayData(assayData, assay):
"""Parse Rpy2 assayData (Environment object)
assayData: Rpy2 Environment object.
assay: An assay name indicating the data to be loaded.
Return a parsed expression dataframe (Pandas).
"""
pandas2ri.activate()
mat = assayData[assay] # rpy2 expression ... | 5,352,583 |
def method_list():
""" list of available electronic structure methods
"""
return theory.METHOD_LST | 5,352,584 |
def test_init_as_for_groutmaterial():
"""Test that the init_as is working as expected for all materials."""
matnames = ['Grout', 'Ground', 'Pipe']
classes = [GroutMaterial, GroundMaterial, PipeMaterial]
for (matname, class_) in zip(matnames, classes):
predmats = PREDEFINED_MATERIALS[matname]
... | 5,352,585 |
def readReadQualities(fastqfile):
"""
Reads a .fastqfile and calculates a defined readscore
input: fastq file
output: fastq dictionary key = readid; value = qualstr
@type fastqfile: string
@param fastqfile: path to fastq file
@rtype: dictionary
@return: dictionary containin... | 5,352,586 |
def test_check_args_no_rules(base_add, a, b, expected):
"""Tests that check_args does nothing"""
add = check_args(base_add)
assert add(a, b) == expected | 5,352,587 |
async def default_field_resolver(
parent: Optional[Any],
args: Dict[str, Any],
ctx: Optional[Any],
info: "ResolveInfo",
) -> Any:
"""
Default callable to use as resolver for field which doesn't implement a
custom one.
:param parent: default root value or field parent value
:param arg... | 5,352,588 |
def revision_list_to_str(diffs: List[Dict]) -> str:
"""Convert list of diff ids to a comma separated list, prefixed with "D"."""
return ', '.join([diff_to_str(d['id']) for d in diffs]) | 5,352,589 |
def find_clouds(images):
"""
While very basic in principle. I found out that by applying a blue
layer to the reflectance instruments images ibands and mbands; I was
able to see the clouds clearly.
Method:
- Get the blue layer out of the 3D images ibands and mbands
- ... | 5,352,590 |
def get_path_of_latest_file() -> Optional[Path]:
"""Gets the path of the latest produced file that contains weight information"""
path = Path(storage_folder)
latest_file = None
time_stamp_latest = -1
for entry in path.iterdir():
if entry.is_file():
if latest_file == None:
... | 5,352,591 |
def index():
"""
A function than returns the home page when called upon
"""
#get all available news sources
news_sources = get_sources()
#get all news articles available
everything = get_everything()
print(everything)
# title = 'Home - Find all the current news at your convinien... | 5,352,592 |
def xclCopyBO(handle, dstBoHandle, srcBoHandle, size, dst_offset, src_offset):
"""
Copy device buffer contents to another buffer
:param handle: Device handle
:param dstBoHandle: Destination BO handle
:param srcBoHandle: Source BO handle
:param size: Size of data to synchronize
:param dst_off... | 5,352,593 |
def parse_secret_from_literal(literal):
"""Parse a literal string, into a secret dict.
:param literal: String containg a key and a value. (e.g. 'KEY=VALUE')
:returns secret: Dictionary in the format suitable for sending
via http request.
"""
try:
key, value = literal.split("=", 1)
... | 5,352,594 |
def test_run_internal_median_filter_piped_input():
"""
The run_median_filter asserts if the input file doesn't exist.
This is to prevent specifying streams we can't rewind.
"""
check_run_raises(mod.run_internal_median_filter, fasta_tests[5])
with pytest.raises(AssertionError) as e:
mod.r... | 5,352,595 |
def blur(img):
"""
:param img: SimpleImage, the input image
:return: the processed image which is blurred
the function calculate the every position and its neighbors' pixel color and then average then
set it as the new pixel's RGB
"""
sum_red = 0
sum_blue = 0
sum_green = 0
neigh... | 5,352,596 |
def delete_project_api_document_annotations_url(document_id: int, annotation_id: int) -> str:
"""
Delete the annotation of a document.
:param document_id: ID of the document as integer
:param annotation_id: ID of the annotation as integer
:return: URL to delete annotation of a document
"""
... | 5,352,597 |
def initiate_strategy_trader(strategy, strategy_trader):
"""
Do it async into the workers to avoid long blocking of the strategy thread.
"""
with strategy_trader._mutex:
if strategy_trader._initialized != 1:
# only if waiting for initialize
return
strategy_trader... | 5,352,598 |
def subprocess_call_wrapper(lst, stdin=None):
"""Wrapper around the subprocess.call functions."""
print_debug('About to run "%s"' % ' '.join(lst))
try:
ret = subprocess.call(lst, stdin=stdin)
except (OSError, IOError):
ret = 127 # an error code
except IndexError:
ret = 127 ... | 5,352,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.