content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_all_listening_ports() -> List[int]:
"""
Returns all tcp port numbers in LISTEN state (on any address).
Reads port state from /proc/net/tcp.
"""
res = []
with open('/proc/net/tcp', 'r') as file:
try:
next(file)
for line in file:
split_line ... | 33,500 |
async def mock_race_result() -> dict:
"""Create a mock race-result object."""
return {
"id": "race_result_1",
"race_id": "190e70d5-0933-4af0-bb53-1d705ba7eb95",
"timing_point": "Finish",
"no_of_contestants": 2,
"ranking_sequence": ["time_event_1", "time_event_2"],
... | 33,501 |
def qr_to_install_code(qr_code: str) -> tuple[zigpy.types.EUI64, bytes]:
"""Try to parse the QR code.
if successful, return a tuple of a EUI64 address and install code.
"""
for code_pattern in QR_CODES:
match = re.search(code_pattern, qr_code, re.VERBOSE)
if match is None:
... | 33,502 |
def vwr(scene, analyzer, test_number, workbook=None, sheet_format=None, agg_dict=None):
"""
Calculates Variability Weighted Return (VWR).
:param workbook: Excel workbook to be saved to disk.
:param analyzer: Backtest analyzer.
:param sheet_format: Dictionary holding formatting information such as co... | 33,503 |
def StepCommandContains(check, step_odict, step, argument_sequence):
"""Assert that a step's command contained the given sequence of arguments.
Args:
step (str) - The name of the step to check the command of.
argument_sequence (list of (str|regex)) - The expected sequence of
arguments. Strings will b... | 33,504 |
def dec2hms(dec):
"""
ADW: This should really be replaced by astropy
"""
DEGREE = 360.
HOUR = 24.
MINUTE = 60.
SECOND = 3600.
dec = float(dec)
fhour = dec*(HOUR/DEGREE)
hour = int(fhour)
fminute = (fhour - hour)*MINUTE
minute = int(fminute)
second = (fminut... | 33,505 |
def soft_update(target, source, tau):
"""
Perform DDPG soft update (move target params toward source based on weight
factor tau)
Inputs:
target (torch.nn.Module): Net to copy parameters to
source (torch.nn.Module): Net whose parameters to copy
tau (float, 0 < x < 1): Weight facto... | 33,506 |
def logfpsd(data, rate, window, noverlap, fmin, bins_per_octave):
"""Computes ordinary linear-frequency power spectral density, then multiplies by a matrix
that converts to log-frequency space.
Returns the log-frequency PSD, the centers of the frequency bins,
and the time points.
Adapted from Matlab... | 33,507 |
def ppg_dual_double_frequency_template(width):
"""
EXPOSE
Generate a PPG template by using 2 sine waveforms.
The first waveform double the second waveform frequency
:param width: the sample size of the generated waveform
:return: a 1-D numpy array of PPG waveform
having diastolic peak at the... | 33,508 |
def init_lg36(init_conf=None):
""" Optional init call to let lg36 know it can go ahead and init itself now. If this call is never made, lg36
would initialize lazily as necessary.
init_conf is optional also, if it is None, this call reduces to just a trigger to run the init procedure now
as opposed to l... | 33,509 |
def _run_fast_scandir(dir, fn_glob):
"""
Quickly scan nested directories to get a list of filenames that match the fn_glob string.
Modified from https://stackoverflow.com/a/59803793/2441026
(faster than os.walk or glob methods, and allows filename matching in subdirectories).
Parameters
-------... | 33,510 |
def wait_for_element_to_be_clickable(
self, timeout=None, poll_frequency=None, select_type=None, element=None
):
"""An Expectation for checking an element is visible and enabled such that
you can click it.
select_type - option that follows after SelectBy. (Examples: CSS, ID, XPATH, NAME)
element - l... | 33,511 |
def str_input(prompt: str) -> str:
"""Prompt user for string value.
Args:
prompt (str): Prompt to display.
Returns:
str: User string response.
"""
return input(f"{prompt} ") | 33,512 |
def action(ra_deg, dec_deg, d_kpc, pm_ra_masyr, pm_dec_masyr, v_los_kms,
verbose=False):
"""
parameters:
----------
ra_deg: (float)
RA in degrees.
dec_deg: (float)
Dec in degress.
d_kpc: (float)
Distance in kpc.
pm_ra_masyr: (float)
RA proper motion... | 33,513 |
def getProcWithParent(host,targetParentPID,procname):
""" returns (parentPID,procPID) tuple for the procname with the specified parent """
cmdStr="ps -ef | grep '%s' | grep -v grep" % (procname)
cmd=Command("ps",cmdStr,ctxt=REMOTE,remoteHost=host)
cmd.run(validateAfter=True)
sout=cmd.get_re... | 33,514 |
def temporal_autocorrelation(array):
"""Computes temporal autocorrelation of array."""
dt = array['time'][1] - array['time'][0]
length = array.sizes['time']
subsample = max(1, int(1. / dt))
def _autocorrelation(array):
def _corr(x, d):
del x
arr1 = jnp.roll(array, d, 0)
ans = arr1 * ar... | 33,515 |
def kv_detail(request, kv_class, kv_pk):
"""
GET to:
/core/keyvalue/api/<kv_class>/<kv_pk>/detail/
Returns a single KV instance.
"""
Klass = resolve_class(kv_class)
KVKlass = Klass.keyvalue_set.related.model
try:
kv = KVKlass.objects.get(pk=kv_pk)
except KVKlass.DoesNotExist... | 33,516 |
def opentrons_protocol(protocol_id):
"""Get OpenTrons representation of a protocol."""
current_protocol = Protocol.query.filter_by(id=protocol_id).first()
if not current_protocol:
flash('No such specification!', 'danger')
return redirect('.')
if current_protocol.user != current_user an... | 33,517 |
def get_link_external():
""" Return True if we should link to system BLAS / LAPACK
If True, attempt to link to system BLAS / LAPACK. Otherwise, compile
lapack_lite, and link to that.
First check ``setup.cfg`` file for section ``[lapack]`` key ``external``.
If this value undefined, then get strin... | 33,518 |
def report_strategy(strategy):
"""
Reports the assembly strategy that will be used to output.
ARGUMENTS
strategy (AssemblyStrategy): the assembly strategy that will be used for assembling
POST
The assembly strategy will be written to output.
"""
click.echo(strategy.report)
... | 33,519 |
def flag(request, comment_id, next=None):
"""
Flags a comment. Confirmation on GET, action on POST.
Templates: `comments/flag.html`,
Context:
comment
the flagged `comments.comment` object
"""
comment = get_object_or_404(comments.get_model(), pk=comment_id, site__pk=settings.... | 33,520 |
def get_nodes_for_homek8s_group(inventory, group_name) -> List[str]:
"""Return the nodes' names of the given group from the inventory as a list."""
hosts_dict = inventory['all']['children']['homek8s']['children'][group_name]['hosts']
if hosts_dict:
return list(hosts_dict.keys())
else:
return [] | 33,521 |
def test_find_by_id_cs_dt(session):
"""Assert that find an change registration DT by ID contains all expected elements."""
registration = Registration.find_by_id(200000009)
assert registration
assert registration.registration_id == 200000009
assert registration.registration_num
assert registrati... | 33,522 |
def is_blank_or_none(value: str):
"""
Returns True if the specified string is whitespace, empty or None.
:param value: the string to check
:return: True if the specified string is whitespace, empty or None
"""
try:
return "".__eq__(value.strip())
except AttributeError:
retur... | 33,523 |
def __get_play_widget(function: typing.Any) -> typing.Any:
"""Generate play widget.
:param function: Function to associate with Play.
:return: Play widget.
"""
play = widgets.interactive(
function,
i=widgets.Play(
value=0,
min=0,
max=500,
... | 33,524 |
def add_data_to_profile(id, profile_id, read_only, tree_identifier, folder_path=None, web_session=None):
"""Shares data to user group
Args:
id (int): The id of the data
profile_id (int): The id of profile
read_only (int): The flag that specifies whether the data is read only
tre... | 33,525 |
def get_activation_function(activation):
"""
Gets an activation function module given the name of the activation.
:param activation: The name of the activation function.
:return: The activation function module.
"""
if activation == 'ReLU':
return nn.ReLU()
elif activation == 'LeakyR... | 33,526 |
def plot_pairwise_analysis(data_mat, feature_columns, dependent_column, column_names):
"""
Does a basic pairwise correlation analysis between features and a dependent variable,
meaning it plots a scatter plot with a linear curve fit through it, with the R^2.
Then it plots a correlation matri... | 33,527 |
def get_value_from_time(a_node="", idx=0):
"""
gets the value from the time supplied.
:param a_node: MFn.kAnimCurve node.
:param idx: <int> the time index.
:return: <tuple> data.
"""
return OpenMaya.MTime(a_node.time(idx).value(), OpenMaya.MTime.kSeconds).value(), a_node.value(idx), | 33,528 |
def getrinputs(rtyper, graph):
"""Return the list of reprs of the input arguments to the 'graph'."""
return [rtyper.bindingrepr(v) for v in graph.getargs()] | 33,529 |
def check_cell_content(filename, sheet, identifier, column, value) :
""" Test if an excel file test content match the hypothesis
---
filename (str) : Xlsx filename to analyze
sheet (str) : Excel sheet in which the cell is located
identifier(str) : identifier identifying the... | 33,530 |
def _apply_mask(head_file, mask_file, write_dir=None,
caching=False, terminal_output='allatonce'):
"""
Parameters
----------
head_file : str
Path to the image to mask.
mask_file : str
Path to the image mask to apply.
write_dir : str or None, optional
Pat... | 33,531 |
def mars_reshape(x_i):
"""
Reshape (n_stacks, 3, 16, 112, 112) into (n_stacks * 16, 112, 112, 3)
"""
return np.transpose(x_i, (0, 2, 3, 4, 1)).reshape((-1, 112, 112, 3)) | 33,532 |
def Rz_to_coshucosv(R,z,delta=1.):
"""
NAME:
Rz_to_coshucosv
PURPOSE:
calculate prolate confocal cosh(u) and cos(v) coordinates from R,z, and delta
INPUT:
R - radius
z - height
delta= focus
OUTPUT:
(cosh(u),cos(v))
HISTORY:
2012-11-27 -... | 33,533 |
def rpFFNET_createdict(cf,ds,series):
""" Creates a dictionary in ds to hold information about the FFNET data used
to gap fill the tower data."""
# get the section of the control file containing the series
section = pfp_utils.get_cfsection(cf,series=series,mode="quiet")
# return without doing an... | 33,534 |
def test_twins_names():
"""Test twins with names"""
base = rsgame.empty(3, 2)
game = paygame.game_names(
['role'], 3, [['a', 'b']], base.all_profiles(),
np.zeros((base.num_all_profiles, base.num_strats)))
redgame = tr.reduce_game(game)
expected = paygame.game_names(
['role'],... | 33,535 |
def test_checkout_data(has_paid):
"""
Test checkout data serializer
"""
application = BootcampApplicationFactory.create()
user = application.user
run = application.bootcamp_run
if has_paid:
line = LineFactory.create(
order__status=Order.FULFILLED,
order__appl... | 33,536 |
def svn_client_relocate(*args):
"""
svn_client_relocate(char dir, char from_prefix, char to_prefix, svn_boolean_t recurse,
svn_client_ctx_t ctx, apr_pool_t pool) -> svn_error_t
"""
return _client.svn_client_relocate(*args) | 33,537 |
def get_pairs(image1, image2, global_shift, current_objects, record, params):
""" Given two images, this function identifies the matching objects and
pairs them appropriately. See disparity function. """
nobj1 = np.max(image1)
nobj2 = np.max(image2)
if nobj1 == 0:
print('No echoes found in ... | 33,538 |
def write(path, **kwargs):
"""Writes the options to the file
Assumes opt has a __print__ method"""
with open(path, 'w') as _file:
for key, arg in kwargs.items():
_file.write("--- {} ---\n\n".format(key))
_file.write(str(arg) + '\n\n')
return | 33,539 |
def stopListening():
"""
Stop the listening server which was created with a call to listen().
"""
global _listener
logging._acquireLock()
try:
if _listener:
_listener.abort = 1
_listener = None
finally:
logging._releaseLock() | 33,540 |
def plot_prediction_det_animate2(save_dir, target, prediction, epoch, index, i_plot,
plot_fn='imshow', cmap='jet', same_scale=False,
vmax=None, vmin=None, vmax_err=None, vmin_err=None):
"""Plot prediction for one input (`index`-th at epoch `epoch`)
Args:
... | 33,541 |
def getComparedVotes(request):
"""
* @api {get} /getComparedVotes/?people_same={people_same_ids}&parties_same={parties_same_ids}&people_different={people_different_ids}&parties_different={parties_different_ids} List all votes where selected MPs/PGs voted the same/differently
* @apiName getComparedVotes
... | 33,542 |
def find_switch():
"""Find switch-like boxes"""
target = [[0, 1, 0, 0], [0, 0, 1, 0]]
find_pattern(target) | 33,543 |
def get_bits(register, index, length=1):
"""
Get selected bit(s) from register while masking out the rest.
Returns as boolean if length==1
:param register: Register value
:type register: int
:param index: Start index (from right)
:type index: int
:param length: Number of bits (default 1... | 33,544 |
def remove(path):
"""
Remove the file or directory
"""
if os.path.isdir(path):
try:
os.rmdir(path)
except OSError:
logger.fatal("Unable to remove the folder: {}".format(path), exc_info=True)
else:
try:
if os.path.exists(path):
os.remove(path)
except OSError:
logger.fatal("Unable to remove t... | 33,545 |
def _dir_travel(
path: Path,
excludes: List[Callable],
handler: Callable,
logger: Optional[logging.Logger] = default_logger,
):
"""Travels the path recursively, calling the handler on each subpath.
Respects excludes, which will be called to check if this path is skipped.
"""... | 33,546 |
def plot_acceptance_ratio(
plotter: Plotter,
mcmc_tables: List[pd.DataFrame],
burn_in: int,
label_font_size=6,
dpi_request=300,
):
"""
Plot the progressive acceptance ratio over iterations.
"""
fig, axis, _, _, _, _ = plotter.get_figure()
full_df = db.load.append_tables(mcmc_tab... | 33,547 |
def addactual():
"""Add actual spendings"""
if request.method == "POST":
allPayments = []
# Current user that is logged-in saved in variable
userId = session["user_id"]
month = request.form.get("month")
housing = request.form.get("housing")
housing = float(housin... | 33,548 |
def parse_move(line):
""" Parse steps from a move string """
text = line.split()
if len(text) == 0:
raise ValueError("No steps in move given to parse. %s" % (repr(line)))
steps = []
for step in text:
from_ix = alg_to_index(step[1:3])
if len(step) > 3:
if step[3] ... | 33,549 |
def test_levensthein_dist() -> None:
"""
Test our implemented levensthein distance function for measuring string similarity.
"""
assert (
levensthein_dist("horse", "ros") == 3
and levensthein_dist("", "hello") == 5
and levensthein_dist("lululul", "") == 7
and levensthein_... | 33,550 |
def get_conf_path(run_id):
"""
Generate path for storing/loading configuration file
:param run_id (str): run ID to be used
:return: full file path for storing/loading config file
"""
return os.path.join('conf', run_id + '.ini') | 33,551 |
def get_tensor_name(node_name, output_slot):
"""Get tensor name given node name and output slot index.
Args:
node_name: Name of the node that outputs the tensor, as a string.
output_slot: Output slot index of the tensor, as an integer.
Returns:
Name of the tensor, as a string.
"""
return "%s:%d"... | 33,552 |
def EstimateMarriageSurvival(resp):
"""Estimates the survival curve.
resp: DataFrame of respondents
returns: pair of HazardFunction, SurvivalFunction
"""
# NOTE: Filling missing values would be better than dropping them.
complete = resp[resp.evrmarry == 1].agemarry.dropna()
ongoing = resp[... | 33,553 |
def generate_all_RGB_combinations(pixel_bits_count: int):
"""Generates all possible combinations of bit spread across all colour channels.
"""
for r in range(0, pixel_bits_count+1):
for g in range(0, pixel_bits_count+1):
for b in range(0, pixel_bits_count+1):
if r + g + b... | 33,554 |
def shipengine_error_with_no_error_type() -> ShipEngineError:
"""Return a ShipEngineError that only has the error_type set to None."""
raise ShipEngineError(
request_id="req_a523b1b19bd54054b7eb953f000e7f15",
message="The is a test exception",
error_source="shipengine",
error_typ... | 33,555 |
def get_cowell_data():
"""
Gets Cowell data.
:return: Data and headers.
"""
n = 10000
Y = np.random.normal(0, 1, n)
X = np.random.normal(Y, 1, n)
Z = np.random.normal(X, 1, n)
D = np.vstack([Y, X, Z]).T
return D, ['Y', 'X', 'Z'] | 33,556 |
def is_str_str_tuple(t):
"""Is this object a tuple of two strings?"""
return (isinstance(t, tuple) and len(t) == 2
and isinstance(t[0], basestring)
and isinstance(t[1], basestring)) | 33,557 |
def test_beer_lambert(fname, fmt, tmp_path):
"""Test converting NIRX files."""
assert fmt in ('nirx', 'fif')
raw = read_raw_nirx(fname)
if fmt == 'fif':
raw.save(tmp_path / 'test_raw.fif')
raw = read_raw_fif(tmp_path / 'test_raw.fif')
assert 'fnirs_cw_amplitude' in raw
assert 'fn... | 33,558 |
def g(dist, aq):
"""
Compute function g (Lemma 5) for a given full parent isntantiation.
Parameters
----------
dists: list ints
Counts of the child variable for a given full parent instantiation.
aq: float
Equivalent sample size divided by the produc... | 33,559 |
def save_2D_animation(embeddings, target_optimizers, emb_space_sizes,
total_train_losses, total_test_losses,
n_bins=100, cmap_name='jet', **plotting_kwargs):
"""Utility function for visualizing the changes in weights over time in
UMAP space. The visualization is in 2D... | 33,560 |
def plot_scatter(ax: Axes,
eps: array,
gnt: array,
labels: Labels,
leg: Labels,
pst: Styles,
psm: Styles,
txtopts: Options,
legopts: Options):
"""
Plot all data and legend
... | 33,561 |
def order_tweets_by_polarity(tweets, positive_highest=True):
"""Sort the tweets by polarity, receives positive_highest which determines
the order. Returns a list of ordered tweets."""
reverse = True if positive_highest else False
return sorted(tweets, key=lambda tweet: tweet.polarity, reverse=reverse... | 33,562 |
def text_file_md5(filename, exclude_lines=None, exclude_re=None,
prepend_lines=None, append_lines=None):
"""Get a MD5 (check) sum of a text file.
Works in the same way as `file_md5()` function but ignores newlines
characters and excludes lines from the file as well as prepend or
appen... | 33,563 |
def read_in_Reff_file(file_date, VoC_flag=None, scenario=''):
"""
Read in Reff h5 file produced by generate_RL_forecast.
Args:
file_date: (date as string) date of data file
VoC_date: (date as string) date from which to increase Reff by VoC
"""
from scipy.stats import beta
from p... | 33,564 |
def main(argv):
"""Main Compute Demo
When invoked from the command line, it will connect using secrets.py
(see secrets.py-dist for instructions and examples), and perform the
following tasks:
- List current nodes
- List available images (up to 10)
- List available sizes (up to 10)
"""
... | 33,565 |
def unregister_domain(domain):
"""Unregisters a domain from reporting.
Unregistering a domain that isn't registered is a no-op.
"""
keys = (
'registered_for_reporting',
'resolution_report',
'resolution_report_updated',
'delta_report',
'delta_report_updated',
... | 33,566 |
def string_with_fixed_length(s="", l=30):
"""
Return a string with the contents of s plus white spaces until length l.
:param s: input string
:param l: total length of the string (will crop original string if longer than l)
:return:
"""
s_out = ""
for i in range(0, l):
if i < len... | 33,567 |
def fetch_ref_proteomes():
"""
This method returns a list of all reference proteome accessions available
from Uniprot
"""
ref_prot_list = []
response = urllib2.urlopen(REF_PROT_LIST_URL)
for ref_prot in response:
ref_prot_list.append(ref_prot.strip())
return ref_prot_list | 33,568 |
def test_create_without_description(location):
"""test_create_without_description.
"""
location_obj = Location.objects.create(name=location.name, is_demo=False)
assert isinstance(location_obj, Location) | 33,569 |
def load(fp: BinaryIO, *, fmt=None, **kwargs) -> TextPlistTypes:
"""Read a .plist file (forwarding all arguments)."""
if fmt is None:
header = fp.read(32)
fp.seek(0)
if FMT_TEXT_HANDLER["detect"](header):
fmt = PF.FMT_TEXT
if fmt == PF.FMT_TEXT:
return F... | 33,570 |
def test_get_points_within_radius_of_cameras_no_points():
"""Catch degenerate input."""
wTi0 = Pose3(Rot3(), np.zeros(3))
wTi1 = Pose3(Rot3(), np.array([10.0, 0, 0]))
wTi_list = [wTi0, wTi1]
points_3d = np.zeros((0, 3))
radius = 10.0
nearby_points_3d = geometry_comparisons.get_points_withi... | 33,571 |
def load_network_interface_instance_to_subnet_relations(neo4j_session: neo4j.Session, update_tag: int) -> None:
"""
Creates (:EC2Instance)-[:PART_OF_SUBNET]->(:EC2Subnet) if
(:EC2Instance)--(:NetworkInterface)--(:EC2Subnet).
"""
ingest_network_interface_instance_relations = """
MATCH (i:EC2Insta... | 33,572 |
def get_rixs(header, light_ROI=[0, np.inf, 0, np.inf],
curvature=np.array([0., 0., 0.]), bins=1, ADU_per_photon=None,
detector='rixscam_centroids',
min_threshold=-np.inf, max_threshold=np.inf,
background=None):
"""
Create rixs spectra according to procces_dict... | 33,573 |
def _swig_add_metaclass(metaclass):
"""Class decorator for adding a metaclass to a SWIG wrapped class - a slimmed down version of six.add_metaclass"""
def wrapper(cls):
return metaclass(cls.__name__, cls.__bases__, cls.__dict__.copy())
return wrapper | 33,574 |
def create_affected_entities_description(security_data: SecurityData, limit: int = 5) -> str:
"""Create a description of the entities which are affected by a security problem.
:param security_data: the security details for which to create the description
:param limit: the maximum number of entities to list ... | 33,575 |
def amac_person_org_list_ext():
"""
中国证券投资基金业协会-信息公示-从业人员信息-基金从业人员资格注册外部公示信息
http://gs.amac.org.cn/amac-infodisc/res/pof/extperson/extPersonOrgList.html
:return:
:rtype: pandas.DataFrame
"""
data = get_data(url=amac_person_org_list_ext_url, payload=amac_person_org_list_ext_payload)
need_... | 33,576 |
def concatenate(arrays, axis=0, _no_check=False, align=False, **kwargs):
""" concatenate several DimArrays
Parameters
-----------
arrays : list of DimArrays
arrays to concatenate
axis : int or str
axis along which to concatenate (must exist)
align : bool, optional
align... | 33,577 |
def ele_types(eles):
"""
Returns a list of unique types in eles
"""
return list(set([e['type'] for e in eles] )) | 33,578 |
def colorful_subgraph(G, colors, k, s, subgraph_type, get_detail=True, verbose=False):
"""Detect if colorful path exists fom s to any node by dynamic programming.
Args:
G (nx.Graph): with n nodes and m edges
colors (list): list of integers represents node colors
k (int): number of colors... | 33,579 |
def find_all_combos(
conformer,
delta=float(120),
cistrans=True,
chiral_centers=True):
"""
A function to find all possible conformer combinations for a given conformer
Params:
- conformer (`Conformer`) an AutoTST `Conformer` object of interest
- delta (int or float):... | 33,580 |
def hmc2(f, x, options, gradf, *args, **kargs):
"""
SAMPLES = HMC2(F, X, OPTIONS, GRADF)
Description
SAMPLES = HMC2(F, X, OPTIONS, GRADF) uses a hybrid Monte Carlo
algorithm to sample from the distribution P ~ EXP(-F), where F is the
first argument to HMC2. The Markov chain starts at the... | 33,581 |
def test_version(decider_mock, command_line_args, capsys):
"""Ensure version is displayed."""
# Run function
parser = seddy_main.build_parser()
with pytest.raises(SystemExit) as e:
parser.parse_args(command_line_args)
assert e.value.code == 0
# Check output
res_out = capsys.readoute... | 33,582 |
def generate_abbreviations(
labels: tp.Iterable[str],
max_abbreviation_len: int = 3,
dictionary: tp.Union[tp.Tuple[str], str] = "cdfghjklmnpqrstvxz"):
"""
Returns unique abbreviations for the given labels. Generates the abbreviations with
:func:`beatsearch.utils.generate_unique_abbre... | 33,583 |
def test_address__DeletePostalAddressForm__1(person_data, browser):
"""`DeletePostalAddressForm` allows to delete a home page address."""
browser.login('editor')
browser.open(browser.PERSON_DELETE_ENTRY_URL)
browser.getControl('RST-Software').click()
browser.getControl('Delete entry').click()
as... | 33,584 |
def test_view_change_done_delayed(txnPoolNodeSet, looper, sdk_pool_handle, sdk_wallet_client):
"""
A node is slow so is behind other nodes, after view change, it catches up
but it also gets view change message as delayed, a node should start
participating only when caught up and ViewChangeCone quorum re... | 33,585 |
def best_hand(hand):
"""Из "руки" в 7 карт возвращает лучшую "руку" в 5 карт """
i = iter(combinations(hand, 5))
best_rank = 0, 0, 0
best_combination = None
for combination in i:
current_rank = hand_rank(combination)
if compare(current_rank, best_rank):
best_rank = curren... | 33,586 |
def calculate_label_counts(examples):
"""Assumes that the examples each have ONE label, and not a distribution over labels"""
label_counts = {}
for example in examples:
label = example.label
label_counts[label] = label_counts.get(label, 0) + 1
return label_counts | 33,587 |
def add_custom_tax(
df,
segment_income,
w,
base_income,
incidence,
name,
total=None,
ratio=None,
verbose=True,
):
"""Add a custom tax based on incidence analysis driven by percentiles.
:param df: DataFrame.
:param segment_income: Income measure used to segment tax units ... | 33,588 |
def printer(arg1):
"""
Even though 'times' is destroyed when printer() has been called,
the 'inner' function created remembers what times is. Same goes
for the argument arg1.
"""
times = 3
def inner():
for i in range(times): print(arg1)
return inner | 33,589 |
def from_get_proxy():
"""
From "http://www.getproxy.jp"
:return:
"""
base = 'http://www.getproxy.jp/proxyapi?' \
'ApiKey=659eb61dd7a5fc509bef01f2e8b15669dfdb0f54' \
'&area={:s}&sort=requesttime&orderby=asc&page={:d}'
urls = [base.format('CN', i) for i in range(1, 25)]
... | 33,590 |
def KORL(a, kappa=None):
""" log rounds k-ary OR """
k = len(a)
if k == 1:
return a[0]
else:
t1 = KORL(a[:k//2], kappa)
t2 = KORL(a[k//2:], kappa)
return t1 + t2 - t1.bit_and(t2) | 33,591 |
def verify(token):
"""Verifies a JWS token, returning the parsed token if the token has a
valid signature by the key provided by the key of the OpenID
Connect server stated in the ISS claim of the token. If the
signature does not match that key, None is returned.
"""
unverified_token_data = jso... | 33,592 |
def get_listing_panel(tool, ghidra):
""" Get the code listing UI element, so we can get up-to-date location/highlight/selection """
cvs = tool.getService(ghidra.app.services.CodeViewerService)
return cvs.getListingPanel() | 33,593 |
def template_data(environment, template_name="report_html.tpl", **kwds):
"""Build an arbitrary templated page.
"""
template = env.get_template(template_name)
return template.render(**environment) | 33,594 |
def resnet152_ibn_a(**kwargs):
"""
Constructs a ResNet-152-IBN-a model.
"""
model = ResNet_IBN(block=Bottleneck_IBN,
layers=[3, 8, 36, 3],
ibn_cfg=('a', 'a', 'a', None),
**kwargs)
return model | 33,595 |
def test_update(session):
"""Assert user updation."""
user = create_user(session)
user.update({'phone': '123456897'})
found = user.find_by_oauth_id(user.oauth_id)
assert found.phone == '123456897' | 33,596 |
def calibratePose(pts3,pts2,cam,params_init):
"""
Calibrates the camera to match the view calibrated by updating R,t so that pts3 projects
as close as possible to pts2
:param pts3: Coordinates of N points stored in a array of shape (3,N)
:param pts2: Coordinates of N points stored in a array of shap... | 33,597 |
def test_wait_for_task_interval_custom(index_with_documents, small_movies):
"""Tests call to wait for an update with custom interval."""
index = index_with_documents()
response = index.add_documents(small_movies)
assert 'uid' in response
start_time = datetime.now()
wait_update = index.wait_for_t... | 33,598 |
def image_to_base64(file_image):
"""
ESSA FUNÇÃO TEM COMO OBJETIVO, CONVERTER FORMATO DE INPUT (PNG) -> BASE64
O ARQUIVO OBTIDO (PNG) É SALVO NA MÁQUINA QUE ESTÁ EXECUTANDO O MODELO.
# Arguments
file_image - Required : Caminho do arquivo
... | 33,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.