content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _GetDatabaseLookupFunction(filename, flaps, omega_hat, thrust_coeff):
"""Produces a lookup function from an aero database file."""
db = load_database.AeroDatabase(filename)
def _Lookup(alpha, beta, dflaps=None, domega=None):
if dflaps is None:
dflaps = np.zeros((system_types.kNumFlaps,))
if dome... | 5,343,800 |
def parse_copy_core_dump(raw_result):
"""
Parse the 'parse_copy_core_dump' command raw output.
:param str raw_result: copy core-dump raw result string.
:rtype: dict
:return: The parsed result of the copy core-dump to server:
::
{
0:{
'status': 'success'
... | 5,343,801 |
def _handle_requirements(hass, component, name):
"""Install the requirements for a component."""
if hass.config.skip_pip or not hasattr(component, 'REQUIREMENTS'):
return True
for req in component.REQUIREMENTS:
if not pkg_util.install_package(req, target=hass.config.path('lib')):
... | 5,343,802 |
def info_fits(fitsfilename, **kwargs):
"""
Print the information about a fits file.
Parameters
----------
fitsfilename : str
Path to the fits file.
**kwargs: optional
Optional arguments to the astropy.io.fits.open() function. E.g.
"output_verify" can be set to ignore, i... | 5,343,803 |
def ticket_id_url(workspace, number):
"""
The url for a specific ticket in a specific workspace
:param workspace: The workspace
:param number: The number of the ticket
:return: The url to fetch that specific ticket
"""
return basic_url + ' spaces/' + workspace + '/tickets/' + number + '.json... | 5,343,804 |
def get_cifar10(data_path):
"""Returns cifar10 dataset.
Args:
data_path: dataset location.
Returns:
tuple (training instances, training labels,
testing instances, testing labels)
Instances of dimension # of instances X dimension.
"""
x_train = np.zeros((50000, 3072))
y_train = np.z... | 5,343,805 |
def compute_lifting_parameter(lamb, lambda_plane_idxs, lambda_offset_idxs, cutoff):
"""One way to compute a per-particle "4D" offset in terms of an adjustable lamb and
constant per-particle parameters.
Notes
-----
(ytz): this initializes the 4th dimension to a fixed plane adjust by an offset
fo... | 5,343,806 |
def create_controller():
"""
1. Check the token
2. Call the worker method
"""
minimum_buffer_min = 3
if views.ds_token_ok(minimum_buffer_min):
# 2. Call the worker method
# More data validation would be a good idea here
# Strip anything other than characters listed
... | 5,343,807 |
def reproduce_load_profile(neural_model, simulation_model: CHPP_HWT, input_data, logger):
"""
Tries to follow a real load profile
"""
# make sure the random seeds are different in each process
#np.random.seed(int.from_bytes(os.urandom(4), byteorder='little'))
temperature, powers, heat_demand = ... | 5,343,808 |
def session_pca(imgs, mask_img, parameters,
n_components=20,
confounds=None,
memory_level=0,
memory=Memory(cachedir=None),
verbose=0,
copy=True):
"""Filter, mask and compute PCA on Niimg-like objects
This is an help... | 5,343,809 |
def numpy_napoleon(prnt_doc, child_doc):
"""Behaves identically to the 'numpy' style, but abides by the docstring sections
specified by the "Napoleon" standard.
For more info regarding the Napoleon standard, see:
http://sphinxcontrib-napoleon.readthedocs.io/en/latest/index.html#docstring-sections
... | 5,343,810 |
def search_unique_identities_slice(db, term, offset, limit):
"""Look for unique identities using slicing.
This function returns those unique identities which match with the
given `term`. The term will be compared with name, email, username
and source values of each identity. When an empty term is given... | 5,343,811 |
def get_change_description(req_sheet, row_num):
""" Accessor for Change Description
Args:
req_sheet: A variable holding an Excel Workbook sheet in memory.
row_num: A variable holding the row # of the data being accessed.
Returns:
A string value of the Change Description
"""
... | 5,343,812 |
def reduce_pca(data_df, n_components=None):
"""
Uses PCA to reduce dimension.
Parameters:
data_df (DataFrame): The input data in DataFrame format
n_components (float): The number of components or to reduce to. If the number if between 0 and 1, n_components is the % of
th... | 5,343,813 |
def get_rule_set_map_file(cntlr, map_name, mode='r'):
"""Get the location of the rule set map
The rule set map will be in the application data folder for the xule plugin. An initial copy is in the
plugin folder for xule. If the map is not found in the application data folder, the initial copy is copied... | 5,343,814 |
def create_disjoint_intervals(draw,
dtype,
n_intervals=10,
dt=1,
time_range=(0, 100),
channel_range=(2000, 2119),
length_range=(1, 1), ):
... | 5,343,815 |
def get_deleted_resources():
"""Get a list of resources that failed to be deleted in OVN.
Get a list of resources that have been deleted from neutron but not
in OVN. Once a resource is deleted in Neutron the ``standard_attr_id``
foreign key in the ovn_revision_numbers table will be set to NULL.
Up... | 5,343,816 |
def load_base_schema(base_schema=None, verbose=False):
"""Load base schema, schema contains base classes for
sub-classing in user schemas.
"""
_base = base_schema or BASE_SCHEMA or []
_base_schema = []
if "schema.org" in _base:
_base_schema.append(
load_schemaorg(verbose=v... | 5,343,817 |
def file_based_convert_examples_for_bilinear(examples,
max_seq_length,
tokenizer,
output_file,
do_copa=False):
"""Convert a set of `InputE... | 5,343,818 |
def ShowX86UserStack(thread, user_lib_info = None):
""" Display user space stack frame and pc addresses.
params:
thread: obj referencing thread value
returns:
Nothing
"""
iss = Cast(thread.machine.iss, 'x86_saved_state_t *')
abi = int(iss.flavor)
user_ip = 0
... | 5,343,819 |
def endgame_score_connectfour(board, is_current_player_maximizer) :
"""Given an endgame board, returns 1000 if the maximizer has won,
-1000 if the minimizer has won, or 0 in case of a tie."""
chains_1 = board.get_all_chains(current_player=is_current_player_maximizer)
chains_2 = board.get_all_chains(curr... | 5,343,820 |
def identify(path_or_file):
"""
Accepts a single file or list of files, Returns a list of Image file names
:param path_or_file:
:return: list of Image file names
"""
files = []
# Included capitalized formats
supported_formats = set(
IMAGE_FORMATS[0] + tuple(map(lambda x: x.uppe... | 5,343,821 |
def add_colorbar(im, aspect=20, pad_fraction=0.5, **kwargs):
"""Add a vertical color bar to an image plot.
Taken from https://stackoverflow.com/questions/18195758/set-matplotlib-colorbar-size-to-match-graph
"""
divider = axes_grid1.make_axes_locatable(im.axes)
width = axes_grid1.axes_size.AxesY(im.ax... | 5,343,822 |
async def stream_capture(samplerate, channels, device, buffersize, dtype='float32'):
"""Generator that yields blocks of input data
captured from sounddevice InputStream into NumPy arrays.
The audio callback pushes the captured data to `in_queue`,
and at the same time is consumed the queue and yields t... | 5,343,823 |
def test_create_with_kargs():
"""Test create passing named arguments"""
name = helper.user.name()
user_key = helper.user.key()
user_id = user_key.public_key
status = rbac.user.new(
signer_user_id=user_id, signer_keypair=user_key, user_id=user_id, name=name
)
assert len(status) == 1
... | 5,343,824 |
def wait_procs(procs, timeout, callback=None):
"""Convenience function which waits for a list of processes to
terminate.
Return a (gone, alive) tuple indicating which processes
are gone and which ones are still alive.
The gone ones will have a new 'retcode' attribute indicating
process exit st... | 5,343,825 |
def select(sel, truecase, falsecase):
""" Multiplexer returning falsecase for select==0, otherwise truecase.
:param WireVector sel: used as the select input to the multiplexer
:param WireVector falsecase: the WireVector selected if select==0
:param WireVector truecase: the WireVector selected if select... | 5,343,826 |
def fish_collision(sprite1, sprite2):
"""Algorithm for determining if there is a collision between the sprites."""
if sprite1 == sprite2:
return False
else:
return collide_circle(sprite1, sprite2) | 5,343,827 |
def normalizePeriodList(periods):
"""
Normalize the list of periods by merging overlapping or consecutive ranges
and sorting the list by each periods start.
@param list: a list of tuples of L{Period}. The list is changed in place.
"""
# First sort the list
def sortPeriods(p1, p2):
"... | 5,343,828 |
def assemble(the_type: Callable[..., TypeT],
profile: Optional[str] = None,
**kwargs: Any) -> TypeT:
"""Create an instance of a certain type,
using constructor injection if needed."""
ready_result = _create(the_type, profile)
if ready_result is not None:
return ready_r... | 5,343,829 |
def validate_ip_ranges(*ip_addresses_ranges) -> None:
"""
IP addresses range validation.
Args:
ip_addresses_ranges (list): List of IP addresses ranges to validate.
Returns:
None
"""
for ip_range in ip_addresses_ranges:
if ip_range:
ip_interval = ip_range.s... | 5,343,830 |
def test_attn_lstm_embedding():
"""Test invoking AttnLSTMEmbedding."""
max_depth = 5
n_test = 5
n_support = 11
n_feat = 10
test = np.random.rand(n_test, n_feat).astype(np.float32)
support = np.random.rand(n_support, n_feat).astype(np.float32)
layer = layers.AttnLSTMEmbedding(n_test, n_support, n_feat, m... | 5,343,831 |
def coord_ijk_to_xyz(affine, coords):
"""
Converts voxel `coords` in cartesian space to `affine` space
Parameters
----------
affine : (4, 4) array-like
Affine matrix
coords : (N,) list of list
Image coordinate values, where each entry is a length three list of int
denoti... | 5,343,832 |
def _get_create_statement(server, temp_datadir,
frm_file, version,
options, quiet=False):
"""Get the CREATE statement for the .frm file
This method attempts to read the CREATE statement by copying the .frm file,
altering the storage engine in the .frm fil... | 5,343,833 |
def delete_driver_vehicle(driver):
"""delete driver"""
try:
driver.vehicle = None
driver.save()
return driver, "success"
except Exception as err:
logger.error("deleteVehicleForDriverRecord@error")
logger.error(err)
return None, str(err) | 5,343,834 |
def passivity(s: npy.ndarray) -> npy.ndarray:
"""
Passivity metric for a multi-port network.
A metric which is proportional to the amount of power lost in a
multiport network, depending on the excitation port. Specifically,
this returns a matrix who's diagonals are equal to the total
power rece... | 5,343,835 |
def sample_distance(sampleA, sampleB, sigma):
"""
I know this isn't the best distance measure, alright.
"""
# RBF!
gamma = 1 / (2 * sigma**2)
similarity = np.exp(-gamma*(np.linalg.norm(sampleA - sampleB)**2))
distance = 1 - similarity
return distance | 5,343,836 |
def test_electronic_type(fixture_code, generate_structure):
"""Test ``PwBandsWorkChain.get_builder_from_protocol`` with ``electronic_type`` keyword."""
code = fixture_code('quantumespresso.pw')
structure = generate_structure()
with pytest.raises(NotImplementedError):
for electronic_type in [Ele... | 5,343,837 |
def replace_non_unique(
in_filename, out_filename, search_string="text_to_replace", prefix=""
):
"""parse the document 'in_filename' and replace all
instances of the string 'search_string' with the
unique string 'prefix_x'.
Parameters
----------
in_filename : name of the file to parse
... | 5,343,838 |
def copy_slice(src, dst, iproc, parameter):
"""
Copies SPECFEM model slice
:type src: str
:param src: source location to copy slice from
:type dst: str
:param dst: destination location to copy slice to
:type parameter: str
:param parameter: parameters to copy, e.g. 'vs', 'vp'
:type... | 5,343,839 |
def read_sequence_item(fp, is_implicit_VR, is_little_endian, encoding,
offset=0):
"""Read and return a single sequence item, i.e. a Dataset"""
seq_item_tell = fp.tell() + offset
if is_little_endian:
tag_length_format = "<HHL"
else:
tag_length_format = ">HHL"
tr... | 5,343,840 |
def check_setup():
"""Check the global parameters."""
global MESHIFY_USERNAME, MESHIFY_PASSWORD, MESHIFY_AUTH, MESHIFY_BASE_URL
if not MESHIFY_USERNAME or not MESHIFY_PASSWORD:
print("Simplify the usage by setting the meshify username and password as environment variables MESHIFY_USERNAME and MESHIF... | 5,343,841 |
def main():
"""
Run the script.
""" | 5,343,842 |
def get_filters(query_metadata: QueryMetadataTable) -> Dict[VertexPath, Set[FilterInfo]]:
"""Get the filters at each VertexPath."""
filters: Dict[VertexPath, Set[FilterInfo]] = {}
for location, _ in query_metadata.registered_locations:
filter_infos = query_metadata.get_filter_infos(location)
... | 5,343,843 |
def get_shuffled_matrix(pssm_mat, iterations, return_dict, ShufflingType):
"""
The functuion generate massive of shuffled matrix.
Parameters
----------
pssm_mat : pandas DataFrame
PSSM profile.
iterations : int
Number of iterations of shuffling.
return_dict : dict
Ma... | 5,343,844 |
def auxiliary_equations(*, F, T_degC, I_sc_A_0, I_rs_1_A_0, n_1_0, I_rs_2_0_A, n_2_0, R_s_Ohm_0, G_p_S_0, E_g_eV_0, N_s,
T_degC_0=T_degC_stc):
"""
Computes the auxiliary equations at F and T_degC for the 8-parameter DDM-G.
Inputs (any broadcast-compatible combination of scalars and ... | 5,343,845 |
def detector(name_file: str, chk_video_det, xy_coord: list, frame_zoom: int, size_detect: int,
lab_o_proc, window, frame_shift, play_speed, but_start, but_pause) -> str:
"""Данная функция производит поиск движения в заданной области, в текущем файле.
name_file - Имя файла, который передается в о... | 5,343,846 |
def get_highest_confidence_transcript_for_each_session(
transcripts: List[db_models.Transcript],
) -> List[db_models.Transcript]:
"""
Filter down a list transcript documents to just a single transcript
per session taking the highest confidence transcript document.
Parameters
----------
tran... | 5,343,847 |
def load_precip_legacy(data, valid, tile_bounds):
"""Compute a Legacy Precip product for dates prior to 1 Jan 2014"""
LOG.debug("called")
ts = 12 * 24 # 5 minute
midnight, tomorrow = get_sts_ets_at_localhour(valid, 0)
now = midnight
m5 = np.zeros((ts, *data["solar"].shape), np.float16)
ti... | 5,343,848 |
def get_groups_data():
"""
Get all groups, get all users for each group and sort groups by users
:return:
"""
groups = [group["name"] for group in jira.get_groups(limit=200)["groups"]]
groups_and_users = [get_all_users(group) for group in groups]
groups_and_users = [sort_users_in_group(group... | 5,343,849 |
def get_sep():
"""Returns the appropriate filepath separator char depending on OS and
xonsh options set
"""
if ON_WINDOWS and builtins.__xonsh__.env.get("FORCE_POSIX_PATHS"):
return os.altsep
else:
return os.sep | 5,343,850 |
def hindu_lunar_holiday(l_month, l_day, g_year):
"""Return the list of fixed dates of occurrences of Hindu lunar
month, month, day, day, in Gregorian year, g_year."""
l_year = hindu_lunar_year(
hindu_lunar_from_fixed(gregorian_new_year(g_year)))
date1 = hindu_date_occur(l_month, l_day, l_year)
... | 5,343,851 |
def identify_all_failure_paths(network_df_in,edge_failure_set,flow_dataframe,path_criteria):
"""Identify all paths that contain an edge
Parameters
---------
network_df_in - Pandas DataFrame of network
edge_failure_set - List of string edge ID's
flow_dataframe - Pandas DataFrame of list of edge ... | 5,343,852 |
def wikipedia_wtap_setup():
"""
A commander has 5 tanks, 2 aircraft and 1 sea vessel and is told to
engage 3 targets with values 5,10,20 ...
"""
tanks = ["tank-{}".format(i) for i in range(5)]
aircrafts = ["aircraft-{}".format(i) for i in range(2)]
ships = ["ship-{}".format(i) for i in range... | 5,343,853 |
def allowed_file(filename: str) -> bool:
"""Determines whether filename is allowable
Parameters
----------
filename : str
a filename
Returns
-------
bool
True if allowed
"""
return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS | 5,343,854 |
def share_is_mounted(details):
"""Check if dev/share/etc is mounted, returns bool."""
mounted = False
if PLATFORM == 'Darwin':
# Weak and naive text search
proc = run_program(['mount'], check=False)
for line in proc.stdout.splitlines():
if f'{details["Address"]}/{details["Share"]}' in line:
... | 5,343,855 |
def update_bitweights(realization, asgn, tileids, tg_ids, tg_ids2idx, bitweights):
"""
Update bit weights for assigned science targets
"""
for tileid in tileids:
try: # Find which targets were assigned
adata = asgn.tile_location_target(tileid)
for loc, tgid in adata.items... | 5,343,856 |
def load_from_input_flags(params, params_source, input_flags):
"""Update params dictionary with input flags.
Args:
params: Python dictionary of hyperparameters.
params_source: Python dictionary to record source of hyperparameters.
input_flags: All the flags with non-null value of overridden
hyper... | 5,343,857 |
def find_tiles_reverse(catalog):
"""Lookup the tile name given an RA, DEC pair."""
N = len(tiles.index)
i = 0
catalog['TILENAME'] = "NONE"
catalog['STATUS'] = "new"
for tile in tiles[["URAMIN", "URAMAX", "UDECMIN", "UDECMAX",
"TILENAME"]].itertuples():
pb(i + 1, N... | 5,343,858 |
def hal(_module_patch):
"""Simulated hal module"""
import hal
return hal | 5,343,859 |
def test_load_plugins(use_plugin_file, workflow):
"""
test loading plugins
"""
plugins_files = [inspect.getfile(PushImagePlugin)] if use_plugin_file else []
runner = PluginsRunner(workflow, [], plugin_files=plugins_files)
assert runner.plugin_classes is not None
assert len(runner.plugin_cla... | 5,343,860 |
def train(args):
""" Function used for training any of the architectures, given an input parse.
"""
def validate(epoch):
model.to_test()
disparities = np.zeros((val_n_img, 256, 512), dtype=np.float32)
model.set_new_loss_item(epoch, train=False)
# For a WGAN architecture we... | 5,343,861 |
def test_register_context_decl_cls1(collector, context_decl):
"""Test handling context class issues : failed import no such module.
"""
tb = {}
context_decl.context = 'exopy_pulses.foo:BaseContext'
context_decl.register(collector, tb)
assert 'exopy_pulses.BaseContext' in tb
assert 'import' ... | 5,343,862 |
def elements(all_isotopes=True):
"""
Loads a DataFrame of all elements and isotopes.
Scraped from https://www.webelements.com/
Returns
-------
pandas DataFrame with columns (element, atomic_number, isotope, atomic_weight, percent)
"""
el = pd.read_pickle(pkgrs.resource_filename('latool... | 5,343,863 |
def prefixes(seq):
"""
Generate all prefixes of a sequence.
Examples
========
>>> from sympy.utilities.iterables import prefixes
>>> list(prefixes([1,2,3,4]))
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]]
"""
n = len(seq)
for i in xrange(n):
yield seq[:i+1] | 5,343,864 |
def sample_colors(config, image):
"""
Samples the source and target colors for replacement
"""
for entry in config['palette']:
sample_color(config, image, entry, 'source_color_box', 'source_color')
sample_color(config, image, entry, 'target_color_box', 'target_color') | 5,343,865 |
def datas(draw):
"""TODO expand to include all optional parameters."""
metric = draw(ascii())
filter = draw(filters())
return flow.Data(metric, filter=filter) | 5,343,866 |
def create_steps_sequence(num_steps: Numeric, axis: str) -> typing.List[typing.Tuple[float, str]]:
"""
Returns a list of num_steps tuples: [float, str], with given string parameter, and
the floating-point parameter increasing lineairly from 0 to 1.
Example:
>>> create_steps_sequence(5, 'X')
[(... | 5,343,867 |
def disable_doze_light(ad):
"""Force the device not in doze light mode.
Args:
ad: android device object.
Returns:
True if device is not in doze light mode.
False otherwise.
"""
ad.adb.shell("dumpsys battery reset")
ad.adb.shell("cmd deviceidle disable light")
adb_sh... | 5,343,868 |
def jobs():
""" List all jobs """
return jsonify(job.get_jobs()) | 5,343,869 |
def test_failover(ReplicationGroupId=None, NodeGroupId=None):
"""
Represents the input of a TestFailover operation which test automatic failover on a specified node group (called shard in the console) in a replication group (called cluster in the console).
For more information see:
Also see, Testing Mul... | 5,343,870 |
def get_pipelines():
"""Get pipelines."""
return PIPELINES | 5,343,871 |
def retry_lost_downloader_jobs() -> None:
"""Retry downloader jobs that went too long without being started.
Idea: at some point this function could integrate with the spot
instances to determine if jobs are hanging due to a lack of
instances. A naive time-based implementation like this could end
u... | 5,343,872 |
def tokenize(s):
"""
Tokenize on parenthesis, punctuation, spaces and American units followed by a slash.
We sometimes give American units and metric units for baking recipes. For example:
* 2 tablespoons/30 mililiters milk or cream
* 2 1/2 cups/300 grams all-purpose flour
The recipe d... | 5,343,873 |
def makeColorMatrix(n, bg_color, bg_alpha, ix=None,
fg_color=[228/255.0, 26/255.0, 28/255.0], fg_alpha=1.0):
"""
Construct the RGBA color parameter for a matplotlib plot.
This function is intended to allow for a set of "foreground" points to be
colored according to integer labels (e.g. according to clustering ou... | 5,343,874 |
def closest_pair(points):
"""
最近点対 O(N log N)
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_5_A&lang=ja
:param list of Point points:
:rtype: (float, (Point, Point))
:return: (距離, 点対)
"""
assert len(points) >= 2
def _rec(xsorted):
"""
:param lis... | 5,343,875 |
def updateParamsPTC(lattice, bunch):
"""
Updates Twiss parameters of lattice.
Updates element parameters.
Updates synchronous particle parameters of the bunch.
"""
(betax, betay, alphax, alphay, etax, etapx) =\
ptc_get_twiss_init_()
lattice.betax0 = betax
lattice.betay0 = betay
lattice.alphax0 = alphax
... | 5,343,876 |
def less_equals(l,r):
"""
| Forms constraint :math:`l \leq r`.
:param l: number,
:ref:`scalar object<scalar_ref>` or
:ref:`multidimensional object<multi_ref>`.
:param r: number,
:ref:`scalar object<scalar_ref>` or
:ref:`multidimensional object<m... | 5,343,877 |
def ensureImageMode(tex : Image, mode="RGBA") -> Image:
"""Ensure the passed image is in a given mode. If it is not, convert it.
https://pillow.readthedocs.io/en/stable/handbook/concepts.html#concept-modes
:param Image tex: The image whose mode to check
:param str mode: The mode to ensure and convert t... | 5,343,878 |
def generate_dada_filelist(filename):
""" Generate a list of DADA files from start filename
Args:
filename (str): Path to file. e.g.
/data/dprice/2020-07-23-02:33:07.587_0000000000000000.000000.dada
Returns:
flist (list): A list of all associated files
"""... | 5,343,879 |
def buildWheels(buildDir, requirements):
"""build wheels
:param buildDir: directory to put wheels in (under 'wheelhouse')
:type buildDir: string
:param requirements: name of file holding names of Python packages
:type requirements: string
"""
wheelhouse = os.path.join(buildDir, 'wheelhouse'... | 5,343,880 |
def code2name(code: int) -> str:
""" Convert prefecture code to name """
return __code2name[code] | 5,343,881 |
def newton(backward_differences, max_num_iters, newton_coefficient, ode_fn_vec,
order, step_size, time, tol, unitary, upper):
"""Runs Newton's method to solve the BDF equation."""
initial_guess = tf.reduce_sum(
tf1.where(
tf.range(MAX_ORDER + 1) <= order,
backward_differences[:M... | 5,343,882 |
def mock_handler(
handler: RequestHandler, uri: str = 'https://hub.example.com', method: str = 'GET', **settings: dict
) -> RequestHandler:
"""Instantiate a Handler in a mock application"""
application = Application(
hub=Mock(base_url='/hub/', server=Mock(base_url='/hub/'),),
cookie_secret=o... | 5,343,883 |
def input(channel):
"""
To read the value of a GPIO pin:
:param channel:
:return:
"""
return LOW if random.random() < 0.5 else HIGH | 5,343,884 |
def kml_start(params):
"""Define basic kml
header string"""
kmlstart = '''
<Document>
<name>%s</name>
<open>1</open>
<description>%s</description>
'''
return kmlstart % (params[0], params[1]) | 5,343,885 |
def add_item_to_do_list():
"""
Asks users to keep entering items to add to a new To Do list until they enter the word 'stop'
:return: to do list with new items
"""
### TO COMPLETE ###
return to_do_list | 5,343,886 |
def handle_connect_event():
"""
A new web client established a connection.
"""
LOGGER.info('[%s] connected' % request.remote_addr)
global thread
if thread == None:
thread = SOCKETIO.start_background_task(target=ack)
emit('connected') | 5,343,887 |
def parse(tokens):
"""Currently parse just supports fn, variable and constant definitions."""
context = Context()
context.tokens = tokens
while tokens:
parse_token(context)
if context.stack:
raise CompileError("after parsing, there are still words on the stack!!:\n{0}".format(
... | 5,343,888 |
def fetch_params_check():
"""If is_fetch is ticked, this function checks that all the necessary parameters for the fetch are entered."""
str_error = [] # type:List
if TIME_FIELD == '' or TIME_FIELD is None:
str_error.append("Index time field is not configured.")
if FETCH_INDEX == '' or FETCH_I... | 5,343,889 |
def _create_rpc_callback(label, result_counter):
"""Creates RPC callback function.
Args:
label: The correct label for the predicted example.
result_counter: Counter for the prediction result.
Returns:
The callback function.
"""
def _callback(result_future):
"""Callback fu... | 5,343,890 |
def get_file_iterator(options):
"""
returns a sequence of files
raises IOError if problemmatic
raises ValueError if problemmatic
"""
# -------- BUILD FILE ITERATOR/GENERATOR --------
if options.f is not None:
files = options.f
elif options.l is not None:
try:
... | 5,343,891 |
def entropy_from_CT(SA, CT):
"""
Calculates specific entropy of seawater.
Parameters
----------
SA : array_like
Absolute salinity [g kg :sup:`-1`]
CT : array_like
Conservative Temperature [:math:`^\circ` C (ITS-90)]
Returns
-------
entropy : array_like
... | 5,343,892 |
def checking_log(input_pdb_path: str, output_log_path: str, properties: dict = None, **kwargs) -> int:
"""Create :class:`CheckingLog <model.checking_log.CheckingLog>` class and
execute the :meth:`launch() <model.checking_log.CheckingLog.launch>` method."""
return CheckingLog(input_pdb_path=input_pdb_path,
... | 5,343,893 |
def _repoint_files_json_dir(filename: str, source_folder: str, target_folder: str, working_folder: str) -> Optional[str]:
""" Repoints the DIR entry in the JSON file to the target folder
Arguments:
filename: the file to load and process
source_folder: the source folder to replace with target fol... | 5,343,894 |
def get_registry_by_name(cli_ctx, registry_name, resource_group_name=None):
"""Returns a tuple of Registry object and resource group name.
:param str registry_name: The name of container registry
:param str resource_group_name: The name of resource group
"""
resource_group_name = get_resource_group_... | 5,343,895 |
def plot_karyotype_summary(haploid_coverage,
chromosomes,
chrom_length,
output_dir,
bed_filename,
bed_file_sep=',',
binsize=1000000,
... | 5,343,896 |
def create_percentile_rasters(
raster_path, output_path, units_short, units_long, start_value,
percentile_list, aoi_shape_path):
"""Creates a percentile (quartile) raster based on the raster_dataset. An
attribute table is also constructed for the raster_dataset that
displays the rang... | 5,343,897 |
def probs_to_mu_sigma(probs):
"""Calculate mean and covariance matrix for each channel of probs
tensor of keypoint probabilites [N, C, H, W]
mean calculated on a grid of scale [-1, 1]
Parameters
----------
probs : torch.Tensor
tensor of shape [N, C, H, W] where each channel along axis 1... | 5,343,898 |
def fetch_biomart_genes_mm9():
"""Fetches mm9 genes from Ensembl via biomart."""
return _fetch_genes_biomart(
host='http://may2012.archive.ensembl.org',
gene_name_attr='external_gene_id') | 5,343,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.