content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def to_bytes( arg ):
"""Converts arg to a 'bytes' object."""
return bytes( bytearray( arg )) # if python2, 'bytes' is synonym for 'str' | 993c9701a5b5fb737f033d227b5b0cf53c2f5672 | 647,144 |
def flatten(l):
"""Return list `l` flattened."""
flat = []
for x in l:
flat += flatten(x) if isinstance(x, list) else [x]
return flat | 042791c9f64dce1bca6ca8aceea8690fe56621ea | 647,149 |
def indent(s, n=1, indent_str=" "):
"""Inserts `n * indent_str` at the start of each non-empty line in `s`."""
p = n * indent_str
return "".join((p + l) if l.lstrip() else l for l in s.splitlines(True)) | d4e6816f1797dd71bbc0c67a9e8b83a9aa1e7b38 | 647,152 |
def get_attack_from_name(self, attack_name):
"""
Get the player's attack with the given name.
Arguments
---------
attack_name : str
The name of the attack to get.
Returns
-------
Attack
The corresponding attack.
"""
for attack in self.entity.attacks:
... | a09ca69ef3ff01b74cd20ffaac3c91dc4863c84a | 647,153 |
def a_test_filter(a, b):
"""Return a string containing both a and b."""
return f"{a}:{b}" | e7a0c140b35f1b98bae45cf742070e8486c7eeb2 | 647,157 |
def is_valid_argument_group_model(arg_group, arguments):
"""
Validates CLI model at specified argument group level.
With this validation, every argument group is mandated to have title, description and arguments that go as a group.
Parameters
----------
arg_group(dict): A dictonary object wh... | 2c42c7a1431887a758fa2c9e15dead8a0972519e | 647,159 |
from typing import List
from typing import Union
def _unicode_def_src_to_str(srclist: List[Union[str, int]]) -> str:
"""
Used to create :data:`UNICODE_CATEGORY_STRINGS`.
Args:
srclist: list of integers or hex range strings like ``"0061-007A"``
Returns:
a string with all characters de... | ca44283bc8cfd03db390874f84f31297d5f8f918 | 647,160 |
import re
def word_wrap(text, line_width=80):
"""
Word wrap long lines to ``line_width``
"""
text = re.sub(r'\n', '\n\n', text)
return re.sub(r'(.{1,%s})(\s+|$)' % line_width, r'\1\n', text).strip() | 41ace0e91231228c340c0535e7785937ef840562 | 647,164 |
def sumatorio_tope(tope):
"""
Va sumando números naturales hasta llegar al tope.
Ejemplos
--------
>>> sumatorio_tope(9)
6
# 1 + 2 + 3
>>> sumatorio_tope(10)
10 # 1 + 2 + 3 + 4
>>> sumatorio_tope(12)
10 # 1 + 2 + 3 + 4
>>> sumatorio_tope(16)
1... | c8a0307f5876b2eb641edc10a4dc93ad38270e95 | 647,167 |
from pathlib import Path
import json
def get_secrets_list(env: str) -> dict[str, set]:
"""Create a list of available app secrets, without their values."""
path = (Path() / "configuration").resolve()
default_file = json.loads((path / "default.json").read_text())
env_file = json.loads((path / f"{env}.js... | f31905458529d1dae8ad6da7a4a60acc8aa9f3d8 | 647,170 |
from typing import OrderedDict
def sortByKey(theDict):
"""
Return an OrderedDict from a dict sorted by keys
"""
return OrderedDict(sorted(theDict.items())) | 275de502ce365efef966bbe9a4afa947ce315bde | 647,171 |
def get_api_bool_string(api_bool):
"""Return KEMP restfull API version of a bool string"""
return 'y' if api_bool else 'n' | a8811d6f06bd7a915adff3b7b6d5b968cf7fdcd9 | 647,172 |
def split_extension(filename):
"""
Splits the extension off the filename and returns a tuple of the
base filename and the extension (without the dot).
:param str filename: The base filename string to split.
:return: A tuple of the head (characters before the last '.') and
the extension (characters after the ... | 5c15426a38c13b7e746406a1f06b821110f12c1f | 647,174 |
def string_SizeInBytes(size_in_bytes):
"""Make ``size in bytes`` human readable.
Doesn"t support size greater than 1000PB.
Usage::
>>> from __future__ import print_function
>>> from weatherlab.lib.filesystem.windowsexplorer import string_SizeInBytes
>>> print(string_SizeInBytes(100... | 2ca967f9196b2f5a36ea83c4937d1cd8624467b9 | 647,175 |
def encode_line_wordwise(line, vocab):
"""Given a string and vocab, return the word encoded version"""
splited = line.split()
sequence_input = [vocab.get(word, vocab['UNK']) for word in splited]
sequence_input = [vocab['GOO']] + sequence_input + [vocab['EOS']]
sequence_length = len(sequence_input) -... | a0742b7fba1963657a63a27045af2f9bf662422f | 647,178 |
def format_runtime(runtime):
"""Formats the given running time (in seconds)."""
if runtime < 60:
# Just seconds.
return '{:.2f}s'.format(runtime)
# Minutes and seconds.
return '{}m {}s'.format(int(runtime // 60), int(runtime % 60)) | dc07f540215f5ceeb476056e75e91b760358ad68 | 647,182 |
import torch
def softor(rasters: torch.Tensor, dim=1, keepdim=False) -> torch.Tensor:
"""Batched soft-or operation to combine rasters.
Args:
rasters: torch.Tensor of size [batch, *, nrasters, D*] representing stacks of nrasters images that will
be composited into a single image
dim... | 7a2b37fb99feb4ea14c229b8454d21b4a8a8d880 | 647,184 |
def clean(s, isInt=False):
"""
This function takes the string input from the HTML text area
field and converts those entries into a list of floating-point numbers or integers
(for bitwise operations) which will be used to intialize the matrices.
This function assumes the string only has number valu... | eb0076b2b1e93ba7239c770582fdfe204ff92e45 | 647,188 |
def register(name: str, registry: dict):
"""
Register a class or a function with name in registry.
For example:
CLS = {}
@register("a", CLS)
class A(object):
def __init__(self, a=1):
self.a = a
cls_a = CLS['a'](1)
In this way you can build... | b1238babbbbc986cee1b1eaae6468ab027081467 | 647,197 |
import time
def DosDateTimeToTimeTuple(dosDateTime):
"""Convert an MS-DOS format date time to a Python time tuple.
"""
dos_date = dosDateTime >> 16
dos_time = dosDateTime & 0xffff
day = dos_date & 0x1f
month = (dos_date >> 5) & 0xf
year = 1980 + (dos_date >> 9)
second = 2 * (dos_time &... | b39c1399c34e0349adc166136f3d46fca7ff5ef3 | 647,199 |
import re
def detect_patient_age(info_par):
"""Returns age of patient described in paragraph of WHO assessment"""
# Searches for "year-old" or 'year old'
if re.findall('(\d{1,2}) ?(:?-?(year|month)(-| )old)',info_par) != []:
age = re.findall('(\d{1,2}) ?(:?-?(year|month)(-| )old)',info_par)[0][0]
... | 60f4027884753872c75814026e351eeaf7eedf3c | 647,204 |
def row(point):
"""
Given a point, return the row of the point.
>>> row((0, 1))
0
>>> row((1, 0))
1
"""
return point[0] | 1e85f0b919907f6cf27b0448fc5a92c1047cfb97 | 647,208 |
import requests
def num_stargates(sys_id):
"""
Returns the number of stargates in a specified system.
:param sys_id: System ID (int) of the designated system to lookup
:return: integer value of the number of gates in a system. Will always be >0
"""
base_url = f"https://esi.evetech.net/latest/... | a0d988a3d03720249ce12b47ee7640eb43b527b5 | 647,210 |
def transpose(matrix):
""" Transpose a matrix (defined as a list of lists, where each sub-list is a row in the matrix) """
# This feels dirty somewhow; but it does do exactly what I want
return list(zip(*matrix)) | a7ce276a812aa007424cb10fdd4ae84743871133 | 647,211 |
import asyncio
async def simulation_timer(sim_duration, quit_app):
""" stops the simulation after 'sim_duration' seconds have elapsed """
# loop = asyncio.get_running_loop()
await asyncio.sleep(sim_duration)
quit_app.set()
return True | d0f79388023852d70a8cf3f3f8919476e5dffd2a | 647,212 |
import torch
def AverageProportion(
delays, src_lens, tgt_lens, ref_len=None, target_padding_mask=None):
"""
Function to calculate Average Proportion from
Can neural machine translation do simultaneous translation?
(https://arxiv.org/abs/1606.02012)
Delays are monotonic steps, range from 1 to ... | 8653f84c4c3e5bd53a06bc1c85a05af9139b69cf | 647,213 |
def _rotate_right(num: int, shift: int, size: int = 32):
"""Rotate an integer right."""
return (num >> shift) | (num << size - shift) | e59dfbdb11da107ae31e5940854ed3846b35a991 | 647,217 |
def get_system_columns(columns):
"""Filters leaderboard columns to get the system column names.
Args:
columns(iterable): Iterable of leaderboard column names.
Returns:
list: A list of channel system names.
"""
excluded_prefices = ['channel_', 'parameter_', 'property_']
return [... | 024dcdcd9c6327d3ac28a3b1c67bf7daa4953b99 | 647,222 |
def _intersection_homogenous(homog_line_0, homog_line_1):
"""Find point of intersection of two lines in homogenous coordinates"""
# NB: renamed from '_intersection'
eps = 1e-13
a,b,c=homog_line_0
u,v,w=homog_line_1
D=float(b*u-v*a)
if abs(D)<eps:
# parallel lines
return None,... | b529411a69870beb3128aebb151d8d3b13de5b61 | 647,226 |
import time
def wait_pipe_len(sock, expected, timeout=10):
"""
Wait up to ``timeout`` seconds for the length of sock.pipes to become
``expected`` value. This prevents hardcoding sleep times, which should be
pretty small for local development but potentially pretty large for CI
runs.
"""
... | 28d1b6e86f4ec5fd6f62e9e5e493df4badf64d24 | 647,235 |
def clean_data(df):
"""
This function cleans data from the provided dataframe
Parameters: df is the dataframe with the messages and categories
Return: df is the dataframe already clean with no duplicates
"""
print("df shape=",df.shape)
duplicate = df[df.duplicated()]
print("df... | 7becbeb82c79ac0319b1dbacc65afcca0a1f7359 | 647,239 |
import re
def _underscore(string):
""" Convert a string from CamelCase to underscored """
string = re.sub(r'([A-Z]+)([A-Z][a-z])', r'\1_\2', string)
return re.sub(r'([a-z0-9])([A-Z])', r'\1_\2', string).lower() | 0a1e81dc2943b9657db355ca328fdee5d8a49a47 | 647,241 |
def double(number: float) -> float:
"""
Here, we say that 'number' should be a float and the double() function
should return a float.
Python treats these annotations as hints, they are not enforced at runtime
"""
return 2 * number | 5f65f49ba4a2616824275af96050d8abe3ab3795 | 647,242 |
def is_rate_limit_error_message(message):
"""Check if the supplied error message belongs to a rate limit error."""
return isinstance(message, list) \
and len(message) > 0 \
and 'code' in message[0] \
and message[0]['code'] == 88 | 38db5d4f61d914339190bb78a13c58e0577f4ef7 | 647,243 |
import json
def _read_missing_references_json(json_path):
"""
Convert from the JSON file to the form used internally by this
extension.
The JSON file is stored as ``{domain_type: {target: [locations,]}}``
since JSON can't store dictionary keys which are tuples. We convert
this back to ``{(dom... | ae9a8dd23769b0e704fa3d1e9b69cf27817c6d06 | 647,244 |
import socket
import struct
def inet_nitoa(i):
"""Like inet_ntoa but expects an integer."""
return socket.inet_ntoa(struct.pack('>I', i)) | 09ce3d3ccbc396b94f37de5bce9d2fb5f3e30899 | 647,245 |
def needs_rename(string):
"""Search input string for illegal characters. If found, return True, list of characters found, cleaned name.
If not, return False and two empty strings"""
bad_characters = ["&", "$", "@", "=", ";", "+", ",", "?", "\\", "{", "^", "}", "%", "`", "]", "\"", ">", "[", "~",
... | 1f49a8295d482828a4724c14b9af1579ea9e7d87 | 647,250 |
def listFile(*ignored_args, **ignored_kwargs):
"""No-op action callable that ignores arguments and returns (True, []).
"""
return True, [] # match only based on file names, which was done by caller | bbba2ccb4031ad3e74d595a20d43fee0eebe3da7 | 647,252 |
def repository(app):
"""GitHub repository."""
return app.repository.html_url | 3a757deddcbaf910659c9e31594f42258134a3ad | 647,253 |
def seasonFromDate(date):
"""
Returns the value of season from month and day data of the timestamp
Parameters
----------
date : String
Timestamp or date string in format of YYYY-MM-DD or followed by timestamp
Returns
-------
season : STRING
Season corresponding to the d... | 0d61a3951c5b997f79c75a11172cd5e3f913a560 | 647,254 |
from typing import List
def parse_to_lines(content: str) -> List[str]:
"""Metin içerisindeki satırların listesini oluşturur
Arguments:
content {str} -- Metin
Returns:
List[str] -- Satır listesi
Examles:
>>> parse_to_lines('Selam\\nNaber\\nNasılsın')
['Selam', 'Naber'... | 4c44803f451699f7142b7eccc455df2316ffa2e7 | 647,255 |
def update_state(reactants, products, state, rxn_ind, reverse):
"""
Updating the system state based on chosen reaction, during kMC simulation.
Args:
reactants: (n_rxns x 2) array, each row containing reactant mol_index of forward reaction
products: (n_rxns x 2) array, each row containing pr... | 7b8ce0daef2e43418dc43e9e37252024c6314bb7 | 647,256 |
def get_param_value(mode, memory, ptr):
"""Returns the value of the parameter at memory[ptr] based on the mode"""
# position mode
if mode == 0:
return memory[memory[ptr]]
# immediate mode
elif mode == 1:
return memory[ptr]
else:
raise Exception | 3472207301a1c32cce2b8bfeaa0ecef44e85670d | 647,257 |
def calc_tstart(num_bins, binsize, t_stop):
"""
Calculates the start point from given parameter.
Calculates the start point :attr:`t_start` from the three parameter
:attr:`t_stop`, :attr:`num_bins` and :attr`binsize`.
Parameters
----------
num_bins: int
Number of bins
binsize: ... | fb1fa026bbfb3978bb0f4aaeeb3a93d3bc471fbd | 647,259 |
import requests
def get_rates(url):
"""Method to get currency rates and returns status of request(boolean)
and request response in JSON format.
@:param str url: Exchange site url
@:return boolean: True for successful response, else False.
@:return dict: Response in case of success else empty dict... | 5706d6dd6fd96d9f364c57b69a29e6c7dde791af | 647,263 |
def _guess_desc(fname):
"""Attempts to guess the menu entry description from the function name."""
return fname.title().replace("_", " ") | 30d346a77e680fb88b8dc80fdb6e465f26c52caa | 647,264 |
def make_actual_args(members):
"""Comma-separated name list used in actual arguments
a, b, c
"""
return ", ".join(name for _, name in members) | 4fb0003a21f7b041ac4b5b30ac94ce044a3b2368 | 647,266 |
def update_parser(parser):
"""Parse the arguments from the CLI and update the parser."""
parser.add_argument(
'--prepro_step',
type=str,
default='preprocessing', #'slicing', 'preprocessing'
help='To execute a preprocessing method')
#this is for allfeatures_preprocessi... | 5cd74d2e50801db7ea7d27a37bca3c224a2b039a | 647,268 |
import json
def readJSONDict(filename):
"""
Retrieve stored dict from JSON file
"""
jsondict = {}
with open(filename, 'rb') as infile:
jsondata = infile.read()
jsondict = json.loads(jsondata)
return jsondict | 7ce79e349538ff23409c5cebcce7317a1e2fe3ac | 647,269 |
def is_member_of_group(status: str):
"""check, whether a given status indicates group-association
Args:
status (str): status to check
Returns:
bool: is a person with status in this group?
"""
possibleStati = ['creator', 'administrator', 'member', 'restricted']
return status in... | 2122e54557672c95cafea7fe3aa12e839241b4ae | 647,274 |
def yaml_transformer(value: str) -> str:
"""A YAML transformer for Ruamel that places a blank line between each top level section."""
lines = value.splitlines()
output = []
for line_no, line in enumerate(lines):
if line_no and not line.startswith(' '):
output.append('')
out... | b8aa628f78607fe837083421e068b801f4689648 | 647,276 |
from typing import Dict
def __attempt_replace(line_args: str, labels_locs: Dict[str, int]) -> str:
"""
Atttempt to replace a label with its memory address.
:param line_args: Part of the line including the arguments.
:param labels_locs: Labels and their memory addresses.
:return: Line with the labe... | 4d08c304792f393220d7aa7259b1d2cffb7453aa | 647,277 |
def agg_loss(method):
"""
Extract aggregate loss from full name of method.
Args:
method (str): full name of method
Returns:
str: aggregate loss
"""
if method[:6] == "hinge_":
return method[6:]
if method[:9] == "logistic_":
return method[9:]
if method[:7]... | a6d8c0c9162788db02cee60aaaee8361595aeaeb | 647,279 |
def nullility_corr(data, method="pearson"):
"""Calculates the nullility correlation between features in a DataFrame.
Leverages pandas method to calculate correlation of nullility. Note that
this method drops NA values to compute correlation. It also employs
`check_missingness` decorator to ensure DataF... | 17dcdaa60d0dd07c404e867f1231ffa61126592b | 647,280 |
import re
def clean_spaces(text: str) -> str:
"""Removes any consecutive white spaces in the text, as well as preceding and
trailing whitespaces.
Arguments:
text:
The text to be filtered.
Returns:
The filtered text.
"""
return re.sub(
" +", " ", text
)... | fd6b826eed4737c87c9c0cec36d33d602056c8af | 647,281 |
def get_active_branch(repo):
"""Returns the active branch of the given local repository.
Args:
repo(git.Repo): Git Repo instance
Returns:
str: The name of the active branch.
"""
return repo.active_branch.name | cb82cbc988d34766050091c9b34fa73ff7506b6c | 647,283 |
def df_set_diag(df, val, copy=True):
"""
Sets the diagonal of a dataframe to a value. Diagonal in this case is anything where row label == column label.
:param df: pd.DataFrame
DataFrame to modify
:param val: numeric
Value to insert into any cells where row label == column label
:pa... | c8dc669fc23b6e38bcb552a72e4fbe418528a242 | 647,284 |
def normalized_intersection(bbox1, bbox2):
"""
Intersection that is normalized with respect to the first bbox.
:param bbox1: bounding boxes in the format [left, top, right, bottom]
and shape [4]; dtype has to be np.ndarray or list
:param bbox2: bounding boxes in the format [left, top, right, bot... | 2b1b1db81c0b7a97aa3e0be74a60c7b87fd79f7d | 647,288 |
def get_token_index(text, offset, tokens):
"""
>>> text = "A quick brownDasheyBhgx fox jump's over the lazy dog"
>>> tokens = ['[CLS]', 'a', 'quick', 'brown', '##das', '##hey', '##bh',
... '##g', '##x', 'fox', 'jump', "'", 's', 'over', 'the', 'lazy',
... 'dog', '[SEP]']
>>> t... | d56aab443b631ae1c8a3eb1f7c6790d5bb77b57f | 647,294 |
def const(v):
"""Return the value passed."""
def f(data):
return v
return f | d0e65671da465dea52a36e64c724645398af8400 | 647,298 |
import torch
def LSIGF_DB(h, S, x, b=None):
"""
LSIGF_DB(filter_taps, GSO, input, bias=None) Computes the output of a
linear shift-invariant graph filter (graph convolution) on delayed
input and then adds bias.
Denote as G the number of input features, F the number of output features,
... | 2126b5b9a291c07e2b10fcb8dd9029fe44fcd3b0 | 647,299 |
def pad(source: str, pad_len: int, align: str) -> str:
"""Return a padded string.
:param source: The string to be padded.
:param pad_len: The total length of the string to be returned.
:param align: The alignment for the string.
:return: The padded string.
"""
return "{s:{a}{n}}".format(s=s... | 6f4b587e224cfeb33ca2aba3ef2c67ff8eb86d3b | 647,301 |
import configparser
def read_setup_cfg(fname="setup.cfg"):
"""
Read the setup.cfg file into a dictionary.
"""
config = configparser.ConfigParser()
# Use read_file to get a FileNotFoundError if setup.cfg is missing. Using
# read returns an empty config instead of raising an exception.
with ... | 312c300dcf09060d86a8ce8f2d09a30b594f230f | 647,304 |
import ast
def _convert_to_expression(node):
""" convert ast node to ast.Expression if possible, None if not """
node = ast.fix_missing_locations(node)
if isinstance(node, ast.Module):
if len(node.body) != 1:
return None
if isinstance(node.body[0], ast.Expr):
expr ... | a24c8c304b21d2a4f90e7946267620a853db1a4b | 647,305 |
def removeListDups(base_list,remove_list):
"""Remove items from one list from another
Args:
base_list (list): list to keep the non-duplicated values from
remove_list (list): list of items to remove from base_list
Returns:
list : list of items in base_list NOT in remove_list
"""... | 52a968f074aa961fe2206c81692206839004c7da | 647,309 |
def test_cache_memoize_arg_normalization(cache):
"""
Test taht cache.memoize() normalizes argument ordering for positional and keyword
arguments.
"""
@cache.memoize(typed=True)
def func(a, b, c, d, **kargs):
return (a, b, c, d)
for args, kargs in (
((1, 2, 3, 4), {"e": 5}),... | 170069c8af7f9debe94029018f8df8bdaf31c01d | 647,313 |
def to_integer(obj):
"""Converts `obj` to an integer.
Args:
obj (str|int|float): Object to convert.
Returns:
int: Converted integer or ``0`` if it can't be converted.
Example:
>>> to_integer(3.2)
3
>>> to_integer('3.2')
3
>>> to_integer('3.9')
... | 04247b146a0d9d9c6fbdb89c9de06e162d37652b | 647,315 |
def get_clinvar_accession_from_clinvarset(elem):
"""
Gets the Clinvar accession from a ClinVarSet element
:param elem: ClinVarSet Element
:return: ClinVar Accession
"""
## elem.xpath("//ClinVarAccession")[0].attrib['Acc'] ## this only works sometimes
try:
# return elem.xpath("//Clin... | bb6620caba7c089dbad35b1c0cc718c5ed39655f | 647,317 |
def children(node):
"""Returns a list containing all child nodes
of a Traversable type node. Returns empty list
when the node has no children. Used by BF/DF/Flat
iterative tree visitor functions."""
try:
k = node.getChildren()
return k
except:
return [] | e2d2fda08c4f22682f599b90a915e94a9e9e599d | 647,321 |
from typing import Union
from typing import Tuple
def divmod_int(numerator: Union[int, float], denominator: Union[int, float]) -> Tuple[int, int]:
"""Return the result of divmod, as a tuple of integers."""
quotient, remainder = divmod(numerator, denominator)
return int(quotient), int(remainder) | 71ae719703d68e6c43a4b01e123fbd08b91acb65 | 647,327 |
import string
def clean_tokens(tokens):
"""Tokens are lower-cased, stripped of punctuation, and filtered for NULL."""
tokens = [w.lower().strip(string.punctuation) for w in tokens]
tokens = [w for w in tokens if w]
tokens = tokens or ["NULL"]
return tokens | 63b36242f4bc44d5018bdd176b62e95b01776649 | 647,329 |
def class_mix_data(data):
"""
> input:
[[label, ...], [label, ...], [label, ...], ... ]
> output:
[ [[label, ...], [label, ...], [label, ...], ... ], <- class 0
[[label, ...], [label, ...], [label, ...], ... ], <- class 1
.
.
.
[[label, ...], [label, ...], ... | 41f6d2d2c4c720ff95cf72d51743d80db7ecc47b | 647,330 |
def show_in_nav_for(level=0, icon=None):
"""
Use as a class / method decorator to flag an exposed object in the site navigation
@show_in_nav_for(users.guest)
@expose
class SubPage:
...
"""
def decorate(f):
f.show_in_nav = level
f.icon = icon
f.exposed = True
... | 030ef8e38ef398f7e3461a11807e12dc15460848 | 647,333 |
def get_sha1_or_none(repo, ref):
"""Return string of the ref's commit hash if valid, else None.
:repo: a callable supporting git commands, e.g. repo("status")
:ref: string of the reference to parse
:returns: string of the ref's commit hash if valid, else None.
"""
commit = repo("rev-parse", "-... | d20473120136b5f2410b5210a013451bfa68e250 | 647,336 |
def anchor_in_soup(soup, anchor_name):
"""Find if a given anchor id is present in a HTML data"""
return bool(soup.find("", {"id" : anchor_name})) or bool(soup.find("", {"name": anchor_name})) | f24d1370f3c1e0f0c7d3e6723014600f219601e4 | 647,337 |
def is_dualtor(tbinfo):
"""Check if the testbed is dualtor."""
return "dualtor" in tbinfo["topo"]["name"] | 2587bf9d8425bc5b1445e02923a52e28aae6fddf | 647,342 |
def read_lines(path):
"""
Reads lines from file into list with leading and trailing whitespace removed.
"""
with path.open() as f:
lines = f.readlines()
lines = [l.strip() for l in lines]
return lines | e7db6ed55daee6aec53deb3aedbdfe8526812801 | 647,344 |
def get_no_aliens(sett, alien_width):
"""Determine the number of aliens that fit in a row.
Spacing between each alien is equal to half alien width"""
available_space_x = sett.screen_width - 1.5 * alien_width
no_of_aliens = int(available_space_x / (1.5 * alien_width))
return no_of_aliens | db9bf8a50c85867dd002fcb70c6e40b24512f606 | 647,351 |
def greet(adventurer: str) -> str:
"""
returns a greeting string that greets the title cased adventurers name
>>> greet('bob')
'Hello Brave Bob'
:param adventurer: the name of the adventurer to greet
:return: a greeting "Hello ..."
"""
return f"Hello Brave {adventurer.title()}" | 3fe2471468254b3f763c07cb80f51fee43466157 | 647,356 |
import re
def process_tex(lines):
"""
Remove unnecessary section titles from the LaTeX file.
"""
new_lines = []
for line in lines:
line = re.sub(r'^\s*\\strong{See Also:}\s*$', r'\paragraph{See Also}', line)
if (line.startswith(r'\section{sknano.')
or line.startswith(r... | 21e81a2d208c775a4d4270655539a327cb8a1eb6 | 647,365 |
def split_csp_str(val):
""" Split comma separated string into unique values, keeping their order.
:returns: list of splitted values
"""
seen = set()
values = val if isinstance(val, (list, tuple)) else val.strip().split(',')
return [x for x in values if x and not (x in seen or seen.add(x))] | e5ef698ed6dbb1dd2c9c832926c95b3e85743051 | 647,371 |
def parse_incar(incar):
"""
Parameters
----------
incar: str
Path to VASP incar
Returns
-------
encut: int
Energy Cutoff
"""
encut = None
with open(incar, "r") as f:
for line in f:
if "ENCUT" in line:
encut = float(line.split("... | 97e006818a36f4fbd825eddb23d02cfed044911d | 647,373 |
def find_indices(nums, val):
"""Given a list, find the two indices that sum to a specific value"""
for i, outer_num in enumerate(nums):
for j, inner_num in enumerate(nums):
if outer_num + inner_num == val:
return (i, j)
return False | 6d162c3a390586cf7e5db6be9a9ed1c5750ac02f | 647,374 |
def expandtabs(s, tabstop=8, ignoring=None):
"""Expand tab characters `'\\\\t'` into spaces.
:param tabstop: number of space characters per tab
(defaults to the canonical 8)
:param ignoring: if not `None`, the expansion will be "smart" and
go from one tabstop to th... | 90220575225518c6db0082c157901dfd19448b9f | 647,379 |
def getOutputShape(model, index = -1):
"""
Gets the shape of a single output. For compatibility returns the shape
of the last output if there are multiple outputs.
Return:
Numeric dimensions, omits dimensions that have no value. eg batch
size.
"""
s = []
... | 87234355b9ab0ae48abe1912a80b07d1f6c45e09 | 647,382 |
def dice_outcome_extractor(run):
"""Return the atmospheric temperature of the final state."""
return run.states[-1].TATM | f1f6dd3e9796964370289389579bda623f6c5572 | 647,384 |
import random
def random_threshold_sequence(n,p,seed=None):
"""
Create a random threshold sequence of size n.
A creation sequence is built by randomly choosing d's with
probabiliy p and i's with probability 1-p.
s=nx.random_threshold_sequence(10,0.5)
returns a threshold sequence of length 10... | b3d4087e1ef0dfdc0e39234fec4a6ac39920ed86 | 647,389 |
def is_np_chunk(tree):
"""
Returns true if given tree is a NP chunk.
A noun phrase chunk is defined as any subtree of the sentence
whose label is "NP" that does not itself contain any other
noun phrases as subtrees.
"""
if tree.label() == 'NP' and \
not list(tree.subtrees(lambda ... | 48fb62410831a3ae3f2454fb1d2551753ed00fd8 | 647,392 |
def linear(x, root):
""" Returns a decay factor based on the linear function
.. math::
f(x) = \\begin{cases} -x/root + 1 & \\mbox{if} x < root; \\\\
0 & otherwise.
\\end{cases}
:param x: The function argument *x*.
... | e7e1cfcdab4775f40e157236fbd36eca42729236 | 647,394 |
def get_flows_from_logbook(logbook, persistence_backend):
"""
Gets all flows for a logbook
:param obj logbook: A TaskFlow logbook
:param obj persistence_backend: A connection to the persistence backend
:return iter[obj, ..] all_flows: An iterable of flow objects
"""
return persistence_backen... | 94b16bfe5de55ad635d47600e773d11a6efafc9b | 647,395 |
def to_layer(operation_list, num_wires):
"""Convert the given list of operations to a layer.
Args:
operation_list (list[~.Operation]): List of Operations in the layer
num_wires (int): Number of wires in the system
Returns:
list[Union[~.Operation,None]]: The corresponding layer
... | e05fed5db3051d4e5d99d2bb91159eabcd87a6f1 | 647,403 |
def add_ids(edges):
"""
Adds ids to edges missing ids
"""
for e in edges:
if 'id' not in e:
e['id'] = e['subject'] + '-' + e['predicate'] + '-' + e['object']
return edges | 6770ff65eeb4e6d722b226c0333363657be1e7bd | 647,404 |
from typing import Hashable
def _key_from_dict(d) -> Hashable:
"""Convert nested dict into a frozen, hashable structure usable as a key."""
if isinstance(d, dict):
return frozenset((k, _key_from_dict(v)) for k, v in d.items())
elif isinstance(d, (list, tuple)):
return tuple(map(_key_from_dict, d))
els... | da98436c65b71933900f0a59f6ef39a84de665c2 | 647,407 |
def compute_optalpha(norm_r, norm_Fty, epsilon, comp_alpha=True):
"""
Compute optimal alpha for WRI
Parameters
----------
norm_r: Float
Norm of residual
norm_Fty: Float
Norm of adjoint wavefield squared
epsilon: Float
Noise level
comp_alpha: Bool
Whether ... | 7206d14d41df1f9d9c5e9989f4b9fc36b9b8ae31 | 647,409 |
def _return_ordered_config(unordered_config: dict, template_config: dict) -> dict:
"""Orders the keys in unordered_config according to the order in template_config.
Note this function assumes all keys in both dictionaries are identical,
including all nested dictionaries.
"""
# create a dictionary ... | f74f62973511bf26b188c77e6ee6d31367c8fcf6 | 647,410 |
def num_to_bitstring(num, length):
"""Returns string of bits from number, truncated at length.
Algorithm: While the number storing the bitvector is greater than
zero, find the last digit as (num mod 2) and then bit-shift the string to
the right to delete the last digit. Add the digits into a string fr... | c31d233f67febe7a34d5874ff7a098d796c9cffc | 647,415 |
import re
def embolden(word, quote):
"""Make word bold in quote, regardless of but maintaining case"""
return re.sub(r"(" + word + r")", r"<b>\1</b>", quote, flags=re.I) | 2b92ac93742bebc8faddf615782679144586b9e5 | 647,418 |
def get_function_name(stack_outputs, function_logical_id):
"""Obtains the function name from given stack outputs.
:type stack_outputs: dict
:param stack_outputs: CloudFormation stack outputs.
:type function_logical_id: str
:param function_logical_id: logical ID of the function resource.
:rtyp... | d718f658804344abf4e9c2d6c1fda3261da7385e | 647,419 |
def header_population(headers):
"""make column headers from a list
:param headers: list of column headers
:return: a list of dictionaries
"""
return [{'id': field, 'name': field, 'field': field, 'sortable': True} for field in headers] | 0f439daf146bb72a8062d950e62ae87673495f5c | 647,420 |
def getRawTimes(grid):
""" A helper function to get all times inside a grid, returns a list of times
"""
times=[]
for i in range(grid.getDomainSet().getLength()):
times.append(grid.getDomainSet()[i].getValue())
return times | 8bc9cdb57069469b9d0ce7eb3a6f3d7dfaf5c67e | 647,426 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.