content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def initialize_window(icon, title, width,
height, graphical): # pragma: no cover
"""
Initialise l'environnement graphique et la fenêtre.
Parameters
----------
icon : Surface
Icone de la fenêtre
title : str
Nom de la fenêtre
width : int
Largeur ... | 5,357,000 |
def get_contour_verts(cn):
"""unpack the SVM contour values"""
contours = []
# for each contour line
for cc in cn.collections:
paths = []
# for each separate section of the contour line
for pp in cc.get_paths():
xy = []
# for each segment of that section
... | 5,357,001 |
def play(data_type, stream_id, name, start=-2, duration=-1, reset=False):
"""
Construct a 'play' message to start receive audio/video data from publishers on the server.
:param data_type: int the RTMP datatype.
:param stream_id: int the stream which the message will be sent on.
:param name: str the ... | 5,357,002 |
def _compute_covariances(precisions_chol):
"""Compute covariancess from Cholesky decomposition of the precision matrices.
Parameters
----------
precisions_chol : array-like, shape (n_components, n_features, n_features)
The Cholesky decomposition of the sample precisions.
Returns
------... | 5,357,003 |
def test_load_by_file_path():
"""
Test if the image can be loaded by passing a filepath as string.
"""
image = ShdlcFirmwareImage(
EKS2.get('HEXFILE'), EKS2.get('BL_ADDR'), EKS2.get('APP_ADDR'))
assert image.size > 0 | 5,357,004 |
def rad2deg(angle):
"""
Convert radian to degree.
Parameters
----------
angle : float
Angle in radians
Returns
-------
degree : float
Angle in degrees
"""
return (180./PI) * angle | 5,357,005 |
def parse_kinetics_splits(level):
"""Parse Kinetics-400 dataset into "train", "val", "test" splits.
Args:
level (int): Directory level of data. 1 for the single-level directory,
2 for the two-level directory.
Returns:
list: "train", "val", "test" splits of Kinetics-400.
"""... | 5,357,006 |
def execute(command, shell=True):
"""
Execute command using os package and return output to log file
:param command: The command to be executed
:type command: str
:param shell: Takes either True or False
:type shell: boolean
:return: Run the command in the background and save the
output... | 5,357,007 |
def rotateContoursAbout(contours, about, degrees=90, ccw=True):
"""\
Rotate the given contours the given number of degrees about the point about
in a clockwise or counter-clockwise direction.
"""
rt = Transform.rotationAbout(about, degrees, ccw)
return rt.applyToContours(contours) | 5,357,008 |
def coordinate_addition(v, b, h, w, A, B, psize):
"""
Shape:
Input: (b, H*W*A, B, P*P)
Output: (b, H*W*A, B, P*P)
"""
assert h == w
v = v.view(b, h, w, A, B, psize)
coor = torch.arange(h, dtype=torch.float32) / h
coor_h = torch.cuda.FloatTensor(1, h, 1, 1, ... | 5,357,009 |
def ticket() -> str:
"""生成请求饿百接口所需的ticket参数"""
return str(uuid.uuid1()).upper() | 5,357,010 |
def create_WchainCNOT_layered_ansatz(qc: qiskit.QuantumCircuit,
thetas: np.ndarray,
num_layers: int = 1):
"""Create WchainCNOT layered ansatz
Args:
- qc (qiskit.QuantumCircuit): init circuit
- thetas (np.ndarray): parameters
... | 5,357,011 |
def test_simple_cases(testdir):
"""Verify a simple passing test and a simple failing test.
The failing test is marked as xfail to have it skipped."""
testdir.makepyfile(
"""
import pytest
from seleniumbase import BaseCase
class MyTestCase(BaseCase):
def test_passi... | 5,357,012 |
def birth_brander():
""" This pipeline operator will add or update a "birth" attribute for
passing individuals.
If the individual already has a birth, just let it float by with the
original value. If it doesn't, assign the individual the current birth
ID, and then increment the global, stored birt... | 5,357,013 |
def find_center_vo(tomo, ind=None, smin=-50, smax=50, srad=6, step=0.5,
ratio=0.5, drop=20, smooth=True):
"""
Find rotation axis location using Nghia Vo's method. :cite:`Vo:14`.
Parameters
----------
tomo : ndarray
3D tomographic data.
ind : int, optional
Inde... | 5,357,014 |
def random_fit_nonnegative(values, n):
"""
Generates n random values using a normal distribution fitted from values used as argument.
Returns only non-negative values.
:param values: array/list to use as model fot the random data
:param n: number of random elements to return
:returns: an array o... | 5,357,015 |
def passthrough(world1, world2, signaling_pipe):
""" Simple passthrough filter: wait for changes on a world world1 and
propagate these changes to world world2.
"""
name = "passthrough_filter_%s_to_%s" % (world1, world2)
with underworlds.Context(name) as ctx:
world1 = ctx.worlds[world1]
... | 5,357,016 |
def connected_components(weak_crossings=None,
strong_crossings=None,
probe_adjacency_list=None,
join_size=None,
channels=None):
"""Find all connected components in binary arrays of threshold crossings.
Parameter... | 5,357,017 |
def channel_values(channel_freqs, channel_samples, dt, t):
"""Computes value of channels with given frequencies, samples, sample size and current time.
Args:
channel_freqs (array): 1d array of channel frequencies
channel_samples (array): 2d array of channel samples, the first index being time s... | 5,357,018 |
def bandpass_voxels(realigned_file, bandpass_freqs, sample_period = None):
"""
Performs ideal bandpass filtering on each voxel time-series.
Parameters
----------
realigned_file : string
Path of a realigned nifti file.
bandpass_freqs : tuple
Tuple containing the bandpass freq... | 5,357,019 |
def get_small_corpus(num=10000):
"""
获取小型文本库,用于调试网络模型
:param num: 文本库前n/2条对联
:return: 默认返回前500条对联(1000句话)的list
"""
list = getFile('/total_list.json')
return list[:num] | 5,357,020 |
def groupby_apply2(df_1, df_2, cols, f, tqdn=True):
"""Apply a function `f` that takes two dataframes and returns a dataframe.
Groups inputs by `cols`, evaluates for each group, and concatenates the result.
"""
d_1 = {k: v for k,v in df_1.groupby(cols)}
d_2 = {k: v for k,v in df_2.groupby(cols)}
... | 5,357,021 |
def login(request):
"""Logs in the user if given credentials are valid"""
username = request.data['username']
password = request.data['password']
try:
user = User.objects.get(username=username)
except:
user = None
if user is not None:
encoded = user.password
hashe... | 5,357,022 |
def replace_data_in_gbq_table(project_id, table_id, complete_dataset):
""" replacing data in Google Cloud Table """
complete_dataset.to_gbq(
destination_table=table_id,
project_id=project_id,
credentials=credentials,
if_exists="replace",
)
return None | 5,357,023 |
def default_pubkey_inner(ctx):
"""Default expression for "pubkey_inner": tap.inner_pubkey."""
return get(ctx, "tap").inner_pubkey | 5,357,024 |
def presenter(poss, last_move):
""" Présenter les choix à l'utilisateur. """
prop = "CHOIX :" + "\n"
prop += " espace : arrière" + "\n"
prop += " entrée : automatique" + "\n"
prop += " autre : hasard" + "\n"
for i, p in enumerate(poss):
star = " "
if last_move == p:
... | 5,357,025 |
def assert_array_almost_equal(x: numpy.ndarray, y: List[complex]):
"""
usage.scipy: 6
"""
... | 5,357,026 |
def quantize_8(image):
"""Converts and quantizes an image to 2^8 discrete levels in [0, 1]."""
q8 = tf.image.convert_image_dtype(image, tf.uint8, saturate=True)
return tf.cast(q8, tf.float32) * (1.0 / 255.0) | 5,357,027 |
def get_clients( wlc, *vargs, **kvargs ):
"""
create a single dictionary containing information
about all associated stations.
"""
rsp = wlc.rpc.get_stat_user_session_status()
ret_data = {}
for session in rsp.findall('.//USER-SESSION-STATUS'):
locs... | 5,357,028 |
def coalmine(eia923_dfs, eia923_transformed_dfs):
"""Transforms the coalmine_eia923 table.
Transformations include:
* Remove fields implicated elsewhere.
* Drop duplicates with MSHA ID.
Args:
eia923_dfs (dict): Each entry in this dictionary of DataFrame objects
corresponds to ... | 5,357,029 |
def _throw_object_x_at_y():
"""
Interesting interactions:
* If anything is breakable
:return:
"""
all_pickupable_objects_x = env.all_objects_with_properties({'pickupable': True})
x_weights = [10.0 if (x['breakable'] or x['mass'] > 4.0) else 1.0 for x in all_pickupable_objects_x]
if len... | 5,357,030 |
def concatenate_best_aligned_pus(peeling_level, aligned_pu_pdb, all_pu_ref):
"""
Write the full PDB of the best aligned PUs by concatenating them in the right order.
Args:
peeling_level (int): Actual peeling level
aligned_pu_pdb (str): Path to the PDB into which will be writ... | 5,357,031 |
def GraficarConstantesAsintoticas(historiaCABIS, historiaCANR, historiaCANRM, historiaCASEC, funcion):
"""
Recibe las historias de de las constantes de ordenes de convergencia, estas deben de ser validas, caso contrario,
se indicara en el grafico la falta de datos.
Necesita tambien de la funcion par... | 5,357,032 |
def plot(
X,
color_by=None,
color_map="Spectral",
colors=None,
edges=None,
axis_limits=None,
background_color=None,
marker_size=1.0,
figsize_inches=(8.0, 8.0),
savepath=None,
):
"""Plot an embedding, in one, two, or three dimensions.
This function plots embeddings. The i... | 5,357,033 |
def test_dqn_pong():
"""Test tf/dqn_pong.py with reduced replay buffer size for reduced memory
consumption.
"""
env = os.environ.copy()
env['GARAGE_EXAMPLE_TEST_N_EPOCHS'] = '1'
assert subprocess.run(
[str(EXAMPLES_ROOT_DIR / 'tf/dqn_pong.py'), '--buffer_size', '5'],
check=False,... | 5,357,034 |
def CausalConvIntSingle(val, time, kernel):
"""
Computing convolution of time varying data with given kernel function.
"""
ntime = time.size
dt_temp = np.diff(time)
dt = np.r_[time[0], dt_temp]
out = np.zeros_like(val)
for i in range(1, ntime):
temp = 0.
if i==0:
temp += val[0]*kernel(time[i]-time[0])*dt... | 5,357,035 |
def sbox1(v):
"""AES inverse S-Box."""
w = mpc.to_bits(v)
z = mpc.vector_add(w, B)
y = mpc.matrix_prod([z], A1, True)[0]
x = mpc.from_bits(y)**254
return x | 5,357,036 |
def _get_photon_info_COS(tag, x1d, traceloc='stsci'):
"""
Add spectral units (wavelength, cross dispersion distance, energy/area)
to the photon table in the fits data unit "tag".
For G230L, you will get several 'xdisp' columns -- one for each segment. This allows for the use of overlapping
backgrou... | 5,357,037 |
def maximum_value(tab):
"""
brief: return maximum value of the list
args:
tab: a list of numeric value expects at leas one positive value
return:
the max value of the list
the index of the max value
raises:
ValueError if expected a list as input
ValueError if no positive value found
"""
if not(isinstan... | 5,357,038 |
def writer(q: Queue):
"""Receives messages from queue and writes to file"""
while True:
try:
data = q.get()
logger.info(data)
if data.get("service_exit", False):
raise SerialDevicePoolError("Restarting device pool")
name = data["name"]
... | 5,357,039 |
def create_index_from_registry(registry_path, index_path, parser):
"""Generate an index files from the IEEE registry file."""
oui_parser = parser(registry_path)
oui_parser.attach(FileIndexer(index_path))
oui_parser.parse() | 5,357,040 |
def pdf(x, k, loc, scale):
"""
Probability density function for the Weibull distribution (for minima).
This is a three-parameter version of the distribution. The more typical
two-parameter version has just the parameters k and scale.
"""
with mpmath.extradps(5):
x = mpmath.mpf(x)
... | 5,357,041 |
def add_flight():
"""Allows users to add flights."""
if request.method == "GET":
return render_template("add.html", airports=AIRPORTS)
else:
# Move request.form into a dictionary that's a bit shorter to access than request.form
form = dict(request.form)
# Change hour and mi... | 5,357,042 |
def rescale_column_test(img, img_shape, gt_bboxes, gt_label, gt_num):
"""rescale operation for image of eval"""
img_data, scale_factor = mmcv.imrescale(img, (config.img_width, config.img_height), return_scale=True)
if img_data.shape[0] > config.img_height:
img_data, scale_factor2 = mmcv.imrescale(im... | 5,357,043 |
async def start_workers(
search_requests: Union[List[SearchIndexRequest], asyncio.Queue]
) -> Set[str]:
"""Runs the pipeline using asyncio concurrency with three main coroutines:
- get results: fetch the search requests queue, perform the search and output the results
- download and parse the body: fetc... | 5,357,044 |
def resolvability_query(m, walks_):
"""
:param m: cost matrix
:param walks_: list of 0-percolation followed by its index of redundancy
as returned by percolation_finder
:return: M again untouched, followed by the list of $0$-percolation with
minimal index of redundancy, and with a flag, True if ... | 5,357,045 |
def teardown_module():
# type: () -> None
""" Removes any created stats files, if any. """
for stats_file in TEST_STATS_FILES:
if os.path.exists(stats_file):
os.remove(stats_file) | 5,357,046 |
def lock_parent_directory(filename, timeout=10):
"""
Context manager that acquires a lock on the parent directory of the given
file path. This will block until the lock can be acquired, or the timeout
time has expired (whichever occurs first).
:param filename: file path of the parent directory to ... | 5,357,047 |
def test_invalid_domain_names_options(absolute_path):
"""End-to-End test to check domain names options validation works."""
process = subprocess.Popen(
[
'flake8',
'--isolated',
'--select',
'WPS',
# values from `allowed-domain-names` cannot int... | 5,357,048 |
def dsh(
incidence1: float, solar_az1: float, incidence2: float, solar_az2: float
):
"""Returns the Shadow-Tip Distance (dsh) as detailed in
Becker et al.(2015).
The input angles are assumed to be in radians.
This is defined as the distance between the tips of the shadows
in the two images for... | 5,357,049 |
def fix_commitment(mod, g, tmp):
"""
Fix committed capacity based on number of committed units and unit size
"""
mod.Commit_Capacity_MW[g, tmp] = \
mod.fixed_commitment[g, mod.prev_stage_tmp_map[tmp]]
mod.Commit_Capacity_MW[g, tmp].fixed = True | 5,357,050 |
def similarity(vec1, vec2):
"""Cosine similarity."""
return np.dot(vec1, vec2) / (np.linalg.norm(vec1) * np.linalg.norm(vec2)) | 5,357,051 |
def epv00(date1, date2):
""" Earth position and velocity, heliocentric and barycentric, with
respect to the Barycentric Celestial Reference System.
:param date1, date2: TDB as a two-part Julian date.
:type date1, date2: float
:returns: a tuple of two items:
* heliocentric Earth position v... | 5,357,052 |
def label(Z, n):
"""Correctly label clusters in unsorted dendrogram."""
uf = LinkageUnionFind(n)
for i in range(n - 1):
x, y = int(Z[i, 0]), int(Z[i, 1])
x_root, y_root = uf.find(x), uf.find(y)
if x_root < y_root:
Z[i, 0], Z[i, 1] = x_root, y_root
else:
... | 5,357,053 |
def comp_pack(ctx: Context):
"""Force packing resources."""
for ent in ctx.vmf.by_class['comp_pack']:
ent.remove()
for key, value in ent.keys.items():
# Not important.
if key in {'classname', 'origin', 'angles', 'hammerid'}:
continue
# We allo... | 5,357,054 |
def algorithm_conflict(old_config, new_config):
"""Generate an algorithm configuration conflict"""
return conflicts.AlgorithmConflict(old_config, new_config) | 5,357,055 |
def nin():
"""
:return:
"""
def nin_block(num_channels, kernel_size, strides, padding):
blk = nn.Sequential()
blk.add(nn.Conv2D(num_channels, kernel_size, strides, padding, activation='relu'),
nn.Conv2D(num_channels, kernel_size=1, activation='relu'),
nn... | 5,357,056 |
def factorial(n):
"""
Return the product of the integers 1 through n.
n must be a nonnegative integer.
"""
return product(range(2, n + 1)) | 5,357,057 |
def nftparams():
""" Show params of all NFTs
"""
nfts = Nfts()
t = PrettyTable(["key", "value"])
t.align = "l"
params = nfts.get_nft_params()
for key in params:
t.add_row([key, str(params[key])])
print(t) | 5,357,058 |
def get_status_lines(frames, check_transposed=True):
"""
Extract status lines from the given frames.
`frames` can be 2D array (one frame), 3D array (stack of frames, first index is frame number), or list of array.
Automatically check if the status line is present; return ``None`` if it's not.
I... | 5,357,059 |
def returnLendingHistory(*, start, end, limit=None):
"""
Returns your lending history within a time range.
:param session: Aiohttp client session object
:param String api_key: The API key
:param String secret_key: The API secret key
:param String start:
UNIX timestamp. Every retur... | 5,357,060 |
async def receiver():
"""receive messages with polling"""
pull = ctx.socket(zmq.PULL)
pull.connect(url)
poller = Poller()
poller.register(pull, zmq.POLLIN)
while True:
events = await poller.poll()
if pull in dict(events):
print("recving", events)
msg = awa... | 5,357,061 |
def quote():
"""Get stock quote."""
if request.method == "POST":
quote = lookup(request.form.get("symbol"))
if quote == None:
return apology("invalid symbol", 400)
return render_template("quoted.html", quote=quote)
# User reached route via GET (as by clicking a link or... | 5,357,062 |
def stats(api, containers=None, stream=True):
"""Get container stats container
When stream is set to true, the raw HTTPResponse is returned.
"""
path = "/containers/stats"
params = {'stream': stream}
if containers is not None:
params['containers'] = containers
try:
response ... | 5,357,063 |
def sendTGMessage(prepared_data):
"""
Prepared data should be json which includes at least `chat_id` and `text`
"""
message_url = Variables.BOT_URL + prepared_data["reqType"]
requests.post(message_url, json=prepared_data["data"]) | 5,357,064 |
def add_engineered(features):
"""Add engineered features to features dict.
Args:
features: dict, dictionary of input features.
Returns:
features: dict, dictionary with engineered features added.
"""
features["londiff"] = features["dropofflon"] - features["pickuplon"]
... | 5,357,065 |
def test_3tris():
"""3 triangles"""
conv = ToPointsAndSegments()
polygons = [
[[(0, 0), (1, 0), (0.5, -0.5), (0, 0)]],
[[(1, 0.5), (2, 0.5), (1.5, 1), (1, 0.5)]],
[[(2, 0), (3, 0), (2.5, -0.5), (2, 0)]],
]
for polygon in polygons:
conv.add_polygon(polygon)
return ... | 5,357,066 |
def test_envvar_windows(
cd_tmp_path: Path, cp_config: CpConfigTypeDef, monkeypatch: MonkeyPatch
) -> None:
"""Test envvars for Windows."""
monkeypatch.setattr("platform.system", MagicMock(return_value="Windows"))
monkeypatch.delenv("MSYSTEM", raising=False)
cp_config("simple_env_vars", cd_tmp_path)... | 5,357,067 |
def program_modules_with_functions(module_type, function_templates):
""" list the programs implementing a given set of functions
"""
prog_lsts = [program_modules_with_function(module_type, function_template)
for function_template in function_templates]
# get the intersection of all of ... | 5,357,068 |
def tasmax_below_tasmin(
tasmax: xarray.DataArray,
tasmin: xarray.DataArray,
) -> xarray.DataArray:
"""Check if tasmax values are below tasmin values for any given day.
Parameters
----------
tasmax : xarray.DataArray
tasmin : xarray.DataArray
Returns
-------
xarray.DataArray, [... | 5,357,069 |
def laplace_attention(q, k, v, scale, normalize):
"""
Laplace exponential attention
Parameters
----------
q : torch.Tensor
Shape (batch_size, m, k_dim)
k : torch.Tensor
Shape (batch_size, n, k_dim)
v : torch.Tensor
Shape (batch_size, n, v_dim)
s... | 5,357,070 |
def test_range_integrity_check_fails(full_range_stream_fresh, error_msg):
"""
Putting a range “into” (i.e. with shared positions on) the central
‘mid-body’ of an existing range (without first trimming the existing
range), will cause the existing range to automatically ‘split’ its
RangeSet to ‘give w... | 5,357,071 |
def instantiate(class_name, *args, **kwargs):
"""Helper to dynamically instantiate a class from a name."""
split_name = class_name.split(".")
module_name = split_name[0]
class_name = ".".join(split_name[1:])
module = __import__(module_name)
class_ = getattr(module, class_name)
return class_... | 5,357,072 |
def fawa(pv_or_state, grid=None, levels=None, interpolate=None):
"""Finite-Amplitude Wave Activity according to Nakamura and Zhu (2010).
- If the first parameter is not a `barotropic.State`, `grid` must be
specified.
- `levels` specifies the number of contours generated for the equivalent
latit... | 5,357,073 |
def bmm_update(context, bmm_id, values, session=None):
"""
Updates Bare Metal Machine record.
"""
if not session:
session = get_session_dodai()
session.begin()
bmm_ref = bmm_get(context, bmm_id, session=session)
bmm_ref.update(values)
bmm_ref.save(session=session)
return... | 5,357,074 |
def to_unified(entry):
"""
Convert to a unified entry
"""
assert isinstance(entry, StatementEntry)
date = datetime.datetime.strptime(entry.Date, '%d/%m/%Y').date()
return UnifiedEntry(date, entry.Reference, method=entry.Transaction_Type, credit=entry.Money_In,
debit=entr... | 5,357,075 |
def evaluate(args, model, data):
""" This function samples images via Gibbs sampling chain in order to inspect the marginal distribution of the
visible variables.
Args:
args: parse_args input command-line arguments (hyperparameters).
model: model to sample from.
data: data to measur... | 5,357,076 |
def call_crawlers(dataset_list):
"""
Call crawlers to get latest data.
"""
for dataset_name in dataset_list:
crawler_module = importlib.import_module(
'thousandaire.crawlers.%s' % dataset_name)
crawler = crawler_module.Crawler(dataset_name)
cur_data = DataLoader([data... | 5,357,077 |
def test_tree():
"""Trains a Tree"""
X, y = getdata()
clf = buildtree(X, y)
clf.predict([[2., 2.]]) | 5,357,078 |
def edit_profile():
"""
POST endpoint that edits the student profile.
"""
user = get_current_user()
json = g.clean_json
user.majors = Major.objects.filter(id__in=json['majors'])
user.minors = Minor.objects.filter(id__in=json['minors'])
user.interests = Tag.objects.filter(id__in=json['i... | 5,357,079 |
def _stringcoll(coll):
"""
Predicate function to determine whether COLL is a non-empty
collection (list/tuple) containing only strings.
Arguments:
- `coll`:*
Return: bool
Exceptions: None
"""
if isinstance(coll, (list, tuple)) and coll:
return len([s for s in coll if isinst... | 5,357,080 |
def create_user_db_context(
database=Database(),
*args, **kwargs):
"""
Create a context manager for an auto-configured :func:`msdss_users_api.tools.create_user_db_func` function.
Parameters
----------
database : :class:`msdss_base_database:msdss_base_database.core.Database`
Database... | 5,357,081 |
def config(base_config):
""":py:class:`nemo_nowcast.Config` instance from YAML fragment to use as config for unit tests."""
config_file = Path(base_config.file)
with config_file.open("at") as f:
f.write(
textwrap.dedent(
"""\
file group: allen
... | 5,357,082 |
def enable_image_registry_default_route():
"""Enables the Image Registry default route with the Custom Resource
Definition
https://docs.openshift.com/container-platform/latest/registry/configuring-registry-operator.html#registry-operator-default-crd_configuring-registry-operator
"""
oc_patch_args ... | 5,357,083 |
def check_nodes_in_graph(graph, nodes):
"""
Validate if nodes are in graph
:param graph: graph that should contain nodes
:type graph: :graphit:GraphBase
:param nodes: nodes to check
:type nodes: :py:list
:return: True if validation successful
:rtype: :py:bool
:raises ... | 5,357,084 |
def __check_complete_list(list_, nb_max, def_value):
"""
make sure the list is long enough
complete with default value if not
:param list_: list to check
:param nb_max: maximum length of the list
:param def_value: if list too small,
completes it with this value
:return: boolean,... | 5,357,085 |
def _fill_function(func, globals, defaults, closure, dct):
""" Fills in the rest of function data into the skeleton function object
that were created via _make_skel_func().
"""
func.func_globals.update(globals)
func.func_defaults = defaults
func.func_dict = dct
if len(closure) ... | 5,357,086 |
def symlink_gfid_to_path(brick, gfid):
"""
Each directories are symlinked to file named GFID
in .glusterfs directory of brick backend. Using readlink
we get PARGFID/basename of dir. readlink recursively till
we get PARGFID as ROOT_GFID.
"""
if gfid == ROOT_GFID:
return ""
out_pa... | 5,357,087 |
def main():
"""
Main function
"""
argument_spec = vmware_argument_spec()
argument_spec.update(
state=dict(type='str', default='present', choices=['present', 'absent']),
datacenter=dict(type='str', required=False, aliases=['datacenter_name']),
cluster=dict(type='str', require... | 5,357,088 |
def resize_img(img, size, keep_aspect_ratio=True):
"""resize image using pillow
Args:
img (PIL.Image): pillow image object
size(int or tuple(in, int)): width of image or tuple of (width, height)
keep_aspect_ratio(bool): maintain aspect ratio relative to width
Returns:
(PIL.... | 5,357,089 |
def calculate_clip_from_vd(circuit: DiodeCircuit, v_d: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
"""
:returns: v_in, v_out
"""
Rs = circuit.Rs
Is = circuit.diode.Is
n = circuit.diode.n
Vt = circuit.diode.Vt
Rp = circuit.Rp
Rd = circuit.Rd
Id = Is * (np.exp(v_d / (n * Vt)) - 1.0)
Vd = v_d
... | 5,357,090 |
def make_timeseries(input_files, roi_file, output_dir, labels=None,
regressor_files=None, regressors=None, as_voxels=False,
discard_scans=None, n_jobs=1, **masker_kwargs):
"""Extract timeseries data from input files using an roi file to demark
the region(s) of interest(s... | 5,357,091 |
def tex_coord(x, y, n=8):
""" Return the bounding vertices of the texture square.
"""
m = 1.0 / n
dx = x * m
dy = y * m
return dx, dy, dx + m, dy, dx + m, dy + m, dx, dy + m | 5,357,092 |
def compareImage(renwin, img_fname, threshold=10):
"""Compares renwin's (a vtkRenderWindow) contents with the image
file whose name is given in the second argument. If the image
file does not exist the image is generated and stored. If not the
image in the render window is compared to that of the figu... | 5,357,093 |
def uniindtemp_compute(da: xr.DataArray, thresh: str = "0.0 degC", freq: str = "YS"):
"""Docstring"""
out = da - convert_units_to(thresh, da)
out = out.resample(time=freq).mean()
out.attrs["units"] = da.units
return out | 5,357,094 |
def verify_parentheses(parentheses_string: str) -> bool:
"""Takes input string of only '{},[],()' and evaluates to True if valid."""
open_parentheses = []
valid_parentheses_set = {'(', ')', '[', ']', '{', '}'}
parentheses_pairs = {
')' : '(',
']' : '[',
'}' : '{'
}
... | 5,357,095 |
def _stableBaselineTrainingAndExecution(env, typeAgent, numberOptions, mode):
""""Function to execute Baseline algorithms"""
if typeAgent == 2:
model = A2C(MlpPolicy, env, verbose=1)
else:
model = PPO2(MlpPolicy, env, verbose=1)
print("Training model....")
startTime = time()
mo... | 5,357,096 |
def string_to_hexadecimale_device_name(name: str) -> str:
"""Encode string device name to an appropriate hexadecimal value.
Args:
name: the desired name for encoding.
Return:
Hexadecimal representation of the name argument.
"""
length = len(name)
if 1 < length < 33:... | 5,357,097 |
def createTeam(
firstIndex, secondIndex, isRed, first = 'DefensiveAgent', second = 'OffensiveAgent'):
"""
This function should return a list of two agents that will form the
team, initialized using firstIndex and secondIndex as their agent
index numbers. isRed is True if the red team is being created, ... | 5,357,098 |
def str_dice(die):
"""Return a string representation of die.
>>> str_dice(dice(1, 6))
'die takes on values from 1 to 6'
"""
return 'die takes on values from {0} to {1}'.format(smallest(die), largest(die)) | 5,357,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.