content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def assert_single_whitespace_after_second_semicolon(docstring: List[str]) -> List[str]:
"""
Find the lines conaining prefixes = [":param", ":return", ":raises"].
For those lines make sure that there is only one whitespace after the second semicolon.
:param docstring: list of lines in docstring
:ret... | 5,298,100 |
def is_graph_equal(lhs_workbench: Dict, rhs_workbench: Dict) -> bool:
"""Checks whether both workbench contain the same graph
Two graphs are the same when the same topology (i.e. nodes and edges)
and the ports at each node have same values/connections
"""
try:
if not set(rhs_workbench.keys(... | 5,298,101 |
def DeleteBucketWithRetry(vm, remove_content_cmd, remove_bucket_cmd):
""" Delete a bucket and all its contents robustly.
First we try to recursively delete its content with retries, if failed,
we raise the error. If successful, we move on to remove the empty bucket.
Due to eventual consistency issu... | 5,298,102 |
def notify(
vias: list,
subject: str = None,
receivers: Union[str, list, models.QuerySet, models.Manager] = None,
template: str = None,
context: dict = None,
final_message: str = None,
email_gateway: str = 'default',
sms_gateway: Optional[str] = None,
files: list = None,
threaded... | 5,298,103 |
def _undrift_from_picked_coordinate_light(
picked_locs, coordinate, info
):
"""Should be identical to _undrift_from_picked_coordinate but with lower
memory usage."""
n_picks = len(picked_locs)
n_frames = info[0]["Frames"]
# Drift per pick per frame
#drift = _np.empty((n_picks, n_frames))
... | 5,298,104 |
def get_model(**kwargs):
"""
Returns the model.
"""
model = MobileNetV2(**kwargs)
return model | 5,298,105 |
def combine(to_merge, extend_by):
"""Merge nested dictionaries."""
def _combine(to_merge, extend_by):
for key, value in extend_by.items():
if key in to_merge:
if isinstance(to_merge[key], dict):
_combine(to_merge[key], value)
else:
... | 5,298,106 |
def timestamp(t=None,sep="_"):
""" Creates a timestamp that can easily be included in a filename. """
if t is None:
t = datetime.datetime.now()
#sargs = (t.year,t.month,t.day,t.hour,t.minute,t.second)
#sbase = "".join(["%04d",sep,"%02d",sep,"%02d",sep,"%02d",sep,"%02d",sep,"%02d"])
sargs = (... | 5,298,107 |
def split_pods_train_test(data_root):
"""
Split the audio files into train,val,test sets
Args:
Returns:
"""
aud_files = [
os.path.join(data_root, s)
for s in os.listdir(data_root)
if s.__contains__(config['AUDIO_READ_FORMAT_PODS'])
]
aud_files_lens = {i: WAVE_... | 5,298,108 |
def test_draft_create_parent(app, db):
"""Test draft creation of the parent record."""
draft = Draft.create({})
db.session.commit()
assert draft.schema.endswith('record-v1.0.0.json')
assert draft.pid
assert draft.parent.schema.endswith('parent-v1.0.0.json')
assert draft.parent.pid
asser... | 5,298,109 |
def triangle_loss(verts, edge2verts):
"""
Encourages dihedral angle to be 180 degrees.
Args:
verts: B X N X 3
edge2verts: B X E X 4
Returns:
loss : scalar
"""
indices_repeat = torch.stack([edge2verts, edge2verts, edge2verts], dim=2) # B X E X 3 X 4
verts_A = torch.... | 5,298,110 |
def randint(lower: int, upper: int):
"""Sample an integer value uniformly between ``lower`` and ``upper``.
``lower`` is inclusive, ``upper`` is exclusive.
Sampling from ``tune.randint(10)`` is equivalent to sampling from
``np.random.randint(10)``
"""
return Integer(lower, upper).uniform() | 5,298,111 |
def _remove_non_numeric_characters(gtin: str) -> str:
"""
Strip non-numeric characters from a string
"""
return _NON_NUMERIC_CHARACTERS_PATTERN.sub("", gtin) | 5,298,112 |
def increment_timeperiod(time_qualifier, timeperiod, delta=1):
""" method performs simple increment/decrement of the timeperiods
For instance: 2010010119 with delta=1 -> 2010010120
Or 2010010000 with delta=-1 -> 2009120000, etc"""
pattern = define_pattern(timeperiod)
t = datetime.strptime(timeperio... | 5,298,113 |
def get_kernel_prefix_and_full_hash(build_id):
"""Download repo.prop and return the full hash and prefix."""
android_kernel_repo_data = _get_repo_prop_data(build_id,
constants.LKL_BUILD_TARGET)
if android_kernel_repo_data:
for line in android_kernel_repo_data.s... | 5,298,114 |
def get_global_cfg_path():
""" Get path to global config file. """
return qisys.sh.get_config_path("qi", "qibuild.xml") | 5,298,115 |
def infrastructure_member_delete(context, data_dict):
"""
Remove a user from an infrastructure.
You must be authorized to edit the infrastructure.
:param id: the id or name of the infrastructure
:type id: string
:param username: name or id of the user
:type username: string
"""
log... | 5,298,116 |
def chr22XY(c):
"""Reformats chromosome to be of the form Chr1, ..., Chr22, ChrX, ChrY, etc.
Args:
c (str or int): A chromosome.
Returns:
str: The reformatted chromosome.
Examples:
>>> chr22XY('1')
'chr1'
>>> chr22XY(1)
'chr1'
>>> c... | 5,298,117 |
def url_to_image(url, flag=cv2.IMREAD_COLOR):
""" download the image, convert it to a NumPy array, and then read
it into OpenCV format """
resp = urlopen(url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, flag)
return image | 5,298,118 |
def test_session_root_path():
"""Ensure and yield the testrun root directory.
If created here, it is also destroyed during teardown. The root directory
is created per test session.
"""
created_test_session_root_path = False
try:
root_path = os.environ[ENV_TMPDIR_VAR]
except KeyErro... | 5,298,119 |
def write_mapping_file(sum_inputs_df, target_dir, is_fm_summary=False):
"""
Writes a summary map file, used to build summarycalc xref files.
:param summary_mapping: dataframe return from get_summary_mapping
:type summary_mapping: pandas.DataFrame
:param sum_mapping_fp: Summary map file path
:t... | 5,298,120 |
def arr2str(a: np.ndarray, format_='e', ndigits=2) -> str:
"""convert ndarray of floats to a string expression.
:param a:
:param format_:
:param ndigits:
:return:
"""
return np.array2string(
a,
formatter=dict(
float_kind=(lambda x: f'{x:.{ndigits}{format_}}' if x... | 5,298,121 |
def test_missing_variable_with_default_variable():
"""ValueError of empty module.
Error is raised by import_variable_from_module.
"""
with pytest.raises(ValueError):
import_variable_from_module("math:", default_variable_name='cos') | 5,298,122 |
def searchLiteral(a_string, patterns):
"""assumes a_string is a string, being searched in
assumes patterns is a list of strings, to be search for in a_string
returns a re span object, representing the found literal if it exists,
else None"""
results = []
for pattern in patterns:
regex = ... | 5,298,123 |
def TStrHashF_OldGLib_GetSecHashCd(*args):
"""
GetSecHashCd(char const * p) -> int
Parameters:
p: char const *
TStrHashF_OldGLib_GetSecHashCd(TStr s) -> int
Parameters:
s: TStr const &
"""
return _snap.TStrHashF_OldGLib_GetSecHashCd(*args) | 5,298,124 |
def t_n_rect(discharge, strickler_roughness, inclination, width, start=1):
"""Calculates the normal depth of a rectangular channel."""
A = lambda w, h: w * h
U = lambda w, h: w + 2 * h
R = lambda w, h: A(w, h) / U(w, h)
return fsolve(
lambda h: strickler_roughness
* inclination ** ... | 5,298,125 |
def validate_choice(value, choices):
"""Check that ``value`` is in ``choices``."""
choices = validate_list(choices)
if value not in choices:
raise ValidationError(
value,
INVALID_CHOICE,
{
'choices': ', '.join(map(str, choices)),
},
... | 5,298,126 |
def tensor_power(a, n:int):
"""
kron(a, kron(a, ...))
"""
if n == 1:
return csr_matrix(a)
else:
tmp = a
for i in range(n-1):
tmp = kron(tmp, a)
return tmp | 5,298,127 |
def _is_punctuation(char):
"""Checks whether `char` is a punctuation character."""
cp = ord(char)
# We treat all non-letter/number ASCII as punctuation.
# Characters such as "^", "$", and "`" are not in the Unicode
# Punctuation class but we treat them as punctuation anyways, for
# consistency.
... | 5,298,128 |
def main():
"""<tbd>""" | 5,298,129 |
def validate(parser:Parser):
"""
Validate the program's tokens against the grammar tree, and then return the
abstract syntax tree.
"""
def error_handler(hint:str, token:Token, ErrorType=GrammarError):
message = parser.message(hint, *token.pos(), *token.pos())
raise ErrorType(message... | 5,298,130 |
def test_contains_partial_false():
"""Partial word returns false."""
from trie import Trie
t = Trie()
t.insert('Banana')
assert not t.contains('ban') | 5,298,131 |
def sub(project_id, subscription_name):
"""Receives messages from a Pub/Sub subscription."""
# [START pubsub_quickstart_sub_client]
# Initialize a Subscriber client
subscriber_client = pubsub_v1.SubscriberClient()
# [END pubsub_quickstart_sub_client]
# Create a fully qualified identifier in the ... | 5,298,132 |
def migrate_forward(apps, schema_editor):
"""
For all videos, populate entity 'metadata' JSON field
based on values from legacy model fields.
"""
Entity = apps.get_model("tournesol", "Entity")
for entity in Entity.objects.filter(type="video").iterator():
metadata_serializer = VideoMetad... | 5,298,133 |
def get_chart_data(physical_events, spell_events, timestamps):
"""Compiles data for the DPS chart"""
total_dps = {}
total_dps = aggregate_dps(spell_events, aggregate_dps(physical_events, total_dps))
# for ts in timestamps:
# if ts not in total_dps.keys():
# total_dps[ts] = 0
so... | 5,298,134 |
def knn_indices_func_cpu(rep_pts : FloatTensor, # (N, pts, dim)
pts : FloatTensor, # (N, x, dim)
K : int, D : int
) -> LongTensor: # (N, pts, K)
"""
EXAMPLE FUNCTION. Imports not included for this.
CPU-based Indexing fu... | 5,298,135 |
def detect_language(html) :
"""
Detect the language of the text content of a page.
"""
h = html2text.HTML2Text()
return langdetect.detect(h.handle(html)) | 5,298,136 |
def calc_P_ref_evp(Theta_ref_evp):
"""蒸発圧力 (12)
Args:
Theta_ref_evp(float): ヒートポンプサイクルの蒸発温度 (℃)
Returns:
float: 蒸発圧力 (MPa)
"""
return get_f_p_sgas(Theta=Theta_ref_evp) | 5,298,137 |
def red_filter(
img: PIL.Image.Image, red_thresh: int, green_thresh: int, blue_thresh: int
) -> np.ndarray:
"""Mask reddish colors in an RGB image.
Create a mask to filter out reddish colors, where the mask is based on a pixel
being above a red channel threshold value, below a green channel threshold v... | 5,298,138 |
def reorder(operator, order_function, num_modes=None, reverse=False):
"""Changes the fermionic order of the Hamiltonian based on the provided
order_function per mode index
Args:
operator (SymbolicOperator): the operator that will be reordered. must
be a SymbolicOperator or any type of o... | 5,298,139 |
def create_item(
*,
item_in: schemas.ItemCreate,
) -> Any:
"""
Create new item.
"""
next_item_id = items[-1].id + 1 # pylint: disable=no-member
item = schemas.Item(
id=next_item_id,
title=item_in.title,
description=item_in.description,
owner_id=2,
)
i... | 5,298,140 |
def get_worker_from_file( fileName:str ) -> Worker.Worker:
"""
Returns a Worker Object
from the given fileName
"""
if not exists(fileName):
print("The FileName given does not exist")
return None
with open( fileName+".pkl", "rb") as file:
return pickle.load(file) | 5,298,141 |
def delete(ctx, profile, config_file, environment, region, retain_resources):
"""
Delete a CloudFormation stack.
"""
try:
cfg = load_config(config_file, ctx.obj.config, environment, False)
runner = create_runner(profile, cfg)
runner.delete(retain_resources)
except (Va... | 5,298,142 |
def NeedANewWaterfallTryJob(master_name,
builder_name,
build_number,
force_try_job,
build_completed=True):
"""Preliminary check if a new try job is needed.
Don't need try job if build not completed yet, ... | 5,298,143 |
def build_tree_recursive(node: PropertyNode,
max_level,
cpvs: Dict[str, str] = {}):
""" Build a property node and its children recusively
until the maximum level."""
result = node.json_blob() # build the property node blobs
value_nodes = node.childr... | 5,298,144 |
def test_no_mentions(reactor):
"""Make sure we still produce messages if there is no special mention config."""
_configure_reactor(reactor)
handler = SlackHandler(reactor)
alert = _get_alert(reactor)
message = handler.get_message('critical', alert, 42, target=0, ntype='graphite')
assert message ... | 5,298,145 |
def load_metrics():
"""
Load metrics from [hosts] section of RC file
"""
global config
if 'hosts' in config:
mets = config.hosts
else:
mets = {}
mets2 = {}
for tm in mets:
try:
mets2[tm.replace('.', '_')] = int(mets[tm])
except:
log... | 5,298,146 |
def handler_get_user_created_events_from_id(userID):
"""Get the events created by the user with the given ID.
.. :quickref: Users; Get the events created by the user with the given ID.
:param int userID: The ID of the user to retrieve the collection from
:status 200: The list was correctly retriev... | 5,298,147 |
def convert_lookups(**query):
"""
Transform a query from Django-style format to Datasore format.
:return: An iterable of filters suitable to pass to :meth:`~gcloudoem.datastore.query.Query.add_filter`.
"""
filters = []
for key, value in sorted(query.items()):
parts = key.rsplit(LOOKUP_S... | 5,298,148 |
def get_tourn_golfer_id(tourn_golfers_list, tourn_id, golfer_id):
"""
Helper function to get the tourn_golfer_id
based on the specified tourn_id and golfer_id
"""
for tourn_golfer in tourn_golfers_list:
if tourn_golfer.get_golfer_id() == golfer_id:
if tourn_golfer.get_tourn_id()... | 5,298,149 |
def get_jti(encoded_token):
"""
Returns the JTI given the JWT encoded token
:param encoded_token: The encoded JWT string
:return: The JTI of the token
"""
return decode_jwt(encoded_token, config.secret_key, config.algorithm, config.csrf_protect).get('jti') | 5,298,150 |
def verify_raw_google_hash_header(google_hash: str) -> bool:
"""Verify the format of the raw value of the "x-goog-hash" header.
Note: For now this method is used for tests only.
:param str google_hash: the raw value of the "x-goog-hash" header
:rtype: bool
"""
return bool(re.match(r'(crc32c=[... | 5,298,151 |
def test_get_package_type_correction_factor_no_package():
"""get_package_type_correction_factor() should raise a KeyError when passed an
unknown package ID."""
with pytest.raises(KeyError):
integratedcircuit.get_package_type_correction_factor(12) | 5,298,152 |
def compare_ssdeep(payload1, payload2):
"""
Compare binary payloads with ssdeep to determine
:param bytes payload1: Binary content to compare
:param bytes payload2: Binary content to compare
:returns: Match score from 0 (no match) to 100
:type: int or None
"""
payload1_hash = get_ssd... | 5,298,153 |
def stream_copy_images(src_folder, dest_folder, valid, ext={'.jpg', '.png'}, fLOG=None): # pylint: disable=W0102
"""
Copies all images from *src_folder* to *dest_folder*
if *valid(name)* is True.
@param src_folder source folder
@param dest_folder destination folder
@param ... | 5,298,154 |
def _get_workstation() -> typing.Optional[str]:
"""Get the current workstation name.
This gets the current workstation name that respects `NETBIOS_COMPUTER_NAME`. The env var is used by the library
that gss-ntlmssp calls and makes sure that this Python implementation is a closer in its behaviour.
Retu... | 5,298,155 |
def stack_operations():
"""Solution to exercise R-6.1.
What values are returned during the following series of stack operations,
if executed upon an initially empty stack? push(5), push(3), pop(),
push(2), push(8), pop(), pop(), push(9), push(1), pop(), push(7), push(6),
pop(), pop(), push(4), pop(... | 5,298,156 |
def configuration_to_safe_dict(method):
"""
This wrapper function calls the method with the configuration converted from a regular dict into a SafeDict
"""
@wraps(method)
def method_wrapper(self, project_and_group, configuration, dry_run):
return method(self, project_and_group, SafeDict(con... | 5,298,157 |
def get_initial_arg(pk):
"""
Builds the initial arg string for rerunning from wells
"""
if int(pk) != 0:
try:
report = models.Results.objects.get(pk=pk)
ret = report.get_report_dir()
return ret
except models.Results.DoesNotExist:
return ""
... | 5,298,158 |
def get_SHA1(variant_rec):
"""Calculate the SHA1 digest from the ref, study, contig, start, ref, and alt attributes of the variant"""
h = hashlib.sha1()
keys = ['seq', 'study', 'contig', 'start', 'ref', 'alt']
h.update('_'.join([str(variant_rec[key]) for key in keys]).encode())
return h.hexdigest().... | 5,298,159 |
def main():
"""Function: main
Description: Initializes program-wide used variables and processes command
line arguments and values.
Variables:
dir_chk_list -> contains options which will be directories.
opt_arg_list -> contains arguments to add to command line by default.
... | 5,298,160 |
def get_labels(data, centroids):
"""
Find nearest centroid to each data point. Returns ndarray of shape (n, d)
containing labels (nearest centroid) of each data point.
"""
# i-th row of the distances matrix represents distances from each data
# point to the i-th centroid.
distances ... | 5,298,161 |
def compare_metadata(context, metadata):
"""Compare a database schema to that given in a
:class:`~sqlalchemy.schema.MetaData` instance.
The database connection is presented in the context
of a :class:`.MigrationContext` object, which
provides database connectivity as well as optional
comparison... | 5,298,162 |
def parse_address_or_network(value):
"""
Parse value as IPAddress or Network
"""
if isinstance(value, (IPAddress, Network)):
return value
try:
return IPAddress(value)
except (ValueError, AddrFormatError):
pass
try:
return Network(value)
except AddrFormatEr... | 5,298,163 |
def render_flag_completion_func(command_dict: dict, name: str) -> (str, str):
"""Renders function for flag completion of command and its subcommands."""
subcommands = get_subcommands(command_dict)
options = get_options(command_dict)
func_name = "__unikube_complete_flags_{name}".format(name=name)
i... | 5,298,164 |
def test_get_querystring():
"""Test get_querystring"""
function = {
"name": "code_test",
"querystring": {
"bool_test": {"static": True},
"pagesize": {"static": 500},
"page": {"variable": "page"},
"apikey": {"function": "get_api_key()"},
},... | 5,298,165 |
def test_extract_fields_from_resource_name_with_extracted_fields(
generated_resource_name: str, generated_resource_fields: utils.Fields
):
"""Verify fields extracted from resource name match the original fields"""
assert (
utils.extract_fields_from_resource_name(resource_name=generated_resource_nam... | 5,298,166 |
def compare_output(prev_solrrec, solrrec, chromo):
"""
process solr_compare_previous_year fields and return solrrec with
extra sum and change fields added
"""
out = dict(solrrec)
for f in chromo['fields']:
comp = f.get('solr_compare_previous_year')
if not comp:
conti... | 5,298,167 |
def build_docs():
""" Builds up a complete chunk-match structure, with a depth of 2 in both directions recursively. """
docs = []
for base_id in range(DOCUMENTS_PER_LEVEL):
d = jina_pb2.Document()
d.granularity = 0
d.adjacency = 0
d.id = base_id
docs.append(d)
... | 5,298,168 |
def fetch(critic, token_id):
"""Fetch an AccessToken object with the given token id"""
import api.impl
assert isinstance(critic, api.critic.Critic)
return api.impl.accesstoken.fetch(critic, int(token_id)) | 5,298,169 |
def verify_checksum(message, previous_csum=0):
"""Verify checksum for incoming message.
:param message: incoming message
:param previous_csum: accumulated checksum value
:return return True if message checksum type is None
or checksum is correct
"""
if message.message_type in CHECKSUM_MSG_... | 5,298,170 |
def destroy_stac_data():
"""
Will delete all STAC API data, for tests.
"""
stac_host = os.getenv("STAC_HOST")
r = requests.get(urljoin(stac_host, "collections"))
collections = r.json()
for c in collections["collections"]:
r = requests.get(urljoin(stac_host, f"collections/{c['id']}/i... | 5,298,171 |
def group_required(*group_names):
"""
Requires user membership in at least one of the groups passed in.
"""
def wrap(view):
def wrapped_view(request, *args, **kwargs):
user = request.user
if user.is_authenticated:
check_groups = bool(user.groups.filter(nam... | 5,298,172 |
def test_types_to_binary_mul_op():
"""Test types to binary multiply operation."""
tests = (
"1 * 1",
"1 / 1"
)
for i in tests:
compile(emptyfn(i + ";")) | 5,298,173 |
def varnish_purge_expr(expr):
"""
Purge the specified expression from Varnish. Does not modify the expression
at all, so be very careful!
"""
connection.cursor().execute("SELECT varnish_purge_expr(%s)", (expr, )) | 5,298,174 |
def readSeven(filename):
"""Read the occurrences of each quality value of wine; Return a list of outliers"""
with open(filename, 'r') as f:
next(f) # Skip format line
for line in f:
if line[-4] == "7":
appendLine(line) | 5,298,175 |
def derive_databases(first, last):
"""Load words of typical word lengths from text and dump as pickle databases."""
for slots in range(first, last + 1):
dump(read_mixed_case_word_text(slots)) | 5,298,176 |
def cirs_radec(body, date=None, deg=False, obs=chime):
"""Converts a Skyfield body in CIRS coordinates at a given epoch to
ICRS coordinates observed from CHIME
Parameters
----------
body : skyfield.api.Star
Skyfield Star object with positions in CIRS coordinates.
Returns
-------
... | 5,298,177 |
def reconcile_S1(T):
"""
Prune the Fitch-Hartigan S1 arrays across T to respect only solutions that are guaranteed to
be sub-optimal in the subtree below any internal node and legal with respect to its parent's
set of potential states.
"""
source = [n for n in T if T.in_degree(n) == 0][0]
... | 5,298,178 |
def stop_deployment(deploymentId=None, autoRollbackEnabled=None):
"""
Attempts to stop an ongoing deployment.
See also: AWS API Documentation
:example: response = client.stop_deployment(
deploymentId='string',
autoRollbackEnabled=True|False
)
:type deploymentI... | 5,298,179 |
def find_pgomgr(chrome_checkout_dir):
"""Find pgomgr.exe."""
win_toolchain_json_file = os.path.join(chrome_checkout_dir, 'build',
'win_toolchain.json')
if not os.path.exists(win_toolchain_json_file):
raise Exception('The toolchain JSON file is missing.')
with open(win_toolchain_json_file) as temp_f:
... | 5,298,180 |
def state_filestub(st, is2005=False):
"""Given a 2-char abbreviation, return the state filestub (directory).
The Census standard is the full state name, camel case, spaces
removed. This generally is true for "United States" too, but in 2005
they put a "0" in front of the name, to make sure it's sorted ... | 5,298,181 |
def parse_experiments(data, symbols):
"""
For the experiment in the data structure that has data recorded in a table column,
the data type string and the list of table values is returned
Returns
-------
tuple
2 tuple of a list of data types/units and the list of elements each output cor... | 5,298,182 |
def refresh_compliance_data(ip_address, headers, baseline_job_id, id_baseline):
""" Reruns baseline job to refresh inventory data """
url = 'https://%s/api/JobService/Actions/JobService.RunJobs' % ip_address
payload = {
"JobIds": [10203]
}
payload["JobIds"][:] = []
payload["JobIds"].append(baseline_job_id)
pri... | 5,298,183 |
def parse_json_arch(arch_json):
"""
Description:
Parse model architecture JSON.
Args:
:arch_json (str): filepath to model json.
Returns:
None
"""
pass | 5,298,184 |
def save_checkpoint(model, optimizer, path, epoch=-1):
"""Save model checkpoint and optimizer state to file."""
state = {
"epoch": epoch,
"state_dict": model.state_dict(),
"optimizer": optimizer.state_dict(),
}
file_path = "%s.pt" % path
print("Saving checkpoint to {}".format... | 5,298,185 |
def generate_urls(row):
"""Generate list of URLS from a given row"""
urls = []
for k in keys_url:
url = row.get(k, "")
if url.strip() != "":
name = get_url_type(url)
urls.append({"name": name, "url": encode_base64(url)})
return urls | 5,298,186 |
def csr_polynomial_expansion(X, interaction_only, degree):
"""Apply polynomial expansion on CSR matrix
Parameters
----------
X : sparse CSR matrix
Input array
Returns
-------
New expansed matrix
"""
assert degree in (2, 3)
interaction_only = 1 if interaction_only else ... | 5,298,187 |
def read_genbank(
file: str,
as_dict: bool = False) -> \
Union[List[Chromosome], Dict[str, Chromosome]]:
"""
Read a genbank file into Chromosome ojbects, i.e. annotated genome
Args:
file: path-like
The input genbank file
as_dict:
... | 5,298,188 |
def get_docs_and_trans():
"""
:return: docs (translated and not) and translator count
:structure: dict('code': string, 'document': dict('documents': int, 'translators': int, 'translated_documents': int)
"""
client = MongoClient()
db = client.highlight
acc = db.accounts
l_s = db.files_inf... | 5,298,189 |
def get_hrnet(version,
model_name=None,
pretrained=False,
root=os.path.join("~", ".tensorflow", "models"),
**kwargs):
"""
Create HRNet model with specific parameters.
Parameters:
----------
version : str
Version of MobileNetV3 ('s' or ... | 5,298,190 |
def http_exception_error_handler(
exception):
"""
Handle HTTP exception
:param werkzeug.exceptions.HTTPException exception: Raised exception
A response is returned, as formatted by the :py:func:`response` function.
"""
assert issubclass(type(exception), HTTPException), type(exception)... | 5,298,191 |
def reverse_list(head):
"""Fantasic code!"""
new_head = None # ptr on previous item
while head:
head.next, head, new_head = new_head, head.next, head # look Ma, no temp vars!
return new_head | 5,298,192 |
def increase_replication_factor(ClusterName=None, NewReplicationFactor=None, AvailabilityZones=None):
"""
Adds one or more nodes to a DAX cluster.
See also: AWS API Documentation
Exceptions
:example: response = client.increase_replication_factor(
ClusterName='string',
NewRe... | 5,298,193 |
def test_madman_reset():
"""
To test the reset of the madman sensor.
"""
kwargs = {
'map_width': 5,
'map_height': 5,
'driving_agent': "pelican",
'panther_agent_filepath': "/Components/plark-game/plark_game/agents/basic/pantherAgent_move_north.py",
'panther_agent... | 5,298,194 |
def namespacesFromSelection():
"""this is get namespace string from current selectionList.
"""
namespaces = ['']
try:
namespaces = a
except NameError as error:
pm.warning('occured nameError. skip get namespace.')
namespaces = ['']
return namespaces | 5,298,195 |
def build_db_changes(change: TasksChange, current_tasks: Dict[str, DbTask]) -> DbTasksChange:
"""Evaluate all changes that must be performed on task to apply the requested changes"""
deleted_tasks_ids = (
{task_id for task_id in current_tasks.keys() if is_task_in_dag(task_id, change.dags)}
- {ta... | 5,298,196 |
def test_invalid_draft_summary_missing_regtype():
"""Assert that an invalid draft summary fails - registration type is missing."""
draft = copy.deepcopy(DRAFT_SUMMARY)
del draft[0]['registrationType']
is_valid, errors = validate(draft, 'draftSummary', 'ppr')
if errors:
for err in errors:
... | 5,298,197 |
def eigprincomp(x, npcs=None, norm=False, weights=None):
"""Does principal components analysis on [x].
Returns coefficients (eigenvectors) and eigenvalues.
If given, only the [npcs] greatest eigenvectors/values will be returned.
If given, the covariance matrix will be computed using [weights] on the sam... | 5,298,198 |
def nco_ocp_Ecker2015_function(sto):
"""
NCO OCP as a function of stochiometry [1, 2, 3].
References
----------
.. [1] Ecker, Madeleine, et al. "Parameterization of a physico-chemical model of
a lithium-ion battery i. determination of parameters." Journal of the
Electrochemical Society 162.... | 5,298,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.