content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def household_id_list(filelist, pidp):
""" For a set of waves, obtain a list of household IDs belonging to the same individual. """
hidp_list = []
wave_list = []
wn = {1:'a', 2:'b', 3:'c', 4:'d', 5:'e', 6:'f', 7:'g'}
c=1
for name in filelist:
print("Loading wave %d data..." % c)
... | 5,333,500 |
def biggest_labelizer_arbitrary(metrics: dict, choice: str, *args, **kwargs) -> Tuple[str, float]:
"""Given dict of metrics result, returns (key, metrics[key]) whose value is maximal."""
metric_values = list(metrics.values())
metric_keys = list(metrics.keys())
# print(items)
big = metric_values[0]
draws = [... | 5,333,501 |
def _seaborn_viz_histogram(data, x: str, contrast: Optional[str] = None, **kwargs):
"""Plot a single histogram.
Args:
data (DataFrame): The data
x (str): The name of the column to plot.
contrast (str, optional): The name of the categorical column to use for multiple contrasts.
*... | 5,333,502 |
def test_connect_args():
"""
Tests connect string
"""
engine = conftest.get_engine()
try:
results = engine.execute('select version from sys.version').fetchone()
assert results is not None
finally:
engine.dispose() | 5,333,503 |
def str2bool( s ):
"""
Description:
----------
Converting an input string to a boolean
Arguments:
----------
[NAME] [TYPE] [DESCRIPTION]
(1) s dict, str The string which
Returns:
----------
T... | 5,333,504 |
def im_detect(net, im, boxes=None):
"""Detect object classes in an image given object proposals.
Arguments:
net (caffe.Net): Fast R-CNN network to use
im (ndarray): color image to test (in BGR order)
boxes (ndarray): R x 4 array of object proposals or None (for RPN)
Returns:
... | 5,333,505 |
def preCSVdatagen(xy_p, radius, nbin, PlainFirst):
"""Format the data before generating the csv input for ili'.
Args:
xy_p (str): path to the X and Y coordiantes of ablation marks .npy file.
radius (int): displayed radius of the marks in ili'.
nbin (int): bin factor used to bin the imag... | 5,333,506 |
def dispatch_error_adaptor(func):
"""Construct a signature isomorphic to dispatch_error.
The actual handler will receive only arguments explicitly
declared, and a possible tg_format parameter.
"""
def adaptor(controller, tg_source,
tg_errors, tg_exceptions, *args, **kw):
tg_for... | 5,333,507 |
def address_split(address, env=None):
"""The address_split() function splits an address into its four
components. Address strings are on the form
detector-detectorID|device-deviceID, where the detectors must be in
dir(xtc.DetInfo.Detector) and device must be in
(xtc.DetInfo.Device).
@param address Full dat... | 5,333,508 |
def solveGroth(A, n, init_val=None):
"""
...
Parameters
----------
A: np.matrix
dfajdslkf
n: int
ddddddd
init_val: float, optional
dsfdsafdasfd
Returns
-------
list of
float:
float:
float:
float:
"""
eps=0.5
eta=... | 5,333,509 |
def verify_any(func, *args, **kwargs):
"""
Assert that any of `func(*args, **kwargs)` are true.
"""
return _verify(func, 'any', *args, **kwargs) | 5,333,510 |
def can_create_election(user_id, user_info):
""" for now, just let it be"""
return True | 5,333,511 |
def get_system_language():
""" Get system language and locale """
try:
default_locale = locale.getdefaultlocale()
except ValueError:
if IS_MAC:
# Fix for "ValueError: unknown locale: UTF-8" on Mac.
# The default English locale on Mac is set as "UTF-8" instead of "en-U... | 5,333,512 |
def circle_pattern(pattern_radius,
circle_radius,
count,
center=[0.0, 0.0],
angle=None,
**kwargs):
"""
Create a Path2D representing a circle pattern.
Parameters
------------
pattern_radius : float
R... | 5,333,513 |
def boolean(input):
"""Convert the given input to a boolean value.
Intelligently handles boolean and non-string values, returning
as-is and passing to the bool builtin respectively.
This process is case-insensitive.
Acceptable values:
True
* yes
* y
* ... | 5,333,514 |
def check_analyzed_packages_count(context, num=1):
"""Check number of analyzed packages."""
context_reponse_existence_check(context)
json_data = context.response.json()
check_attribute_presence(json_data, "result")
result = json_data["result"]
check_attribute_presence(result, "data")
data ... | 5,333,515 |
def generate_edges(graph, bucketing='epsilon', eps=1e-2, k=3):
"""Generate the set of edges
"""
u, v, w = find(graph)
if bucketing == 'epsilon':
w_prime = np.array(w/eps, dtype=np.int32)
elif bucketing == 'kmeans':
clf = KMeans(n_clusters=k)
clf.fit(w.reshape((-1, 1)))
... | 5,333,516 |
def find_horizontal_up_down_links(tc, u, out_up=None, out_down=None):
"""Find indices of nodes that locate
at horizontally upcurrent and downcurrent directions
"""
if out_up is None:
out_up = np.zeros(u.shape[0], dtype=np.int)
if out_down is None:
out_down = np.zeros(u.shape[0], d... | 5,333,517 |
def PyParser_SimpleParseStringFlagsFilename(space, str, filename, start, flags):
"""Parse Python source code from str using the start token start according to
the flags argument. The result can be used to create a code object which can
be evaluated efficiently. This is useful if a code fragment must be eva... | 5,333,518 |
def write_file(filename, content):
"""Write content to a file and set the correct file permission """
with open(os.open(filename,
os.O_CREAT | os.O_WRONLY, 0o600), 'w') as file:
yaml.safe_dump(content, file, default_flow_style=False, sort_keys=False) | 5,333,519 |
def _compute_composite_beta(model, robo, j, i):
"""
Compute the composite beta wrench for link i.
Args:
model: An instance of DynModel
robo: An instance of Robot
j: link number
i: antecedent value
Returns:
An instance of DynModel that contains all the new values... | 5,333,520 |
def check_system_type(product_dict):
""" This function checks for errors in the system name input
Parameters - YAML for product information .dict
----------
Returns - checked product_dict
-------
"""
#System system assertions
System_Type = product_dict.get('Syst... | 5,333,521 |
def pos(x, y):
"""Returns floored and camera-offset x,y tuple.
Setting out of bounds is possible, but getting is not; mod in callers for get_at.
"""
return (flr(xo + x), flr(yo + y)) | 5,333,522 |
def test_create_vm_on_available_memory_node(request, admin_session, image,
keypair, harvester_api_endpoints):
"""
Create VM with resource with one node in cluster memory
Covers:
virtual-machines-72-vm with resource with one node in cluster memory
"""
... | 5,333,523 |
def _check_blockstream_for_transactions(
accounts: List[BTCAddress],
) -> Dict[BTCAddress, Tuple[bool, FVal]]:
"""May raise connection errors or KeyError"""
have_transactions = {}
for account in accounts:
url = f'https://blockstream.info/api/address/{account}'
response_data = request... | 5,333,524 |
def metropolis_hastings(
proposal: Proposal,
state: State,
step_size: float,
ns: int,
unif: float,
inverse_transform: Callable
) -> Tuple[State, Info, np.ndarray, bool]:
"""Computes the Metropolis-Hastings accept-reject criterion given a proposal, a
current state ... | 5,333,525 |
def continuous_future(root_symbol_str, offset=0, roll="volume", adjustment="mul", bundle=None):
"""
Return a ContinuousFuture object for the specified root symbol in the specified bundle
(or default bundle).
Parameters
----------
root_symbol_str : str
The root symbol for the future chai... | 5,333,526 |
def Now():
"""Returns a datetime.datetime instance representing the current time.
This is just a wrapper to ease testing against the datetime module.
Returns:
An instance of datetime.datetime.
"""
return datetime.datetime.now() | 5,333,527 |
def test_basic_auth_with_session(basic_auth_client):
"""
"""
res = None
with basic_auth_client._session() as s:
res = s.basic_auth('user', 'password')
assert res['authenticated'] is True | 5,333,528 |
def ndvi_list_hdf(hdf_dir, satellite=None):
"""
List all the available HDF files, grouped by tile
Args:
hdf_dir: directory containing one subdirectory per year which contains
HDF files
satellite: None to select both Tera and Aqua, 'mod13q1' for MODIS,
'myd... | 5,333,529 |
def read_levels(dir_path: str,
progress_monitor: PyramidLevelCallback = None) -> List[xr.Dataset]:
"""
Read the of a multi-level pyramid with spatial resolution
decreasing by a factor of two in both spatial dimensions.
:param dir_path: The directory path.
:param progress_monitor: An... | 5,333,530 |
def register_type_representer(t, func):
"""
Register a function that will act as a type representer for the specified type.
Parameters:
t: the type
func: the function that will be used to produce a representation for values of type t
"""
typerepresenters[t] = func | 5,333,531 |
def test_cback():
"""
Test the C backend.
"""
assert all(
map(
lambda x: x is not None,
ising.__main__.main(pass_args=__ARGS + ["--backend", "c"], test=True),
)
) | 5,333,532 |
def create_provisioned_product_name(account_name: str) -> str:
"""
Replaces all space characters in an Account Name with hyphens,
also removes all trailing and leading whitespace
"""
return account_name.strip().replace(" ", "-") | 5,333,533 |
def case34():
"""
Create the IEEE 34 bus from IEEE PES Test Feeders:
"https://site.ieee.org/pes-testfeeders/resources/”.
OUTPUT:
**net** - The pandapower format network.
"""
net = pp.create_empty_network()
# Linedata
# CF-300
line_data = {'c_nf_per_km': 3.825097... | 5,333,534 |
def set_metadata(candidates, traces, dependencies, pythons):
"""Add "metadata" to candidates based on the dependency tree.
Metadata for a candidate includes markers and a specifier for Python
version requirements.
:param candidates: A key-candidate mapping. Candidates in the mapping will
have ... | 5,333,535 |
def _hack_namedtuple(cls):
"""Make class generated by namedtuple picklable."""
name = cls.__name__
fields = cls._fields
def reduce(self):
return (_restore, (name, fields, tuple(self)))
cls.__reduce__ = reduce
cls._is_namedtuple_ = True
return cls | 5,333,536 |
def create_symbolize_task_if_needed(testcase):
"""Creates a symbolize task if needed."""
# We cannot run symbolize job for custom binaries since we don't have any
# archived symbolized builds.
if build_manager.is_custom_binary():
return
# Make sure we have atleast one symbolized url pattern defined in jo... | 5,333,537 |
def load_config(settings_file='./test_settings.py'):
"""
Loads the config files merging the defaults
with the file defined in environ.PULLSBURY_SETTINGS if it exists.
"""
config = Config(os.getcwd())
if 'PULLSBURY_SETTINGS' in os.environ:
config.from_envvar('PULLSBURY_SETTINGS')
els... | 5,333,538 |
def build_model():
"""
Returns built and tuned model using pipeline
Parameters:
No arguments
Returns:
cv (estimator): tuned model
"""
pipeline = Pipeline([
('Features', FeatureUnion([
('text_pipeline', Pipeline([
('vect', CountVe... | 5,333,539 |
def date_range(
start: pandas._libs.tslibs.timestamps.Timestamp,
end: pandas._libs.tslibs.timestamps.Timestamp,
freq: Literal["1M"],
):
"""
usage.dask: 1
"""
... | 5,333,540 |
def INPUT_BTN(**attributes):
"""
Utility function to create a styled button
"""
return SPAN(INPUT(_class = "button-right",
**attributes),
_class = "button-left") | 5,333,541 |
def load_annotations(file_path):
"""Loads a file containing annotations for multiple documents.
The file should contain lines with the following format:
<DOCUMENT ID> <LINES> <SPAN START POSITIONS> <SPAN LENGTHS> <SEVERITY>
Fields are separated by tabs; LINE, SPAN START POSITIONS and SPAN LENGTHS
... | 5,333,542 |
def search(request, template_name='blog/post_search.html'):
"""
Search for blog posts.
This template will allow you to setup a simple search form that will try to return results based on
given search strings. The queries will be put through a stop words filter to remove words like
'the', 'a', or 'h... | 5,333,543 |
def orient_data (data, header, header_out=None, MLBG_rot90_flip=False, log=None,
tel=None):
"""Function to remap [data] from the CD matrix defined in [header] to
the CD matrix taken from [header_out]. If the latter is not
provided the output orientation will be North up, East left.
I... | 5,333,544 |
def _batchnorm_to_groupnorm(module: nn.modules.batchnorm._BatchNorm) -> nn.Module:
"""
Converts a BatchNorm ``module`` to GroupNorm module.
This is a helper function.
Args:
module: BatchNorm module to be replaced
Returns:
GroupNorm module that can replace the BatchNorm module provi... | 5,333,545 |
def uninstall_problem(problem_name):
"""
Uninstalls a given problem, which means that the generated debian package
and source files within the SHARED_ROOT directory are removed.
An uninstalled problem will no longer appear when listing problems, even
if deployed instances remain (undeploying all in... | 5,333,546 |
def _check_wd():
"""
This function checks that the working directory exists with write permission
:raises SystemExit: if the folder is absent or the user has no write permission
"""
if not os.path.exists(_plot_dir):
_logger.warning('Impossible to read %s' % _plot_dir)
raise SystemExi... | 5,333,547 |
def main(cfg, dry_run):
"""Work with domino compute nodes from your local machine.
To work with files in a domino project locally, you need
to either mount the domino directory on your machine (not yet
supported by this script) or copy files back and forth.
This script manages that copy back-and-fo... | 5,333,548 |
def _compute_bic(
data: np.array,
n_clusters: int
) -> BICResult:
"""Compute the BIC statistic.
Parameters
----------
data: np.array
The data to cluster.
n_clusters: int
Number of clusters to test.
Returns
-------
results: BICResult
The results as a BICR... | 5,333,549 |
def release_branch_name(config):
"""
build expected release branch name from current config
"""
branch_name = "{0}{1}".format(
config.gitflow_release_prefix(),
config.package_version()
)
return branch_name | 5,333,550 |
def torch2numpy(data):
""" Transfer data from the torch tensor (on CPU) to the numpy array (on CPU). """
return data.numpy() | 5,333,551 |
def test_openmm_nonbonded_methods(inputs):
"""See test_nonbonded_method_resolution in openff/toolkit/tests/test_forcefield.py"""
vdw_method = inputs["vdw_method"]
electrostatics_method = inputs["electrostatics_method"]
periodic = inputs["periodic"]
result = inputs["result"]
molecules = [create_... | 5,333,552 |
def register_cli_handler(instance, **options):
"""
registers a new alembic cli handler or replaces the existing one
if `replace=True` is provided. otherwise, it raises an error
on adding a cli handler which is already registered.
:param AlembicCLIHandlerBase instance: alembic cli handler to be regi... | 5,333,553 |
def read_point_cloud_file(file_path):
"""Read bfpc dump and print the frame ID and number of returns in the received frame.
This example will stop, when the dump is completly read out.
:param file_path: Path to dump file
"""
file_stream = blickfeld_scanner.stream.point_cloud(from_file=file_path) ... | 5,333,554 |
def new_schema(name, public_name, is_active=True, **options):
"""
This function adds a schema in schema model and creates physical schema.
"""
try:
schema = Schema(name=name, public_name=public_name, is_active=is_active)
schema.save()
except IntegrityError:
raise Exception('... | 5,333,555 |
def ROW(cell_reference):
"""Returns the row number of a specified cell."""
raise NotImplementedError() | 5,333,556 |
def find_appropriate_timestep(simulation_factory,
equilibrium_samples,
M,
midpoint_operator,
temperature,
timestep_range,
DeltaF_neq_thresho... | 5,333,557 |
def critical_bands():
"""
Compute the Critical bands as defined in the book:
Psychoacoustics by Zwicker and Fastl. Table 6.1 p. 159
"""
# center frequencies
fc = [
50,
150,
250,
350,
450,
570,
700,
840,
1000,
1170,
... | 5,333,558 |
def repackage(r, amo_id, amo_file, target_version=None, sdk_dir=None):
"""Pull amo_id/amo_file.xpi, schedule xpi creation, return hashtag
"""
# validate entries
# prepare data
hashtag = get_random_string(10)
sdk = SDK.objects.all()[0]
# if (when?) choosing sdk_dir will be possible
# sdk ... | 5,333,559 |
def execute_shifts(node):
"""
The function only needs one traversal of the children of v to
execute all shifts computed and memorized in MOVESUBTREE.
"""
shift = 0
change = 0
for child in node.children[::-1]: # all children from right to left
child.prelim += shift
ch... | 5,333,560 |
def save_group_df_lengths(df,
root_path:str):
"""Finds the number of posts made in each group, orders them and saves in file
Args:
df: pandas DataFrame
root_path: path to the current directory
Returns: saves a resource file of group ids and their lengths
"""
df =... | 5,333,561 |
def _click(event, x, y, flags, param):
"""
Helper func.
Record the pixel location of click on an image and annotate the image with
a color coded box. Green box: recorded as a "positive example", Blue box:
recorded as a "negative example."
Modified from:
http://www.pyimagesearch.com/2015/03... | 5,333,562 |
def edges_to_adj_list(edges):
"""
Transforms a set of edges in an adjacency list (represented as a dictiornary)
For UNDIRECTED graphs, i.e. if v2 in adj_list[v1], then v1 in adj_list[v2]
INPUT:
- edges : a set or list of edges
OUTPUT:
- adj_list: a dictionary with the vertices as ... | 5,333,563 |
def _get_lookups(
name: str,
project: interface.Project,
base: Optional[str] = None) -> list[str]:
"""[summary]
Args:
name (str): [description]
design (Optional[str]): [description]
kind (Optional[str]): [description]
Returns:
list[str]: [description]
... | 5,333,564 |
def _assign_id(obj, seen_objs, obj_by_id, attr='_id', seen_obj=None):
"""Assign a unique ID to obj, and track all ids in obj_by_id."""
if seen_obj is None:
seen_obj = obj
if seen_obj not in seen_objs:
if not hasattr(obj, attr):
obj_by_id.append(obj)
setattr(obj, attr,... | 5,333,565 |
def unwrap(value):
"""
Unwraps the given Document or DocumentList as applicable.
"""
if isinstance(value, Document):
return value.to_dict()
elif isinstance(value, DocumentList):
return value.to_list()
else:
return value | 5,333,566 |
def home_all():
"""Home page view.
On this page a summary campaign manager view will shown with all campaigns.
"""
context = dict(
oauth_consumer_key=OAUTH_CONSUMER_KEY,
oauth_secret=OAUTH_SECRET,
all=True,
map_provider=map_provider()
)
# noinspection PyUnresol... | 5,333,567 |
def _sqrt(x):
"""_sqrt."""
isnumpy = isinstance(x, np.ndarray)
isscalar = np.isscalar(x)
return np.sqrt(x) if isnumpy else math.sqrt(x) if isscalar else x.sqrt() | 5,333,568 |
def cli_make_release_metadata(raw_metadata):
"""Make a data packet suitable for release."""
raw_meta = pd.read_csv(raw_metadata, dtype=str)
meta, cntrl_meta, dupe_meta, dupe_map = clean_metadata_table(raw_meta)
meta.to_csv('release_metadata.csv')
cntrl_meta.to_csv('control_metadata.csv')
dupe_m... | 5,333,569 |
def update_subnet(context, id, subnet):
"""Update values of a subnet.
: param context: neutron api request context
: param id: UUID representing the subnet to update.
: param subnet: dictionary with keys indicating fields to update.
valid keys are those that have a value of True for 'allow_put'... | 5,333,570 |
def run_system(
main: Callable,
args: Optional[Tuple] = None,
kwargs: Optional[Dict] = None,
requirements: Optional[List[str]] = None,
startup: Optional[Callable] = None,
cleanup: Optional[Callable] = None,
keyboard_interrupt: Optional[Callable] = None,
sy... | 5,333,571 |
def validate_params():
"""@rtype bool"""
def validate_single_param(param_name, required_type):
"""@rtype bool"""
inner_result = True
if not rospy.has_param(param_name):
rospy.logfatal('Parameter {} is not defined but needed'.format(param_name))
inner_result = Fal... | 5,333,572 |
def run_test_general_base_retrieval_methods(query_dic, query_types, trec_cast_eval, similarity, string_params,
searcher: SimpleSearcher, reranker,
write_to_trec_eval, write_results_to_file, reranker_query_config,
... | 5,333,573 |
def user_exists(username):
"""Return True if the username exists, or False if it doesn't."""
try:
adobe_api.AdobeAPIObject(username)
except adobe_api.AdobeAPINoUserException:
return False
return True | 5,333,574 |
def bags_containing_bag(bag: str, rules: dict[str, list]) -> int:
"""Returns the bags that have bag in their rules."""
return {r_bag
for r_bag, r_rule in rules.items()
for _, r_color in r_rule
if bag in r_color} | 5,333,575 |
def default_mutable_arguments():
"""Explore default mutable arguments, which are a dangerous game in themselves.
Why do mutable default arguments suffer from this apparent problem? A function's
default values are evaluated at the point of function definition in the defining
scope. In particular, we can ... | 5,333,576 |
def is_text_file(file_):
"""
detect if file is of type text
:param file_: file to be tested
:returns: `bool` of whether the file is text
"""
with open(file_, 'rb') as ff:
data = ff.read(1024)
return not is_binary_string(data) | 5,333,577 |
def soft_update_datetime_field(
model_inst: models.Model,
field_name: str,
warehouse_field_value: Union[datetime, None],
) -> List[str]:
"""
Uses Django ORM to update DateTime field of model instance if the field value is null and the warehouse data is non-null.
"""
model_name: str = model_i... | 5,333,578 |
def plot_confusion_matrix(
y_true,
y_pred,
normalize=False,
cmap=plt.cm.Blues,
label_list = None,
visible=True,
savepath=None):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
... | 5,333,579 |
def test_budget_get_nonexistent(base_data, client):
"""The status code is 404 when the budget does not exist"""
user, token, base_budget_list = base_data
response = client.get('/budgets/22968743-5e64-481d-a5d7-8cb46df035e5', headers={
'Authorization': f'bearer {token}'
})
assert response.status_code... | 5,333,580 |
def _test_pressure_reconstruction(self, g, recon_p, point_val, point_coo):
"""
Testing pressure reconstruction. This function uses the reconstructed
pressure local polynomial and perform an evaluation at the Lagrangian
points, and checks if the those values are equal to the point_val array.
Param... | 5,333,581 |
def main():
""" Main
"""
generate_recipes(5) | 5,333,582 |
def logout():
"""Logout
:return: Function used to log out the current user
"""
logout_user()
return redirect(url_for('index')) | 5,333,583 |
def get_authorization_url(
app_id, redirect_uri, scope='all', state='', extra_data='', **params):
"""
Get the url to start the first leg of OAuth flow.
Refer to `Authentication Docs <https://developers.kloudless.com/docs/latest/
authentication#oauth-2.0>`_ for more information.
:param str ... | 5,333,584 |
def poolmanager_get_pool_group(args):
"""
Get information about a poolgroup. Requires admin role.
"""
LOGGER.debug('args: %s' % str(args))
with get_client(args) as dcache:
response = dcache.poolmanager.get_pool_group(**vars(args))
print_response(response) | 5,333,585 |
def runMultiQueryBatch(scenario, queries, xmldb='', queryPath=None, outputDir=None,
miLogFile=None, regions=None, regionMap=None, rewriteParser=None,
batchFileIn=None, batchFileOut=None, noRun=False, noDelete=False):
"""
Create a single GCAM XML batch file that runs... | 5,333,586 |
def get_user_messages(user, index=0, number=0):
"""
返回指定user按时间倒序的从index索引开始的number个message
"""
if not user or user.is_anonymous or index < 0 or number < 0:
return tuple()
# noinspection PyBroadException
try:
if index == 0 and number == 0:
all_message = user.messa... | 5,333,587 |
def third_party_apps_default_dc_modules_and_settings(klass):
"""
Decorator for DefaultDcSettingsSerializer class.
Updates modules and settings fields defined in installed third party apps.
"""
logger.info('Loading third party apps DEFAULT DC modules and settings.')
for third_party_app, app_dc_... | 5,333,588 |
def test_nonlocals_set(nonlocals):
"""Test setting attribute through setatttr and setitem.
"""
nonlocals.attribute1 = 3
assert nonlocals.attribute1 == 3
nonlocals['attribute1'] = 4
assert nonlocals.attribute1 == 4
nonlocals.prop2 = 3
assert nonlocals.prop2 == 3
nonlocals['prop2'] =... | 5,333,589 |
def split_lvis(
n_experiences: int,
train_transform=None,
eval_transform=None,
shuffle=True,
root_path: Union[str, Path] = None,
):
"""
Creates the example Split LVIS benchmark.
This is a toy benchmark created only to show how a detection benchmark can
be created. It was not meant t... | 5,333,590 |
def spoof(target_ip, host_ip, verbose=True):
"""
Spoofs `target_ip` saying that we are `host_ip`.
it is accomplished by changing the ARP cache of the target (poisoning)
"""
target_mac = get_mac(target_ip) # get the mac address of the target
arp_response = ARP(pdst=target_ip, hwdst=target_m... | 5,333,591 |
def compute_log_ksi_normalized(log_edge_pot, #'(t-1,t)',
log_node_pot, # '(t, label)',
T,
n_labels,
log_alpha,
log_beta,
temp_array_1,
temp_array_2):
""" to obtain the two-slice posteri... | 5,333,592 |
def flushcache():
"""
CLI: Delete all cached data (if cache is activated)
Usage: "flask flushcache"
"""
if read_config("CACHE"):
echo("Cache successfully flushed")
CACHE.clear()
else:
echo("Cache inactive, unable to flush") | 5,333,593 |
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser(description="Map gleason data to standard format.")
parser.add_argument("-d", "--data_path", type=Path, help="Path to folder with the data.", required=True)
parser.add_argument("-n", "--n_jobs", type=int, help="Number of jo... | 5,333,594 |
def test_whitepaper_model():
"""Tests the whitepaper 'measurement' model - generation
of ASL data using the DRO, then quantification using the
white paper equation"""
asldro_params = {
"lambda_blood_brain": 0.9,
"t1_arterial_blood": 1.65,
"label_efficiency": 0.85,
"asl_c... | 5,333,595 |
def process_file(filename, f, num=float('Inf')):
"""read the given filename and extract information;
for each film, call f() with string arguments:
actor, date, title, role """
fp = open_gunzip(filename)
i = 0
# skip over the header until you get to the following magic line
for line in... | 5,333,596 |
def _deserialize_union(x: Any, field_type: Type) -> Any:
"""Deserialize values for Union typed fields
Args:
x (Any): value to be deserialized.
field_type (Type): field type.
Returns:
[Any]: desrialized value.
"""
for arg in field_type.__args__:
# stop after first ma... | 5,333,597 |
def read_simplest_expandable(expparams, config):
"""
Read expandable parameters from config file of the type `param_1`.
Parameters
----------
expparams : dict, dict.keys, set, or alike
The parameter names that should be considered as expandable.
Usually, this is a module subdictiona... | 5,333,598 |
def rec_map_reduce_array_container(
reduce_func: Callable[[Iterable[Any]], Any],
map_func: Callable[[Any], Any],
ary: ArrayOrContainerT) -> "DeviceArray":
"""Perform a map-reduce over array containers recursively.
:param reduce_func: callable used to reduce over the components of *ary*
... | 5,333,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.