content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def remove_apostrophe(text):
"""Remove apostrophes from text"""
return text.replace("'", " ") | 5,357,900 |
def generate_initials(text):
"""
Extract initials from a string
Args:
text(str): The string to extract initials from
Returns:
str: The initials extracted from the string
"""
if not text:
return None
text = text.strip()
if text:
split_text = text.split(" ... | 5,357,901 |
def nmf_manifold_vec_update(X, U, V, k_to_W, k_to_D, k_to_L, k_to_feat_inds, n_steps=10, gamma=1.0, delta=1.0, i=0, verbose=False, norm_X=None):
"""
Perform <n_steps> update steps with a fixed Laplacian matrix for each latent factor
Parameters
----------
X : np.array
data to factor
U : np.array
pr... | 5,357,902 |
def check_xyz_species_for_drawing(xyz, species):
"""A helper function to avoid repetative code"""
if species is not None and xyz is None:
xyz = xyz if xyz is not None else species.final_xyz
if species is not None and not isinstance(species, ARCSpecies):
raise InputError('Species must be an A... | 5,357,903 |
def test_simple_single_sitemap():
"""
Tests a single sitemap
"""
with test_sitemap() as sitemap:
sitemap.add_section("articles")
for url in urls_iterator():
sitemap.add_url(url)
print(sitemap)
assert len(sitemap) == 10
assert "(10 URLs)" in repr(sit... | 5,357,904 |
def GetUDPStreamSample(command_out, sending_vm, receiving_vm, request_bandwidth,
network_type, iteration):
"""Get a sample from the nuttcp string results.
Args:
command_out: the nuttcp output.
sending_vm: vm sending the UDP packets.
receiving_vm: vm receiving the UDP packets.
... | 5,357,905 |
def _mixed_compare_sample(train_sample: Tuple, predict_sample: Tuple):
"""
For models relying on MixedCovariates.
Parameters:
----------
train_sample
(past_target, past_covariates, historic_future_covariates, future_covariates, future_target)
predict_sample
(past_target, past_co... | 5,357,906 |
def initial_checks():
"""Perform a series of checks to be sure the race data is good."""
#TODO check if user-config.py is present
print("{} race editions found in {}.".format(len(race_editions), root_dir + races_dir))
filecount_errors = 0
for race in race_editions:
files_count = len(os.listdir(race))
if file... | 5,357,907 |
def test_load_from_both_py_and_pyi_files():
"""Check that the loader is able to merge data loaded from `*.py` and `*.pyi` files."""
with temporary_pypackage("package", ["mod.py", "mod.pyi"]) as tmp_package:
tmp_package.path.joinpath("mod.py").write_text(
dedent(
"""
... | 5,357,908 |
def setSwaggerParamDesc(swagger,searchParams):
"""
Set the Swagger GET Parameter Description to what is stored in the search Parameters using helper function
"""
for id in range(len(swagger['tags'])):
# Paths are prefaced with forward slash
idName = '/'+swagger['tags'][id]['name']
... | 5,357,909 |
def parse_args(args=[], doc=False):
"""
Handle parsing of arguments and flags. Generates docs using help from `ArgParser`
Args:
args (list): argv passed to the binary
doc (bool): If the function should generate and return manpage
Returns:
Processed args and a copy of the `ArgPa... | 5,357,910 |
def interact(u, v):
"""Compute element-wise mean(s) from two arrays."""
return tuple(mean(array([u, v]), axis=0)) | 5,357,911 |
def part_allocation_count(build, part, *args, **kwargs):
""" Return the total number of <part> allocated to <build> """
return build.getAllocatedQuantity(part) | 5,357,912 |
def _disable_tracing():
"""Disable system-wide tracing, if we specifically switched it on."""
global _orig_sys_trace
if _orig_sys_trace is None:
sys.settrace(None) | 5,357,913 |
def stat_threshold(Z,mce='fdr_bh',a_level=0.05,side='two',copy=True):
"""
Threshold z maps
Parameters
----------
mce: multiple comparison error correction method, should be
among of the options below. [defualt: 'fdr_bh'].
The options are from statsmodels packages:
... | 5,357,914 |
def esmf_grid(lon, lat, periodic=False, mask=None):
"""
Create an ESMF.Grid object, for constructing ESMF.Field and ESMF.Regrid.
Parameters
----------
lon, lat : 2D numpy array
Longitute/Latitude of cell centers.
Recommend Fortran-ordering to match ESMPy internal.
Shape... | 5,357,915 |
def magic_series(grid):
""" Check if grid satisfies the definition
series[k] == sum(series[i] == k) """
logging.debug("Grid:\n{}".format(grid))
magic = (grid.sum(1) == np.where(grid.T)[1])
logging.debug("Magic check:\n{}".format(magic))
return magic.all() | 5,357,916 |
def convert_to_numeral(decimal_integer: int, roman_format="brackets"):
"""Convert decimal to Roman numeral.
roman_format is a str containing either 'brackets' or 'latex'
The default option, 'brackets', converts 3,000,000,000 to [[MMM]] and
3,000,000 to [MMM].
'latex' outputs a LaTeX formula for th... | 5,357,917 |
def transpose(x):
"""Tensor transpose """
return np.transpose(x) | 5,357,918 |
def greedy_reduction_flat(m: Mat2) -> Optional[List[Tuple[int, int]]]:
"""Returns a list of tuples (r1,r2) that specify which row should be added to which other row
in order to reduce one row of m to only contain a single 1.
In contrast to :func:`greedy_reduction`, it preforms the brute-force search startin... | 5,357,919 |
def validate_access_and_security_params(config):
"""
Checks the presence of access_and_security parameters
"""
logger.info("checking basic_authentication params")
sec_params = config_utils.get_k8s_dict(config).get(consts.ACCESS_SEC_KEY)
if consts.AUTH_KEY in sec_params:
auth_key = sec_p... | 5,357,920 |
def estimate_psd(vec, num_segs=DEFAULT_NUM_SEGS, overlap=DEFAULT_OVERLAP, dt=DEFAULT_DT, tukey_alpha=DEFAULT_TUKEY_ALPHA, one_sided=True):
"""
estimates the PSD using a DFT
divides vec into "num_segs" with a fractional overlap of "overlap" between neighbors
returns the average PSD from t... | 5,357,921 |
def load_data(connection_string: str):
"""
Load data from a source. Source could be:
- A JSON File
- A MongoDB
Load data from a file
---------------------
If you want to load data from a File, you must to provide this connection string:
>>> connection_string = "/path/to/my/file.json"... | 5,357,922 |
def himmelblau(xy):
"""
Himmelblau's function, as a set of residuals (cost = sum(residuals**2))
The standard Himmelbau's function is with data as [11, 7], and four
minimum at (3.0, 2.0), ~(-2.8, 3.1), ~(-3.8, -3.3), ~(3.6, -1.8).
Himmelblau's function is a quadratic model in both x and y. Its data-... | 5,357,923 |
def parse_instrument_data(smoothie_response: str) -> Dict[str, bytearray]:
"""
Parse instrument data.
Args:
smoothie_response: A string containing a mount prefix (L or R) followed by :
and a hex string.
Returns:
mapping of the mount prefix to the hex string.
"""
try... | 5,357,924 |
def count_frames(directory):
"""
counts the number of consecutive pickled frames in directory
Args:
directory: str of directory
Returns:
0 for none, otherwise >0
"""
for i in itertools.count(start=0):
pickle_file = os.path.join(directory, f"{str(i).zfill(12)}.pickle")... | 5,357,925 |
def _volume_sum_check(props: PropsDict, sum_to=1, atol=1e-3) -> bool:
"""Check arrays all sum to no more than 1"""
check_broadcastable(**props)
sum_ar = np.zeros((1,))
for prop in props:
sum_ar = sum_ar + props[prop]
try:
assert sum_ar.max() <= sum_to + atol
except As... | 5,357,926 |
def list_partition_deltas(
partition: Partition,
include_manifest: bool = False,
*args,
**kwargs) -> ListResult[Delta]:
"""
Lists a page of deltas committed to the given partition.
To conserve memory, the deltas returned do not include manifests by
default. The manifests... | 5,357,927 |
def main():
"""Entry point"""
parser = argparse.ArgumentParser(description="Analyse Maven dependency trees")
parser.add_argument("--files", required=False, default="target/dependency-reports/*-tree.txt",
help="Maven dependency plugin output files to analyse")
parser.add_argument(... | 5,357,928 |
def HLA_flag4and8_hunter_killer_OLD(photfilename):
"""This function searches through photometry catalogs for sources whose flags contain
both bits 4 (multi-pixel saturation), and 8 (faint magnitude limit).
If found, the subroutine removes the "8" bit value from the set of flags for that source.
Paramet... | 5,357,929 |
def get_management_confs_in_domain(body=None): # noqa: E501
"""get management configuration items and expected values in the domain
get management configuration items and expected values in the domain # noqa: E501
:param body: domain info
:type body: dict | bytes
:rtype: ConfFiles
"""
if... | 5,357,930 |
def small_view(data, attribute):
"""
Extract a downsampled view from a dataset, for quick statistical summaries
"""
shp = data.shape
view = tuple([slice(None, None, np.intp(max(s / 50, 1))) for s in shp])
return data[attribute, view] | 5,357,931 |
def playerStandings():
"""Returns a list of the players and their win records, sorted by wins.
The first entry in the list should be the player in first place, or a player
tied for first place if there is currently a tie.
Returns:
A list of tuples, each of which contains (id, name, wins, ... | 5,357,932 |
def get_all_feature_names(df: pd.DataFrame, target: str = None) -> list:
"""Get a list of all feature names in a dataframe.
Args:
df (pd.DataFrame): dataframe of features and target variable
target (str): name of target column in df
Returns:
all_feature_names (list): list of al... | 5,357,933 |
def skipUnlessAddressSanitizer(func):
"""Decorate the item to skip test unless Clang -fsanitize=thread is supported."""
def is_compiler_with_address_sanitizer(self):
compiler_path = self.getCompiler()
compiler = os.path.basename(compiler_path)
f = tempfile.NamedTemporaryFile()
i... | 5,357,934 |
def generate_enhancer_promoter_pair(ep_df):
"""
"""
std_ep_pair = ep_df[['chrom-Enh','chromStart','chromEnd','TSS']]
min_ep_gap = abs((std_ep_pair['chromEnd']-std_ep_pair['chromStart']).min())
max_ep_gap = abs((std_ep_pair['chromEnd']-std_ep_pair['chromStart']).max())
fake_samples = []
for enhancer ... | 5,357,935 |
def constant_lrs(
draw, return_kwargs: bool = False
) -> Union[
st.SearchStrategy[lr_scheduler_pb2.ConstantLR],
st.SearchStrategy[Tuple[lr_scheduler_pb2.ConstantLR, Dict]],
]:
"""Returns a SearchStrategy for an ConstantLR plus maybe the kwargs."""
kwargs: Dict = {}
# initialise and return
a... | 5,357,936 |
def get_read_only_storage_manager():
"""Get the current Flask app's read only storage manager, create if
necessary"""
return current_app.config.setdefault('read_only_storage_manager',
ReadOnlyStorageManager()) | 5,357,937 |
def change_base(x: int, base: int):
"""Change numerical base of input number x to base.
return string representation after the conversion.
base numbers are less than 10.
>>> change_base(8, 3)
'22'
>>> change_base(8, 2)
'1000'
>>> change_base(7, 2)
'111'
Example solution:
... | 5,357,938 |
def __parse_sql(sql_rows):
"""
Parse sqlite3 databse output. Modify this function if you have a different
database setup. Helper function for sql_get().
Parameters:
sql_rows (str): output from SQL SELECT query.
Returns:
dict
"""
... | 5,357,939 |
def assert_almost_equal(
actual: Tuple[numpy.float64, numpy.float64],
desired: List[numpy.float64],
decimal: int,
err_msg: Literal["(0, 30)agresti_coull"],
):
"""
usage.statsmodels: 1
"""
... | 5,357,940 |
def _generate_to(qubo, seed, oct_upper_bound, bias=0.5):
"""
Given a QUBO, an upper bound on oct, and a bias of bipartite vertices,
generate an Erdos-Renyi graph such that oct_upper_bound number of vertices
form an OCT set and the remaining vertices are partitioned into partites
(left partite set wi... | 5,357,941 |
def sqlCreate(fields=None, extraFields=None, addCoastGuardFields=True, dbType='postgres'):
"""Return the sqlhelp object to create the table.
@param fields: which fields to put in the create. Defaults to all.
@param extraFields: A sequence of tuples containing (name,sql type) for additional fields
@par... | 5,357,942 |
def _section_cohort_management(course, access):
""" Provide data for the corresponding cohort management section """
course_key = course.id
ccx_enabled = hasattr(course_key, 'ccx')
section_data = {
'section_key': 'cohort_management',
'section_display_name': _('Cohorts'),
'access'... | 5,357,943 |
def rivers_by_station_number(stations, N):
"""Returns a list of N tuples on the form (river name, number of stations on the river). These tuples are sorted in decreasing order of station numbers.
If many stations have the same number of stations as the 'Nth' river, these are also included."""
riversLi... | 5,357,944 |
def load_default_data() -> dict[str, str]:
"""Finds and opens a .json file with streamer data.
Reads from the file and assigns the data to streamer_list.
Args:
None
Returns:
A dict mapping keys (Twitch usernames) to their corresponding URLs.
Each row is represented as a se... | 5,357,945 |
def get_value_key(generator, name):
"""
Return a key for the given generator and name pair.
If name None, no key is generated.
"""
if name is not None:
return f"{generator}+{name}"
return None | 5,357,946 |
def wav_to_log_spectrogram_clips(wav_file):
"""convert audio into logrithmic spectorgram, then chop it into 2d-segmentation of 100 frames"""
# convert audio into spectorgram
sound, sr = librosa.load(wav_file, sr=SR, mono=True)
stft = librosa.stft(sound, n_fft=N_FFT, hop_length=HOP_LEN, win_length=WIN_LE... | 5,357,947 |
def main():
"""
Main entry point into the SeisFlows package
"""
# Easy way to convert strings to functions
acceptable_args = {"submit": submit, "resume": resume, "clean": clean,
"restart": restart, "debug": debug}
try:
main_arg = get_args().main_args[0]
except... | 5,357,948 |
def get_title(mods):
"""
Function takes the objects MODS and extracts and returns the text of the title.
"""
title = mods.find("{{{0}}}titleInfo/{{{0}}}title".format(MODS_NS))
if title is not None:
return title.text | 5,357,949 |
def get_from_identity(session, key, passive):
"""Look up the given key in the given session's identity map,
check the object for expired state if found.
"""
instance = session.identity_map.get(key)
if instance is not None:
state = attributes.instance_state(instance)
# expired - en... | 5,357,950 |
def sample_ingredient(user, name='Cinnamon'):
"""
Create and return a sample ingredient
:param user: User(custom) object
:param name: name of the ingredient
:return: Ingredient object
"""
return Ingredient.objects.create(user=user, name=name) | 5,357,951 |
def check_if_string(data):
"""
Takes a data as argument and checks if the provided argument is an
instance of string or not
Args:
data: Data to check for.
Returns:
result: Returns a boolean if the data provided is instance or not
"""
if sys.version_info[0] == 2:
ret... | 5,357,952 |
def viterbi(O,S,Y, pi, A, B):
"""Generates a path which is a sequence of most likely states that generates the given observation Y.
Args:
O (numpy.ndarray): observation space. Size: 1 X N
S (numpy.ndarray): state space. Size: 1 X K
Y (list): observation sequence. ... | 5,357,953 |
def int_to_bigint(value):
"""Convert integers larger than 64 bits to bytearray
Smaller integers are left alone
"""
if value.bit_length() > 63:
return value.to_bytes((value.bit_length() + 9) // 8, 'little', signed=True)
return value | 5,357,954 |
def test_contact(client):
""" Test the contact. """
# all fields are required:
rv = client.post("/contact", data=dict(name="user"))
assert b"Something fishy in the request" in rv.data
# email address must be `valid`:
rv = client.post(
"/contact",
data=dict(
name="",... | 5,357,955 |
def xcorr(S, dtmax=10):
"""
Cross correlate each pair of columns in S at offsets up to dtmax
"""
# import pdb; pdb.set_trace()
(T,N) = S.shape
H = np.zeros((N,N,dtmax))
# Compute cross correlation at each time offset
for dt in np.arange(dtmax):
# print "Computing cross correlati... | 5,357,956 |
def register_hooks():
"""Exec all the rules files. Gather the hooks from them
and load them into the hook dict for later use.
"""
global HOOKS_LOADED
for name, path in load_rules().items():
globals = {}
with open(path) as f:
exec(compile(f.read(), path, 'exec'), globals)... | 5,357,957 |
def jboss_status(jboss_cli_home, server_ip, jboss_admin_port, jboss_admin, jboss_admin_pwd, timeout='60000'):
"""
| ##@函数目的: Jboss状态
| ##@参数说明:
| ##@返回值:
| ##@函数逻辑:
| ##@开发人:jhuang
| ##@时间:
"""
time_start = time.time()
jboss_cli = 'jboss-cli.sh'
if jboss_cli_home[-1] != '/':... | 5,357,958 |
def proxy_rotator():
"""Return a cycle object of proxy dict"""
return Proxy.get_proxy_rotator() | 5,357,959 |
def xpdacq_list_grid_scan(detectors: list, *args,
snake_axes: typing.Union[bool, typing.Iterable[bool], None] = None,
per_step: typing.Callable = xpdacq_per_step,
md: typing.Union[dict, None] = None) -> typing.Generator:
"""
Scan over... | 5,357,960 |
def pow(a, b):
""" Return an attribute that represents a ^ b. """
return multiplyDivide(a, b, MultiplyDivideOperation.POWER) | 5,357,961 |
async def send_simple_embed_to_channel(bot: commands.Bot, channel_name: str, message: str, color: str = config["colors"]["default"]) -> discord.Message:
"""Send a simple embed message to the channel with the given name in the given guild, using the given message and an optional colour.
Args:
bot (comma... | 5,357,962 |
def retry_on_server_errors_timeout_or_quota_issues_filter(exception):
"""Retry on server, timeout and 403 errors.
403 errors can be accessDenied, billingNotEnabled, and also quotaExceeded,
rateLimitExceeded."""
if HttpError is not None and isinstance(exception, HttpError):
if exception.status_code == 403:
... | 5,357,963 |
def load_all_data(data_path):
"""Load all mode data."""
image_list = []
for cam in os.listdir(data_path):
image_dir = os.path.join(data_path, cam, 'dets')
cam_image_list = glob(image_dir+'/*.png')
cam_image_list = sorted(cam_image_list)
print(f'{len(cam_image_list)} images f... | 5,357,964 |
def cmd_line_parser():
"""
This function parses the command line parameters and arguments
"""
parser = argparse.ArgumentParser(usage="python " + sys.argv[0] + " [-h] [passive/active] -d [Domain] [Options]", epilog='\tExample: \r\npython ' + sys.argv[0] + " passive -d baidu.com -o html")
parser._opti... | 5,357,965 |
def CSourceForElfSymbolTable(variable_prefix, names, str_offsets):
"""Generate C source definition for an ELF symbol table.
Args:
variable_prefix: variable name prefix
names: List of symbol names.
str_offsets: List of symbol name offsets in string table.
Returns:
String containing C source fragme... | 5,357,966 |
def _kahan_reduction(x, y):
"""Implements the Kahan summation reduction."""
(s, c), (s1, c1) = x, y
for val in -c1, s1:
u = val - c
t = s + u
# TODO(b/173158845): XLA:CPU reassociates-to-zero the correction term.
c = (t - s) - u
s = t
return s, c | 5,357,967 |
def get_endpoint_access(endpoint_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetEndpointAccessResult:
"""
Resource schema for a Redshift-managed VPC endpoint.
:param str endpoint_name: The name of the endpoint.
"""
__args__ = dict()
... | 5,357,968 |
def wait_until_active(tol=5):
"""
When the system is in inactive mode, this process signals the
beginning od the user activity
Parameters
----------
tol : TYPE, optional
DESCRIPTION. The default is 5.
Returns
-------
None.
"""
liinfo = LASTINPUTINFO(... | 5,357,969 |
def predictor(
service: MLFlowDeploymentService,
data: np.ndarray,
) -> Output(predictions=np.ndarray):
"""Run a inference request against a prediction service"""
service.start(timeout=10) # should be a NOP if already started
prediction = service.predict(data)
prediction = prediction.argmax(ax... | 5,357,970 |
def test_datasets_provenance_after_remove(
runner, client, directory_tree, load_dataset_with_injection, get_datasets_provenance_with_injection
):
"""Test datasets provenance is updated after removing a dataset."""
assert 0 == runner.invoke(cli, ["dataset", "add", "my-data", "-c", str(directory_tree)]).exit_... | 5,357,971 |
def test_block_template_with_missing_template(app_with_mail):
"""Test that a missing template raises an exception."""
with app_with_mail.app_context():
with pytest.raises(TemplateNotFound):
BlockTemplatedMessage("missing.html") | 5,357,972 |
def get_domain(ns, domain):
"""
Return LMIInstance of given LMI_SSSDDomain.
:type domain: string
:param domain: Name of the domain to find.
:rtype: LMIInstance of LMI_SSSDDomain
"""
keys = {'Name': domain}
try:
inst = ns.LMI_SSSDDomain.new_instance_name(keys).to_instance()
e... | 5,357,973 |
def mmd_loss(embedding, auxiliary_labels, weights_pos, weights_neg, params):
""" Computes mmd loss, weighted or unweighted """
if weights_pos is None:
return mmd_loss_unweighted(embedding, auxiliary_labels, params)
return mmd_loss_weighted(embedding, auxiliary_labels,
weights_pos, weights_neg, params) | 5,357,974 |
def perdidas (n_r,n_inv,n_x,**kwargs):
"""Calcula las perdidas por equipos"""
n_t=n_r*n_inv*n_x
for kwargs in kwargs:
n_t=n_t*kwargs
return n_t | 5,357,975 |
def _symlink_dep_cmd(lib, deps_dir, in_runfiles):
"""
Helper function to construct a command for symlinking a library into the
deps directory.
"""
lib_path = lib.short_path if in_runfiles else lib.path
return (
"ln -sf " + relative_path(deps_dir, lib_path) + " " +
deps_dir + "/" ... | 5,357,976 |
def boundingBoxEdgeLengths(domain):
"""
Returns the edge lengths of the bounding box of a domain
:param domain: a domain
:type domain: `escript.Domain`
:rtype: ``list`` of ``float``
"""
return [ v[1]-v[0] for v in boundingBox(domain) ] | 5,357,977 |
def get_user(isamAppliance, user):
"""
Get permitted features for user
NOTE: Getting an unexplained error for this function, URL maybe wrong
"""
return isamAppliance.invoke_get("Get permitted features for user",
"/authorization/features/users/{0}/v1".format(user)) | 5,357,978 |
def autoupdate(
config_file: str,
store: Store,
tags_only: bool,
freeze: bool,
repos: Sequence[str] = (),
add_unused_hooks: bool = False,
) -> int:
"""Auto-update the pre-commit config to the latest versions of repos."""
migrate_config(config_file, quiet=True)
... | 5,357,979 |
def plot_energy_resolution_cta_performance(cta_site, ax=None, **kwargs):
"""
Plot the cta performances (June 2018) for the true_energy resolution
Parameters
----------
cta_site: string
see `ctaplot.ana.cta_performance`
ax: `matplotlib.pyplot.axes`
kwargs: args for `matplotlib.pyplot... | 5,357,980 |
def _n_nested_blocked_random_indices(sizes, n_iterations):
"""
Returns indices to randomly resample blocks of an array (with replacement) in
a nested manner many times. Here, "nested" resampling means to randomly resample
the first dimension, then for each randomly sampled element along that dimension,
... | 5,357,981 |
def check_if_folder_is_empty_true(mocker):
"""
Test must NOT call 'os.mkdir'
:param mocker:
:return:
"""
mock_os = Mock()
mocker.patch('src.io.utils.os', mock_os)
mock_os.path.listdir.return_value = []
folder_path = 'bla/bla1/bla2/bla3'
is_empty = check_if_folder_is_emp... | 5,357,982 |
def phase_type_from_parallel_erlang2(theta1, theta2, n1, n2):
"""Returns initial probabilities :math:`\\alpha` and generator matrix :math:`S`
for a phase-type representation of two parallel Erlang channels with parametrisation
:math:`(\\theta_1, n_1)` and :math:`(\\theta_2, n_2)` (rate and steps of Erlang
... | 5,357,983 |
def get_regions(max_time_value):
"""
Partition R into a finite collection of one-dimensional regions depending on the appearing max time value.
"""
regions = []
bound = 2 * max_time_value + 1
for i in range(0, bound + 1):
if i % 2 == 0:
temp = i // 2
r = Const... | 5,357,984 |
def test_input_wsp():
""" Test putting constructor attributes in a default sub workspaces """
wsp = Workspace(input_wsp="cakes", flapjack=4, fruit=3, defaults=[])
assert(wsp.cakes is not None)
assert(wsp.cakes.flapjack == 4)
assert(wsp.cakes.fruit == 3)
assert(wsp.flapjack is None)
assert(ws... | 5,357,985 |
def write_nb(nb_node, nb_filename):
"""Rewrites notebook."""
nbformat.write(nb_node, nb_filename) | 5,357,986 |
def label_edges(g: nx.DiGraph) -> nx.DiGraph:
"""Label all the edges automatically.
Args:
g: the original directed graph.
Raises:
Exception: when some edge already has attribute "label_".
Returns:
The original directed graph with all edges labelled.
"""
g_labelled = nx... | 5,357,987 |
def report_charts(request, report, casetype='Call'):
"""Return charts for the last 4 days based on the Call Summary Data"""
# The ussual filters.
query = request.GET.get('q', '')
interval = request.GET.get('interval', 'daily')
category = request.GET.get('category', '')
if report == 'categorysumm... | 5,357,988 |
def test_nslookup():
"""
Test if it query DNS for information about a domain or ip address
"""
ret = (
"Server: ct-dc-3-2.cybage.com\n"
"Address: 172.27.172.12\n"
"Non-authoritative answer:\n"
"Name: google.com\n"
"Addresses: 2404:6800:4007:806::200e\n"
... | 5,357,989 |
def print_table(my_dict: dict, col_list: list=None):
"""
Pretty print a list of dictionaries as a dynamically sized table.
:param my_dict: The dictionary or list of dictionaries to print
:type my_dict: dict
:param col_list: The list of columns to include that correspond to keys in the dictiona... | 5,357,990 |
def test_backend_write_digital_state() -> None:
"""Test that we can write the digital state of a pin."""
backend = SBArduinoHardwareBackend("COM0", SBArduinoSerial)
serial = cast(SBArduinoSerial, backend._serial)
serial.check_data_sent_by_constructor()
# This should put the pin into the most recent ... | 5,357,991 |
def _get_optimizer(learning_rate: float, gradient_clip_norm: float):
"""Gets model optimizer."""
kwargs = {'clipnorm': gradient_clip_norm} if gradient_clip_norm > 0 else {}
return tf.keras.optimizers.Adagrad(learning_rate, **kwargs) | 5,357,992 |
def package_context(target, action='install'):
"""
A context for installing the build dependencies for a given target (or
targets). Uses apt. Removes the dependencies when the context is
exited. One may prevent the removal of some or all packages by modifying
the list within the context.
"""
... | 5,357,993 |
def is_my_message(msg):
"""
Функция для проверки, какому боту отправлено сообщение.
Для того, чтобы не реагировать на команды для других ботов.
:param msg: Объект сообщения, для которого проводится проверка.
"""
text = msg.text.split()[0].split("@")
if len(text) > 1:
if text[1] != config.bot_name:
return Fa... | 5,357,994 |
def execute_search_query(client: Client, query: Any, data_range: str) -> Dict[str, Any]:
"""Execute search job and waiting for the results
:type client: ``Client``
:param client: Http client
:type query: ``Any``
:param query: Search query
:type data_range: ``str``
:param data_range: http ... | 5,357,995 |
def static(directory: str) -> WSGIApp:
"""Return a WSGI app that serves static files under the given directory.
Powered by WhiteNoise.
"""
app = WhiteNoise(empty_wsgi_app())
if exists(directory):
app.add_files(directory)
return app | 5,357,996 |
def check_filter(id):
"""
Helper function to determine if the current crime is in the dictionary
"""
if id not in important_crime:
return 30
else:
return important_crime[id] * 30 | 5,357,997 |
def test_notebook_basics_lesson2():
""" Regression test data from notebook example.
Data created on 5/30/2015 with
np.savez('data_notebook_basics_lesson2.npz',t_resamp=t_resamp,hp_resamp=hp_resamp,hc_resamp=hc_resamp)
After gwtools changes to constants (8/24/2018), _v2 of this data was created"""
#t... | 5,357,998 |
def get_attendees_from_order(transaction):
"""
GET /v1/orders/{identifier}/attendees
:param transaction:
:return:
"""
with stash['app'].app_context():
order = OrderFactory()
order.identifier = "7201904e"
db.session.add(order)
db.session.commit() | 5,357,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.