content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def clustering_from_distance(dendrogram, distance):
"""
Given a dendrogram and a distance level, compute the partitions corresponding to the distance level
Parameters
----------
dendrogram: numpy.array
Each line of the dendrogram contains the merged nodes, the distance between merged n... | 5,316,500 |
def main(host, portFrom, portTo, timeout, connections, outputFile = 'ports_open.txt'):
""" Reads the dictionary and attempts to connect with the username and password on each line
Keyword arguments:
host -- Host to scan for open ports
portFrom -- Port number to scan from (default 1)
portTo -- Port number to scan ... | 5,316,501 |
def _loss_from_outputs_batch(loss_function, outputs_per_chunk, targets_per_chunk):
"""
Applies the loss function to batch of outputs (unpadded, masked) and batch of targets (padded, unmasked).
:param loss_function: e.g., NLLLoss.
:param outputs_per_chunk: a list of tensors, each the relevant (i.e., mask... | 5,316,502 |
def save_to_sql_client_data_from_client_data(
cd: tff.simulation.datasets.ClientData,
database_filepath: str,
allow_overwrite: bool = False,
) -> None:
"""Serialize a federated dataset into a `SqlClientData` from an existing ClientData."""
client_ids = cd.client_ids
dataset_fn = cd.create_tf_dataset_f... | 5,316,503 |
def dataInput(fileName):
"""Reads a line of data from a file and returns either a string for
when there is only a single line of data or a list when there is
more than one line.
"""
data = []
if os.path.isfile(fileName):
file = open(fileName, "r")
data = file.readlines()
else... | 5,316,504 |
def equivPhkv(k,v,n):
"""
Checks if two values are the same and implicitly checks if id actually checks if two variables
point to an object at the same memory location
"""
return equivValue(k,v,n) and referenceIdentity(n,v) and referenceIdentity(n.node,v.node) | 5,316,505 |
def get_spherical_bounding_box(lons, lats):
"""
Given a collection of points find and return the bounding box,
as a pair of longitudes and a pair of latitudes.
Parameters define longitudes and latitudes of a point collection
respectively in a form of lists or numpy arrays.
:return:
A t... | 5,316,506 |
def get_similarity_score(dict1, dict2, dissimilarity = False):
"""
The keys of dict1 and dict2 are all lowercase,
you will NOT need to worry about case sensitivity.
Args:
dict1: frequency dictionary of words or n-grams for one text
dict2: frequency dictionary of words or n-grams ... | 5,316,507 |
def visualize():
"""Visualizes the sample flow graph"""
flow = so_ana_flow.get_flow()
flow.visualize() | 5,316,508 |
def predict_fn(input_data, model):
"""Predict using input and model"""
return model(input_data) | 5,316,509 |
def run_ability_check_of_not_ending_function(target, args, timeout=None):
"""check if a function can run without error within the given timeout.
There are possibly better solutions like some decorators out there i guess?
"""
p = ProcessWithException(target=target, args=args)
p.start()
print... | 5,316,510 |
def solve_challenge(challenge):
"""
The parameter challenge comes in binary already
"""
global IA
# 1) get the location of the certificates and keys
SC = os.environ["SC"] if "SC" in os.environ else os.path.join(str(pathlib.Path.home()), "go", "src", "github.com", "scionproto", "scion")
SC = ... | 5,316,511 |
def scalereg(self, percentage):
"""Scale a region by a give percentage; > 100% will increase the area; < 100% will decrease the area"""
output = self.g.read_command('g.region', flags = 'g')
d = self.out2dic(output)
n = d['n']
s = d['s']
w = d['w']
e = d['e']
ns = n - s
... | 5,316,512 |
def uniform_2_sphere(num: int = None):
"""Uniform sampling on a 2-sphere
Source: https://gist.github.com/andrewbolster/10274979
Args:
num: Number of vectors to sample (or None if single)
Returns:
Random Vector (np.ndarray) of size (num, 3) with norm 1.
If num is None returned ... | 5,316,513 |
def main(data_dirpath, model_dirpath, preds_dirpath):
"""
Make predictions with model from model_dirpath on data from data_dirpath
and stores them in preds_dirpath
"""
logger = logging.getLogger(__name__)
logger.info("Loading data")
X_test = sp.load_npz(os.path.join(data_dirpath, "X_test.np... | 5,316,514 |
def nce_past(z_next_trans_dist, z_next_enc):
"""
z_next_trans_dist: p(.|z, u)
z_next_enc: samples from p(.|x')
"""
batch_size, z_dim = z_next_enc.size(0), z_next_enc.size(1)
z_next_trans_dist_rep = repeat_dist(z_next_trans_dist, batch_size, z_dim)
z_next_enc_rep = z_next_enc.repeat(1, batch... | 5,316,515 |
def plot_performance(barcode_counts,
tick_label_size = 8,
cbar_label_size = 5,
dpi = 300,
barcode_threshold = 1,
absent_color = "black",
present_color = "green",
save = False,
... | 5,316,516 |
def get_simple_countings(df, start_yr=START_YR, end_yr=END_YR):
"""Generates simple counting statistics for the criterias ports, authors,
platforms, file extensions and types of exploits. It determines the 10
largest countings of each criteria.
:param df (DataFrame): A DataFrame object.
:param start... | 5,316,517 |
def get_engine():
"""Return the active database engine (the database engine of the active
application). If no application is enabled this has an undefined behavior.
If you are not sure if the application is bound to the active thread, use
:func:`~zine.application.get_application` and check it for `None... | 5,316,518 |
def get_unnormalized_text(words):
""" Returns the (unnormalized) text composed from the given words."""
return "".join([x.unnormalized_with_whitespaces for x in words]) | 5,316,519 |
def pytest_runtest_makereport(item, call):
"""Pytest hook for test run"""
outcome = yield
result = outcome.get_result()
if result.when == 'call':
item.session.results[item] = result | 5,316,520 |
async def test_add_new_climate_device(hass):
"""Test successful creation of climate entities."""
await setup_gateway(hass, {})
sensor = Mock()
sensor.name = 'name'
sensor.type = 'ZHAThermostat'
sensor.register_async_callback = Mock()
async_dispatcher_send(hass, 'deconz_new_sensor', [sensor])... | 5,316,521 |
def getCurrentUsersHomePath():
""" Return the path to the users home directory. Usually C:/Users/<user> """
return (shell.SHGetFolderPath (0, shellcon.CSIDL_PROFILE, None, 0)) | 5,316,522 |
def alpha_num_order(string: str) -> str:
"""Returns all numbers on 5 digits to let sort the string with numeric order.
Ex: alphaNumOrder("a6b12.125") ==> "a00006b00012.00125"
"""
return "".join(
[
format(int(x), "05d") if x.isdigit() else x
for x in re.split(r"(\d+)", st... | 5,316,523 |
def detect(model, dataset_dir, subset):
"""
Run detection on images in the given directory
"""
print("Running on {}".format(dataset_dir))
# Create directory
if not os.path.exists(RESULTS_DIR):
os.makedirs(RESULTS_DIR)
submit_dir = "submit_{:%Y%m%dT%H%M%S}".format(datetime.datetime.n... | 5,316,524 |
def setup_logging_streams(model, log_to_file=True, log_to_stdout=False):
"""Utility function for setting up logging handlers for `model`."""
formatter = logging.Formatter(
'[%(name)s][%(asctime)s][%(levelname)s]: %(message)s',
datefmt='%m:%d:%Y:%I:%M:%S'
)
handlers = []
if log_to_fil... | 5,316,525 |
def setup_logger():
"""Set up the logger output.
"""
import tempfile
def get_console_handler(stream_level="INFO"):
console_handler = logging.StreamHandler()
console_handler.setLevel(level=getattr(logging, stream_level))
console_handler.setFormatter(FORMATTER)
return cons... | 5,316,526 |
def test_atomic_base64_binary_enumeration_2_nistxml_sv_iv_atomic_base64_binary_enumeration_3_2(mode, save_output, output_format):
"""
Type atomic/base64Binary is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/atomic/base64Binary/Schema+Instance/NISTSchema-SV-IV-atomic-bas... | 5,316,527 |
def _web_services_request(endpoint, params, method='GET'):
"""
Perform a request on an NYC.ID Web Services endpoint.
'userName' and 'signature' are added to the specified params.
:param endpoint: web services endpoint (e.g. "/account/validateEmail.htm")
:param params: request parameters excluding '... | 5,316,528 |
def write_nk_file(target_dir, target_name, data):
"""
Args:
target_dir(str): must be in an existing directory
target_name(str): name of the file without the extension
data(str):
Returns:
str: path the file has been written to.
"""
target_path = os.path.join(target_d... | 5,316,529 |
def dihedral_group(n):
"""
Return the dihedral group S_n.
>>> from qitensor import dihedral_group
>>> S3 = dihedral_group(3)
>>> S3.order
6
>>> S3.elements
[<S3.r0>, <S3.r1>, <S3.r2>, <S3.s0>, <S3.s1>, <S3.s2>]
>>> S3.e
<S3.r0>
>>> S3.r1 * S3.s0
<S3.s1>
>>> import p... | 5,316,530 |
def _half(X):
"""Returns the lower triangular part of
a matrix with half of diagonal part.
Args:
X: tensor of shape (..., m, m).
Returns:
tensor of shape (..., m, m), a set of matrices with half
of diagonal and without upper triangular parts."""
dim = tf.shape(X)[-1]
d... | 5,316,531 |
def top_about(root, options, state) :
"""
@param root: a DOM node for the top level element
@param options: invocation options
@type options: L{Options<pyRdfa.options>}
@param state: top level execution state
@type state: L{State<pyRdfa.state>}
"""
def set_about(node) :
if has_one_of_attributes(node, "rel", "... | 5,316,532 |
def skel_agent(name, destination='', knowledge=False):
"""Create a new project element from skeleton."""
env.skel_create_agent(ENVIRONMENT, name,
dst=destination, has_knowledge=knowledge) | 5,316,533 |
def multipart_encode_for_requests(params, boundary=None, cb=None):
"""streams uploads instead of loading entire file into memory"""
datagen, headers = multipart_encode(params, boundary, cb)
return IterableToFileAdapter(datagen), headers | 5,316,534 |
def get_ability_icons(champion, input_path):
"""
This function takes a champion and input path strings as input and returns a
dictionary of png file paths with keys corresponding to the following
abilities: Passive, Q, W, E, and R
"""
global ability_icon_paths
ability_icon_paths = dict()
... | 5,316,535 |
def build_json_response(data, response_code='200 OK'):
"""
data (str | dict) : JSON encodable data
response_code (str) : HTTP response code
----
Return (bytes) HTTP response of JSON-encoded data.
"""
if type(data) == str:
data = json.loads(data)
elif type(data) == dict:
... | 5,316,536 |
def run_query_validators(
request_path: str,
request_headers: Dict[str, str],
request_body: bytes,
request_method: str,
databases: Set[VuforiaDatabase],
) -> None:
"""
Run all validators.
Args:
request_path: The path of the request.
request_headers: The headers sent with... | 5,316,537 |
def eval_biot_savart(xcp0, xnode1, xnode2, gamma, l0, delta_visc=0.025):
"""
This function uses the Biot-Savart law to evaluate the induced velocities
at control points (xcp), due to vortex line elements defined by locations xnode1, xnode2,
with strengths gamme and lengths l0. The delta_visc parameter ... | 5,316,538 |
def validate_params(func):
"""
@note: validate decorator
"""
def _decorator(*args, **kwargs):
def _get_param_items(func, args, kwargs):
import inspect
parameters = inspect.signature(func).parameters
arg_keys = tuple(parameters.keys())
vparams = [... | 5,316,539 |
def techniques_used(technique_list, technique):
""" Add technique to technique list and make distinction between techniques
subtechniques
"""
attack_id = util.buildhelpers.get_attack_id(technique['object'])
has_subtechniques = False
if attack_id:
# Check if technique not already in... | 5,316,540 |
def rec_process(proc, conf_file, datafile, dir, gpus, r, q):
"""
Calls the reconstruction function in a module identified by parameter. After the reconstruction is finished, it enqueues th eprocess id wit associated list of gpus.
Parameters
----------
proc : str
processing library, chices a... | 5,316,541 |
def admin_view_semesters_of_a_curriculum(request, curriculum_id):
""" gets all the semesters of a specfic curriculum """
curriculum = Curriculum.objects.get(id=curriculum_id)
semesters = Curriculum.get_semesters_objects(curriculum)
semester_slots = []
for sem in semesters:
a = list(Semester... | 5,316,542 |
def fetch_lightcurve_dr2(gaia_id, output_dir='../data/'):
""" Fetch Gaia Lightcurve for a Gaia Source ID (of a variable star) from Gaia DR2 Data Link
Returns path of csv file stored for given source
Args:
gaia_id (string): String. Gaia Source ID of the variable star you need to fetch the l... | 5,316,543 |
def imap(f, s, max_workers=None, use_mpi=False, if_serial="raise", chunksize=None):
"""
Parameters
----------
f : callable
function that operates on values in s
s : iterable
series of inputs to f
max_workers : int or None
maximum number of workers. Defaults to 1-maximum a... | 5,316,544 |
def test_global_creation_always_possible(all_views):
"""To not make life very difficult for clients, this test
asserts that all creatable resources can be created by
POSTing to the global resource list
"""
views_by_model = {}
for View in all_views:
if not getattr(View, 'deprecated', Fals... | 5,316,545 |
async def _aw_to_coro(aw: Awaitable[T]) -> T:
"""Wrap a given awaitable so it appears as a coroutine."""
return await aw | 5,316,546 |
def print_help():
"""
Print help message
"""
script_name = os.path.basename(sys.argv[0])
print(f"""
Usage: {script_name} [command]
commands:
initialize - Initialize configuration file
start - Start tracking product price
"""
)
sys.exit() | 5,316,547 |
def get_text_recursive(tag: Union[Tag, NavigableString, None]) -> str:
"""Extract the text using the childrens."""
if tag is None:
return ""
if isinstance(tag, NavigableString):
return str(tag).strip().replace("\n", " ")
tag_name = tag.name
# Special tags, like headers, lists, tabl... | 5,316,548 |
async def test_authenticator_returns_instructor_role_in_auth_state_with_instructor_role(monkeypatch, auth_state_dict):
"""
Do we set the instructor role in the auth_state when receiving a valid resource link request?
"""
authenticator = LTI13Authenticator()
request_handler = mock_handler(RequestHand... | 5,316,549 |
def plot_overlap(overlap_data, fig_name):
""" Level 4: plot function for simulate_overlap() """
e_data_vec = overlap_data['e_data_vec']
t_data_vec = overlap_data['t_data_vec']
e_avgs_vec = overlap_data['e_avgs_vec']
t_avgs_vec = overlap_data['t_avgs_vec']
plt.figure(figsize=(4,4))
plt.hold(T... | 5,316,550 |
def read_eval_print_loop(next_line, env, interactive=False, quiet=False,
startup=False, load_files=()):
"""Read and evaluate input until an end of file or keyboard interrupt."""
if startup:
for filename in load_files:
scheme_load(filename, True, env)
while True:
... | 5,316,551 |
def _l1_regularization(l1, model):
"""Computes the L1 regularization for the given model
Args:
l1 (float): L1 parameter
model (:obj:`torch.nn.Module`): Model to use
Returns:
float: L1 loss (i.e. l1 * l1_norm(params))
"""
l1_loss = sum(param.norm(1) for param in model.parame... | 5,316,552 |
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return Conv2D(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias_attr=False) | 5,316,553 |
def test_authenticate_missing_email(user_factory, verified_email_auth_backend):
"""
If the provided email doesn't exist in the system, ``None`` should
be returned.
"""
user_factory(password="password")
assert (
verified_email_auth_backend.authenticate(
email="missing@example.com", pa... | 5,316,554 |
def create_feature_extractor(model, device=None):
"""
Factory function for creating an evaluator for supervised models
Args:
model (`torch.nn.Module`): the model to evaluate
device (str, optional): device type specification (default: None).
Applies to both model and ba... | 5,316,555 |
def callit(iteratee, *args, **kwargs):
"""Inspect argspec of `iteratee` function and only pass the supported arguments when calling
it."""
maxargs = len(args)
argcount = kwargs["argcount"] if "argcount" in kwargs else getargcount(iteratee, maxargs)
argstop = min([maxargs, argcount])
return iter... | 5,316,556 |
def assignPropertyToAll(a, prop):
"""Assign the provided property to all children"""
if type(a) == list:
for child in a:
assignPropertyToAll(child, prop)
elif isinstance(a, ast.AST):
for node in ast.walk(a):
setattr(node, prop, True) | 5,316,557 |
def get_doc_tokens(paragraph_text):
"""Tokenize the given paragraph and return character to word token offset for answer ranges"""
doc_tokens = []
char_to_word_offset = []
prev_is_whitespace = True
for c in paragraph_text:
if is_whitespace(c):
prev_is_whitespace = True
el... | 5,316,558 |
def test_texteditor(qtbot):
"""Run TextEditor dialog."""
text = """01234567890123456789012345678901234567890123456789012345678901234567890123456789
dedekdh elkd ezd ekjd lekdj elkdfjelfjk e"""
texteditor = setup_texteditor(qtbot, text)
texteditor.show()
assert texteditor
dlg_text = texteditor.ge... | 5,316,559 |
def ispython(script_path):
"""
Check to see if file is a python script file by extension
:param script_path:
:return:
"""
return hasextension(script_path, ".py") | 5,316,560 |
def num_to_name(num):
"""
(int) -> str
Get IO pin name from its numeric identifier
>> num_to_name(8)
gpio_8
>> num_to_name(107)
D7
>>num_to_name(115)
A1
"""
# Pi pin numeric identifiers are the actual GPIO number
if num <= 27:
pname = "gpio_" + str(nu... | 5,316,561 |
def test_disp_corr_matrix_nacl(nacl_pbe):
"""Test of DispCorrMatrix class with NaCl."""
_test_disp_corr_matrix(nacl_pbe) | 5,316,562 |
def ConnectToInstance(cmd_args, sql_user):
"""Connects to the instance using the relevant CLI."""
try:
log.status.write(
'Connecting to database with SQL user [{0}].'.format(sql_user))
execution_utils.Exec(cmd_args)
except OSError:
log.error('Failed to execute command "{0}"'.format(' '.join(cm... | 5,316,563 |
def load_cifar_datasets(data_dir):
"""Load CIFAR10 and SVHN dataset from np array."""
tr_in = load_tfdata_from_np(os.path.join(data_dir, 'cifar10_train.npy'))
val_in = load_tfdata_from_np(os.path.join(data_dir, 'cifar10_val.npy'))
test_in = load_tfdata_from_np(os.path.join(data_dir, 'cifar10_test.npy'))
test... | 5,316,564 |
def ConnectToDb_Return_Df_table(id,pwd,host,db_name,table_name):
"""
This method will Connect to Data base and return the requested table in the form of a dataframe
Better to make it a singleton to ensure multiple db connections are not spawned
:param id:
:param pwd:
:param host:
:param db_n... | 5,316,565 |
def update_model(
model_artifact,
parameters: dict = None,
metrics: dict = None,
extra_data: dict = None,
inputs: List[Feature] = None,
outputs: List[Feature] = None,
feature_vector: str = None,
feature_weights: list = None,
key_prefix: str = "",
labels: dict = None,
write_sp... | 5,316,566 |
def debug_tokens():
"""Used to debug a troublesome token"""
asset = '0x85b294139E77E7dE519A9bA9553D274d79E4812e'
#using a local copy for speed & convenience. Retrieved from etherscan '0x67Db14E73C2Dce786B5bbBfa4D010dEab4BBFCF9'
cerc20_abi = json.loads(open('interfaces/CErc20Delegate.json').read())
... | 5,316,567 |
def parse_tag_line(parent_tag: str, parent: typing.Iterable[str]) -> None:
"""Processing tag 'Line'.
Args:
parent_tag (str): Parent tag.
parent (Iterable[str): Parent data structure.
"""
debug_xml_element_all("Start", parent_tag, parent.attrib, parent.text)
init_parse_result_line()... | 5,316,568 |
def runscript(scriptname, args, in_directory=None,
fail_ok=False, sandbox=False):
"""Run a Python script using exec().
Run the given Python script, with the given args, in the given directory,
using 'exec'. Mimic proper shell functionality with argv, and capture
stdout and stderr.
W... | 5,316,569 |
def n_prop_vs_rec(sorted_props, gt, n=100):
"""
sort n proposals by their score.
returns #proposals vs. recall -> [[a], [b], ..., [n]]
a = recall for 1 proposal
b = recall for 2 proposals
.
.
.
n = recall for (n+1) proposals
:param sorted_props: [[prop_0], [prop_1], ... | 5,316,570 |
def test_order_based():
""" Runs the order_based test """
run_in_separate_process(target=launch_order_based, timeout=240) | 5,316,571 |
def workchain_res(process, info, label, show, keys, fmt):
"""Print data from Dict nodes returned or created by any fleur process."""
returned_dicts_info = []
returned_dicts = []
try:
results = process.get_outgoing().all()
except ValueError as exception:
echo.echo_critical(str(except... | 5,316,572 |
def user_input_from_gui(min_score, head_dir, max_score="NO"):
"""
The interface of user request from GUI of our web app. The request handler
should call this method to filter and write data into server's current
working directory. file format: min.csv, if there is no max or min-max.to_csv
otherwise.... | 5,316,573 |
def addSkyBox(prefix, extension = None):
""" add a skybox starting with the prefix and ending with the extension """
if extension:
OpenNero.getSimContext().addSkyBox(prefix, extension)
else:
OpenNero.getSimContext().addSkyBox(prefix) | 5,316,574 |
def cmd_networking(udid, network, format):
""" Print information about current network activity. """
def _callback(res):
api_util.network_caller(res, print_json)
with InstrumentsBase(udid=udid, network=network) as rpc:
rpc.networking(_callback) | 5,316,575 |
def gas_3parallel(method="nikuradse"):
"""
:param method: Which results should be loaded: nikuradse or prandtl-colebrook
:type method: str, default "nikuradse"
:return: net - STANET network converted to a pandapipes network
:rtype: pandapipesNet
:Example:
>>> pandapipes.networks.simple... | 5,316,576 |
def get_coordinates(df, year: str):
"""
Add column to the given DataFrame which contains coordinates of
all films filmed at given year.
"""
df = df[df["Year"] == year]
coordinates = []
geolocator = Nominatim(user_agent="main.py")
for i in range(120):
df_location = df.iloc[i, 2]
... | 5,316,577 |
def get_partyname_wordlist(
json_path: Path,
filter_full_name: t.List = [],
name_keys: t.List = ["full_name", "label", "short_name", "other_names"],
lowercase: bool = False,
add_spaces: bool = False,
):
"""Create a set of all possible and abreviatoions of party names"""
parties = json.loads(... | 5,316,578 |
def ceil_even(x):
"""
Return the smallest even integer not less than x. x can be integer or float.
"""
return round_even(x+1) | 5,316,579 |
def dict_to_PI(d, classes):
"""
Convert a dictionary to a PresentationInfo,
using a pre-fetched dictionary of CssClass objects
"""
if d['prestype'] == 'command':
return PresentationInfo(prestype=d['prestype'], name=d['name'])
else:
c = classes.get(d['name'])
if c is None:... | 5,316,580 |
def process_message(message, server, error_messages, output_messages, store_function, producer):
"""
Anchors the message m in a DLT specified by the store_function parameter.
Sends error (non hex message and timeouts) in the errorQueue.
Sends JSON docs containing the txid and the input data in q... | 5,316,581 |
def no_batch_embed(sentence: str) -> typing.List[float]:
"""Returns a list with the numbers of the vector into which the
model embedded the string."""
return model.encode(sentence).tolist() | 5,316,582 |
def generate_config(
config_file,
predictive_service_client=None,
**kwargs
):
"""Given a configuration, generate a config file at config_file.
Recommended values for config_file:
* psclient.conf (in current working directory)
* psclient.conf (in sys.argv[0])
... | 5,316,583 |
def make_video(video_images_files, name, fps=30):
"""Given list of image files, create video"""
# create video
print('\nCreating video...')
clip = ImageSequenceClip(video_images_files, fps)
# write video
clip.write_videofile(name)
return clip | 5,316,584 |
def find_internal_gaps(seq):
"""
Accepts a string and returns the positions of all of the gaps in the sequence which are flanked by nt bases
:param seq: str
:return: list of [start,end] of all of the internal gaps
"""
gaps = find_gaps(seq)
seq_len = len(seq) -1
internal_gaps = []
iu... | 5,316,585 |
def join_threads ():
"""Join all threads for main process
"""
# Verify that all threads are end
all_threads_end = True
for thread, status in globals_status.get_credentials().items():
if status != "ended":
all_threads_end = False
if all_threads_end:
... | 5,316,586 |
def test_loop(model, ins, batch_size=None, verbose=0, steps=None):
"""Abstract method to loop over some data in batches.
Arguments:
model: Model instance that is being evaluated in Eager mode.
ins: list of tensors to be fed to `f`.
batch_size: integer batch size or `None`.
verbose: verbosit... | 5,316,587 |
def find_bands(bands, target_avg, target_range, min_shows):
"""
Searches dictionary of bands with band name as keys and
competition scores as values for bands that are within the
range of the target average and have performed the minimum
number of shows. Returns a list of bands that meet the search
... | 5,316,588 |
def get_named_targets():
""" Return a list of named target date ranges """
return ["std_train", "std_val", "std_test", "std_ens", "std_all", \
"std_future", "std_contest_fri", "std_contest", "std_contest_daily", "std_contest_eval", \
"std_contest_eval_daily", "std_paper", "std_paper_daily"] | 5,316,589 |
def create_edge_linestrings(G_, remove_redundant=True, verbose=False):
"""
Ensure all edges have the 'geometry' tag, use shapely linestrings.
Notes
-----
If identical edges exist, remove extras.
Arguments
---------
G_ : networkx graph
Input networkx graph, with edges assumed to... | 5,316,590 |
def bump_version(xml_path, version=None):
""" Bump Version """
tree = qisys.qixml.read(xml_path)
root = tree.getroot()
if version is None:
previous_version = root.get("version")
version = qisys.version.increment_version(previous_version)
root.set("version", version)
qisys.qixml.w... | 5,316,591 |
def get_licenses(service_instance, license_manager=None):
"""
Returns the licenses on a specific instance.
service_instance
The Service Instance Object from which to obrain the licenses.
license_manager
The License Manager object of the service instance. If not provided it
will... | 5,316,592 |
def is_installed(request, project_id=None):
"""Check whether the extension {{ cookiecutter.project_name }} is installed."""
return JsonResponse({'is_installed': True, 'msg': '{{ cookiecutter.project_name }} is installed'}) | 5,316,593 |
def predict(model, data, out_fname = None):
"""
Description:
-----------
This function is used to predict the EV values for a given dataframe
Parameters:
-----------
model: The model to be finetuned (tf.keras.models.Model)
data: The dataframe to be predicted (pandas.DataFrame)
out_... | 5,316,594 |
def clear_testcase_directories():
"""Clear the testcases directories on the worker."""
remove_directory(
rebase_to_worker_root(environment.get_value('FUZZ_INPUTS')),
recreate=True)
remove_directory(
rebase_to_worker_root(environment.get_value('FUZZ_INPUTS_DISK')),
recreate=True) | 5,316,595 |
def test_unique_together_exception() -> None:
"""
Asserts special handling of __all__ exceptions.
"""
response = exception_handler(
ValidationError(
{"__all__": ["User with this name and email already exists."]},
code="unique_together",
)
)
assert response... | 5,316,596 |
def line_order(line):
"""Recursive search for the line's hydrological level.
Parameters
----------
line: a Centerline instance
Returns
-------
The line's order
"""
if len(line.inflows) == 0:
return 0
else:
levels = [line_order(s) for s in line.inflows]
... | 5,316,597 |
def get_data_colums(epoch):
"""Return the data columns of a given epoch
:param epoch: given epoch in a numpy array, already readed from .csv
"""
ID = epoch[:,0];
RA = epoch[:,1];
RA_err = epoch[:,2];
Dec = epoch[:,3];
Dec_err = epoch[:,4];
Flux = epoch[:,5];
Flux_err = epoch[:,... | 5,316,598 |
def reset_columns_DataFrame(df, new_columns=None):
"""
Rename *all* columns in a dataframe (and return a copy).
Possible new_columns values:
- None: df.columns = list(df.columns)
- List: df.columns = new_columns
- callable: df.columns = [new_columns(x) for x in df.columns]
- str && df.shap... | 5,316,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.