content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def abort_training(config, instance_id, submission_id):
"""
Stop training a submission.
This is done by killing the screen where
the training process is.
Parameters
----------
instance_id : str
instance id
submission_id : int
submission id
"""
cmd = 'screen -S ... | 5,307,100 |
def get_renamed_job_folder_from_list(job_id, file_list):
"""
Get renamed job folder from list of filenames
Parameters
----------
job_id : int
job_id to check the existence of a renamed job folder for
file_list : list
List of filenames to check the existence of the job folder in.... | 5,307,101 |
def elu(x, alpha=1.0):
""" Exponential linear unit
# Arguments
x: Tensor to compute the activation function for.
alpha: scalar
"""
_assert_has_capability(T.nnet, 'elu')
return T.nnet.elu(x, alpha) | 5,307,102 |
def save_configs(configs: Dict[str, TgcliConfiguration]):
"""Save the entire dictionary of configurations to files at $HOME/.tgcli/
- .tgcli/config stores non-sensitive information
- .tgcli/credentials stores sensitive information (username, password, and secrets)
"""
combined_config = configparser... | 5,307,103 |
def guess_region(local_client):
"""
1. read the consts.py
2. try read the battlenet db OR config get the region info.
3. try query https://www.blizzard.com/en-us/user
4. failed return ""
"""
from consts import REGION
if REGION:
return REGION
try:
if local_client._loa... | 5,307,104 |
def textfsm_to_pd(srt, name, adj):
"""
Parses routing table in textfsm format as returned by netmiko
:param srt: Source routing table
:param name: Name of the router
:param adj: Adjacency information
:return: Routing table as pandas dataframe
"""
logger = logging.getLogger('network-test... | 5,307,105 |
def set_categorical_variables(column_names, categorical_variables=None):
"""
Set categorical variables.
This helper functions determines a logical boolean vector based on the column names
and the designation for which ones are categorical variables.
:param column_names: A list of strings; ... | 5,307,106 |
def compute_features(lyrics, tdm_indices):
"""Create new superficial lyrics features. Return df with the new features in columns and one row per track."""
import time
start = time.time()
total_num_words = np.zeros(len(tdm_indices))
tdm = lyrics['tdm'].toarray()
for i in range(len(tdm_indice... | 5,307,107 |
def from_json_string(my_str):
"""Returns an object (Python data structure) represented by
a JSON string:
Arguments:
my_str (obj) -- json str
Returns:
obj -- object
"""
return json.loads(my_str) | 5,307,108 |
def getProgress():
"""Get progress of jackalify."""
global it
global max_it
return (it * 100 // max_it) if max_it > 0 else 0 | 5,307,109 |
def _start_interactively():
"""Start the program interactively through the command line."""
while True:
number = int(input("Please type in the number "
"you want to convert: "))
print(arabic_to_roman(number))
print("") | 5,307,110 |
def save(account):
"""
saves a credencial
"""
account.save_user() | 5,307,111 |
def generate_round():
"""
Генерируем раунд.
Returns:
str: question Вопрос пользователю
str: result Правильный ответ на вопрос
"""
first_num, second_num = generate_question()
question = "{one} {two}".format(one=first_num, two=second_num)
answer = str(math.gcd(first_num, secon... | 5,307,112 |
def filter_separation(catalogue, T_observed, antenna=None, separation_deg=1, sunmoon_separation_deg=10):
""" Removes targets from the supplied catalogue which are within the specified distance from others or either the Sun or Moon.
@param catalogue: [katpoint.Catalogue]
@param T_observed: UTC times... | 5,307,113 |
def cconv_transpose_backprop_filter(
filter, out_positions, out_importance, extent, offset, inp_positions,
inp_features, inp_neighbors_index, inp_neighbors_importance,
inp_neighbors_row_splits, neighbors_index, neighbors_importance,
neighbors_row_splits, out_features_gradient, align_corn... | 5,307,114 |
def to_str(object_: Any) -> str:
"""
>>> to_str(b"ass")
'ass'
>>> to_str("ass")
'ass'
>>> to_str(None)
''
>>> to_str({"op": "oppa"})
"{'op': 'oppa'}"
"""
if object_ is None:
return ""
if isinstance(object_, bytes):
return object_.decode("utf-8")
retu... | 5,307,115 |
def _create_dummy_adata(n_obs: int) -> AnnData:
"""
Create a testing :class:`anndata.AnnData` object.
Call this function to regenerate the ground truth objects.
Parameters
----------
n_obs
Number of cells.
Returns
-------
:class:`anndata.AnnData`
The created adata ... | 5,307,116 |
async def fetch_stats_data(label: str) -> Dict[str, Optional[float]]:
"""Get available stats in Redis."""
try:
return await get_stats_dict(label)
except NotFoundError:
raise HTTPException(404) | 5,307,117 |
def get_bse(da, da_peak_times):
"""
Takes an xarray DataArray containing veg_index values and calculates the vegetation
value base (bse) for each timeseries per-pixel. The base is calculated as the mean
value of two minimum values; the min of the slope to the left of peak of season, and
the min of... | 5,307,118 |
def send_data(rank, node_data, node_features, edge_data, node_part_ids, ntypes_map):
"""
Wrapper function to send graph data to non-rank-0 processes.
Parameters:
-----------
rank : integer
rank of the process
node_data : numpy ndarray
node_data, augmented, from xxx_nodes.... | 5,307,119 |
def approx_2rd_deriv(f_x0,f_x0_minus_1h,f_x0_minus_2h,h):
"""Backwards numerical approximation of the second derivative of a function.
Args:
f_x0: Function evaluation at current timestep.
f_x0_minus_1h: Previous function evaluation.
f_x0_minus_2h: Function evaluations two timesteps ago.... | 5,307,120 |
def plot_tracing(results, gem, plot_satgem=True):
"""
standard plotting function for viewing ray tracing results
"""
if not isinstance(gem, satGEM_field):
raise ValueError('satGEM input must be a satGEM field object')
fig1 = plt.figure(figsize = (15,8))
plt.subpl... | 5,307,121 |
def ind_from_latlon(lats,lons,lat,lon,verbose=False):
"""Find the nearest neighbouring index to given location.
Args:
lats (2d array): Latitude grid
lons (2d array): Longitude grid
lat (float): Latitude of location
lon (float): ... | 5,307,122 |
def remove_included_clip_from_filter(fid: int, cid: int) -> None:
"""
Removes a included clip from a filter.
:param fid: The filter's id.
:param cid: The camera's id.
"""
f = get_filter_by_id(fid=fid)
assert f is not None
clip = get_clip_by_id(cid)
assert clip is not None
f.incl... | 5,307,123 |
def get_dict_key_by_value(val, dic):
"""
Return the first appeared key of a dictionary by given value.
Args:
val (Any): Value of the key.
dic (dict): Dictionary to be checked.
Returns:
Any, key of the given value.
"""
for d_key, d_val in dic.items():
if d_val ==... | 5,307,124 |
def main():
"""
Main execution routine
"""
description = ('Simple application that logs on to the APIC'
' and displays all the faults. If tenant name is given, '
' shows the faults associated with that tenant')
creds = ACI.Credentials('apic', description)
cr... | 5,307,125 |
def isJson(var=''):
""" Check json
>>> isJson(var='')
False
>>> isJson('')
False
>>> isJson('{}')
True
"""
result = True
try:
json.loads(var)
except Exception as e:
result = False
return result | 5,307,126 |
def test_hass_components_var(mock_collector):
"""Test detecting a hass_components_var reference."""
mock_collector.visit(
ast.parse(
"""
def bla(hass):
hass.components.hass_components_var.async_do_something()
"""
)
)
assert mock_collector.unfiltered_referenced == {"hass_c... | 5,307,127 |
def token_stream(gamestate, tokenizer=tokenizer.tokenizer):
"""
Take each value obtained from the tokenizer and wrap it in an appropriate
Token object.
:param gamestate: Gamestate dictionary
:param tokenizer: tokenizer function. Passed as an argument to allow either the cython one or the regex toke... | 5,307,128 |
def trim_video(input_path: str, output_path: str, start_at: int, end_at: int=None, duration: int=None):
"""
trim a video clip from given video. if both end_at and duration are not given, it will trim to the end by default.
:param input_path: path to the raw input video
:param output_path: path to the o... | 5,307,129 |
def count_ontarget_samples(df, human_readable=False):
"""
Function to count usable samples.
Parameters
----------
df: DataFrame
human_readable: Boolean, optional
default=False
Returns
-------
ontarget_counts: DataFrame
MultiIndexed if human_readable, otherwise
... | 5,307,130 |
def read_file_from_bucketfs_to_file(bucket_file_path: str, bucket_config: BucketConfig, local_file_path: Path) -> None:
"""
Read a file from the specified path in the bucket in the BucketFs and save as a local file
Can be used inside of an UDF.
:param bucket_config: BucketConfig for the bucket to downl... | 5,307,131 |
def export_obj(mesh,
include_normals=True,
include_color=True,
include_texture=True):
"""
Export a mesh as a Wavefront OBJ file
Parameters
-----------
mesh : trimesh.Trimesh
Mesh to be exported
Returns
-----------
export : str
OBJ ... | 5,307,132 |
def configure_interval(min_id, max_id):
"""Configures the server to manage debtor IDs between MIN_ID and MAX_ID.
The passed debtor IDs must be between -9223372036854775808 and
9223372036854775807. Use "--" to pass negative integers. For
example:
$ flask swpt_debtors configure_interval -- -16 0
... | 5,307,133 |
def test_complete_endpoint_with_freetext_bool_method(session, query):
"""
test of /complete endpoint with X_FEATURE_FREETEXT_BOOL_METHOD set to 'and' / 'or' / default value
Verifies that results are identical regardless of bool method
"""
params = {'q': query, 'limit': 0}
# no special header, d... | 5,307,134 |
def parse_csv_data(csv_filename: str) -> list:
"""This function will take the csv data from the csv file and return it as a list """
dataframe = pd.read_csv(csv_filename)
return dataframe.values.tolist() | 5,307,135 |
async def do_run():
"""Connect to the PLM and load the ALDB."""
devices = await async_connect(device=DEVICE)
# modem = await async_connect(host=HOST,
# username=USERNAME,
# password=PASSWORD)
modem = devices.modem
_LOGGER.info('Connecte... | 5,307,136 |
def create_month(cls):
"""Creates one ``Month`` object."""
cls.year = mixer.blend(
'freckle_budgets.Year', year=2015, sick_leave_days=12,
vacation_days=12, rate=100)
cls.month = mixer.blend(
'freckle_budgets.Month', month=1, year=cls.year, public_holidays=1,
employees=2) | 5,307,137 |
def classification_three_depth_manual_pipeline():
"""
Returns pipeline with the following structure:
logit \
knn \
rf / knn -> final prediction
rf -> qda /
Where rf - xg boost classifier, logit - logistic regression, knn - K nearest neighbors classifier,
qda - discriminant... | 5,307,138 |
def convert_ref_to_link (match):
"""Converts a reference to a model object to an HTML link.
:param match: match on a reference
:type match: `re.MatchObject`
"""
model_name = match.group('model')
obj_id = match.group('id')
if model_name == 'site':
try:
site = sculpture.m... | 5,307,139 |
def find_many_shortest_paths(source_node, target_nodes, get_edges, max_path_cost=None):
"""
Like `find_shortest_path`, except that it finds shortest paths
between the source node to a list of target nodes.
It returns a list of tuples (path, path_cost). If a path is not
found, the corresponding tupl... | 5,307,140 |
def update():
""" Update buildout from git/master """
with cd(env.code_root):
run('nice git pull') | 5,307,141 |
def convertToMapPic(byteString, mapWidth):
"""convert a bytestring into a 2D row x column array, representing an existing map of fog-of-war, creep, etc."""
data = []
line = ""
for idx,char in enumerate(byteString):
line += str(ord(char))
if ((idx+1)%mapWidth)==0:
data.append(... | 5,307,142 |
def test_day1_step2_test3():
"""
The fuel required by a module of mass 100756 and its fuel is:
33583 + 11192 + 3728 + 1240 + 411 + 135 + 43 + 12 + 2 = 50346.
"""
spaceship = get_fuel_module_requirement(100756)
assert spaceship.fuel_requirements == 50346 | 5,307,143 |
def compute_edge_costs(probs, edge_sizes=None, z_edge_mask=None,
beta=.5, weighting_scheme=None, weighting_exponent=1.):
""" Compute edge costs from probabilities with a pre-defined weighting scheme.
Arguments:
probs [np.ndarray] - Input probabilities.
edge_sizes [np.ndar... | 5,307,144 |
def correlation_coefficient(lagged_x, y, lag):
"""
Routine to determine the correlation coefficient between two data series
with a certain lag shift on one of the series
Input:
lagged_x: The series that will be shifted by a certain lag
y: The series that will not be affected by the lag shift
lag: The n... | 5,307,145 |
def phar_from_mol(ligand):
"""Create Pharmacophore from given pybel.Molecule object."""
if not isinstance(ligand, pybel.Molecule):
raise TypeError("Invalid ligand! Expected pybel.Molecule object, got "
"%s instead" % type(ligand).__name__)
matches = {}
for (phar, pattern... | 5,307,146 |
def solve(data):
"""Solves an instance of the flow shop scheduling problem"""
# We initialize the strategies here to avoid cyclic import issues
initialize_strategies()
global STRATEGIES
# Record the following for each strategy:
# improvements: The amount a solution was improved by this strate... | 5,307,147 |
def player_embed_url(key, player, format='js'):
"""
Return a signed URL pointing to a player initialised with a specific media item.
:param key: JWPlatform key for the media.
:param player: JWPlatform player key.
:param format: (optional) Either ``'js'`` or ``'html'`` depending on whether you want ... | 5,307,148 |
def __regex_parse_documents_from_file(file_path, encoding='latin-1'):
"""Loads all documents from the given SGML file
using REGEX and returns them
"""
# read whole file
content = None
with codecs.open(file_path, 'r', encoding=encoding) as file:
content = file.read()
documents = []
... | 5,307,149 |
def create_directory(directory):
"""
Checks if a directory exists and if not, creates it.
"""
try:
os.stat(directory)
except:
os.mkdir(directory)
return | 5,307,150 |
def test_entity_find_by_business_id_no_model(session, auth_mock): # pylint:disable=unused-argument
"""Assert that an Entity which does not exist cannot be retrieved."""
entity = EntityService.find_by_business_identifier(TestEntityInfo.entity1['businessIdentifier'])
assert entity is None | 5,307,151 |
def tone_to_note(tone):
"""Convert a tone to a music21 note."""
if not isinstance(tone, Tone):
raise ValueError('{} is not a Tone instance'.format(tone))
if isinstance(tone, Rest):
return note.Rest(quarterLength=tone.duration)
if isinstance(tone, (Frequency, Vector)):
p = pitch... | 5,307,152 |
def nr(a, graph_num):
"""Plots numerical range of a matrix with its eigenvalues."""
nv = 120 #some kind of precision
m, n = a.shape
if(m!=n):
print('Warning: matrix is non-square')
return
else:
e = np.linalg.eigvals(a)
f = []
for k in range(1,nv+1):
... | 5,307,153 |
def info(state, bundle, layer):
"""Show the contents of a configuration layer.
NOTE: This does not take into account any layering of multiple
layers. It only shows the contents of the single specified layer.
Output is returned as valid YAML.
"""
click.echo(yaml.dump(layer['config'],
... | 5,307,154 |
def _write_kpoints(self, directory="", fname=None):
"""Write out the KPOINTS file.
The KPOINTS file format is as follows:
line 1: a comment
line 2: number of kpoints
n <= 0 Automatic kpoint generation
n > 0 explicit number of kpoints
line 3: kpt format
if n > 0:
... | 5,307,155 |
def register(plugin):
"""Register a signal handler which calls plugin.handle_sigterm on SIGTERM.
"""
signal.signal(signal.SIGTERM, create_registerer(plugin)) | 5,307,156 |
def validate_flows_routines_are_linked(flows: Dict[str, Flow], wires: Dict[tuple, Wire]):
"""Validate that all routines flows are linked to other routines.
Raises:
FloatingRoutine: If a routine contained in flow but not link to any other routines.
"""
for flow in flows.values():
for r... | 5,307,157 |
def _extract_multipart_params(
data: MultiDictProxy,
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
"""Validate and extract the operations and map fields from the data.
:param data: the data from which extract fields
:type data: MultiDictProxy
:return: the operations and map fields
:rtype: Tuple[D... | 5,307,158 |
def create_commit(timestamp: datetime.datetime, author: str) -> None:
"""Create a randomly named file and commit it using the provided metadata."""
name = str(uuid.uuid4())
pathlib.Path(name).touch()
subprocess.run(["git", "add", name])
subprocess.run(
[
"git",
"commi... | 5,307,159 |
def build_metadata(sequence, prefix, idx, keys, metadata_type="synergy"):
"""when adding non NN sequences, make metadata to match up sequences
"""
# generate for all keys
metadata = {}
for key in keys:
metadata[key] = 0
# adjust some manually
metadata[DataKeys.SEQ_METADATA] = "featu... | 5,307,160 |
def shout():
"""Print a string with three exclamation marks"""
# Concatenate the strings: shout_word
shout_word = 'congratulations' + '!!!'
# Print shout_word
print(shout_word) | 5,307,161 |
def test_cray_hsm_state_components_bulk_enabled_update(cli_runner, rest_mock):
"""Test `cray hsm state components bulkEnabled update` with valid
params
"""
runner, cli, config = cli_runner
url_template = '/apis/smd/hsm/v1/State/Components/BulkEnabled'
ids = ['x0c0s0b0n0', 'x0c0s1b0n0']
enab... | 5,307,162 |
def _read_file_to_dict(path):
"""
Load the problems and the corresponding labels from the *.txt file.
:param path: The full path to the file to read
:return: The dictionary with the problem names as keys and the true class labels as values
"""
label_dict = {}
with open(path, 'r', encoding='u... | 5,307,163 |
def histograms():
""" histograms page """
_js_resources = Resources(mode="cdn", log_level='info').render_js()
_css_resources = Resources(mode="cdn", log_level='info').render_css()
_histograms = server_document(FLASK_URL + '/bkapp-histograms', resources=None)
return render_template("embed.html",
... | 5,307,164 |
def rotate_petals(fp):
"""Rotate the X/Y offsets according to petal location.
The X / Y offsets of each device are rotated to the petal
location for that device. The focalplane dictionary is
modified in place.
Args:
fp (dict): The focalplane dictionary.
Returns:
None
""... | 5,307,165 |
def test_rank_test_output_against_R_no_censorship():
"""
> time <- c(10,20,30,10,20,50)
> status <- c(1,1,1,1,1,1)
> treatment <- c(1,1,1,0,0,0)
> survdiff(Surv(time, status) ~ treatment)
"""
result = stats.multivariate_logrank_test([10, 20, 30, 10, 20, 50], [1, 1, 1, 0, 0, 0])
r_p_value... | 5,307,166 |
def closest_val(val, arr):
"""
Finds the closest value in `arr` to `val`
Parameters
-------------
val: int or float
value to be looked at
arr: numpy.ndarray
numpy array used for finding closest value to `val`
Returns
-------------
idx_choice: int
index for ... | 5,307,167 |
def generate_prior(dist, **kwargs):
"""Generate a Prior distribution.
The parameter ``kwargs`` is used to pass hyperpriors that are assigned to the parameters of
the prior to be built.
Parameters
----------
dist: str, int, float
If a string, it is the name of the prior distribution wit... | 5,307,168 |
def thc_via_cp3(eri_full, nthc, thc_save_file=None, first_factor_thresh=1.0E-14, conv_eps=1.0E-4,
perform_bfgs_opt=True, bfgs_maxiter=5000, random_start_thc=True, verify=False):
"""
THC-CP3 performs an SVD decomposition of the eri matrix followed by a CP decomposition
via pybtas. The CP de... | 5,307,169 |
def draw_rect(ax, xy, width, height):
"""
Draw a rectangle on a given axis with outlines
Args:
ax (matplotlib.axis.Axis): A matplotlib axis
xy (tuple): The x and y position of the text to draw
width (int): Rectangle width
height (int): Rectangle height
"""
patch = ax.... | 5,307,170 |
def sla_list_safe_domain(cluster, percentage, duration):
"""usage: sla_list_safe_domain
[--exclude_file=FILENAME]
[--exclude_hosts=HOSTS]
[--grouping=GROUPING]
[--include_file=FILENAME]
[--include_hosts=HOSTS]
[--list_jobs]
[--min_job... | 5,307,171 |
def download_fn(args):
"""Download buildcache entry from a remote mirror to local folder. This
command uses the process exit code to indicate its result, specifically,
a non-zero exit code indicates that the command failed to download at
least one of the required buildcache components."""
if not ar... | 5,307,172 |
def check_safety_line(path, safety_line):
"""Return true if the file starts with the safety line."""
with open_file(path, "r") as file:
return file.readline().rstrip('\n') == safety_line | 5,307,173 |
def zopen(filename, mode):
"""Open filename.xz, filename.gz or filename."""
filenamexz = str(filename) if str(filename).endswith(".xz") else str(filename) + '.xz'
filenamegz = str(filename) if str(filename).endswith(".gz") else str(filename) + '.gz'
if os.path.exists(filenamexz):
return lzma.ope... | 5,307,174 |
def main():
"""
this program will draw triangle recursively
"""
sierpinski_triangle(ORDER, LENGTH, UPPER_LEFT_X, UPPER_LEFT_Y) | 5,307,175 |
def make_input(subject, attribute):
"""Generates the HTML for an input field for the given attribute.
'subject' can be None to set up an empty form for a new subject."""
name = attribute.key().name()
return ATTRIBUTE_TYPES[attribute.type].make_input(
name, subject and subject.get_value(name), at... | 5,307,176 |
def hs_mod_opti_step(x_n, x, u, u_n, F, dt, params):
"""
Must be equal to zero in order to fulfill the implicit scheme
Returns
-------
res : Numpy array or Casadi array
Residue to minimize
"""
dim = vec_len(x) // 2
f = F(x, u, params)[dim:]
f_n = F(x_n, u_n, params)[dim:]
... | 5,307,177 |
async def async_setup_platform(
homeassistant, config, async_add_entities, discovery_info=None
):
"""Set up the Enphase Envoy sensor."""
ip_address = config[CONF_IP_ADDRESS]
monitored_conditions = config[CONF_MONITORED_CONDITIONS]
name = config[CONF_NAME]
username = config[CONF_USERNAME]
pas... | 5,307,178 |
def window_rowcol(lon_arr, lat_arr, bbox=None):
"""Get the row bounds and col bounds of a box in lat/lon arrays
Returns:
(row_top, row_bot), (col_left, col_right)
"""
if bbox is None or len(bbox) == 0:
return (0, len(lat_arr)), (0, len(lon_arr))
left, bot, right, top = bbox
lat... | 5,307,179 |
def success() -> int:
"""Represent `200` success status code"""
return _success | 5,307,180 |
def close_connection(self, connection):
"""Summary
Method closes a specific connection or the class scoped
connection if none specified.
Args:
connection (ibm_db.connection, optional): connection to close
Returns:
boolean: Success or fail of connection closing
"""
re... | 5,307,181 |
def pa(text, nlp, language_code='en'):
"""Percentage of Adjectives in text."""
pa = None
doc = nlp(text)
words_num, _ = word_counter(text, language_code)
adjectives = [token.lemma_ for token in doc if token.pos_ == 'ADJ']
adjectives_num = len(adjectives)
if words_num != 0:
pa = ... | 5,307,182 |
def less_than(lhs: typing.SupportsFloat, rhs: typing.SupportsFloat):
"""Compare the left-hand-side to the right-hand-side.
Follows the Numpy logic for normalizing the numeric types of *lhs* and *rhs*.
"""
import numpy as np
dtype = int
if any(isinstance(operand, float) for operand in (lhs, rhs)... | 5,307,183 |
def test_person__PersonAddForm__10(translated_address_book, browser):
"""`PersonAddForm` translates country names."""
browser.login('editor')
browser.lang('de-DE')
browser.open(browser.PERSON_ADD_URL)
assert ['Deutschland'] == browser.getControl('Land').displayValue
browser.getControl('Land').di... | 5,307,184 |
def _run(run_uri):
"""Run stage of PKB benchmark.
Args:
run_uri: (string).
"""
if FLAGS.per_second_graphs:
logging.info('Will generate per second logs for this run.')
plotter = plot_sysbench_results.Plotter(FLAGS.sysbench_run_seconds,
FLAGS.sysbench_report... | 5,307,185 |
def is_revoked(jti: str) -> bool:
"""
Returns True if a given token is revoked.
"""
b = TokenBlocklist.query.filter_by(jti=jti).first()
return b is not None | 5,307,186 |
def test_parse__all_exception_names__param_section(raise_directive_name):
"""Parse all raise directives.
Parameters:
raise_directive_name: A parametrized directive name.
"""
sections, _ = parse(
f"""
Docstring with one line attribute.
:{raise_directive_name} {SOME_EXCEP... | 5,307,187 |
def scan_htmli(url, value_forms_malforms, htmli_data):
"""
Given a `url`, it prints all cmdi vulnerable forms and
returns True if any is vulnerable, False otherwise
"""
try:
# get all the forms from the URL
forms = get_all_forms(url)
print(G + "[+]" + C + f" Det... | 5,307,188 |
def plot_roc(fpr_dict, tpr_dict, auc_roc_dict, ax, plot_prop=get_class_plot_prop()):
"""
Generates receiver-operating characteristic (roc) curve plot with embellishments
"""
if len(fpr_dict):
# plot diagonal
ax.plot(np.linspace(0, 1), np.linspace(0, 1), linestyle='--', color='gray')
... | 5,307,189 |
def gen_neutral_srcmap_func(original_text: Union[StringView, str], original_name: str = '') -> SourceMapFunc:
"""Generates a source map functions that maps positions to itself."""
if not original_name: original_name = 'UNKNOWN_FILE'
return lambda pos: SourceLocation(original_name, original_text, pos) | 5,307,190 |
def get_request(url: str, headers: dict) -> requests.Response:
"""
Wrapper for requests.get call to use refresh token
:param url: request URL
:param headers: request headers
:return: requests.Response
"""
response = requests.get(url, headers=headers)
if response.status_code in BAD_TOKEN_... | 5,307,191 |
def geometric_progression_for_stepsize(x, update, dist, randomimg, params):
"""
Geometric progression to search for stepsize.
Keep decreasing stepsize by half until reaching
the desired side of the boundary,
"""
epsilon = dist / np.sqrt(params['cur_iter'])
def phi(epsilon):
new = x ... | 5,307,192 |
def cli(env, identifier):
"""Reset connections on a certain service group."""
mgr = SoftLayer.LoadBalancerManager(env.client)
loadbal_id, group_id = loadbal.parse_id(identifier)
mgr.reset_service_group(loadbal_id, group_id)
env.fout('Load balancer service group connections are being reset!') | 5,307,193 |
def trace(fn):
"""Decorator that marks a function to be traced."""
fn.should_trace = True
return fn | 5,307,194 |
def ape_update_bios_firmware_version(cookie, in_config):
""" Auto-generated UCS XML API Method. """
method = ExternalMethod("ApeUpdateBIOSFirmwareVersion")
method.cookie = cookie
method.in_config = in_config
xml_request = method.to_xml(option=WriteXmlOption.DIRTY)
return xml_request | 5,307,195 |
def restore_bindpose(selected=True):
"""Restore the rig controls to their bindpose.
Args:
selected (bool): If True, reset only selected controls, otherwise
reset every controls of each selected rigs.
"""
nodes = cmds.ls(selection=True)
if not selected:
namespaces = set(... | 5,307,196 |
def set_ss_value(tag, value):
"""
Setter for data that also work with implicit transfersyntax
:param value: the value to set on the tag
:param tag: the tag to read
"""
if tag.VR == 'OB' or tag.VR == 'UN':
value = struct.pack('h', value)
tag.value = value | 5,307,197 |
def squish_sound(src, percent):
"""Squish an audio file."""
sr, sound = wav.read(src)
# Stretch the sound by the given percentage
squish = rb.pyrb.time_stretch(sound, sr, 1 + percent)
# Add silence to produce a sound with the same length as the original
silence = np.zeros(len(sound) - len(squish... | 5,307,198 |
def FileCopy(path, destinationPath):
"""
Copy a File
:param path:Source File
:param destinationPath:Destination Path
:return:
"""
shutil.copy(path, destinationPath) | 5,307,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.