content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def display():
""" duisplay the banner """
print(color(" ββββββββββββββββββββββββββββββββββββββββββββ", fg="#b61042"))
print(
color(" β ", fg="#b61042")
+ color(f"Ο-hole 5 list tool v{__version__}", "#FFF")
+ color(" β", fg="#b61042")
)
print(color(" β... | 5,345,600 |
def calculate_class_probabilities(summaries, row) -> dict():
"""
Calculate the probability of a value using the Gaussian Probability Density Function from inputs:
summaries: prepared summaries of dataset
row: a row in the dataset for predicting its label (a row of X_test)
This function uses th... | 5,345,601 |
def discard_missing_files(df: pd.DataFrame, path_colname: str) -> pd.DataFrame:
"""Discard rows where the indicated file does not exist or has
filesize 0.
Log a warning with the number of rows discarded, if not zero.
Args:
df
path_colname: Name of `df` column that specifies paths to ch... | 5,345,602 |
def find(sequence: Sequence, target_element: Any) -> int:
"""Find the index of the first occurrence of target_element in sequence.
Args:
sequence: A sequence which to search through
target_element: An element to search in the sequence
Returns:
The index of target_element's first oc... | 5,345,603 |
def read_time_data(fname, unit):
"""
Read time data (csv) from file and load into Numpy array
"""
data = np.loadtxt(fname, delimiter=',')
t = data[:,0]
x = data[:,1]*unit
f = interp1d(t, x, kind='linear', bounds_error=False, fill_value=x[0])
return f | 5,345,604 |
def configure_concepts(cursor,load_concepts,author):
"""This method configures concepts when a NEW CONFIGURATION is performed"""
if author == 'admin':
to_add = 'Manual and Automatic'
elif author == 'robot':
to_add = 'Automatic'
for usecase in load_concepts:
disease = ''
... | 5,345,605 |
def main():
"""run the test suite"""
usage = "usage: %prog [options] file"
nose.run() | 5,345,606 |
def get_compliance_detail(PolicyId=None, MemberAccount=None):
"""
Returns detailed compliance information about the specified member account. Details include resources that are in and out of compliance with the specified policy. Resources are considered noncompliant for AWS WAF and Shield Advanced policies if t... | 5,345,607 |
async def feature(message: discord.Message, plugin: plugin_in_req, req_id: get_req_id=None):
""" Handle plugin feature requests where plugin is a plugin name.
See `{pre}plugin` for a list of plugins. """
if req_id is not None:
assert feature_exists(plugin, req_id), "There is no such feature."
... | 5,345,608 |
def for_I():
""" Upper case Alphabet letter 'I' pattern using Python for loop"""
for row in range(6):
for col in range(5):
if row in (0,5) or col==2:
print('*', end = ' ')
else:
... | 5,345,609 |
def run(connection, args):
"""Prints it out based on command line configuration.
Exceptions:
- SAPCliError:
- when the given type does not belong to the type white list
"""
types = {'program': sap.adt.Program, 'class': sap.adt.Class, 'package': sap.adt.Package}
try:
... | 5,345,610 |
def read_nli_data(p: Path) -> List[Dict]:
"""Read dataset which has been converted to nli form"""
with open(p) as f:
data = json.load(f)
return data | 5,345,611 |
def stanley_control(state, cx, cy, cyaw, last_target_idx):
"""
Stanley steering control.
:param state: (State object)
:param cx: ([float])
:param cy: ([float])
:param cyaw: ([float])
:param last_target_idx: (int)
:return: (float, int)
"""
current_target_idx, error_front_axle = c... | 5,345,612 |
def get_predictions(my_map, reviews, restaurants):
"""
Get the topic predictions for all restaurants.
Parameters:
my_map - the Map object representation of the current city
reviews - a dictionary of reviews with restaurant ids for keys
restaurants - a list of restaurants of the curr... | 5,345,613 |
def pin_memory_inplace(tensor):
"""Register the tensor into pinned memory in-place (i.e. without copying)."""
if F.backend_name in ['mxnet', 'tensorflow']:
raise DGLError("The {} backend does not support pinning " \
"tensors in-place.".format(F.backend_name))
# needs to be writable to a... | 5,345,614 |
def decode_token(token, secret_key):
"""
θ§£ε―websocket token
:param token:
:param secret_key:
:return:
"""
info = jwt.decode(token, secret_key, algorithms=['HS256'])
return info | 5,345,615 |
def assertUrisEqual(testcase, expected, actual):
"""Test that URIs are the same, up to reordering of query parameters."""
expected = urllib.parse.urlparse(expected)
actual = urllib.parse.urlparse(actual)
testcase.assertEqual(expected.scheme, actual.scheme)
testcase.assertEqual(expected.netloc, actual.netloc)
... | 5,345,616 |
def manning_friction_explicit(domain):
"""Apply (Manning) friction to water momentum
Wrapper for c version
"""
from .shallow_water_ext import manning_friction_flat
from .shallow_water_ext import manning_friction_sloped
xmom = domain.quantities['xmomentum']
ymom = domain.quantities['ymoment... | 5,345,617 |
def getPatternID(pattern_url):
"""asssumes pattern_url is a string, representing the URL of a ravelry pattern
e.g.https://www.ravelry.com/patterns/library/velvet-cache-cou
returns an int, the pattern ID
"""
permalink = pattern_url[41:]
with requests.Session() as a_session:
auth_name = "r... | 5,345,618 |
def make_multibonacci_modulo(history_length, limit):
"""Creates a function that generates the Multibonacci sequence modulo n."""
def sequence_fn(seq):
return np.sum(seq[-history_length:]) % limit
return sequence_fn | 5,345,619 |
def checkpoint_nets(config, shared, task_id, mnet, hnet, hhnet=None, dis=None):
"""Checkpoint the main and (if existing) the current hypernet.
Args:
config (argparse.Namespace): Command-line arguments.
shared (argparse.Namespace): Miscellaneous data shared among training
functions (... | 5,345,620 |
def _get_key(arguments):
"""
Determine the config key based on the arguments.
:param arguments: A dictionary of arguments already processed through
this file's docstring with docopt
:return: The datastore path for the config key.
"""
# Get the base path.
if arguments.get("felix"):
... | 5,345,621 |
def prepare_data_from_stooq(df, to_prediction = False, return_days = 5):
"""
Prepares data for X, y format from pandas dataframe
downloaded from stooq. Y is created as closing price in return_days
- opening price
Keyword arguments:
df -- data frame contaning data from stooq
return_days -- nu... | 5,345,622 |
def represents_int_above_0(s: str) -> bool:
"""Returns value evaluating if a string is an integer > 0.
Args:
s: A string to check if it wil be a float.
Returns:
True if it converts to float, False otherwise.
"""
try:
val = int(s)
if val > 0:
return True... | 5,345,623 |
def resnet18(pretrained=False, **kwargs):
"""Constructs a ResNet-18 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url('https://download.pytor... | 5,345,624 |
def sydney():
"""Import most recent Sydney dataset"""
d = {
'zip':'Sydney_geol_100k_shape',
'snap':-1,
}
return(d) | 5,345,625 |
def test_vm_entrypoint_stdin(mock_vm_from_stdin,
mock_vm_parser):
""" Test the vm entrypoint with stdin input. """
test_program = StringIO("""
A DATA 0
HLT A
""")
with patch("sys.stdin", test_program):
with patch("sys.stdout", new_callable=StringIO):
... | 5,345,626 |
async def apiAdminRoleNotExists(cls:"PhaazebotWeb", WebRequest:ExtendedRequest, **kwargs) -> Response:
"""
Optional keywords:
------------------
* msg `str` : (Default: None) * [Overwrites default]
* name `str` *
* role_id `str` *
Default message (*gets altered by optional keywords):
--------------------------... | 5,345,627 |
def format_non_date(value):
"""Return non-date value as string."""
return_value = None
if value:
return_value = value
return return_value | 5,345,628 |
def get_loss(loss_str):
"""Get loss type from config"""
def _get_one_loss(cur_loss_str):
if hasattr(keras_losses, cur_loss_str):
loss_cls = getattr(keras_losses, cur_loss_str)
elif hasattr(custom_losses, cur_loss_str):
loss_cls = getattr(custom_losses, cur_loss_str)
... | 5,345,629 |
def read(filename, columns, row_num):
"""test file reade"""
if not pd:
raise Exception("Module pandas is not found, please use pip install it.")
df = pd.read_csv(CSV_FILE)
count = 0
reader = FileReader(filename)
for _, x in enumerate(reader.get_next()):
for col in columns:
... | 5,345,630 |
def _hashable_policy(policy, policy_list):
"""
Takes a policy and returns a list, the contents of which are all hashable and sorted.
Example input policy:
{'Version': '2012-10-17',
'Statement': [{'Action': 's3:PutObjectAcl',
'Sid': 'AddCannedAcl2',
... | 5,345,631 |
def test_database(test_session):
"""Tests that the mock database was set up correctly"""
# execute
surveys = test_session.query(Survey).all()
# validation
assert len(surveys) == 2
for survey in surveys:
assert survey.name in ["survey1", "survey2"]
assert len(survey.responses) == ... | 5,345,632 |
def LF_CD_NO_VERB(c):
"""
This label function is designed to fire if a given
sentence doesn't contain a verb. Helps cut out some of the titles
hidden in Pubtator abstracts
"""
if len([x for x in nltk.pos_tag(word_tokenize(c.get_parent().text)) if "VB" in x[1]]) == 0:
if "correlates with... | 5,345,633 |
def has_file_allowed_extension(filename: PATH_TYPE, extensions: Tuple[str, ...]) -> bool:
"""Checks if a file is an allowed extension.
Args:
filename (string): path to a file
extensions (tuple of strings): extensions to consider (lowercase)
Returns:
bool: True if the filename ends ... | 5,345,634 |
def get_account_html(netid, timestamp=None):
"""
The Libraries object has a method for getting information
about a user's library account
"""
return _get_resource(netid, timestamp=timestamp, style='html') | 5,345,635 |
def AddBookkeepingOperators(model):
"""This adds a few bookkeeping operators that we can inspect later.
These operators do not affect the training procedure: they only collect
statistics and prints them to file or to logs.
"""
# Print basically prints out the content of the blob. to_file=1 routes t... | 5,345,636 |
def gcd_multiple(*args) -> int:
"""Return greatest common divisor of integers in args"""
return functools.reduce(math.gcd, args) | 5,345,637 |
def sleep_countdown(duration, steps=1):
"""Sleep that prints a countdown in specified steps
Input
duration: int for seconds of sleep duration
steps: in which steps the countdown is printed
Return
None: sys.stdout output in console
"""
sys.stdout.write("\r Seconds remaining:")
for remaining in range(dur... | 5,345,638 |
def chars_to_family(chars):
"""Takes a list of characters and constructs a family from them. So, A1B2
would be created from ['B', 'A', 'B'] for example."""
counter = Counter(chars)
return "".join(sorted([char + str(n) for char, n in counter.items()])) | 5,345,639 |
def get_config_properties(config_file="config.properties", sections_to_fetch = None):
"""
Returns the list of properties as a dict of key/value pairs in the file config.properties.
:param config_file: filename (string).
:param section: name of section to fetch properties from (if specified); all section... | 5,345,640 |
def process_speke():
"""Processes an incoming request from MediaLive, which is using SPEKE
A key is created and stored in DynamoDB."""
input_request = request.get_data()
# Parse request
tree = ET.fromstring(input_request)
content_id = tree.get("id")
kid = tree[0][0].get("kid")
iv = t... | 5,345,641 |
def yaml_save(filename, data):
"""
Save contents of an OrderedDict structure to a yaml file
:param filename: name of the yaml file to save to
:type filename: str
:param data: configuration data to to save
:type filename: str
:type data: OrderedDict
:returns: Nothing
"""
ordered... | 5,345,642 |
def start_model_server(handler_service=DEFAULT_HANDLER_SERVICE):
"""Configure and start the model server.
Args:
handler_service (str): python path pointing to a module that defines a class with the following:
- A ``handle`` method, which is invoked for all incoming inference requests to the... | 5,345,643 |
def merge(source: Dict, destination: Dict) -> Dict:
"""
Deep merge two dictionaries
Parameters
----------
source: Dict[Any, Any]
Dictionary to merge from
destination: Dict[Any, Any]
Dictionary to merge to
Returns
-------
Dict[Any, Any]
New dictionary with fi... | 5,345,644 |
async def async_api_adjust_volume_step(hass, config, directive, context):
"""Process an adjust volume step request."""
# media_player volume up/down service does not support specifying steps
# each component handles it differently e.g. via config.
# For now we use the volumeSteps returned to figure out ... | 5,345,645 |
def CreateHead(turtle):
"""
Creates the head for the puppy we're making!
:return: none
"""
turtle.penup()
turtle.speed(0)
turtle.setpos(100,-50)
turtle.pendown()
turtle.color("#bd9f60")
turtle.shape('arrow')
turtle.begin_fill()
for head in range(4):
turtle.left(90... | 5,345,646 |
def load_recordings(path: str, activityLabelToIndexMap: dict, limit: int = None) -> 'list[Recording]':
"""
Load the recordings from a folder containing csv files.
"""
recordings = []
recording_files = os.listdir(path)
recording_files = list(filter(lambda file: file.endswith('.csv'), recording_f... | 5,345,647 |
def minio_prometheus(storage_share):
"""Contact Minio's Prometheus URL to obtain storage information.
Obtains storage stats from Minio's Prometheus URL by extracting these
metrics:
minio_disk_storage_available_bytes
minio_disk_storage_total_bytes
minio_disk_storage_used_bytes
or for newer ... | 5,345,648 |
def add_storage_capacity(obj, info):
"""Sets storage parameters in change table.
:param powersimdata.input.change_table.ChangeTable obj: change table
:param list info: each entry is a dictionary. The dictionary gathers
the information needed to create a new storage device.
Required keys: "b... | 5,345,649 |
def load_img(path, grayscale=False, color_mode='rgb', target_size=None,
interpolation='nearest'):
"""Loads an image into PIL format.
# Arguments
path: Path to image file.
grayscale: DEPRECATED use `color_mode="grayscale"`.
color_mode: The desired image format. One of "graysc... | 5,345,650 |
def check_compatible_system_and_kernel_and_prepare_profile(args):
"""
Checks if we can do local profiling, that for now is only available
via Linux based platforms and kernel versions >=4.9
Args:
args:
"""
res = True
logging.info("Enabled profilers: {}".format(args.profilers))
lo... | 5,345,651 |
def crop_file(in_file, out_file, ext):
"""Crop a NetCDF file to give rectangle using NCO.
The file is automatically converted to [0,360] Β°E longitude format.
Args:
in_file: Input file path.
out_file: Output file path. It will not be overwritten.
ext: The rectangular region (extent)... | 5,345,652 |
def get_instance_string(params):
""" combine the parameters to a string mostly used for debug output
use of OrderedDict is advised
"""
return "_".join([str(i) for i in params.values()]) | 5,345,653 |
def recv_bgpmon_updates(host, port, queue):
"""
Receive and parse the BGP update XML stream of bgpmon
"""
logging.info ("CALL recv_bgpmon_updates (%s:%d)", host, port)
# open connection
sock = _init_bgpmon_sock(host,port)
data = ""
stream = ""
# receive data
logging.info(" + rece... | 5,345,654 |
def is_string_expr(expr: ast.AST) -> bool:
"""Check that the expression is a string literal."""
return (
isinstance(expr, ast.Expr)
and isinstance(expr.value, ast.Constant)
and isinstance(expr.value.value, str)
) | 5,345,655 |
def events_to_img(
xs: np.ndarray,
ys: np.ndarray,
tots: np.ndarray,
cluster_ids: np.ndarray,
x_img: np.ndarray,
y_img: np.ndarray,
minimum_event_num: int = 30,
extinguish_dist: float = 1.41422, # sqrt(2) = 1.41421356237
) -> np.ndarray:
"""
Conve... | 5,345,656 |
def plot_average_spatial_concs4lon(ds, year=2018, vars2use=None,
use_local_CVAO_area=False,
show_plot=False, dpi=320,
verbose=False,):
"""
Make a PDF of average spatial concentrations by level
"""
# ... | 5,345,657 |
def test_sleep_physionet_age_missing_recordings(physionet_tmpdir, subject,
recording, download_is_error):
"""Test handling of missing recordings in Sleep Physionet age fetcher."""
with pytest.raises(
ValueError, match=f'Requested recording {recording} ... | 5,345,658 |
def _chromosome_collections(df, y_positions, height, **kwargs):
"""
Yields BrokenBarHCollection of features that can be added to an Axes
object.
Parameters
----------
df : pandas.DataFrame
Must at least have columns ['chrom', 'start', 'end', 'color']. If no
column 'width', it ... | 5,345,659 |
def connect_colour(scene, attributes, ui_name, ui_mix_with,
ui_mix_spin, ui_mix_slider,
ui_strength_spin, ui_strength_slider):
"""Connect colour."""
ui_name.currentIndexChanged.connect(
lambda x: connect_combobox_abstract(x, scene, attributes, 'name', c.attribute_values(c.Colour), True))... | 5,345,660 |
def worker(job):
"""Run a single download job."""
logger = logging.getLogger("ncbi-genome-download")
ret = False
try:
if job.full_url is not None:
req = requests.get(job.full_url, stream=True)
ret = save_and_check(req, job.local_file, job.expected_checksum)
if... | 5,345,661 |
def test_upload_findings():
"""Tests uploading of findings"""
responses.add(responses.PUT, get_project_service_mock('add-external-findings'),
body=SUCCESS, status=200)
resp = get_client().upload_findings(_get_test_findings(), datetime.datetime.now(), "Test message", "partition-name")
... | 5,345,662 |
def generate_ar(n_series, n_samples, random_state=0):
"""Generate a linear auto-regressive series.
This simple model is defined as::
X(t) = 0.4 * X(t - 1) - 0.6 * X(t - 4) + 0.5 * N(0, 1)
The task is to predict the current value using all the previous values.
Parameters
----------
n_... | 5,345,663 |
def get_current_commit_id() -> str:
"""Get current commit id.
Returns:
str: current commit id.
"""
command = "git rev-parse HEAD"
commit_id = (
subprocess.check_output(command.split()).strip().decode("utf-8") # noqa: S603
)
return commit_id | 5,345,664 |
def get_raw_code(file_path):
"""
Removes empty lines, leading and trailing whitespaces, single and multi line comments
:param file_path: path to .java file
:return: list with raw code
"""
raw_code = []
multi_line_comment = False
with open(file_path, "r") as f:
for row in f:
... | 5,345,665 |
def test_is_component_dockerised():
"""Tests for is_component_dockerised()."""
from reana.cli import is_component_dockerised
assert is_component_dockerised(
'reana') is False | 5,345,666 |
def load_content(file_path):
"""
Loads content from file_path if file_path's extension
is one of allowed ones (See ALLOWED_EXTS).
Throws UnsupportedMetaException on disallowed filetypes.
:param file_path: Absolute path to the file to load content from.
:type file_path: ``str``
:rtype: ``dict... | 5,345,667 |
def _yaml_comment_regex() -> Pattern:
"""
From https://yaml-multiline.info/, it states that `#` cannot appear *after* a space
or a newline, otherwise it will be a syntax error (for multiline strings that don't
use a block scalar). This applies to single lines as well: for example, `a#b` will be
trea... | 5,345,668 |
def to_list(name: str) -> "Expr":
"""
Aggregate to list
"""
return col(name).list() | 5,345,669 |
def format_ipc_dimension(number: float, decimal_places: int = 2) -> str:
"""
Format a dimension (e.g. lead span or height) according to IPC rules.
"""
formatted = '{:.2f}'.format(number)
stripped = re.sub(r'^0\.', '', formatted)
return stripped.replace('.', '') | 5,345,670 |
def mean_test(data, muy0, alternative = 'equal', alpha = 0.95):
"""
This function is used to create a confidence interval of two.sided hypothesis
Input:
data (1D array): the sample of the whole column that you want to evaluate
confidence (float) : confidence_level, must be in... | 5,345,671 |
def __build_command(command, name, background=None, enable=None):
""" Constuct args for systemctl command.
Args:
command: The systemctl command
name: The unit name or name pattern
background: True to have systemctl perform the command in the background
enable: True to enable/disable, False to start... | 5,345,672 |
def dockerFetchLatestVersion(image_name: str) -> list[str]:
"""
Fetches the latest version of a docker image from hub.docker.com
:param image_name: image to search for
:return: list of version suggestions for the image or 'not found' if error was returned
"""
base_url = "https://hub.docker.com/v... | 5,345,673 |
def _dataset(
dataset_type: str,
transform: str,
train: bool = True
) -> torch.utils.data.Dataset:
"""
Dataset:
mnist: MNIST
cifar10: CIFAR-10
cifar100: CIFAR-100
Transform:
default: the default transform for each data set
simclr: the transform introduced in SimCLR
"""... | 5,345,674 |
def inferCustomerClasses(param_file, evidence_dir, year):
"""
This function uses the variable elimination algorithm from libpgm to infer the customer class of each AnswerID, given the evidence presented in the socio-demographic survey responses.
It returns a tuple of the dataframe with the probability... | 5,345,675 |
def MidiSegInfo(segment):
""" Midi file info saved in config file for speed """
class segInfo:
iMsPerTick = 0
bpm = 4
ppqn = 480
total_ticks = 0
iLengthInMs = 0
iTracks = 0
trackList = []
ver = "1.5"
ret = segInfo()
savedVer =... | 5,345,676 |
def num_in_row(board, row, num):
"""True if num is already in the row, False otherwise"""
return num in board[row] | 5,345,677 |
def load_mnist(dataset="mnist.pkl.gz"):
"""
dataset: string, the path to dataset (MNIST)
"""
data_dir, data_file = os.path.split(dataset)
# download MNIST if not found
if not os.path.isfile(dataset):
import urllib
origin = (
'http://www.iro.umontreal.ca/~lisa... | 5,345,678 |
def select_sklearn_training_regiment(model: base.ModelType, cross_validate: int = None, grid_search: dict = None,
**kwargs):
"""
Select the type of sklearn training regime.
:model (base.ModelType): The model to be trained.
:cross_validate (int, default = None): The ... | 5,345,679 |
def test_row_units() -> None:
"""First row unit is as expected"""
first_row = ['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9']
# pylint: disable=protected-access
assert SB._row_units()[0] == first_row | 5,345,680 |
def _patch_streams(out: TextIO) -> Iterator[None]:
"""Patch and subsequently reset a text stream."""
sys.stderr = sys.stdout = out
try:
yield
finally:
sys.stderr = sys.__stderr__
sys.stdout = sys.__stdout__ | 5,345,681 |
def colmap_localize(kapture_path: str,
colmap_path: str,
input_database_path: str,
input_reconstruction_path: str,
colmap_binary: str,
pairs_file_path: Optional[str],
keypoints_type: Optional[str],
... | 5,345,682 |
def load_hs13_ZSBB_params():
"""Load the standard parameters to generate SocioPatterns HS13
surrogate networks using the ZSBB model.
Returns
-------
:obj:`dict`
The `kwargs` to pass to :func:`tacoma.ZSBB_model`.
"""
fn = os.path.join(path,'ht09_zsbb_params.json')
return tc.loa... | 5,345,683 |
def factorial_3(n, acc=1):
"""
Replace all recursive tail calls f(x=x1, y=y1, ...) with (x, y, ...) = (x1, y1, ...); continue
"""
while True:
if n < 2:
return 1 * acc
(n, acc) = (n - 1, acc * n)
continue
break | 5,345,684 |
def load(filename='haas.cfg'):
"""Load the configuration from the file 'haas.cfg' in the current directory.
This must be called once at program startup; no configuration options will
be available until then.
If the configuration file is not available, this function will simply load
an empty config... | 5,345,685 |
async def app(scope, receive, send):
"""Example application which servers a simple HTML page"""
html = b"""
<!doctype html>
<html>
<head>
<title>Hello ASGI!</title>
</head>
<body>
<main>
<h1>Hello ASGI!</h1>
... | 5,345,686 |
def test_upload_file(mocker):
"""Sanity check upload function."""
runner = CliRunner()
with runner.isolated_filesystem():
with open("foo.txt", "w") as fastq_file:
fastq_file.write("AAABBB")
mocked_s3_client = mocker.Mock()
assert upload_file(
mocked_s3_client,... | 5,345,687 |
def get_all_functions(module: types.ModuleType) -> Iterator[Callable]:
"""
Retrieve all functions defined inside a module, including all it submodules
Args:
module: Module inside which functions are to be searched
Returns:
Iterator over all functions inside the modu... | 5,345,688 |
def main(criteria1, criteria2, criteria3, ad_steps, path=DIR, out_freq=FREQ, output=OUTPUT_FOLDER, numfolders=False, topology=None, skip_first=False,
resname="LIG", percentage=30, threshold=None, cpus=1):
"""
Description: Rank the traj found in the report files under path
by the chosen criteria. Fi... | 5,345,689 |
def autocorr(x, axis=0, fast=False):
"""
Estimate the autocorrelation function of a time series using the FFT.
:param x:
The time series. If multidimensional, set the time axis using the
``axis`` keyword argument and the function will be computed for every
other axis.
:param ax... | 5,345,690 |
def decode_element(
elem: "DataElement", dicom_character_set: Optional[Union[str, List[str]]]
) -> None:
"""Apply the DICOM character encoding to a data element
Parameters
----------
elem : dataelem.DataElement
The :class:`DataElement<pydicom.dataelem.DataElement>` instance
containi... | 5,345,691 |
def parse_date(filename_html):
"""Parse a file, and return the date associated with it.
filename_html -- Name of file to parse.
"""
match = re.search(r"\d{4}-\d{2}-\d{2}", filename_html)
if not match:
return None
match_date = match.group()
file_date = dateutil.parser.parse... | 5,345,692 |
def build_static_runtime(
workspace,
compiler,
module,
compiler_options,
executor=None,
extra_libs=None,
):
"""Build the on-device runtime, statically linking the given modules.
Parameters
----------
compiler : tvm.micro.Compiler
Compiler instance used to build the runti... | 5,345,693 |
def mod(a1, a2):
"""
Function to give the remainder
"""
return a1 % a2 | 5,345,694 |
async def autopaginate(
text: str,
limit: int,
ctx: Union[commands.Context, KurisuContext],
codeblock: bool = False,
):
"""Automatic Paginator"""
wrapped_text: list[str] = wrap(text, limit)
embeds: list[discord.Embed] = []
for t in wrapped_text:
embeds.append(
... | 5,345,695 |
def _unfreeze_and_add_param_group(module: torch.nn.Module,
optimizer: Optimizer,
lr: Optional[float] = None,
train_bn: bool = True):
"""Unfreezes a module and adds its parameters to an optimizer."""
_make_train... | 5,345,696 |
def select_theme_dirs():
"""
Load theme templates, if applicable
"""
if settings.THEME_DIR:
return ["themes/" + settings.THEME_DIR + "/templates", "templates"]
else:
return ["templates"] | 5,345,697 |
def encode_string(s):
"""
Simple utility function to make sure a string is proper
to be used in a SQL query
EXAMPLE:
That's my boy! -> N'That''s my boy!'
"""
res = "N'"+s.replace("'","''")+"'"
res = res.replace("\\''","''")
res = res.replace("\''","''")
return res | 5,345,698 |
def monitor_submissions(syn, api):
"""Monitoring evaluating submissions"""
evaluation_queue_id = 9614883
sub_bundles = syn.getSubmissionBundles(evaluation_queue_id,
status='EVALUATION_IN_PROGRESS')
for _, sub_status in sub_bundles:
task_id = sub_status.submiss... | 5,345,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.