content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def rgb(data):
""" normalize rgb
data [H, W, C], data type is float32 (0 to 1) or uint8 (0 to 255)
"""
if data.dtype == np.float32:
return (data - 0.5) / 0.5
else:
return (data.astype(np.float32) - 127.0) / 127.0 | 5,311,000 |
def print_group(pair_product_group_list, data):
"""Print the group"""
print('\n---------------------Groups--------------------')
pair_product_group_list = sorted(pair_product_group_list, key = lambda x: x[1])
group_index = -1
for pair_product_group in pair_product_group_list:
if group_index != pair_produ... | 5,311,001 |
def create_base_feed() -> FeedGenerator:
"""Create feed generator and configure feed-level data."""
fg = FeedGenerator()
fg.id(PG_URL)
fg.title("Paul Graham Essays (Audio)")
# fg.author({"name": "App Champ", "email": "app.engine.champ@gmail.com"})
fg.link(
href="https://podcast.app/p... | 5,311,002 |
def putJobMetric(job, timestamp, metricname, value, METRICSTREAM):
"""
Push a single job metric into METRICSTREAM
:param job: JSON job data struture from dynamodb
:param timestamp: Timestamp to use for the metric
:param metricname: Name of the metric
:param value: Value of the metric
:param... | 5,311,003 |
def _split_hdf5_path(path):
"""Return the group and dataset of the path."""
# Make sure the path starts with a leading slash.
if not path.startswith('/'):
raise ValueError(("The HDF5 path '{0:s}' should start with a "
"leading slash '/'.").format(path))
if '//' in path:... | 5,311,004 |
def mission_derivs(s,t,**kwargs):
"""
Returns right-hand side of Kepler ODE; used by Runge-Kutta routines
Inputs
s State vector [[m r(1) r(2) v(1) v(2)]...]
t Time (not used)
Output
deriv Derivatives [[dr(1)/dt dr(2)/dt dv(1)/dt dv(2)/dt]...]
"""
sun_mass = kwa... | 5,311,005 |
def remove_non_whole_numbers(
df: pd.DataFrame, var_name: str
) -> pd.DataFrame:
"""Removes non-whole-number floats. Preserves other missing
values."""
unrounded = df.loc[df[var_name].notnull(), var_name]
rounded = unrounded.round()
diff = rounded != unrounded
diff_i = diff[diff == True]... | 5,311,006 |
def get_entropy(word, data: pd.DataFrame, obs: list = []):
"""Get the optimal guess given previous observations.
Args:
data: a DataFrame containing all possible function outputs
obs: a list of observed guess, value pairs
Returns:
The word that maximizes the partition entropy over t... | 5,311,007 |
def countTof(evt, record, signalThreshold=1, minWindow=0, maxWindow=-1, hitscoreThreshold=2, outkey="tof: "):
"""A simple hitfinder that performs a peak counting test on a time-of-flight detector signal,
in a specific subwindow and adds the result to ``evt["analysis"][outkey + "isHit"]``,
and the hitscor... | 5,311,008 |
def add_config(name, config_parser):
"""
Add a config_parser object to metaconfig.
"""
if _metaconfig is None:
init()
return _metaconfig.add_config(name, config_parser) | 5,311,009 |
def rebuildEventList(events, eventList = None):
"""
Add all events (top and nested) from event trees to a list.
"""
if eventList == None:
eventList = []
for event in events:
if event not in eventList:
eventList.append(event)
for arg in event.arguments:
... | 5,311,010 |
def rpc_blocktime_participation(rpc):
"""
Determine if node is returning stale data
"""
ret = wss_query(rpc, ["database", "get_objects", [["2.1.0"]]])[0]
unix = from_iso_date(ret["time"])
participation = bin(int(ret["recent_slots_filled"])).count("1") / 1.28
return unix, participation | 5,311,011 |
def snr_upload_config(sw):
"""
Function to upload config to tftp server
for SNR-S2995G model
:param sw: snmp_cmds.api.Session object
:return: None
"""
sw.set(oid='.1.3.6.1.4.1.40418.7.100.1.10.3.0', value_type='s', value=TFTP_SERVER)
sw.set(oid='.1.3.6.1.4.1.40418.7.100.1.10.4.0', value... | 5,311,012 |
def make_quadratic_eq(x="x", rhs = None):
"""
Generates quadratic equation problem expression and
set of solutions
x : charector for the variable to be solved for. defaults to "x".
OR
a list of possible charectors. A random selection will be made from them.
... | 5,311,013 |
def generate_rules_engine(config):
"""Generate Terraform for the Rules Engine
Args:
config (dict): The loaded config from the 'conf/' directory
Returns:
dict: Rules Engine Terraform definition to be marshaled to JSON
"""
prefix = config['global']['account']['prefix']
result = in... | 5,311,014 |
def generated_edge_compute(e1, e2):
"""
Return the distance between colors of two edges for generated puzzle.
:param e1: Edge object
:param e2: Edge object
:return: distance Float
"""
#edge size
shapevalue, distvalue = dist_edge(e1, e2)
#edges diff
edge_shape_... | 5,311,015 |
def package():
""" [deploy] Creates a deployment package. """
branch, summary, version = _get_versioning_metadata()
# Builds the deployment package.
local('fpm -s dir -t deb -n endagaweb -a all -v %(version)s \
--description "%(branch)s: %(cs)s" \
-d byobu -d nginx -d python-pip... | 5,311,016 |
def _pack_64b_int_arg(arg):
"""Helper function to pack a 64-bit integer argument."""
return ((arg >> 56) & 0xff), ((arg >> 48) & 0xff), ((arg >> 40) & 0xff), ((arg >> 32) & 0xff), \
((arg >> 24) & 0xff), ((arg >> 16) & 0xff), ((arg >> 8) & 0xff), (arg & 0xff) | 5,311,017 |
def coregister(dataset):
"""
add reference value for year and value
"""
try:
path_term = str(dataset + '_src_query')
path_dst = os.path.join(retrieve_path(path_term))
file_dst = os.path.join(path_dst, dataset + '.csv')
df = pd.read_csv(file_dst)
df = clea... | 5,311,018 |
def write(data: orm.Data, filename: str) -> None:
"""
Write an AiiDA Data instance to a file in bands_inspect HDF5 format.
Parameters
----------
data :
The AiiDA data instance to be written.
filename :
Path of the file being written to.
"""
save(to_bands_inspect(data), h... | 5,311,019 |
def subroutine_to_c_header(subroutine, export=True):
"""Returns the function declaration in C"""
output = ['\n/*>']
output.append('\n *>'.join(subroutine.comment_lines))
output.append(' */\n')
output.append('{0}cmfe_Error {1}('.format('IRON_C_EXPORT ' if export else '', subroutine_c_names(subroutin... | 5,311,020 |
def list_array_paths(path, array_dict):
"""
Given a dictionary containing each directory (experiment folder) as a
key and a list of array data files (analysis of array containing Log2Ratio
data) as its value (i.e., the output of 'find_arrays'), returns a list of
full paths to array files.
"""
... | 5,311,021 |
def log_simple(n, k):
"""
A function that simply finds how many k's does n have.
For example 28 = 2 * 2 * 7, so log_simple(28, 2) will return 2
and log_simple(28, 7) will return 1
"""
log_result = 0
while (n % k == 0):
log_result += 1
n /= k
return n, log_resu... | 5,311,022 |
def parse_fq(fq):
"""Parse a FASTQ file
Args:
fq(str): path to fastq file
Returns:
fqd(dict): dictionary with read names as keys, seq and quality as values
in a list
"""
def get_fq_reads(allreads):
read_dict = {}
for title, seq, qual in FastqGeneralIterator(al... | 5,311,023 |
def force_ref(w_obj):
"""Convert a reference-or-object into a reference"""
if not isinstance(w_obj, W_Reference):
return W_Reference(w_obj)
else:
return w_obj | 5,311,024 |
def main(base_path, chrom_sizes_path, out_path, chunk_size):
"""
Converts a set of BPNet ChIPseq and one pair of control ChIPseq profile
BigWigs into an HDF5 file. HDF5 has separate datasets for each chromosome.
Each chromosome's dataset is stored as an L x (T + 1) x 2 array, where L is
the size of ... | 5,311,025 |
def test_gsmote_default_init():
"""Test the intialization with default parameters."""
gsmote = GeometricSMOTE()
assert gsmote.sampling_strategy == 'auto'
assert gsmote.random_state is None
assert gsmote.truncation_factor == 1.0
assert gsmote.deformation_factor == 0.0
assert gsmote.selection_... | 5,311,026 |
def createtxt(fpath):
"""
Description:
Create an empty .txt file
Input:
fpath - file path
"""
# create empty file
open(fpath, 'a').close() | 5,311,027 |
def http_file_upload_post(host, port, uri, params={}, files=[]):
"""Perform a plain HTTP file upload post (for task farming)"""
content_type, body = client._encode_multipart_formdata(params, files)
h = httplib.HTTP(host, port)
h.putrequest('POST', uri)
h.putheader('content-type', content_type)
h... | 5,311,028 |
def bleu_score(references, hypotheses):
"""Computes bleu score.
Args:
references: list of list (one hypothesis)
hypotheses: list of list (one hypothesis)
Returns:
BLEU-4 score: (float)
"""
references = [[ref] for ref in references] # for corpus_bleu func
BLEU_4 = nltk... | 5,311,029 |
def main():
"""Shows basic usage of the Sheets API.
Creates a Sheets API service object and prints the names and majors of
students in a sample spreadsheet:
https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
"""
service = get_service()
spreadsheetId = ... | 5,311,030 |
def calcAveragePosition(vertexSelection):
"""
Calculate the average position of all points.
@param points: An iterable sequence of _nukemath.Vector3 objects.
@return: A _nukemath.Vector3 containing the average of all the points.
"""
pass | 5,311,031 |
def conv_block(x, filters, kernel_size = (7,7), padding="same", strides=1):
"""
conv_block(x, filters, kernel_size = (7,7), padding="same", strides=1)
This function applies batch normalization to an input layer, then convolves with a 2D convol layer
The two actions combined is called a convolutional blo... | 5,311,032 |
def lgr_set_annotate(lgr, script_lgr, set_labels_input, labels_input):
"""
Annotate a list of labels with their disposition.
:param lgr: The LGR set object.
:param script_lgr: The LGR object for the script used to check label validity.
:param set_labels_input: The labels in the lgr set.
:param ... | 5,311,033 |
def test_logging_decorator_res_only(caplog):
"""Verify that only the response gets logged"""
caplog.set_level(logging.INFO)
@log_traffic(log_request=False)
def mock_func():
return {'foo': 'bar'}
with app.test_request_context(environ_base=REQ):
mock_func()
assert 'Incoming reque... | 5,311,034 |
def tmpdir(*args, **kwargs):
"""Create a NamedTemporaryDirectory "as" the str path"""
with NamedTemporaryDirectory() as d:
yield d.name | 5,311,035 |
def download_media(request):
"""
Make a gzip copy of all media files.
"""
lazy_create_permission('make_backup')
if not request.user.has_perm('make_backup'):
return HttpResponseForbidden('you do not have permission to create backups')
zip_pth = join(gettempdir(), 'media_export')
make_archive(zip_pth, 'zip', ro... | 5,311,036 |
def square_to_square_dataframe(df, cov_func, **cov_func_kwargs):
""" Map square dataframe to square dataframe """
return pd.DataFrame( index=df.index, columns=df.columns, data=cov_func(df.values, **cov_func_kwargs)) | 5,311,037 |
def test_style(rel_path=''):
""" Test style using flake8
"""
# Test if flake is there
try:
from flake8.main import main # noqa
except ImportError:
sys.exit('Cannot do flake8 test, flake8 not installed')
path = os.path.join(ROOT_DIR, rel_path)
# Reporting
print(... | 5,311,038 |
def fitparams_for_update(fitparams):
"""
Extracts a dictionary of fitparameters from
modelmiezelb.io.ContrastData.fitparams for updating e.g. a sqe model
via modelmiezelb.sqe_model.SqE.update_params
Parameters
----------
fitparams : modelmiezelb.io.ContrastData.fitparam
Return
-... | 5,311,039 |
def detectorResponseToCell(r):
"""
Given helicopter over a cell, calculate detector response to particular cell
"""
return (((MONITOR_PROPORTION_COEF) * (1 + (RADIATION_BUILDUP_FAC * r)) * (math.exp(-1 * RADIATION_ABSORPTION_COEF * r))) / (r) ** 2) | 5,311,040 |
def datetime_to_timestamp(dt=None):
"""Convert a datetime to a timestamp string.
Parameters
----------
dt : datetime (defaults to now)
Returns
-------
str
"""
if dt is None:
dt = arrow.now()
return dt.strftime("%Y%m%d_%H%M%S") | 5,311,041 |
def buildAction(obj, actionName, target):
"""Setup an object QAction triggering a callable
A `QAction` will be created with name `actionName`, added as a child of `obj`.
When the action's `triggered()` signal is emitted, the `target` will be called.
See :any:`QObject.setObjectName`.
:param obj: the object in wh... | 5,311,042 |
def get_hash_family(n_funcs, num_shingles):
""" Get N hash functions:
f(x = ((a*x + b) % p )
"""
h_funcs = []
a_done = []
b_done = []
p = get_prime_larger_than(num_shingles)
while h_funcs.__len__() < n_funcs:
a = random.randint(1, num_shingles)
b = random.randint... | 5,311,043 |
def _get_new_computed_partition_spec(storage_system, device_path, partition_info):
"""
Computes the new disk partition info when adding a new vmfs partition that
uses up the remainder of the disk; returns a tuple
(new_partition_number, vim.HostDiskPartitionSpec
"""
log.trace(
"Adding a p... | 5,311,044 |
def simulation_is_complete(mc_run_dir):
"""Check that a grand canonical monte carlo simulation has finished
Args:
mc_run_dir(str): Path to a monte carlo simulation directory.
Returns:
simulation_status(bool): simulation is complete (True) or simulation is not complete (False)
"""
# ... | 5,311,045 |
def debug_call_trace(loger=None, name=None):
"""
Trace a fun call with loger.
:param loger: logging.Logger
:param name: function name
"""
def _(func):
fname = name or func.__name__
@functools.wraps(func)
def f(*args, **kwg):
fid = id(args) ^ id(kwg)
... | 5,311,046 |
def loads(s, *v, cls=None, parse_float=None, parse_int=None, parse_constant=None,**kw):
"""
json.loads互換の関数です。
"""
return json.loads(s, *v, cls=cls, object_hook=_load_hook,parse_float=parse_float, parse_int=parse_int, parse_constant=parse_constant,**kw) | 5,311,047 |
def get_export_collections(only_selected=False):
"""Returns a list of Export Collections in the current scene.
:param only_selected: If `True`, only return selected Export Collections, defaults to `False`
:return: List of :class:`ExportCollection` objects
"""
collections = [coll for coll in bpy.dat... | 5,311,048 |
def test_list_posts_anonymous(mocker, client, public_channel, reddit_factories):
"""Anonymous users can see posts for a public channel, if the feature flag is set"""
user = UserFactory.create(username="01CBFJMB9PD3JP17KAX3E5JQ46")
post = reddit_factories.link_post("link_post", user=user, channel=public_chan... | 5,311,049 |
def levenshtein_distance(s1, s2):
"""Compute Levenshtein distance btw two strings
Note
----
Taken from wikibooks.org-wiki-Algorithm_Implementation
"""
if len(s1) < len(s2):
return levenshtein_distance(s2, s1)
# len(s1) >= len(s2)
if len(s2) == 0:
return len(s1)
pr... | 5,311,050 |
def sample_videos_to_images(
video_dataset,
image_dataset_path,
stride=None,
num_images=None,
frame_filter=lambda labels: True,
image_extension=".jpg",
description=None,
):
"""Creates a `LabeledImageDataset` by extracting frames and their
corresponding labels from a `LabeledVideoData... | 5,311,051 |
def execute_commands(c, v):
"""
Executes a control command with an associated value.
@param c: The Command object representing the command to be executed.
@param v: The integer value.
"""
msg = [c.value, v]
port.write(msg) | 5,311,052 |
def deg_monitoring(year, ts_status, path, row, old_coefs, train_ndfi,
first, tmean):
""" Main function for monitoring, should be looped over for each year """
# REGRESSION
# train array = ndfi collection as arrays
train_array = ee.ImageCollection(train_ndfi).select('NDFI').map(
... | 5,311,053 |
def test_get_remote_ip():
"""
Ensure remote IPs are returned for all gateway types
"""
eventv1 = get_json_fixture_file('api_gateway_request_urlencoded_base64.json')
eventv2 = get_json_fixture_file('httpapiv2_gateway_request_urlencoded_base64.json')
assert RequestProvider(eventv1).get_remote_ip(... | 5,311,054 |
def distmat2dqueuing(B1, B2):
"""
Creates distance matrix for queuing
Parameters
----------
B1 - Buffer size of first queue
B2 - Buffer size of second queue
Returns
-------
distance matrix
"""
nStates = (B1 + 1) * (B2 + 1)
d = np.ones((nStates, nStates))
vec_tuple = ... | 5,311,055 |
def mismatch_rate_mapqge20(mqc):
"""
The fraction of bases that mismatch the reference in reads with MAPQ>=20.
Source: picard AlignmentSummaryMetrics (PF_HQ_ERROR_RATE)
"""
k = inspect.currentframe().f_code.co_name
try:
d = next(iter(mqc["multiqc_picard_AlignmentSummaryMetrics"].values... | 5,311,056 |
def _validate(cmd, references):
""" Make sure all references in the command are in the reference mapping
Raises
------
TypeError, if a tag is missing from references
"""
replacements = {}
references_new = {}
for match in TAG_RE.finditer(cmd):
tag = match.group('tag')
if... | 5,311,057 |
def donot_config_oam_list(cc, args):
"""List external oams."""
iextoams = cc.iextoam.list()
field_labels = ['uuid', 'oam_subnet', 'oam_gateway_ip',
'oam_floating_ip', 'oam_c0_ip',
'oam_c1_ip']
fields = ['uuid', 'oam_subnet', 'oam_gateway_ip',
'oam... | 5,311,058 |
def rebuildCurve(*args, **kwargs):
"""
This command rebuilds a curve by modifying its parameterization. In some cases the shape may also change. The
rebuildType (-rt) determines how the curve is to be rebuilt. The optional second curve can be used to specify a
reference parameterization.
Flags:... | 5,311,059 |
def generate():
"""Used to generate code with cog."""
import orwell.messages.controller_pb2 as pb_controller
import orwell.messages.robot_pb2 as pb_robot
import orwell.messages.server_game_pb2 as pb_server_game
import orwell.messages.server_web_pb2 as pb_server_web
TEMPLATE = """
class {name}(y... | 5,311,060 |
def readUInt(stream, size):
""" Read an unsigned integer from a file (or file-like stream).
@param stream: The source file-like object.
@param size: The number of bytes to read from the stream.
@return: The decoded value.
"""
if size == 0:
return 0
data = stream.read(s... | 5,311,061 |
def addToDF_SOS_EOS_White(pd_TS, VegIdx = "EVI", onset_thresh=0.15, offset_thresh=0.15):
"""
In this methods the NDVI_Ratio = (NDVI - NDVI_min) / (NDVI_Max - NDVI_min)
is computed.
SOS or onset is when NDVI_ratio exceeds onset-threshold
and EOS is when NDVI_ratio drops below off-set-threshold.
... | 5,311,062 |
def safe_execute_script(driver, script):
""" When executing a script that contains a jQuery command,
it's important that the jQuery library has been loaded first.
This method will load jQuery if it wasn't already loaded. """
try:
driver.execute_script(script)
except Exception:
... | 5,311,063 |
def validate_model( # noqa: C901 (ignore complexity)
model: Type[BaseModel], input_data: 'DictStrAny', cls: 'ModelOrDc' = None
) -> Tuple['DictStrAny', 'SetStr', Optional[ValidationError]]:
"""
validate data against a model.
"""
values = {}
errors = []
# input_data names, possibly alias
... | 5,311,064 |
def convert_flatten(net, node, model, builder):
"""Convert a flatten layer from mxnet to coreml.
Parameters
----------
network: net
A mxnet network object.
layer: node
Node to convert.
model: model
An model for MXNet
builder: NeuralNetworkBuilder
A neural ... | 5,311,065 |
def spinChainProductSum(spins):
"""
Calculate the Ising nearest neighbor interactions of a spin chain, periodic boundary condition(PBC).
Parameters
----------
spins : list of ints or floats
The given spin under PBC.
Returns
float
The nearest neighbor interactions(products).... | 5,311,066 |
def fs_error_handler(f: Any) -> Any:
"""
A Decorator that handles error from FileSystem for HiveTableLastUpdatedExtractor use case
If it's client side error, it logs in INFO level, and other errors is logged as error level with stacktrace.
The decorator is intentionally not re-raising exception so that ... | 5,311,067 |
def run(base_commit, ignore_config, step: Optional[Step], report: Optional[Report]):
"""Apply clang-tidy and return if no issues were found."""
if report is None:
report = Report() # For debugging.
if step is None:
step = Step() # For debugging.
r = subprocess.run(f'git diff -U0 --no-p... | 5,311,068 |
def has_ext_state(section: str, key: str) -> bool:
"""
Return whether extended state exists for given section and key.
Parameters
----------
section : str
Extended state section.
key : str
Extended state key.
Returns
-------
has_ext_state : bool
"""
has_ext_... | 5,311,069 |
def build_udp_header(src_port, dest_port, ip_header, data):
"""
Building an UDP header requires fields from
IP header in order to perform checksum calculation
"""
# build UDP header with sum = 0
udp_header = UDPHEADER(src_port,
dest_port,
UD... | 5,311,070 |
def get_webhooks():
"""
GET /domains/<domain>/webhooks
:return:
"""
req = client.domains_webhooks.get(domain=domain)
print(req.json()) | 5,311,071 |
def run_sim(nns, task_rate, track, num_inputs):
"""
Run the simulation for this set of nns
"""
vehs, is_alive, nn_inputs, nn_outputs, t_stationary = init_pop(len(nns), task_rate, track, num_inputs)
tSim = 0.0
max_steer = np.zeros(len(nns)) # log the maximum steering angle applied
while a... | 5,311,072 |
def join(uvedge_a, uvedge_b, size_limit=None, epsilon=1e-6):
"""
Try to join other island on given edge
Returns False if they would overlap
"""
class Intersection(Exception):
pass
class GeometryError(Exception):
pass
def is_below(self, other, correct_geometry=True):
... | 5,311,073 |
def magma_solverinfo(solver_par, precond_par, queue):
"""
solver_par is magma_x_solver_par with x = z, c, d, s
precond is magma_x_preconditioner with x = z, c, d, s
queue is of type magma_queue_t
"""
if isinstance(solver_par, magma_z_solver_par):
magma_zsolverinfo(solver_par, precond_pa... | 5,311,074 |
def test_default_next_offset_to_read(tmpdir, mocker):
"""Override the default setup because we want to mock out the
the query result of _get_last_apply_record to return nothing
"""
(oracle_processor,
mock_target_db,
mockargv,
mock_audit_factory,
mock_audit_db) = cdc_utils.setup_depen... | 5,311,075 |
def delete(user_id=None):
"""
This will delete a user from the Database
:param user_id: int of the users id
:return: User dict of the user created
"""
user = User.query.filter_by(user_id=user_id).first()
return user | 5,311,076 |
def get_uutils_default_adafactor_from_torch_optimizer_and_scheduler_default(mdl: nn.Module,
lr: float = 1e-4,
scheduler_opt: Optional[str] = None
... | 5,311,077 |
def fnot(function: Callable) -> Callable:
"""Inverse of composing a function with bool.
For example:
```
fnot(identity)(True) == False
fnot(identity)(False) == True
greater_or_equal_to = less | fnot
greater_or_equal_to(2).lmap([1, 2, 3]) == [False, True, True]
```
"""
return Fun... | 5,311,078 |
def load_fort70_wfn(chkdata, fort70file, verbose=10):
"""Loads a (multideterminant) wave function from fort.70 file.
This is necessary to get the wave function in the orthogonal basis.
Another alternative would be to reconstitute the X basis-orthogonalization
matrix from fort.70 and transform the wave function ... | 5,311,079 |
def analisis_info(info:pd.DataFrame, Level:int, Coincidences:str)->tuple:
"""Usa la columna de elemntos a ingresar, lo corta a la cantidad de elementos necesarios y
lo multiplica por la cantidad de coincidencias necesarias para llenar los botones y
la mezcla para obtener posiciones aleatorias.
Args:
... | 5,311,080 |
def plot_argus_phosphenes(X, argus, scale=1.0, axon_map=None, show_fovea=True,
ax=None):
"""Plots phosphenes centered over the corresponding electrodes
.. versionadded:: 0.7
Parameters
----------
X : pd.DataFrame
argus : :py:class:`~pulse2percept.implants.ArgusI` or :... | 5,311,081 |
def _escape_for_regex(text):
"""Escape ``text`` to allow literal matching using egrep"""
regex = re.escape(text)
# Seems like double escaping is needed for \
regex = regex.replace("\\\\", "\\\\\\")
# Triple-escaping seems to be required for $ signs
regex = regex.replace(r"\$", r"\\\$")
# Whe... | 5,311,082 |
def color_to_256(color):
"""Convert color into ANSI 8-bit color format.
Red is converted to 196
This converter emits the 216 RGB colors and the 24 grayscale colors.
It does not use the 16 named colors.
"""
output = 0
if color.r == color.g == color.b:
# grayscale case
if color... | 5,311,083 |
def cmd_app_config(mixcli: MixCli, **kwargs: Union[str, bool]):
"""
Default funciton when app lookup command is called.
:param mixcli: MixCli instance
:param kwargs: keyword arguments from keyword arguments from cmd line
:return: True
"""
ns_name = kwargs['ns']
ns_id = kwargs['ns_id']
... | 5,311,084 |
def t_low(t, df):
"""Returns left-hand tail of Student's t distribution (-infinity to x).
df, the degrees of freedom, ranges from 1 to infinity.
Typically, df is (n-1) for a sample size of n.
Result ranges from 0 to 1.
See Cephes docs for details.
"""
if df < 1:
raise ValueError("... | 5,311,085 |
def breadcrumb(*args):
""""Render a breadcrumb trail
Args:
args (list) : list of urls and url name followed by the final name
Example: url1, name1, url2, name2, name3
"""
def pairs(l):
a = iter(l)
return list(zip(a,a))
return {
'urls': pairs(ar... | 5,311,086 |
def get_sampling_frequency_and_duration_from_frequency_array(frequency_array):
"""
Calculate sampling frequency and duration from a frequency array
Attributes:
-------
frequency_array: array_like
Frequency array to get sampling_frequency/duration from: array_like
Returns
-------
... | 5,311,087 |
def parse_args(args: argparse.ArgumentParser) -> argparse.Namespace:
"""Parse command line parameters
Args:
args ([str]): command line parameters as list of strings
Returns:
:obj:`argparse.Namespace`: command line parameters namespace
"""
parser = argparse.ArgumentParser(
desc... | 5,311,088 |
def sequence_layers(layers):
"""Go through the list of layers and fill in the missing bits of information.
The basic rules are this:
* If the current layer has data set to None, take the data from previous layer.
* For each aesthetic mapping, if that mapping is set to None, take it from previous layer.
... | 5,311,089 |
def start_end(data, num_start=250, num_end=100, full_output=False):
"""
Gate out first and last events.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
num_start, num_en... | 5,311,090 |
def init():
"""Top level command handler."""
@click.group(cls=cli.make_multi_command(__name__,
chain=True,
invoke_without_command=True))
@click.option('--cell', required=True,
envvar='TREADMILL_CELL',
... | 5,311,091 |
def test_matching_daemon():
""" Test with matching package with daemon """
w = TcpWrappersFacts(daemon_lists=[DaemonList(value=["sshd"])])
p = ["openssh", "systemd", "pam"]
d = [("openssh", ["sshd"])]
packages = config_affects_daemons(w, p, d)
assert len(packages) == 1
assert "openssh" in p... | 5,311,092 |
def to_rpc_literal(value):
"""
void @0 :Void;
bool @1 :Bool;
int8 @2 :Int8;
int16 @3 :Int16;
int32 @4 :Int32;
int64 @5 :Int64;
uint8 @6 :UInt8;
uint16 @7 :UInt16;
uint32 @8 :UInt32;
uint64 @9 :UInt64;
float32 @10 :Float32;
float64 @11 :Float64;
text @12 :Text;
... | 5,311,093 |
def fit_gaussian( df ):
"""
Fit a Gaussian to the data
:param df: A Pandas DataFrame inedxed by wavelength with spectral data
:returns: A Pandas DataFrame of the fit parameters
"""
gaussian = lambda x, A, mu, sigma: (
A* np.exp( -np.power( ( x - mu ), 2 )/( 2* np.power( sigma, 2 ) ) )... | 5,311,094 |
def test_set_initial_temperature(new_test_sim, new_test_sim_white, new_sim2,
new_sim2_white, new_sim5, new_sim5_white):
"""Test initial temperature calculation."""
np.random.seed(seed=1)
# Kirkpatrick method
assert new_test_sim._initial_T == 10e10
assert new_test_sim._cu... | 5,311,095 |
def get_activation(fn_name,only_layer=False):
"""
Args:
only_layer (bool):
fn_name ():
Returns:
Examples:
>>> a=get_activation('relu')
>>> print(get_activation('swish'))
"""
if fn_name is None:
return None
fn_modules = ['trident.layers.pytorch_ac... | 5,311,096 |
def filter_shapefile_non_overlapping(base, base_shapefile, data_directory):
"""
Shapefiles may deal with data over multiple path/rows.
This is a method to get the minimum number of
path/rows required to cover all features.
Data directory: where the split shapefiles will be saved.
base: director... | 5,311,097 |
def _conv_filter(state_dict, patch_size=16):
""" convert patch embedding weight from manual patchify + linear proj to conv"""
out_dict = {}
for k, v in state_dict.items():
if 'patch_embed.proj.weight' in k:
if v.shape[-1] != patch_size:
patch_size = v.shape[-1]
... | 5,311,098 |
def loadFilesFromPath(inputPath, tilelimits):
"""
Load wind field data for each subset into a 3-D array.
:param str inputPath: str path to wind field files.
:param tuple tilelimits: tuple of index limits of a tile.
:returns: 3-D `numpy.narray` of wind field records.
"""
fileList = os.li... | 5,311,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.