content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def dictize(aniter, mode, initial=None):
"""iter must contain (key,value) pairs. mode is a string, one of: replace, keep,
tally, sum, append, or a custom function that takes two arguments.
replace: default dict behavior. New value overwrites old if key exists. This
is essentially a pass-thru.
... | 5,306,600 |
async def test_loading_while_delay(hass, store, hass_storage):
"""Test we load new data even if not written yet."""
await store.async_save({'delay': 'no'})
assert hass_storage[store.key] == {
'version': MOCK_VERSION,
'key': MOCK_KEY,
'data': {'delay': 'no'},
}
store.async_de... | 5,306,601 |
def flatten_composition(EXX):
"""Convert the ternary composition of B2 into
a binary by taking out the vacancy composition
degree of freedom.
:EXX: ndarray (E, xa, xb)
:returns: ndarray (E,x)
"""
E=EXX[:,0]
a=EXX[:,1]
b=EXX[:,2]
xNi=1+a-b
xAl=1-a
xVa=b
x=xNi/(xNi+... | 5,306,602 |
def param_Valide_Algo_3(Lambda) :
"""Il faut que lambda soit valide"""
return valide_Lambda(Lambda) | 5,306,603 |
def migrate(migrator, database, fake=False, **kwargs):
"""Write your migrations here."""
@migrator.create_model
class Medic(pw.Model):
id = pw.AutoField()
academic = pw.TextField()
city = pw.TextField()
name = pw.TextField()
specialty = pw.TextField()
title = ... | 5,306,604 |
def extract_from(treatment):
"""Extract the data from the genus treatment.
Parameters:
treatment - a pdf file name of the genus treatment.
data_type - "locations" or "classifiers"
Returns a dict of results with the following format
"locations" - a string of species names and locat... | 5,306,605 |
def make_snapshots_of_each_scope_vars(
*, locals_: Dict[str, Any], globals_: Dict[str, Any]) -> str:
"""
Make snapshots of each scope's variables.
Parameters
----------
locals_ : dict
Local scope's variables.
globals_ : dict
Global scope's variables.
Ret... | 5,306,606 |
def test_diff_manifest_missing_files(test_data, testname, monkeypatch):
"""Diff two fileinfo lists having one file's name changed.
"""
monkeypatch.chdir(test_data)
with Archive().open(Path("archive.tar")) as archive:
manifest_ref = archive.manifest
base_dir = Path("base")
mtime_base = os... | 5,306,607 |
def get_registered_themes():
"""Get registered themes.
Gets a list of registered themes in form of tuple (plugin name, plugin
description). If not yet auto-discovered, auto-discovers them.
:return list:
"""
return get_registered_plugins(theme_registry) | 5,306,608 |
def polyfit2d(pmap):
"""
Fit a 2nd order polynomial surface (paraboloid) to the map of Pearson's correlation
coefficients (pmap) and return a list (a) containing the fit parameters.
Model: C(i, j) = a0*i*i + a1*j*j + a2*i*j + a3*i + a4*j + a5
where (i, j) are the rows and columns in pmap.
:pa... | 5,306,609 |
def apriori_zc(data_set, data_set_dict, min_support=5):
"""
Apriori算法过程
:param data_set: 数据集
:param min_support: 最小支持度,默认值 0.5
:return:
"""
c1 = init_c1(data_set_dict, min_support)
data = map(set, data_set) # 将dataSet集合化,以满足scanD的格式要求
freq_items = {}
l1 = scan_data(data, c1, min... | 5,306,610 |
def find_replace_line_endings(fp_readlines):
"""
special find and replace function
to clean up line endings in the file
from end or starttag characters
"""
clean = []
for line in fp_readlines:
if line.endswith("=<\n"):
line = line.replace("<\n", "lt\n")
clean.appe... | 5,306,611 |
def process_properties(partition, vfunction, params):
"""
Process the properties specified in the 'properties' module parameter,
and return two dictionaries (create_props, update_props) that contain
the properties that can be created, and the properties that can be updated,
respectively. If the reso... | 5,306,612 |
def drop_same_type_existing_controllers(net, this_ctrl_type, index=None, matching_params=None,
**kwargs):
"""
Drops same type controllers to create a new controller of this type.
INPUT:
**net** - pandapower net
**this_ctrl_type** (controller object or... | 5,306,613 |
def resize_and_project(features,
resize_size,
num_projection_layers,
num_projection_channels):
"""Resizes input features and passes them through a projection head.
Args:
features: A [batch_size, height, width, num_channels] tensor
resize_... | 5,306,614 |
def test_plot_operator_counts(fig_test, fig_ref):
"""
Tests if the ``plot_operator_counts`` method returns the same figure as a
reference plot below.
"""
result = get_result(Sentinel())
# Tested plot
result.plot_operator_counts(fig_test)
# Reference plot
get_operator_plot(fig_ref,
... | 5,306,615 |
def send_data_to_backend():
"""
Sends the msgpack binary data to the backend
"""
thestr = StringIO(mydata.getvalue())
post_response = requests.post(url=HTTP_POST_URL, data=thestr)
print "HTTP Response:" + str(post_response)
mydata.truncate(0) | 5,306,616 |
def _download_file_from_google_drive(id_file, destination, proxy=None):
"""
From https://stackoverflow.com/a/39225272/8195528.
"""
def get_confirm_token(response):
for key, value in response.cookies.items():
if key.startswith('download_warning'):
return value
... | 5,306,617 |
def generate_text_consumer(filter_pattern: Optional[str]) -> ObservabilityEventConsumer:
"""
Creates a console event consumer, which is used to display events in the user's console
Parameters
----------
filter_pattern : str
Filter pattern is used to display certain words in a different patt... | 5,306,618 |
def verify_lacp_link_state(device,
interface,
links,
state_name,
expected_state,
max_time=30,
check_interval=10):
""" Verify links of lag interface
... | 5,306,619 |
def wfc3_bandpass(request):
"""Fixture to read in the pysynphot bandpass for a WFC3 filter"""
return nebulio.Bandpass(','.join(['wfc3', 'uvis1', request.param])) | 5,306,620 |
def adaptive_basic_iterative_method(sess, model, X, Y, eps, eps_iter, nb_iter=50,
clip_min=None, clip_max=None, batch_size=256,
log_dir = None, model_logits = None,
binary_steps =2, attack_type = "bim-b",
... | 5,306,621 |
def exists(profile, name):
"""Check if a role exists.
Args:
profile
A profile to connect to AWS with.
name
The name of a role.
Returns:
True if it exists, False if it doesn't.
"""
result = fetch_by_name(profile, name)
return len(result) > 0 | 5,306,622 |
def _right_h5(value: list, fmt: str, meta: dict) -> dict:
"""Right-aligned header 5."""
return Plain([RawInline(fmt, '<h5 style="text-align:right !important">')]
+ value + [RawInline(fmt, '</h5>')]) | 5,306,623 |
def find_long_period(bool_array: List, min_duration:int, scale:int) -> List:
"""find_long_period. identify long period of motion
:param bool_array: bool array with check of motion
:type bool_array: List
:param min_duration: minimum duration in index unit
:type min_duration: int
:param scale: sc... | 5,306,624 |
def worker_cmd():
"""Start a Celery worker."""
w = worker.worker(app=app)
w.run(loglevel='INFO') | 5,306,625 |
def test_success(database):
""" Test that TAS values can be found, and null matches work correctly """
approp = AppropriationFactory(other_budgetary_resources_cpe=600, contract_authority_amount_cpe=100,
borrowing_authority_amount_cpe=200, spending_authority_from_of_cpe=300)
... | 5,306,626 |
def nnc_compile(model: torch.nn.Module, example_inputs) -> torch.nn.Module:
"""
nnc_compile(model, example_inputs) returns a function with the same args
as `model.forward`, with an extra argument corresponding to where the
output is stored. This function takes the inputs (which must be PyTorch
tenso... | 5,306,627 |
def _DeleteGridCellMetaData(zoom, x, y, uss_id):
"""Removes the USS entry in the metadata stored in a specific GridCell.
Removes the USS entry in the metadata using optimistic locking behavior.
Args:
zoom: zoom level in slippy tile format
x: x tile number in slippy tile format
y: y tile number in sl... | 5,306,628 |
def compute_speed(pos, pos_tt):
"""Compute boolean of whether the speed of the animal was above a threshold
for each time point
Parameters
----------
pos: np.ndarray(dtype=float)
in meters
pos_tt: np.ndarray(dtype=float)
in seconds
smooth_param: float, optional
Returns
... | 5,306,629 |
def layer(ctx,_layer=None,_overwrite=False,_all=False):
"""
update layer(s) in geonode
"""
if not _layer and not _all:
print("Use either --layer or --all option")
return
if _all:
if _overwrite:
importlayer='cd {geonode_dir};python ./manage.py importlayers -o -v3... | 5,306,630 |
def test_config_without_server_confluence_config(full_config) -> None:
"""
A config without Server/Confluence node must be created to None value.
"""
del full_config["Server"]["Confluence"]
with pytest.raises(Exception):
Config(full_config) | 5,306,631 |
def unitsapi_Check(*args):
"""
* Checks the coherence between the quantity <aQuantity> and the unit <aUnits> in the current system and //! returns False when it's WRONG.
:param aQuantity:
:type aQuantity: char *
:param aUnit:
:type aUnit: char *
:rtype: bool
"""
return _UnitsAPI.unit... | 5,306,632 |
def read_txt_file(file_path, n_num=-1, code_type='utf-8'):
"""
read .txt files, get all text or the previous n_num lines
:param file_path: string, the path of this file
:param n_num: int, denote the row number decided by \n, but -1 means all text
:param code_type: string, the code of this file
... | 5,306,633 |
def load_cluster(args):
"""
Load a single CourtListener cluster with its opinions from disk, and return metadata.
This is called within a process pool; see ingest_courtlistener for how it's used.
"""
cluster_member, opinions_dir = args
with cluster_member.open() as f:
cluster = j... | 5,306,634 |
def annotate(data, image_column=None, annotation_column='annotations', image_similarity=True):
"""
Annotate your images loaded in either an SFrame or SArray Format
The annotate util is a GUI assisted application used to create labels in
SArray Image data. Specifying a column, with dtype Ima... | 5,306,635 |
def test_fk5_seps():
"""
This tests if `separation` works for FK5Coordinate objects.
This is a regression test for github issue #891
"""
from astropy.coordinates import FK5
a = FK5(1., 1., unit=('deg', 'deg'))
b = FK5(2., 2., unit=('deg', 'deg'))
a.separation(b) | 5,306,636 |
def ring(wav, buzzer, trigger, log):
"""Ring the school bell
"""
log.info("ring!")
threads = []
for remote, command in trigger.items():
threads.append(Thread(target=remote_ring,
args=(remote, [command, wav, '&'], log)))
threads.append(Thread(target=play, ar... | 5,306,637 |
def ParseSuccessMsg(msg):
"""Attempt to parse the message for a user_op_manager SUCCESS line and extract user, device, op, class, and method.
Return None otherwise.
"""
parsed = re.match(kSuccessMsgRe, msg)
if not parsed:
return None
try:
user, device, op, class_name, method_name = parsed.groups()
... | 5,306,638 |
def pow(x, y):
"""Return the logarithm of x with base y (default to e)"""
if x <= 0 and not isinstance(y, int):
raise ValueError(f"Exponent must be an integer if negative base. Received base {x} with exponent {y}.")
return math.pow(x, y) | 5,306,639 |
def main():
"""Main function to convert the dataset into JAMS."""
parser = argparse.ArgumentParser(description=
"Converts old jams2 files to the JAMS 0.2 version.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("in_dir",
action="store",
... | 5,306,640 |
def GetWavelength():
""" Get a single frequency reading """
return getwave(DZERO) | 5,306,641 |
def sum_while_same(xs, x):
"""Sum points for same date representation"""
if not xs:
return [x]
if xs[-1][0] == x[0]:
return xs[:-1] + [(xs[-1][0], xs[-1][1] + x[1])]
else:
return xs + [x] | 5,306,642 |
def main():
"""Main function"""
module = GcpModule(
argument_spec=dict(
state=dict(default='present', choices=['present', 'absent'], type='str'),
name=dict(required=True, type='str'),
type=dict(required=True, type='str', choices=['A', 'AAAA', 'CAA', 'CNAME', 'MX', 'N... | 5,306,643 |
def download_artifact_from_aml_uri(uri: str, destination: str, datastore_operation: DatastoreOperations):
"""Downloads artifact pointed to by URI of the form `azureml://...` to destination
:param str uri: AzureML uri of artifact to download
:param str destination: Path to download artifact to
:param Da... | 5,306,644 |
def get_file_metadata(file_path, if_noent=None):
"""
Get a string with the metadata for a file.
For purposes of this function, 'file' includes directories,
symlinks, etc.
Format is similar to 'ls -l':
mode links owner group size mtime name
Does not follow symlinks.
Returns if_no... | 5,306,645 |
def get_pdf(work_dir,obsid,manual,manual_cutoff,obsname,doplot,impose_xlim,impose_ylim,ylim1,ylim2,ylim1_diff,ylim2_diff):
"""
Given the working directory, OBSID and object name, create a PDF which has
...
"""
from matplotlib.backends.backend_pdf import PdfPages
filename = work_dir +... | 5,306,646 |
def l1_loss(pred_traj, pred_traj_gt):
"""
Input:
:param pred_traj: Tensor of shape (batch, seq_len)/(batch, seq_len). Predicted trajectory along one dimension.
:param pred_traj_gt: Tensor of shape (batch, seq_len)/(batch, seq_len).
Groud truth predictions along one dimension.
... | 5,306,647 |
def calculate_summary_statistics(processed_fx_obs, categories):
"""
Calculate summary statistics for the processed data using the provided
categories and all metrics defined in :py:mod:`.summary`.
Parameters
----------
proc_fx_obs : datamodel.ProcessedForecastObservation
categories : list o... | 5,306,648 |
def create_stage_file(stage_file_path):
"""Cria um arquivo para conter a lista de estágios
já realizados"""
directory = os.path.dirname(stage_file_path)
if not os.path.exists(directory):
os.makedirs(directory, exist_ok=True)
register_latest_stage(stage_file_path, "") | 5,306,649 |
def splitting_division_semi(f, group, table, sample_indices, splitting_fold):
"""Saving indices of each splitting group to a list that will be fed later to the deep learning model.
Specific for the semi_resampling strategy, since there only training and validation need to be splitted."""
t0 = time.time()
... | 5,306,650 |
def draw_element(t, element):
"""
Parameters:
t, turtle object
element, str representing an element
Function:
Draws a colored dot if the element is something other than C
"""
dot_size = 15
element_dict = {
"N": "blue",
"O": "red",
"S": ... | 5,306,651 |
def extract(keys: Tuple[str, ...], state: State) -> Tuple[Any, ...]:
"""Extract multiple values from dictionary.
Args:
keys: Tuple of key whose values should be extracted from the dictionary.
state: The dictionary where values need to be extracted from.
Returns:
Tuple with values f... | 5,306,652 |
def hiram(place, sLink, stats, name, pronouns):
"""
Agender scientist studying a "secret" project
"I'm a scientist"
:param place: where you are talking to Hiram
:param sLink: your level of friendship with Hiram
:param name: str, your name
:param pronouns: list of your pronouns in the format ... | 5,306,653 |
def distorted_bounding_box_crop(image,
bbox,
min_object_covered=0.1,
aspect_ratio_range=(0.75, 1.33),
area_range=(0.05, 1.0),
max_attempts=100):
"""Generate... | 5,306,654 |
def mkdir_p(path):
"""
It creates directory recursively if it does not already exist
"""
import errno
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise | 5,306,655 |
def constructBoard(numCards=52):
""""Create a board out of a shuffled deck of numCards
numCards(default 52): number of cards in the board (even #, 8-52)"""
deck = pd.Deck()
## Split the deck using the initial set of cards if numCards < 52
if numCards < 52:
deck = splitDeck(deck, numCards)
... | 5,306,656 |
def ChenFoxLyndon(s: [list, tuple, str]) -> [SupportsIndex, Iterable, Sized]:
"""
Decompose s into Lyndon words according to the Chen-Fox-Lyndon theorem.
The arguments are the same as for ChenFoxLyndonBreakpoints but the
return values are subsequences of s rather than indices of breakpoints.
"""
... | 5,306,657 |
def list_branches(build, plan_id):
"""List branches for build plan."""
LOG.debug("Getting plan branches %s", plan_id)
try:
handler = BuildHandler(build.get_config())
handler.list_plan_branches(plan_id)
except Exception:
traceback.print_exc()
raise click.ClickException("L... | 5,306,658 |
def load_config():
"""
Load plugin configurations.
:return: a namespace containing the configurations
:rtype: SimpleNamespace
"""
# load
with open(sys.argv[1], 'r') as f:
plugin_config = yaml.safe_load(f)
resources = plugin_config.get('resources', [])
# validation
va... | 5,306,659 |
def get_short_description(dict, value):
"""Get layout class based on value."""
return dict.get(value, {}).get('short_description') | 5,306,660 |
def cdlconcealbabyswallow(
client,
symbol,
timeframe="6m",
opencol="open",
highcol="high",
lowcol="low",
closecol="close",
):
"""This will return a dataframe of conceal baby swallow for the given symbol across
the given timeframe
Args:
client (pyEX.Client): Client
... | 5,306,661 |
def rectangular_hollow_section(b: float, d: float, t: float, r_out: float, n_r: int, material: pre.Material = pre.DEFAULT_MATERIAL) -> Geometry:
"""Constructs a rectangular hollow section (RHS) centered at *(b/2, d/2)*, with depth *d*, width *b*,
thickness *t* and outer radius *r_out*, using *n_r* points to con... | 5,306,662 |
def _is_subexpansion_optional(query_metadata, parent_location, child_location):
"""Return True if child_location is the root of an optional subexpansion."""
child_optional_depth = query_metadata.get_location_info(child_location).optional_scopes_depth
parent_optional_depth = query_metadata.get_location_info(... | 5,306,663 |
def get_uuid(key, value, is_list=False, is_optional=False, default=None, options=None):
"""
Get the value corresponding to the key and converts it to `uuid`/`list(uuid)`.
Args:
key: the dict key.
value: the value to parse.
is_list: If this is one element or a list of elements.
... | 5,306,664 |
def to_tensor(data):
"""Convert objects of various python types to :obj:`torch.Tensor`.
Supported types are: :class:`numpy.ndarray`, :class:`torch.Tensor`,
:class:`Sequence`, :class:`int` and :class:`float`.
"""
if isinstance(data, torch.Tensor):
return data
elif isinstance(data, np.nda... | 5,306,665 |
def _filter_labels(text, labels, allowed_labels):
"""Keep examples with approved labels.
:param text: list of text inputs.
:param labels: list of corresponding labels.
:param allowed_labels: list of approved label values.
:return: (final_text, final_labels). Filtered version of text and labels
... | 5,306,666 |
def _Itype():
"""Loop iterator data type."""
return tf.int32 if use_xla() else tf.int64 | 5,306,667 |
def Q(fastev,lagev,fastrc,lagrc):
"""Following Wuestefeld et al. 2010"""
omega = math.fabs((fastev - fastrc + 3645)%90 - 45) / 45
delta = lagrc / lagev
dnull = math.sqrt(delta**2 + (omega-1)**2) * math.sqrt(2)
dgood = math.sqrt((delta-1)**2 + omega**2) * math.sqrt(2)
if dnull < dgood:
re... | 5,306,668 |
def w_median(a, weights):
"""
Compute the weighted median of a 1D numpy array.
Parameters
----------
a : ndarray
Input array (one dimension).
weights : ndarray
Array with the weights of the same size of `data`.
Returns
-------
median : float
The output value.
... | 5,306,669 |
def flatten(iterable):
"""
Generator to flatten an iterable by one level
"""
for i in iterable:
yield from i | 5,306,670 |
def find_source_files(
path,
extensions=(".ts", ".py"),
skip_folders=("tests", "test", "node_modules", "lib", ".git", ".ipynb_checkpoints"),
):
"""
Find source files in given `path`.
Parameters
----------
extensions: sequence
FIXME:
skip_folders: sequence
FIXME:
... | 5,306,671 |
def from_trends_top_query_by_category(n=NUM_KEYWORDS):
"""
Get a set of keyword objects by querying Google Trends
Each keyword obj is a dict with keys: keyword, category
"""
keyword_objs = []
for cid in POPULAR_CATEGORIES:
yearmonth = '2016'
pytrends = TrendReq(hl='en-US', t... | 5,306,672 |
def test_notification_settings_patch(
user, client, trigger_frequency, notification_type
):
"""Tests that the notifications settings returns a specific notification settings"""
if notification_type == NOTIFICATION_TYPE_MODERATOR:
channel = ChannelFactory.create(moderator_notifications=True)
... | 5,306,673 |
def get_document_type(doc):
"""
Return the document type lowercased
Parameters
----------
doc : str
The document string
Returns
-------
doc_type : str
The document type lowercased
"""
type_pattern=re.compile(r'<TYPE>[^\n]+')
type_i=[x[len('<TYPE>'):] for x i... | 5,306,674 |
def list_vpc_cidrs(vpc_id: str, account_id: str, region: str) -> List[str]:
"""
Returns a list of vpc cidrs associated with a given vpc.
Example use cases:
1. Get the CIDRs to install on other side of a peering.
2. See if there are any common CIDRs between two VPCs
:param vpc_id: A vpc id e.g. ... | 5,306,675 |
def test_fetch_incidents_with_incidents_and_full_last_run(mocker):
"""
Given
- Jira fetch incidents command
- Last run is populated with idOffset and lastCreatedTime
When
- Sending HTTP request and getting new issue
Then
- Verify last run is updated with the ticket id offset and are up... | 5,306,676 |
def read_fasta_box(fasta_text):
"""
:param fasta_text: Contents of text box containing FASTA format text
"""
header, seq = None, []
for line in fasta_text:
line = line.rstrip()
if line.startswith(">"):
if header:
yield(header.replace('>', ''), ''.join(seq)... | 5,306,677 |
def _cmd_debugger_getcontext(shell, _args: [str]) -> Result:
"""
Print basic set of registers for the active thread context."""
if not shell._debugger:
print("ERROR: /attach debugger first.")
return Result.HANDLED
info: Optional[Thread.Context] = shell._debugger.get_thread_context()
... | 5,306,678 |
def _multi_dot(arrays, order, i, j, precision):
"""Actually do the multiplication with the given order."""
if i == j:
return arrays[i]
else:
return np.dot(_multi_dot(arrays, order, i, order[i, j], precision),
_multi_dot(arrays, order, order[i, j] + 1, j, precision),
... | 5,306,679 |
def creation_date_demographics(route, label):
"""Return tweet creation dates."""
dataset = {'hateval': Tweet.objects.filter(hateval=True),
'offenseval': Tweet.objects.filter(offenseval=True),
'all': Tweet.objects.all()}
db = dataset.get(route)
if label == 'abuse':
... | 5,306,680 |
def array_check(lst):
"""
Function to check whether 1,2,3 exists in given array
"""
for i in range(len(lst)-2):
if lst[i] == 1 and lst[i+1] == 2 and lst[i+2] == 3:
return True
return False | 5,306,681 |
async def test_update_with_create_disconnect(
client: Prisma, user_id: str, method: str
) -> None:
"""Removing a relational field"""
user = await client.user.find_unique(
where={'id': user_id}, include={'posts': True}
)
assert user is not None
assert len(user.posts) == 0 # pyright: repo... | 5,306,682 |
def fastmri_unet_transform_multicoil(
kspace=None, mask=None, ground_truth=None, attrs=None, fname=None, slice_id=None
):
"""Transform to use as input to fastMRI's Unet model for multicoil data.
This is an adapted version of the code found in
`fastMRI <https://github.com/facebookresearch/fastMRI/blob/m... | 5,306,683 |
def stylize_cartoon(image, blur_ksize=3, segmentation_size=1.0,
saturation=2.0, edge_prevalence=1.0,
suppress_edges=True,
from_colorspace=colorlib.CSPACE_RGB):
"""Convert the style of an image to a more cartoonish one.
This function was primarily desi... | 5,306,684 |
def tca_model (image: Image.Image, order: int=2) -> ndarray:
"""
Compute a lens model which corrects transverse chromatic aberration.
Parameters:
image (PIL.Image): Input image.
order (int): Polynomial order of lens model. Quadratic or cubic model is ideal.
Returns:
ndarray: Re... | 5,306,685 |
def _group_result_from_fields(json, fields):
"""Helper that creates a group response object from the given fields.
:param json: original JSON string
:param fields: the JSON fields
:return: the created group response
:rtype: GroupResult
"""
result = api.GroupResult()
result.child_group... | 5,306,686 |
def debounce(wait):
""" Decorator that will postpone a function's
execution until after `wait` seconds
have elapsed since the last time it was invoked. """
def decorator(fn):
timer = None
def debounced(*args, **kwargs):
nonlocal timer
def call_it():
... | 5,306,687 |
def __post(url, body, params=dict()):
"""
Internal post
:param url:
:param body:
:param params:
:return:
"""
try:
headers = {'Content-type': 'application/json'}
requests.post(url, data=body, params=params, headers=headers)
except Exception as e:
print(e) | 5,306,688 |
def list_difference(list_1: List[Any], list_2: List[Any]) -> List[Any]:
""" This Function that takes two lists as parameters
and returns a new list with the values that are in l1, but NOT in l2"""
differ_list = [values for values in list_1 if values not in list_2]
return differ_list | 5,306,689 |
def train_single_cnn(params):
"""
Trains a single CNN and writes:
- logs obtained with Tensorboard during training,
- best models obtained according to two metrics on the validation set (loss and balanced accuracy),
- for patch and roi modes, the initialization state is saved as it is id... | 5,306,690 |
def test_generator_tuple_repeat_repeat_1():
"""
test generator tuple repeat repeat 1
"""
logger.info("Test 1D Generator : 0 - 63")
# apply dataset operations
data1 = ds.GeneratorDataset(generator_1d, ["data"])
data1 = data1.repeat(2)
data1 = data1.repeat(3)
iter1 = data1.create_tupl... | 5,306,691 |
def truncate_msg(msg, max_len=2000):
"""
Truncate a message string so it doesn't get lost (todo: automatically do this in realtime logger class)
"""
if len(msg) <= max_len:
return msg
else:
trunc_info = '<log message truncated to fit buffer>'
assert len(trunc_info) < max_len
... | 5,306,692 |
def rlsp(
_run,
mdp,
s_current,
p_0,
horizon,
temp=1,
epochs=1,
learning_rate=0.2,
r_prior=None,
r_vec=None,
threshold=1e-3,
check_grad_flag=False,
solver="value_iter",
reset_solver=False,
solver_iterations=1000,
):
"""The RLSP algorithm."""
check_in("... | 5,306,693 |
def load_vsmi() -> pd.DataFrame:
"""
"""
vsmi = pd.read_csv("../statistics/h_vsmi_30.csv", sep=";")
vsmi.columns = vsmi.columns.str.lower()
vsmi.rename(columns={"indexvalue": "VSMI"}, inplace=True)
vsmi["date"] = pd.to_datetime(vsmi["date"], format="%d.%m.%Y")
vsmi.set_index("date", inplace=... | 5,306,694 |
def create_app(context: GhiaContext = None) -> Flask:
"""
Create the Flask app.
Args:
context (GhiaContext, optional): If no context is provided a new default one is automatically created. Defaults to None.
Returns:
Flask: Newly created Flask application.
"""
return ghia_web_logic.create_app(context=cont... | 5,306,695 |
def shift_until_PSD(M, tol):
""" Add the identity until a p x p matrix M has eigenvalues of at least tol"""
p = M.shape[0]
mineig = np.linalg.eigh(M)[0].min()
if mineig < tol:
M += (tol - mineig) * np.eye(p)
return M | 5,306,696 |
def test_pydotprint_cond_highlight():
"""
This is a REALLY PARTIAL TEST.
I did them to help debug stuff.
"""
# Skip test if pydot is not available.
if not theano.printing.pydot_imported:
raise SkipTest('pydot not available')
x = tensor.dvector()
f = theano.function([x], x * 2)... | 5,306,697 |
def NestItem(parent, item):
"""Adds the given item to a (multi-column) row beneath the parent model or
item.
@details Since \c{QStandardItemModel} is not supposed to be subclassed,
this hack automatically adds a second information column (when
appropriate) using an attribute f... | 5,306,698 |
def map_all_modules(dataset, mapping, hce_columns):
"""Map and save data for all modules to binary symptom files.
Two files are saved for each module. The first contains the fully mapped
data. The second includes the same columns, but all ``hce_columns`` have
been set to missing. The value for missing ... | 5,306,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.